limixbot 0.3.79 → 0.3.81

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.
Files changed (127) hide show
  1. package/dist/assets/{ActivityPanel-BVNkqBIC.js → ActivityPanel-BXFEtu90.js} +1 -1
  2. package/dist/assets/{App-CvsehEe_.js → App-Di_RKfDE.js} +63 -63
  3. package/dist/assets/{AppEventEditor-BYguwqDN.js → AppEventEditor-Bxo59GaM.js} +1 -1
  4. package/dist/assets/BotSettingsDialog-BtdhqHMV.js +16 -0
  5. package/dist/assets/{BrowserPanel-BTCGczPf.js → BrowserPanel-8mHeGOLP.js} +1 -1
  6. package/dist/assets/{BrowserProfilesManager-DZ2gX0y2.js → BrowserProfilesManager-DNDenex_.js} +1 -1
  7. package/dist/assets/{CloudAddDialog-DuhiNoO8.js → CloudAddDialog-B3mItSdo.js} +1 -1
  8. package/dist/assets/{ComputerFilesPane-CGP2MSqh.js → ComputerFilesPane-DUM3BGn5.js} +1 -1
  9. package/dist/assets/{ComputerPanel-C3jYTvzh.js → ComputerPanel-B1ProOmB.js} +2 -2
  10. package/dist/assets/{DataPanel-B5sek_0y.js → DataPanel-B9dG-xFC.js} +1 -1
  11. package/dist/assets/{DesktopViewer-DBMUDqPa.js → DesktopViewer-CxgTWyru.js} +1 -1
  12. package/dist/assets/{FilesView-CGdJc4B8.js → FilesView-BdErJPbS.js} +1 -1
  13. package/dist/assets/{GrokMoveDialog-BxE7bO-C.js → GrokMoveDialog-DmZmbC5L.js} +1 -1
  14. package/dist/assets/{InspectorPanel-CKLUT8oB.js → InspectorPanel-B1sIo1J5.js} +1 -1
  15. package/dist/assets/{KeyboardShortcutsModal-DxL0bhz0.js → KeyboardShortcutsModal-C5hjzxvv.js} +1 -1
  16. package/dist/assets/{LiveDesktop-DZHAgYhr.js → LiveDesktop-CN8YTqUZ.js} +1 -1
  17. package/dist/assets/{LocalVmWorkspace-5FdM1GcK.js → LocalVmWorkspace-C3kwGTKa.js} +1 -1
  18. package/dist/assets/{MacLocalControl-COa2bTeU.js → MacLocalControl-OTlnJ0ZN.js} +1 -1
  19. package/dist/assets/{MarkdownFilePreview-wV4LMjz6.js → MarkdownFilePreview-Da65BUFR.js} +1 -1
  20. package/dist/assets/{MenuMotion-CcuJn489.js → MenuMotion-B5n2ZkGC.js} +1 -1
  21. package/dist/assets/{NewBotDialog-BTHPAm-H.js → NewBotDialog-yIDxcMQJ.js} +1 -1
  22. package/dist/assets/{PhoneAppDialog-Dqcmnx_B.js → PhoneAppDialog-Bl38QRBo.js} +1 -1
  23. package/dist/assets/{PlacesRail-CRmtzh8u.js → PlacesRail-PNE_Y9GC.js} +1 -1
  24. package/dist/assets/{PluginsPanel-XaOSjVze.js → PluginsPanel-uBfd1z73.js} +1 -1
  25. package/dist/assets/{ProIntroduction-BlMy0JGo.js → ProIntroduction-CJI7fYhZ.js} +1 -1
  26. package/dist/assets/{RemoteAgentSettingsPanel-BYE04c1Y.js → RemoteAgentSettingsPanel-B5JBGc4J.js} +1 -1
  27. package/dist/assets/{RoomPanel-Dlzb2mxc.js → RoomPanel-B8o0-I0t.js} +1 -1
  28. package/dist/assets/{RoutinesPage-esNzRfID.js → RoutinesPage-K_BfBMn8.js} +1 -1
  29. package/dist/assets/{SettingsModal-_yGtX6l0.js → SettingsModal-DXSZCYBo.js} +1 -1
  30. package/dist/assets/{ShareTeamDialog-NiBljKHE.js → ShareTeamDialog-DTyuq4lx.js} +1 -1
  31. package/dist/assets/{SignedInSites-L4aSrXYW.js → SignedInSites-C-qamp3R.js} +1 -1
  32. package/dist/assets/{TeamLibraryPanel-CXiA_ll-.js → TeamLibraryPanel-D18289iU.js} +1 -1
  33. package/dist/assets/{TeamMapPage-C-qti0hy.js → TeamMapPage-CtEOY0Vl.js} +1 -1
  34. package/dist/assets/{TriggersPage-C497fuYj.js → TriggersPage-Cjpc4tVU.js} +1 -1
  35. package/dist/assets/{VisibilitySection-BGZ0rqTi.js → VisibilitySection-BFDrnzbh.js} +1 -1
  36. package/dist/assets/{WebhookTrigger-BH1BByzy.js → WebhookTrigger-YBoFyBq8.js} +1 -1
  37. package/dist/assets/{WorksOnGrid-DWH93kqg.js → WorksOnGrid-CAcjXdeB.js} +1 -1
  38. package/dist/assets/{abnfDiagram-YUKMZFIV-65Eq1Je6.js → abnfDiagram-YUKMZFIV-B5MGbjZP.js} +1 -1
  39. package/dist/assets/{activity-ZDWVxHRW.js → activity-i4SOTxBA.js} +1 -1
  40. package/dist/assets/{architectureDiagram-47P4ROYG-DrG8Yma0.js → architectureDiagram-47P4ROYG-z1L1R8jr.js} +1 -1
  41. package/dist/assets/{blockDiagram-E7TT5TSB-D54NTWSM.js → blockDiagram-E7TT5TSB-BgCJ5XqR.js} +1 -1
  42. package/dist/assets/{c4Diagram-CRA5TL53-3og_-YU_.js → c4Diagram-CRA5TL53-BxQ3fhnE.js} +1 -1
  43. package/dist/assets/{calendar-days-BMi-5cJi.js → calendar-days-D81dmGeW.js} +1 -1
  44. package/dist/assets/channel-Nvi2Z0SJ.js +1 -0
  45. package/dist/assets/{chunk-2Q5K7J3B-r3qgqOqv.js → chunk-2Q5K7J3B-CSVcU4dl.js} +1 -1
  46. package/dist/assets/{chunk-5VM5RSS4-DR43CCkD.js → chunk-5VM5RSS4-HqrufCgf.js} +1 -1
  47. package/dist/assets/{chunk-7TKQ45FW-Cjbd6ZLp.js → chunk-7TKQ45FW-D6I-6CLD.js} +1 -1
  48. package/dist/assets/{chunk-AW2ZBBNX-CmpcWqjE.js → chunk-AW2ZBBNX-nl3ozUZV.js} +1 -1
  49. package/dist/assets/{chunk-FVRAUYC3--y-kcX08.js → chunk-FVRAUYC3-wr6Np7EE.js} +2 -2
  50. package/dist/assets/{chunk-HTAEGDNF-dBj3y-VC.js → chunk-HTAEGDNF-XZGyfK8y.js} +1 -1
  51. package/dist/assets/{chunk-JWPE2WC7-B3uOSoFW.js → chunk-JWPE2WC7-pVRLXa0H.js} +1 -1
  52. package/dist/assets/{chunk-KQW6MTUR-DfT1IF3I.js → chunk-KQW6MTUR-Cb22vGIM.js} +1 -1
  53. package/dist/assets/{chunk-XXDRQBXY-CygLCvpM.js → chunk-XXDRQBXY-CmETcGZq.js} +1 -1
  54. package/dist/assets/{classDiagram-v2-K4WV4PDN-DGTDBVvN.js → classDiagram-v2-K4WV4PDN-eKf7q2Qc.js} +1 -1
  55. package/dist/assets/{coins-2Ipg9jSL.js → coins-GsXVRnl_.js} +1 -1
  56. package/dist/assets/{core-D_78Ynu8.js → core-B-k_7y0P.js} +1 -1
  57. package/dist/assets/{cose-bilkent-JH36ORCC-Bb0KgTtB.js → cose-bilkent-JH36ORCC-D4VzuikC.js} +1 -1
  58. package/dist/assets/{cynefin-EF2NZ3EQ-qGBA_DIq.js → cynefin-EF2NZ3EQ-CeoYk0bd.js} +1 -1
  59. package/dist/assets/{cynefinDiagram-3GCD6N5R-hF9YSVOq.js → cynefinDiagram-3GCD6N5R-ru8_qbbj.js} +1 -1
  60. package/dist/assets/{dagre-W4DXFKR2-3q_zIjPm.js → dagre-W4DXFKR2-wL6sYRlF.js} +1 -1
  61. package/dist/assets/{diagram-2UJZ2QOL-BOTHlOcq.js → diagram-2UJZ2QOL-BbNSoiqa.js} +1 -1
  62. package/dist/assets/{diagram-OVF4WLC6-Dnya3JUJ.js → diagram-OVF4WLC6-k8AAT5zq.js} +1 -1
  63. package/dist/assets/{diagram-PFPMY2P6-Bm2_1jj-.js → diagram-PFPMY2P6-ifjP4RXu.js} +1 -1
  64. package/dist/assets/{diagram-UMYRVEAY-CQrHk9Kj.js → diagram-UMYRVEAY-Ew2tVPDg.js} +1 -1
  65. package/dist/assets/{diagram-YEKJPTXX-DLdp-cKw.js → diagram-YEKJPTXX-Dovy7WaK.js} +1 -1
  66. package/dist/assets/{diagram-ZIFT7M5P-C542U79M.js → diagram-ZIFT7M5P-rtKhjRxK.js} +1 -1
  67. package/dist/assets/{ebnfDiagram-VR2GEFS7-DsKKpNma.js → ebnfDiagram-VR2GEFS7-BE67RFVg.js} +1 -1
  68. package/dist/assets/{elk-IJKZMXRS-DZL2zCKo.js → elk-IJKZMXRS-By_AEbig.js} +1 -1
  69. package/dist/assets/{erDiagram-O2IAPWRE-D4IGRyB_.js → erDiagram-O2IAPWRE-NMF3USSg.js} +1 -1
  70. package/dist/assets/{file-up-CZXyq-v_.js → file-up-CwVtVDwM.js} +1 -1
  71. package/dist/assets/{flowDiagram-OXPTDLAJ-xHZwGby9.js → flowDiagram-OXPTDLAJ-7VJ7i6mz.js} +1 -1
  72. package/dist/assets/{ganttDiagram-R7TSEDQI-eCuinfuc.js → ganttDiagram-R7TSEDQI-BsGUeaLq.js} +1 -1
  73. package/dist/assets/{gitGraphDiagram-XJZIOB7I-Cyhck_tc.js → gitGraphDiagram-XJZIOB7I-B5SdxDl8.js} +1 -1
  74. package/dist/assets/{import-name-k9CSvERS.js → import-name-CF2rJETO.js} +1 -1
  75. package/dist/assets/{index-BMsqhtYl.js → index-BOBBoSRI.js} +3 -3
  76. package/dist/assets/{index-C3-UCB9t.js → index-BoIJ2PWD.js} +1 -1
  77. package/dist/assets/{infoDiagram-5W2HQ5XZ-Cz9xYKn8.js → infoDiagram-5W2HQ5XZ-BqpdF76u.js} +1 -1
  78. package/dist/assets/{ishikawaDiagram-K3B6WC7H-Cms6sZIz.js → ishikawaDiagram-K3B6WC7H-ChPuwoRo.js} +1 -1
  79. package/dist/assets/{journeyDiagram-COXZFDF6-C918DJxn.js → journeyDiagram-COXZFDF6-AJsQ9Sal.js} +1 -1
  80. package/dist/assets/{kanban-definition-P3RFRI5V-Dh4rnCl5.js → kanban-definition-P3RFRI5V-Cbf53EMp.js} +1 -1
  81. package/dist/assets/{mcp-servers-R17O9xFq.js → mcp-servers-BjChYca1.js} +1 -1
  82. package/dist/assets/{mermaid.core-nsP0cVsp.js → mermaid.core-5XOzwbA1.js} +4 -4
  83. package/dist/assets/{mindmap-definition-LZFPQGKD-CFrq5gkA.js → mindmap-definition-LZFPQGKD-CD-WwEpo.js} +1 -1
  84. package/dist/assets/{minimize-OWlsq-0s.js → minimize-BBAOsm2F.js} +1 -1
  85. package/dist/assets/{monitor-76fhlY80.js → monitor-ByVtOtHb.js} +1 -1
  86. package/dist/assets/{new-bot-D4-p5E80.js → new-bot-Brnt-vsQ.js} +1 -1
  87. package/dist/assets/{org-library-IoJj_iDs.js → org-library-BqPtAtfm.js} +1 -1
  88. package/dist/assets/{package-format-Dek_P3eO.js → package-format-DswU6LQA.js} +1 -1
  89. package/dist/assets/{pegDiagram-BGZESJAR-CpRYFAU1.js → pegDiagram-BGZESJAR-p2NJ2LJo.js} +1 -1
  90. package/dist/assets/{pieDiagram-CAPJLFHJ-BaqH4FaB.js → pieDiagram-CAPJLFHJ-BiLTUs2q.js} +1 -1
  91. package/dist/assets/{quadrantDiagram-GDMTTRAM-CGj6xfEM.js → quadrantDiagram-GDMTTRAM-BLtReWzy.js} +1 -1
  92. package/dist/assets/{rail-Dil29FKU.js → rail-B292SI4O.js} +1 -1
  93. package/dist/assets/{railroadDiagram-SM67HX2B-T8YW5IRA.js → railroadDiagram-SM67HX2B-CmU-L8x-.js} +1 -1
  94. package/dist/assets/{remote-desktop-panel-CmslCBxy.js → remote-desktop-panel-C320nXM7.js} +1 -1
  95. package/dist/assets/{requirementDiagram-X7JNWC4A-vX99IzDT.js → requirementDiagram-X7JNWC4A-C7POybJi.js} +1 -1
  96. package/dist/assets/{sankeyDiagram-UM26HJRW-BfgAMAiw.js → sankeyDiagram-UM26HJRW-Bh1astOc.js} +1 -1
  97. package/dist/assets/{sequenceDiagram-ZO4K6R2Y-BxqhI_5G.js → sequenceDiagram-ZO4K6R2Y-j_M4G1u_.js} +1 -1
  98. package/dist/assets/{sizeCapture-INFHLROL-DivsEQN9.js → sizeCapture-INFHLROL-Ca-8iWQF.js} +1 -1
  99. package/dist/assets/{stateDiagram-v2-TBUQTH76-gvw7v1YG.js → stateDiagram-v2-TBUQTH76-BEwcaRZx.js} +1 -1
  100. package/dist/assets/styles-fasgTjLK.css +1 -0
  101. package/dist/assets/{swimlanes-N4OXWK64-BHxjZqDS.js → swimlanes-N4OXWK64-DmlmxFf2.js} +1 -1
  102. package/dist/assets/swimlanesDiagram-K3J5GTZL-rbSiIYPg.js +8 -0
  103. package/dist/assets/{team-share-DzmYPtMt.js → team-share-DI90Vqwa.js} +1 -1
  104. package/dist/assets/{timeline-definition-YOQAKGHF-CkrkdnYL.js → timeline-definition-YOQAKGHF-CHX-HOfh.js} +1 -1
  105. package/dist/assets/{usecaseDiagram-VIAY4XPW-D4LWhANl.js → usecaseDiagram-VIAY4XPW-eeJvKlcE.js} +1 -1
  106. package/dist/assets/{vennDiagram-BLWOH2XV-CX4YR6o_.js → vennDiagram-BLWOH2XV-DylhYeUG.js} +1 -1
  107. package/dist/assets/{wardleyDiagram-YMQ3BMBF-BXx0E2ta.js → wardleyDiagram-YMQ3BMBF-CUUtluRt.js} +1 -1
  108. package/dist/assets/{xychartDiagram-TAQBALBS-DxVI0fYE.js → xychartDiagram-TAQBALBS-C-gwkNiy.js} +1 -1
  109. package/dist/index.html +3 -3
  110. package/dist/rail.html +5 -5
  111. package/dist-server/index.js +7234 -5599
  112. package/dist-server/package.json +1 -1
  113. package/dist-server/server/bot-api-host.js +1 -1
  114. package/dist-server/server/bot-channels/adapters.js +6 -0
  115. package/dist-server/server/bot-channels/discord.js +152 -0
  116. package/dist-server/server/bot-channels/engine.js +424 -0
  117. package/dist-server/server/bot-channels/facebook.js +94 -0
  118. package/dist-server/server/bot-channels/telegram.js +79 -0
  119. package/dist-server/server/bot-channels/zalo.js +111 -0
  120. package/dist-server/server/index.js +6 -5
  121. package/package.json +1 -1
  122. package/dist/assets/BotSettingsDialog-Be44NFrp.js +0 -16
  123. package/dist/assets/channel-BhUqydpo.js +0 -1
  124. package/dist/assets/styles-BABP9ycC.css +0 -1
  125. package/dist/assets/swimlanesDiagram-K3J5GTZL-CynVazVQ.js +0 -8
  126. package/dist-server/server/limix-telegram.js +0 -329
  127. /package/dist/assets/{styles-1Sa7mQdy.js → styles-DdM6yn_a.js} +0 -0
@@ -1 +1 @@
1
- {"type":"module","version":"0.3.79"}
1
+ {"type":"module","version":"0.3.81"}
@@ -173,7 +173,7 @@ export function createBotApiHost(deps) {
173
173
  fail(502, COULD_NOT_ANSWER, settled.text);
174
174
  return { status: 200, body: { reply: replyText(after()), thread: threadId } };
175
175
  }
176
- /** Limix: a message from a chat channel this server itself reads (limix-telegram.ts), never from an outside caller. The
176
+ /** Limix: a message from a chat channel this server itself reads (server/bot-channels), never from an outside caller. The
177
177
  * bot's verified owner talks to it as from the app, in a conversation of its own at Full access; anyone else is a
178
178
  * Bot API caller, confined. Waits for the answer up to `waitMs`. */
179
179
  async function askFromChannel(botId, input) {
@@ -0,0 +1,6 @@
1
+ import { discordAdapter } from "./discord.js";
2
+ import { facebookAdapter } from "./facebook.js";
3
+ import { telegramAdapter } from "./telegram.js";
4
+ import { zaloAdapter, zaloLogin } from "./zalo.js";
5
+ export const botChannelAdapters = () => [telegramAdapter(), discordAdapter(), zaloAdapter(), facebookAdapter()];
6
+ export const botChannelLogins = () => ({ zalo: zaloLogin() });
@@ -0,0 +1,152 @@
1
+ // Discord through its Gateway (API v10) for incoming messages and REST for replies. Only the non-privileged intents are
2
+ // asked for: Discord still hands a bot the text of direct messages and of messages that mention it, which is all it answers.
3
+ import WebSocket from "ws";
4
+ import { ChannelError, wait } from "./engine.js";
5
+ const API = "https://discord.com/api/v10";
6
+ const GATEWAY = "wss://gateway.discord.gg/?v=10&encoding=json";
7
+ const INTENTS = (1 << 9) | (1 << 12);
8
+ const FATAL_CLOSE = {
9
+ 4004: "Token Discord không còn dùng được. Dán token mới từ Discord Developer Portal.",
10
+ 4010: "Discord từ chối kết nối (4010).", 4011: "Bot Discord cần chia shard: bot đang ở quá nhiều server.",
11
+ 4012: "Discord từ chối phiên bản kết nối (4012).", 4013: "Discord từ chối quyền đọc tin (4013).", 4014: "Discord từ chối quyền đọc tin (4014).",
12
+ };
13
+ export function discordAdapter(options = {}) {
14
+ const call = options.fetch ?? fetch;
15
+ const openSocket = options.openSocket ?? ((url) => new WebSocket(url));
16
+ const sleep = options.sleep ?? wait;
17
+ async function rest(token, method, path, body) {
18
+ const response = await call(`${API}${path}`, { method, headers: { authorization: `Bot ${token}`, ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) })
19
+ .catch((error) => { throw new ChannelError("retry", `Discord: ${error instanceof Error ? error.message : String(error)}`); });
20
+ if (response.ok)
21
+ return response.status === 204 ? null : response.json().catch(() => null);
22
+ const data = await response.json().catch(() => ({}));
23
+ if (response.status === 401)
24
+ throw new ChannelError("auth", FATAL_CLOSE[4004]);
25
+ if (response.status === 429 || response.status >= 500)
26
+ throw new ChannelError("retry", `Discord báo lỗi ${response.status}.`, data.retry_after ? Math.ceil(data.retry_after * 1000) : undefined);
27
+ throw new ChannelError("drop", `Discord báo lỗi ${response.status}${data.message ? `: ${data.message}` : ""}.`);
28
+ }
29
+ return {
30
+ kind: "discord",
31
+ label: "Discord",
32
+ textMax: 2000,
33
+ async check(token) {
34
+ if (!/^[\w.-]{50,100}$/.test(token))
35
+ throw new ChannelError("auth", "Token không đúng dạng. Copy token ở mục Bot của Discord Developer Portal.");
36
+ const me = await rest(token, "GET", "/users/@me").catch(() => null);
37
+ if (!me?.username || !me.bot)
38
+ throw new ChannelError("auth", "Discord không nhận token bot này.");
39
+ return { username: me.username, name: me.global_name ?? me.username };
40
+ },
41
+ async open(token, io) {
42
+ let self = "";
43
+ let resume;
44
+ let seq = null;
45
+ const toMessage = (event) => {
46
+ if (!event?.author || event.author.bot || event.author.id === self)
47
+ return null;
48
+ const direct = !event.guild_id;
49
+ const mentioned = Array.isArray(event.mentions) && event.mentions.some((user) => user?.id === self);
50
+ if (!direct && !mentioned)
51
+ return null;
52
+ return {
53
+ id: String(event.id), chatId: String(event.channel_id), direct,
54
+ from: { id: String(event.author.id), name: event.member?.nick ?? event.author.global_name ?? event.author.username ?? String(event.author.id) },
55
+ text: String(event.content ?? "").replace(new RegExp(`<@!?${self}>`, "g"), "").trim(),
56
+ ...(Array.isArray(event.attachments) && event.attachments.length ? { media: true } : {}),
57
+ };
58
+ };
59
+ /** One Gateway connection; resolves when it closes in a way worth reconnecting after. */
60
+ const connectOnce = () => new Promise((resolve, reject) => {
61
+ const socket = openSocket(resume?.url ? `${resume.url}/?v=10&encoding=json` : GATEWAY);
62
+ let beat;
63
+ let acked = true;
64
+ const stop = () => { if (beat)
65
+ clearInterval(beat); io.signal.removeEventListener("abort", onAbort); };
66
+ const onAbort = () => { stop(); socket.close(1000); resolve(); };
67
+ io.signal.addEventListener("abort", onAbort, { once: true });
68
+ socket.on("error", () => { });
69
+ socket.on("close", (code) => {
70
+ stop();
71
+ if (FATAL_CLOSE[code])
72
+ return reject(new ChannelError(code === 4004 ? "auth" : "conflict", FATAL_CLOSE[code]));
73
+ if (code === 4007 || code === 4009) {
74
+ resume = undefined;
75
+ seq = null;
76
+ }
77
+ resolve();
78
+ });
79
+ socket.on("message", (raw) => {
80
+ let packet;
81
+ try {
82
+ packet = JSON.parse(String(raw));
83
+ }
84
+ catch {
85
+ return;
86
+ }
87
+ if (typeof packet.s === "number")
88
+ seq = packet.s;
89
+ if (packet.op === 10) {
90
+ const every = Number(packet.d?.heartbeat_interval) || 41_250;
91
+ beat = setInterval(() => {
92
+ if (!acked) {
93
+ socket.close(4000);
94
+ return;
95
+ }
96
+ acked = false;
97
+ socket.send(JSON.stringify({ op: 1, d: seq }));
98
+ }, every);
99
+ socket.send(JSON.stringify(resume && seq !== null
100
+ ? { op: 6, d: { token, session_id: resume.id, seq } }
101
+ : { op: 2, d: { token, intents: INTENTS, properties: { os: process.platform, browser: "limix-bot", device: "limix-bot" } } }));
102
+ }
103
+ else if (packet.op === 11)
104
+ acked = true;
105
+ else if (packet.op === 1)
106
+ socket.send(JSON.stringify({ op: 1, d: seq }));
107
+ else if (packet.op === 7)
108
+ socket.close(4000);
109
+ else if (packet.op === 9) {
110
+ if (!packet.d) {
111
+ resume = undefined;
112
+ seq = null;
113
+ }
114
+ socket.close(4000);
115
+ }
116
+ else if (packet.op === 0) {
117
+ if (packet.t === "READY") {
118
+ self = String(packet.d?.user?.id ?? "");
119
+ resume = { id: String(packet.d?.session_id ?? ""), url: String(packet.d?.resume_gateway_url ?? "") };
120
+ io.healthy();
121
+ }
122
+ else if (packet.t === "RESUMED")
123
+ io.healthy();
124
+ else if (packet.t === "MESSAGE_CREATE") {
125
+ const message = toMessage(packet.d);
126
+ if (message)
127
+ io.deliver(message);
128
+ }
129
+ }
130
+ });
131
+ });
132
+ const done = (async () => {
133
+ let drops = 0;
134
+ while (!io.signal.aborted) {
135
+ const started = Date.now();
136
+ await connectOnce();
137
+ if (io.signal.aborted)
138
+ return;
139
+ drops = Date.now() - started > 60_000 ? 0 : drops + 1;
140
+ if (drops > 5)
141
+ throw new ChannelError("retry", "Discord liên tục ngắt kết nối.");
142
+ await sleep(1_000 + Math.random() * 4_000, io.signal);
143
+ }
144
+ })();
145
+ return {
146
+ done,
147
+ send: async (chatId, text) => { await rest(token, "POST", `/channels/${chatId}/messages`, { content: text, allowed_mentions: { parse: [] } }); },
148
+ typing: async (chatId) => { await rest(token, "POST", `/channels/${chatId}/typing`); },
149
+ };
150
+ },
151
+ };
152
+ }
@@ -0,0 +1,424 @@
1
+ // Limix Bot: a bot answers on Telegram, Discord, Zalo or a Facebook Page from its own settings. This server holds each connection itself
2
+ // (no webhook, no address to open): the owner links their own account with a one-time code (/link CODE) and then talks
3
+ // to the bot as from the app, at Full access, in a direct chat of its own; everyone else, and every group, is answered
4
+ // only when the owner allows it, through the confined Bot API path. Secrets are sealed on disk and never leave this server.
5
+ //
6
+ // The duplicate filter, retry with backoff, per-account send pacing and the channel adapter contract follow ChannelHub,
7
+ // Copyright (c) 2026 TheOwlOps, used under the MIT License (third_party/channelhub/LICENSE).
8
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
9
+ import { mkdirSync, readFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { z } from "zod";
12
+ import { writeFileAtomic } from "../atomic.js";
13
+ import { PASS } from "../routes/table.js";
14
+ /** Why a connection or a send failed: "auth" stops the channel until a new secret, "conflict" and "retry" try again. */
15
+ export class ChannelError extends Error {
16
+ reason;
17
+ retryAfterMs;
18
+ constructor(reason, message, retryAfterMs) { super(message); this.reason = reason; this.retryAfterMs = retryAfterMs; }
19
+ }
20
+ const LINK_MS = 15 * 60_000;
21
+ const BACKOFF_MS = [2_000, 5_000, 15_000, 60_000];
22
+ const SEND_RETRIES = 3;
23
+ const SEEN_MS = 10 * 60_000;
24
+ const KEY_FILE = "limix-telegram.key";
25
+ const botSchema = z.object({
26
+ sealed: z.string(),
27
+ username: z.string().default(""),
28
+ name: z.string().default(""),
29
+ enabled: z.boolean().default(true),
30
+ access: z.enum(["owner", "everyone"]).default("owner"),
31
+ owner: z.object({ id: z.union([z.string(), z.number()]).transform(String), name: z.string() }).optional(),
32
+ link: z.object({ hash: z.string(), expiresAt: z.number() }).optional(),
33
+ offset: z.number().default(0),
34
+ chats: z.record(z.string(), z.string()).default({}),
35
+ error: z.string().optional(),
36
+ });
37
+ const fileSchema = z.object({ v: z.literal(1), bots: z.record(z.string(), botSchema) });
38
+ const text = (label) => ({
39
+ start: `Chào bạn! Đây là bot Limix. Nhắn tin để trò chuyện. Chủ bot: gửi /link MÃ để liên kết.`,
40
+ linked: "Đã liên kết. Từ giờ bạn nhắn ở đây như nhắn trong app Limix.",
41
+ badCode: `Mã không đúng hoặc đã hết hạn. Tạo mã mới trong app Limix: bot → Cài đặt → ${label}.`,
42
+ linkHere: "Hãy gửi /link MÃ trong tin nhắn riêng với bot.",
43
+ ownerOnly: "Bot này hiện chỉ trả lời chủ bot.",
44
+ textOnly: "Hiện bot chỉ đọc tin nhắn chữ.",
45
+ fresh: "Đã bắt đầu cuộc trò chuyện mới.",
46
+ approval: "Bot đang chờ bạn duyệt một bước trong app Limix.",
47
+ working: "Bot vẫn đang làm việc này. Xem kết quả trong app Limix.",
48
+ failed: "Bot chưa trả lời được lúc này. Thử lại sau.",
49
+ empty: "Bot đã làm xong nhưng không có câu trả lời bằng chữ.",
50
+ });
51
+ /** Splits a reply at paragraph, then line, then word boundaries so each piece fits one message. */
52
+ export function chunkText(body, max) {
53
+ const out = [];
54
+ let rest = body.trim();
55
+ while (rest.length > max) {
56
+ const window = rest.slice(0, max);
57
+ const cut = Math.max(window.lastIndexOf("\n\n"), window.lastIndexOf("\n"), window.lastIndexOf(" "));
58
+ const at = cut > max / 2 ? cut : max;
59
+ out.push(rest.slice(0, at).trimEnd());
60
+ rest = rest.slice(at).trimStart();
61
+ }
62
+ if (rest)
63
+ out.push(rest);
64
+ return out;
65
+ }
66
+ const hashCode = (code) => createHash("sha256").update(code.trim().toUpperCase()).digest("hex");
67
+ const failure = (error) => (error instanceof Error ? error.message : String(error));
68
+ export function wait(ms, signal) {
69
+ return new Promise((resolve) => {
70
+ if (signal.aborted)
71
+ return resolve();
72
+ const timer = setTimeout(resolve, ms);
73
+ signal.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true });
74
+ });
75
+ }
76
+ export function createBotChannels(deps) {
77
+ const now = deps.now ?? Date.now;
78
+ const log = deps.log ?? (() => { });
79
+ const sleep = deps.sleep ?? wait;
80
+ const keyFile = join(deps.dataDir, KEY_FILE);
81
+ const adapters = new Map(deps.adapters.map((adapter) => [adapter.kind, adapter]));
82
+ const runs = new Map();
83
+ const queues = new Map();
84
+ const paces = new Map();
85
+ const seen = new Map();
86
+ const logins = new Map();
87
+ let running = false;
88
+ const fileOf = (kind) => join(deps.dataDir, `limix-${kind}.json`);
89
+ function read(kind) {
90
+ try {
91
+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(fileOf(kind), "utf8")));
92
+ if (parsed.success)
93
+ return parsed.data;
94
+ }
95
+ catch { }
96
+ return { v: 1, bots: {} };
97
+ }
98
+ function write(kind, data) { mkdirSync(deps.dataDir, { recursive: true }); writeFileAtomic(fileOf(kind), `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 }); }
99
+ function patch(kind, botId, change) {
100
+ const data = read(kind);
101
+ const entry = data.bots[botId];
102
+ if (!entry)
103
+ return;
104
+ const next = change(entry);
105
+ if (next)
106
+ data.bots[botId] = next;
107
+ else
108
+ delete data.bots[botId];
109
+ write(kind, data);
110
+ }
111
+ function key(create) {
112
+ try {
113
+ const hex = readFileSync(keyFile, "utf8").trim();
114
+ if (/^[0-9a-f]{64}$/.test(hex))
115
+ return Buffer.from(hex, "hex");
116
+ }
117
+ catch { }
118
+ if (!create)
119
+ return null;
120
+ const made = randomBytes(32);
121
+ mkdirSync(dirname(keyFile), { recursive: true });
122
+ writeFileAtomic(keyFile, `${made.toString("hex")}\n`, { mode: 0o600 });
123
+ return made;
124
+ }
125
+ function seal(secret) {
126
+ const nonce = randomBytes(12);
127
+ const cipher = createCipheriv("aes-256-gcm", key(true), nonce);
128
+ const body = Buffer.concat([cipher.update(secret, "utf8"), cipher.final()]);
129
+ return Buffer.concat([nonce, body, cipher.getAuthTag()]).toString("base64");
130
+ }
131
+ function unseal(sealed) {
132
+ const k = key(false);
133
+ if (!k)
134
+ return null;
135
+ try {
136
+ const data = Buffer.from(sealed, "base64");
137
+ const decipher = createDecipheriv("aes-256-gcm", k, data.subarray(0, 12));
138
+ decipher.setAuthTag(data.subarray(data.length - 16));
139
+ return Buffer.concat([decipher.update(data.subarray(12, data.length - 16)), decipher.final()]).toString("utf8");
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ }
145
+ function firstSight(id) {
146
+ const at = now();
147
+ if ((seen.get(id) ?? 0) > at)
148
+ return false;
149
+ if (seen.size > 5_000)
150
+ for (const [old, until] of seen)
151
+ if (until <= at)
152
+ seen.delete(old);
153
+ seen.set(id, at + SEEN_MS);
154
+ return true;
155
+ }
156
+ /** Sends on one account one after another, paced, retrying what the channel says to retry. */
157
+ function paced(adapter, botId, job) {
158
+ const lane = `${adapter.kind}:${botId}`;
159
+ const run = async () => {
160
+ if (adapter.paceMs) {
161
+ const [low, high] = adapter.paceMs;
162
+ await new Promise((resolve) => setTimeout(resolve, low + Math.random() * Math.max(0, high - low)));
163
+ }
164
+ for (let attempt = 0;; attempt++) {
165
+ try {
166
+ return await job();
167
+ }
168
+ catch (error) {
169
+ const retry = error instanceof ChannelError && error.reason === "retry" && attempt < SEND_RETRIES;
170
+ if (!retry)
171
+ throw error;
172
+ await new Promise((resolve) => setTimeout(resolve, error.retryAfterMs ?? 500 * 2 ** attempt));
173
+ }
174
+ }
175
+ };
176
+ const next = (paces.get(lane) ?? Promise.resolve()).then(run, run);
177
+ paces.set(lane, next.catch(() => { }));
178
+ return next;
179
+ }
180
+ async function reply(adapter, botId, session, chatId, body) {
181
+ try {
182
+ for (const piece of chunkText(body, adapter.textMax))
183
+ await paced(adapter, botId, () => session.send(chatId, piece));
184
+ }
185
+ catch (error) {
186
+ log(`${adapter.kind}: send failed (${failure(error)})`);
187
+ }
188
+ }
189
+ async function handle(adapter, botId, session, message) {
190
+ const kind = adapter.kind, say = text(adapter.label);
191
+ const entry = read(kind).bots[botId];
192
+ if (!entry)
193
+ return;
194
+ const send = (body) => reply(adapter, botId, session, message.chatId, body);
195
+ const command = /^\/(\w+)(?:@\w+)?(?:\s+(.*))?$/s.exec(message.text.trim());
196
+ if (command?.[1] === "start" && !command[2])
197
+ return void await send(say.start);
198
+ if (command?.[1] === "link") {
199
+ if (!message.direct)
200
+ return void await send(say.linkHere);
201
+ const code = (command[2] ?? "").trim();
202
+ const ok = entry.link && entry.link.expiresAt > now() && code && timingSafeEqual(Buffer.from(hashCode(code)), Buffer.from(entry.link.hash));
203
+ if (!ok)
204
+ return void await send(say.badCode);
205
+ patch(kind, botId, (current) => { const { link: _used, ...rest } = current; return { ...rest, owner: { id: message.from.id, name: message.from.name } }; });
206
+ return void await send(say.linked);
207
+ }
208
+ const owner = message.direct && entry.owner?.id === message.from.id;
209
+ if (!owner && entry.access !== "everyone")
210
+ return message.direct && !adapter.quietToStrangers ? void await send(say.ownerOnly) : undefined;
211
+ const conversation = message.direct ? message.chatId : `${message.chatId}:${message.from.id}`;
212
+ if (command?.[1] === "new") {
213
+ patch(kind, botId, (current) => { const chats = { ...current.chats }; delete chats[conversation]; return { ...current, chats }; });
214
+ return void await send(say.fresh);
215
+ }
216
+ if (!message.text.trim())
217
+ return void await send(say.textOnly);
218
+ const pulse = () => void session.typing?.(message.chatId).catch(() => { });
219
+ pulse();
220
+ const typing = setInterval(pulse, 4_000);
221
+ try {
222
+ const known = read(kind).bots[botId]?.chats[conversation];
223
+ const answer = await deps.ask(botId, { text: message.text, ...(known ? { threadId: known } : {}), title: `${adapter.label} · ${message.from.name}`, owner });
224
+ patch(kind, botId, (current) => ({ ...current, chats: { ...current.chats, [conversation]: answer.threadId } }));
225
+ clearInterval(typing);
226
+ await send(answer.reply.trim() || (answer.status === "needs_approval" ? say.approval : answer.status === "working" ? say.working : say.empty));
227
+ }
228
+ catch (error) {
229
+ log(`${kind}: ${failure(error)}`);
230
+ await send(say.failed);
231
+ }
232
+ finally {
233
+ clearInterval(typing);
234
+ }
235
+ }
236
+ /** One chat's messages run one after another; different chats run side by side. */
237
+ function enqueue(adapter, botId, session, message) {
238
+ if (!firstSight(`${adapter.kind}:${botId}:${message.chatId}:${message.id}`))
239
+ return;
240
+ const chat = `${adapter.kind}:${botId}:${message.chatId}`;
241
+ const next = (queues.get(chat) ?? Promise.resolve()).then(() => handle(adapter, botId, session, message)).catch(() => { });
242
+ queues.set(chat, next);
243
+ void next.finally(() => { if (queues.get(chat) === next)
244
+ queues.delete(chat); });
245
+ }
246
+ async function loop(adapter, botId, abort) {
247
+ const kind = adapter.kind, lane = `${kind}:${botId}`;
248
+ let failures = 0;
249
+ while (!abort.signal.aborted) {
250
+ const entry = read(kind).bots[botId];
251
+ const secret = entry ? unseal(entry.sealed) : null;
252
+ if (!entry || !entry.enabled || !secret || !deps.botExists(botId))
253
+ break;
254
+ try {
255
+ let session;
256
+ const io = {
257
+ signal: abort.signal,
258
+ offset: entry.offset,
259
+ saveOffset: (offset) => patch(kind, botId, (current) => ({ ...current, offset })),
260
+ deliver: (message) => { if (session)
261
+ enqueue(adapter, botId, session, message); },
262
+ healthy: () => { failures = 0; if (read(kind).bots[botId]?.error)
263
+ patch(kind, botId, (current) => ({ ...current, error: undefined })); },
264
+ };
265
+ session = await adapter.open(secret, io);
266
+ await session.done;
267
+ if (abort.signal.aborted)
268
+ break;
269
+ throw new ChannelError("retry", `${adapter.label} ngắt kết nối.`);
270
+ }
271
+ catch (error) {
272
+ if (abort.signal.aborted)
273
+ break;
274
+ const reason = error instanceof ChannelError ? error.reason : "retry";
275
+ const message = error instanceof ChannelError && reason !== "retry" ? error.message : `${adapter.label}: ${failure(error)}`;
276
+ log(`${kind}: ${message}`);
277
+ if (reason !== "retry" || failures >= 2)
278
+ patch(kind, botId, (current) => ({ ...current, error: message }));
279
+ if (reason === "auth")
280
+ break;
281
+ await sleep(BACKOFF_MS[Math.min(failures++, BACKOFF_MS.length - 1)], abort.signal);
282
+ }
283
+ }
284
+ if (runs.get(lane) === abort)
285
+ runs.delete(lane);
286
+ }
287
+ function ensure(kind, botId) {
288
+ const adapter = adapters.get(kind);
289
+ const lane = `${kind}:${botId}`;
290
+ if (!running || !adapter || runs.has(lane) || !read(kind).bots[botId]?.enabled)
291
+ return;
292
+ const abort = new AbortController();
293
+ runs.set(lane, abort);
294
+ void loop(adapter, botId, abort);
295
+ }
296
+ function halt(kind, botId) { const lane = `${kind}:${botId}`; runs.get(lane)?.abort(); runs.delete(lane); }
297
+ function view(kind, botId) {
298
+ const entry = read(kind).bots[botId];
299
+ const login = logins.get(`${kind}:${botId}`)?.state;
300
+ if (!entry)
301
+ return { connected: false, ...(login ? { login } : {}) };
302
+ return {
303
+ connected: true, username: entry.username, name: entry.name, enabled: entry.enabled, access: entry.access,
304
+ ...(entry.owner ? { owner: entry.owner.name } : {}),
305
+ ...(entry.link && entry.link.expiresAt > now() ? { linkExpiresAt: entry.link.expiresAt } : {}),
306
+ ...(entry.error ? { error: entry.error } : {}),
307
+ ...(login ? { login } : {}),
308
+ };
309
+ }
310
+ async function connect(kind, botId, secret) {
311
+ const adapter = adapters.get(kind);
312
+ const account = await adapter.check(secret).catch((error) => { throw Object.assign(new Error(error instanceof ChannelError ? error.message : `${adapter.label} không nhận thông tin đăng nhập này.`), { status: 400 }); });
313
+ halt(kind, botId);
314
+ const data = read(kind);
315
+ const kept = data.bots[botId];
316
+ const sameAccount = kept?.username === account.username;
317
+ data.bots[botId] = botSchema.parse({
318
+ sealed: seal(secret), username: account.username, name: account.name, enabled: true, access: kept?.access ?? "owner",
319
+ ...(kept?.owner ? { owner: kept.owner } : {}), offset: sameAccount ? kept.offset : 0, chats: sameAccount ? kept.chats : {},
320
+ });
321
+ write(kind, data);
322
+ ensure(kind, botId);
323
+ }
324
+ function startLogin(kind, botId) {
325
+ const login = deps.logins?.[kind];
326
+ if (!login)
327
+ throw Object.assign(new Error("not supported"), { status: 404 });
328
+ const lane = `${kind}:${botId}`;
329
+ logins.get(lane)?.abort.abort();
330
+ const abort = new AbortController();
331
+ const current = { abort, state: {} };
332
+ logins.set(lane, current);
333
+ const live = () => logins.get(lane) === current;
334
+ void login.start((state) => { if (live())
335
+ current.state = { ...current.state, ...state }; }, abort.signal)
336
+ .then(async (secret) => { if (!live())
337
+ return; await connect(kind, botId, secret); if (live())
338
+ logins.delete(lane); })
339
+ .catch((error) => { if (live() && !abort.signal.aborted)
340
+ current.state = { error: failure(error) }; });
341
+ }
342
+ const PATH = /^\/api\/bots\/([\w-]{1,128})\/(telegram|discord|zalo|facebook)(?:\/(link|unlink|login))?$/;
343
+ const changeSchema = z.object({ token: z.string().max(400).optional(), enabled: z.boolean().optional(), access: z.enum(["owner", "everyone"]).optional() }).strict();
344
+ const routes = async ({ req, res, path, method, auth, json, readBody }) => {
345
+ const match = PATH.exec(path);
346
+ if (!match || !adapters.has(match[2]))
347
+ return PASS;
348
+ const botId = match[1], kind = match[2], action = match[3];
349
+ if (!deps.botExists(botId))
350
+ return json(res, 404, { error: "no such bot" });
351
+ const refusal = deps.manageRefusal(auth, botId);
352
+ if (refusal)
353
+ return json(res, 403, { error: refusal });
354
+ try {
355
+ if (method === "GET" && !action)
356
+ return json(res, 200, view(kind, botId));
357
+ if (method === "DELETE" && action === "login") {
358
+ logins.get(`${kind}:${botId}`)?.abort.abort();
359
+ logins.delete(`${kind}:${botId}`);
360
+ return json(res, 200, view(kind, botId));
361
+ }
362
+ if (method === "DELETE" && !action) {
363
+ halt(kind, botId);
364
+ const data = read(kind);
365
+ delete data.bots[botId];
366
+ write(kind, data);
367
+ return json(res, 200, view(kind, botId));
368
+ }
369
+ if (method !== "POST")
370
+ return json(res, 405, { error: "method not allowed" });
371
+ if (action === "login") {
372
+ startLogin(kind, botId);
373
+ return json(res, 202, view(kind, botId));
374
+ }
375
+ if (action === "link") {
376
+ if (!read(kind).bots[botId])
377
+ return json(res, 409, { error: `Kết nối ${adapters.get(kind).label} trước.` });
378
+ const code = randomBytes(4).toString("hex").toUpperCase().slice(0, 6);
379
+ patch(kind, botId, (current) => ({ ...current, link: { hash: hashCode(code), expiresAt: now() + LINK_MS } }));
380
+ return json(res, 200, { code, ...view(kind, botId) });
381
+ }
382
+ if (action === "unlink") {
383
+ patch(kind, botId, (current) => { const { owner: _gone, ...rest } = current; return rest; });
384
+ return json(res, 200, view(kind, botId));
385
+ }
386
+ const parsed = changeSchema.safeParse(await readBody(req));
387
+ if (!parsed.success)
388
+ return json(res, 400, { error: "invalid request" });
389
+ if (parsed.data.token !== undefined) {
390
+ if (deps.logins?.[kind])
391
+ return json(res, 400, { error: "invalid request" });
392
+ await connect(kind, botId, parsed.data.token.trim());
393
+ }
394
+ if (parsed.data.enabled !== undefined || parsed.data.access !== undefined) {
395
+ patch(kind, botId, (current) => ({ ...current, ...(parsed.data.enabled !== undefined ? { enabled: parsed.data.enabled } : {}), ...(parsed.data.access ? { access: parsed.data.access } : {}) }));
396
+ if (parsed.data.enabled === false)
397
+ halt(kind, botId);
398
+ else
399
+ ensure(kind, botId);
400
+ }
401
+ return json(res, 200, view(kind, botId));
402
+ }
403
+ catch (error) {
404
+ const status = typeof error?.status === "number" ? error.status : 500;
405
+ return json(res, status, { error: failure(error) });
406
+ }
407
+ };
408
+ return {
409
+ routes,
410
+ view,
411
+ start() { running = true; for (const kind of adapters.keys())
412
+ for (const botId of Object.keys(read(kind).bots))
413
+ ensure(kind, botId); },
414
+ stop() {
415
+ running = false;
416
+ for (const abort of runs.values())
417
+ abort.abort();
418
+ for (const login of logins.values())
419
+ login.abort.abort();
420
+ runs.clear();
421
+ logins.clear();
422
+ },
423
+ };
424
+ }