limixbot 0.3.80 → 0.3.82

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 (128) hide show
  1. package/dist/assets/{ActivityPanel-S8N72936.js → ActivityPanel-DM7XKkg8.js} +1 -1
  2. package/dist/assets/{App-HW8yjLRz.js → App-BBWe-BMD.js} +9 -9
  3. package/dist/assets/{AppEventEditor-DfI0W0or.js → AppEventEditor-CHopog41.js} +1 -1
  4. package/dist/assets/BotSettingsDialog-BEJ0O2vT.js +16 -0
  5. package/dist/assets/{BrowserPanel-kj4YC5Qy.js → BrowserPanel-BO20dlmK.js} +1 -1
  6. package/dist/assets/{BrowserProfilesManager-GJvIJ3jk.js → BrowserProfilesManager-Bm6JGnyn.js} +1 -1
  7. package/dist/assets/{CloudAddDialog-CGsu_spO.js → CloudAddDialog-lXlU01dN.js} +1 -1
  8. package/dist/assets/{ComputerFilesPane-C1TYWEXK.js → ComputerFilesPane-D1mc8uSi.js} +1 -1
  9. package/dist/assets/{ComputerPanel-BAc5h7WK.js → ComputerPanel-DLirS7bA.js} +2 -2
  10. package/dist/assets/{DataPanel-BPV-4cwk.js → DataPanel-wVjM0YA2.js} +1 -1
  11. package/dist/assets/{DesktopViewer-DBMUDqPa.js → DesktopViewer-CxgTWyru.js} +1 -1
  12. package/dist/assets/{FilesView-CLv7fEIC.js → FilesView-BUjjeSn9.js} +1 -1
  13. package/dist/assets/{GrokMoveDialog-CEhM3Y7h.js → GrokMoveDialog-p0J0U9Zd.js} +1 -1
  14. package/dist/assets/{InspectorPanel-DgGkECBS.js → InspectorPanel-CXovyiOF.js} +1 -1
  15. package/dist/assets/{KeyboardShortcutsModal-BVeai0YF.js → KeyboardShortcutsModal-BDSfDMWY.js} +1 -1
  16. package/dist/assets/{LiveDesktop-BonA5qgy.js → LiveDesktop-z5gXk9NP.js} +1 -1
  17. package/dist/assets/{LocalVmWorkspace-MMkoTadR.js → LocalVmWorkspace-D5gET16S.js} +1 -1
  18. package/dist/assets/{MacLocalControl-Cl_LnIQz.js → MacLocalControl-Be-wf_gj.js} +1 -1
  19. package/dist/assets/{MarkdownFilePreview-DmJungQ-.js → MarkdownFilePreview-BsW50aAi.js} +1 -1
  20. package/dist/assets/{MenuMotion-CcuJn489.js → MenuMotion-B5n2ZkGC.js} +1 -1
  21. package/dist/assets/{NewBotDialog-BDimjm0l.js → NewBotDialog-By-ZkDDr.js} +1 -1
  22. package/dist/assets/{PhoneAppDialog-DHjcrHJt.js → PhoneAppDialog-CqnpLVk3.js} +1 -1
  23. package/dist/assets/{PlacesRail-CRmtzh8u.js → PlacesRail-PNE_Y9GC.js} +1 -1
  24. package/dist/assets/{PluginsPanel-BWJtrENZ.js → PluginsPanel-D6sL0tj-.js} +1 -1
  25. package/dist/assets/{ProIntroduction-D2wTzv3K.js → ProIntroduction-B1gOMiD4.js} +1 -1
  26. package/dist/assets/{RemoteAgentSettingsPanel-By1EPD8m.js → RemoteAgentSettingsPanel-f2oombQ4.js} +1 -1
  27. package/dist/assets/{RoomPanel-D35iQMAm.js → RoomPanel-CGIh7NNr.js} +1 -1
  28. package/dist/assets/{RoutinesPage-Cl5NJllS.js → RoutinesPage-FKm-78G_.js} +1 -1
  29. package/dist/assets/{SettingsModal-bofTlpGs.js → SettingsModal-Df3bxTkK.js} +1 -1
  30. package/dist/assets/{ShareTeamDialog-DO5ROGD-.js → ShareTeamDialog-Ccyue2jJ.js} +1 -1
  31. package/dist/assets/{SignedInSites-BCqePKLy.js → SignedInSites-DtdPGi0s.js} +1 -1
  32. package/dist/assets/{TeamLibraryPanel-DnUDr6lc.js → TeamLibraryPanel-C8UK4a_J.js} +1 -1
  33. package/dist/assets/{TeamMapPage-Dkdm2BRX.js → TeamMapPage-S6caq88r.js} +1 -1
  34. package/dist/assets/{TriggersPage-B0zPNQFf.js → TriggersPage-CSPFuxiZ.js} +1 -1
  35. package/dist/assets/{VisibilitySection-CzFnoTF_.js → VisibilitySection-CBr_z_A6.js} +1 -1
  36. package/dist/assets/{WebhookTrigger-4sQc3A-N.js → WebhookTrigger-CAgIYgFS.js} +1 -1
  37. package/dist/assets/{WorksOnGrid-BD86kGXr.js → WorksOnGrid-DAlkmP8Z.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-DVQLw1wk.js → core-DuQT_rTE.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-XFgPgP_a.js → import-name-BuYapWfv.js} +1 -1
  75. package/dist/assets/{index-BAOvp5uC.js → index-CH5861ZZ.js} +1 -1
  76. package/dist/assets/{index-B4zS2jrs.js → index-CT2XrX7R.js} +3 -3
  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-CXnomHbG.js → mcp-servers-Dwfx3xBi.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-Cx7fv2NF.js → new-bot-Cs6CRz4i.js} +1 -1
  87. package/dist/assets/{org-library-BMWET-ld.js → org-library-yB0dqNIc.js} +1 -1
  88. package/dist/assets/{package-format-KuG7amsA.js → package-format-tFXI9Dkp.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-bK6V3V6T.js → remote-desktop-panel-Bkmf04MK.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 +7240 -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 +11 -0
  115. package/dist-server/server/bot-channels/discord.js +152 -0
  116. package/dist-server/server/bot-channels/engine.js +427 -0
  117. package/dist-server/server/bot-channels/facebook.js +94 -0
  118. package/dist-server/server/bot-channels/messenger.js +106 -0
  119. package/dist-server/server/bot-channels/telegram.js +79 -0
  120. package/dist-server/server/bot-channels/zalo.js +111 -0
  121. package/dist-server/server/index.js +7 -6
  122. package/package.json +1 -1
  123. package/dist/assets/BotSettingsDialog-CoZp2pXg.js +0 -16
  124. package/dist/assets/channel-BhUqydpo.js +0 -1
  125. package/dist/assets/styles-BABP9ycC.css +0 -1
  126. package/dist/assets/swimlanesDiagram-K3J5GTZL-CynVazVQ.js +0 -8
  127. package/dist-server/server/limix-telegram.js +0 -329
  128. /package/dist/assets/{styles-1Sa7mQdy.js → styles-DdM6yn_a.js} +0 -0
@@ -0,0 +1,94 @@
1
+ // A Facebook Page's Messenger inbox through the Graph API with a Page access token. Messages are read by polling the
2
+ // Page's conversations, so no webhook address is needed; Meta counts each call against the Page's daily rate budget
3
+ // (about 4,800 calls per engaged person per day), which is what sets the poll interval.
4
+ import { ChannelError, wait } from "./engine.js";
5
+ const GRAPH = "https://graph.facebook.com/v23.0";
6
+ const BUSY_MS = 8_000;
7
+ const IDLE_MS = 20_000;
8
+ const BUSY_FOR_MS = 3 * 60_000;
9
+ const FIELDS = "updated_time,messages.limit(5){id,message,from,created_time,attachments}";
10
+ export function facebookAdapter(options = {}) {
11
+ const call = options.fetch ?? fetch;
12
+ const sleep = options.sleep ?? wait;
13
+ const now = options.now ?? Date.now;
14
+ async function graph(token, method, path, body, signal) {
15
+ const url = new URL(`${GRAPH}${path}`);
16
+ if (method === "GET")
17
+ url.searchParams.set("access_token", token);
18
+ const response = await call(url, {
19
+ method, ...(signal ? { signal } : {}),
20
+ ...(method === "POST" ? { headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify(body ?? {}) } : {}),
21
+ }).catch((error) => { throw new ChannelError("retry", `Facebook: ${(error instanceof Error ? error.message : String(error)).replaceAll(token, "…")}`); });
22
+ const data = await response.json().catch(() => ({}));
23
+ if (response.ok && !data.error)
24
+ return data;
25
+ const code = data.error?.code ?? 0;
26
+ if (code === 190 || code === 102 || response.status === 401)
27
+ throw new ChannelError("auth", "Page Access Token đã hết hạn hoặc bị thu hồi. Tạo token mới và dán lại.");
28
+ if (code === 10 || code === 200 || code === 230 || code === 3)
29
+ throw new ChannelError("auth", "Token thiếu quyền Messenger của Page (pages_messaging). Tạo lại token có quyền này.");
30
+ if (code === 4 || code === 17 || code === 32 || code === 613 || response.status >= 500)
31
+ throw new ChannelError("retry", "Facebook đang giới hạn số lần gọi. Bot sẽ thử lại.", 60_000);
32
+ throw new ChannelError("drop", `Facebook báo lỗi${data.error?.message ? `: ${data.error.message}` : ` ${response.status}`}.`);
33
+ }
34
+ return {
35
+ kind: "facebook",
36
+ label: "Facebook Page",
37
+ textMax: 2000,
38
+ quietToStrangers: true,
39
+ async check(token) {
40
+ if (!/^EA[\w-]{40,600}$/.test(token))
41
+ throw new ChannelError("auth", "Token không đúng dạng. Dán Page Access Token (bắt đầu bằng EA…).");
42
+ const page = await graph(token, "GET", "/me?fields=id,name,category");
43
+ if (!page.id || !page.category)
44
+ throw new ChannelError("auth", "Đây không phải token của một Page. Chọn Page khi tạo token.");
45
+ return { username: String(page.id), name: String(page.name ?? "") };
46
+ },
47
+ async open(token, io) {
48
+ const page = await graph(token, "GET", "/me?fields=id", undefined, io.signal);
49
+ const self = String(page.id);
50
+ const done = (async () => {
51
+ let since = io.offset || now();
52
+ if (!io.offset)
53
+ io.saveOffset(since);
54
+ let lastActive = 0;
55
+ while (!io.signal.aborted) {
56
+ const list = await graph(token, "GET", `/me/conversations?platform=messenger&limit=10&fields=${encodeURIComponent(FIELDS)}`, undefined, io.signal)
57
+ .catch((error) => { if (io.signal.aborted)
58
+ return { data: [] }; throw error; });
59
+ io.healthy();
60
+ const fresh = [];
61
+ for (const conversation of Array.isArray(list.data) ? list.data : []) {
62
+ if (Date.parse(conversation.updated_time) <= since)
63
+ continue;
64
+ for (const message of conversation.messages?.data ?? []) {
65
+ const at = Date.parse(message.created_time);
66
+ if (!(at > since) || !message.from?.id || String(message.from.id) === self)
67
+ continue;
68
+ fresh.push({
69
+ at, id: String(message.id), chatId: String(message.from.id), direct: true,
70
+ from: { id: String(message.from.id), name: String(message.from.name ?? message.from.id) },
71
+ text: typeof message.message === "string" ? message.message : "",
72
+ ...(message.attachments?.data?.length ? { media: true } : {}),
73
+ });
74
+ }
75
+ }
76
+ if (fresh.length) {
77
+ fresh.sort((a, b) => a.at - b.at);
78
+ since = fresh[fresh.length - 1].at;
79
+ io.saveOffset(since);
80
+ lastActive = now();
81
+ for (const { at: _at, ...message } of fresh)
82
+ io.deliver(message);
83
+ }
84
+ await sleep(now() - lastActive < BUSY_FOR_MS ? BUSY_MS : IDLE_MS, io.signal);
85
+ }
86
+ })();
87
+ return {
88
+ done,
89
+ send: async (chatId, text) => { await graph(token, "POST", "/me/messages", { recipient: { id: chatId }, messaging_type: "RESPONSE", message: { text } }); },
90
+ typing: async (chatId) => { await graph(token, "POST", "/me/messages", { recipient: { id: chatId }, sender_action: "typing_on" }); },
91
+ };
92
+ },
93
+ };
94
+ }
@@ -0,0 +1,106 @@
1
+ import { PASS } from "../routes/table.js";
2
+ import { ChannelError } from "./engine.js";
3
+ const OUTBOX_WAIT_MS = 25_000;
4
+ const SEND_WAIT_MS = 90_000;
5
+ export function messengerBridge(options) {
6
+ const now = options.now ?? Date.now;
7
+ const bridges = new Map();
8
+ const pending = new Map();
9
+ let nextId = 0;
10
+ const adapter = {
11
+ kind: "messenger",
12
+ label: "Messenger",
13
+ textMax: 2000,
14
+ quietToStrangers: true,
15
+ guestsOnly: true,
16
+ paceMs: [800, 2_000],
17
+ async check(secret) {
18
+ let account;
19
+ try {
20
+ account = JSON.parse(secret);
21
+ }
22
+ catch {
23
+ throw new ChannelError("auth", "Đăng nhập Facebook trong cửa sổ của app trước.");
24
+ }
25
+ if (typeof account.uid !== "string" || !/^\d{3,25}$/.test(account.uid))
26
+ throw new ChannelError("auth", "Đăng nhập Facebook trong cửa sổ của app trước.");
27
+ return { username: account.uid, name: typeof account.name === "string" ? account.name.slice(0, 100) : "" };
28
+ },
29
+ async open(_secret, io) {
30
+ const botId = io.botId;
31
+ const bridge = { io, outbox: [], waiters: [], seenAt: 0 };
32
+ bridges.set(botId, bridge);
33
+ const done = new Promise((resolve) => io.signal.addEventListener("abort", () => {
34
+ if (bridges.get(botId) === bridge)
35
+ bridges.delete(botId);
36
+ for (const item of bridge.outbox)
37
+ item.settle("stopped");
38
+ for (const wake of bridge.waiters.splice(0))
39
+ wake();
40
+ resolve();
41
+ }, { once: true }));
42
+ return {
43
+ done,
44
+ send: (chatId, text) => new Promise((resolve, reject) => {
45
+ const id = ++nextId;
46
+ const timer = setTimeout(() => item.settle("timeout"), SEND_WAIT_MS);
47
+ const item = { id, chatId, text, settle: (error) => {
48
+ clearTimeout(timer);
49
+ pending.delete(id);
50
+ bridge.outbox = bridge.outbox.filter((each) => each !== item);
51
+ if (error)
52
+ reject(new ChannelError(error === "timeout" ? "retry" : "drop", `Messenger: ${error}`));
53
+ else
54
+ resolve();
55
+ } };
56
+ pending.set(id, item);
57
+ bridge.outbox.push(item);
58
+ for (const wake of bridge.waiters.splice(0))
59
+ wake();
60
+ }),
61
+ };
62
+ },
63
+ };
64
+ const PATH = /^\/api\/bots\/([\w-]{1,128})\/messenger\/(outbox|inbox|sent)$/;
65
+ const routes = async ({ req, res, path, method, auth, json, readBody }) => {
66
+ if (path === "/api/messenger/bots" && method === "GET")
67
+ return json(res, 200, { bots: [...bridges.keys()].filter((botId) => !options.manageRefusal(auth, botId)) });
68
+ const match = PATH.exec(path);
69
+ if (!match)
70
+ return PASS;
71
+ const botId = match[1], action = match[2];
72
+ const refusal = options.manageRefusal(auth, botId);
73
+ if (refusal)
74
+ return json(res, 403, { error: refusal });
75
+ const bridge = bridges.get(botId);
76
+ if (!bridge)
77
+ return json(res, 409, { error: "Messenger is off for this bot." });
78
+ bridge.seenAt = now();
79
+ if (action === "outbox" && method === "GET") {
80
+ if (!bridge.outbox.length)
81
+ await new Promise((resolve) => { const timer = setTimeout(resolve, OUTBOX_WAIT_MS); bridge.waiters.push(() => { clearTimeout(timer); resolve(); }); });
82
+ bridge.io.healthy();
83
+ return json(res, 200, { items: bridge.outbox.map(({ id, chatId, text }) => ({ id, chatId, text })) });
84
+ }
85
+ if (method !== "POST")
86
+ return json(res, 405, { error: "method not allowed" });
87
+ const body = await readBody(req);
88
+ if (action === "sent") {
89
+ const item = pending.get(Number(body?.id));
90
+ item?.settle(typeof body?.error === "string" ? body.error.slice(0, 200) : undefined);
91
+ return json(res, 200, { ok: Boolean(item) });
92
+ }
93
+ const messages = Array.isArray(body?.messages) ? body.messages.slice(0, 50) : [];
94
+ for (const raw of messages) {
95
+ const chatId = typeof raw?.chatId === "string" && /^[\w.-]{1,64}$/.test(raw.chatId) ? raw.chatId : null;
96
+ const text = typeof raw?.text === "string" ? raw.text.slice(0, 8_000) : "";
97
+ if (!chatId || typeof raw.id !== "string")
98
+ continue;
99
+ const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 100) : chatId;
100
+ bridge.io.deliver({ id: raw.id.slice(0, 200), chatId, direct: true, from: { id: chatId, name }, text });
101
+ }
102
+ bridge.io.healthy();
103
+ return json(res, 200, { ok: true });
104
+ };
105
+ return { adapter, routes };
106
+ }
@@ -0,0 +1,79 @@
1
+ // Telegram Bot API over long polling (getUpdates): no webhook, so nothing has to reach this server from outside.
2
+ import { ChannelError } from "./engine.js";
3
+ const TOKEN = /^\d{5,15}:[\w-]{30,60}$/;
4
+ const POLL_S = 25;
5
+ export function telegramAdapter(options = {}) {
6
+ const base = (options.apiBase ?? "https://api.telegram.org").replace(/\/$/, "");
7
+ const call = options.fetch ?? fetch;
8
+ async function api(token, method, body, signal) {
9
+ const response = await call(`${base}/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), ...(signal ? { signal } : {}) })
10
+ .catch((error) => { throw new ChannelError("retry", `Telegram: ${(error instanceof Error ? error.message : String(error)).replaceAll(token, "…")}`); });
11
+ const data = await response.json().catch(() => ({}));
12
+ if (response.ok && data.ok === true)
13
+ return data.result;
14
+ const status = response.status;
15
+ if (status === 401 || status === 404)
16
+ throw new ChannelError("auth", "Token không còn dùng được. Dán token mới từ @BotFather.");
17
+ if (status === 409)
18
+ throw new ChannelError("conflict", "Bot Telegram này đang được nơi khác nhận tin (máy khác, Cloud hoặc webhook). Chỉ để một nơi nhận tin.");
19
+ if (status === 429 || status >= 500)
20
+ throw new ChannelError("retry", `Telegram báo lỗi ${status}.`, data.parameters?.retry_after ? data.parameters.retry_after * 1000 : undefined);
21
+ throw new ChannelError("drop", `Telegram báo lỗi ${status}${data.description ? `: ${data.description}` : ""}.`);
22
+ }
23
+ return {
24
+ kind: "telegram",
25
+ label: "Telegram",
26
+ textMax: 4096,
27
+ async check(token) {
28
+ if (!TOKEN.test(token))
29
+ throw new ChannelError("auth", "Token không đúng dạng. Copy nguyên dòng token từ @BotFather.");
30
+ const me = await api(token, "getMe", {}).catch(() => null);
31
+ if (!me?.username)
32
+ throw new ChannelError("auth", "Telegram không nhận token này.");
33
+ return { username: me.username, name: me.first_name ?? "" };
34
+ },
35
+ async open(token, io) {
36
+ const me = await api(token, "getMe", {}, io.signal);
37
+ const mentioned = new RegExp(`@${me.username}\\b`, "iu");
38
+ const mention = new RegExp(mentioned.source, "giu");
39
+ const toMessage = (message) => {
40
+ if (!message?.chat || !message.from || message.from.is_bot)
41
+ return null;
42
+ const direct = message.chat.type === "private";
43
+ const raw = typeof message.text === "string" ? message.text : typeof message.caption === "string" ? message.caption : "";
44
+ const addressed = direct || mentioned.test(raw) || message.reply_to_message?.from?.id === me.id;
45
+ if (!addressed)
46
+ return null;
47
+ const from = message.from;
48
+ return {
49
+ id: String(message.message_id), chatId: String(message.chat.id), direct,
50
+ from: { id: String(from.id), name: [from.first_name, from.last_name].filter(Boolean).join(" ") || from.username || String(from.id) },
51
+ text: raw.replace(mention, "").trim(),
52
+ ...(message.photo || message.document || message.sticker || message.voice || message.video ? { media: true } : {}),
53
+ };
54
+ };
55
+ const done = (async () => {
56
+ let offset = io.offset;
57
+ while (!io.signal.aborted) {
58
+ const updates = await api(token, "getUpdates", { offset, timeout: POLL_S, allowed_updates: ["message"] }, io.signal).catch((error) => { if (io.signal.aborted)
59
+ return []; throw error; });
60
+ io.healthy();
61
+ if (!Array.isArray(updates) || !updates.length)
62
+ continue;
63
+ offset = Math.max(...updates.map((update) => Number(update?.update_id) || 0)) + 1;
64
+ io.saveOffset(offset);
65
+ for (const update of updates) {
66
+ const message = toMessage(update?.message);
67
+ if (message)
68
+ io.deliver(message);
69
+ }
70
+ }
71
+ })();
72
+ return {
73
+ done,
74
+ send: async (chatId, text) => { await api(token, "sendMessage", { chat_id: Number(chatId), text }); },
75
+ typing: async (chatId) => { await api(token, "sendChatAction", { chat_id: Number(chatId), action: "typing" }); },
76
+ };
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,111 @@
1
+ // Zalo personal accounts through zca-js (the Zalo Web protocol, unofficial): the owner signs a spare Zalo account in by
2
+ // scanning a QR code, and the session cookies are what this server keeps, sealed. Zalo allows one web session per account,
3
+ // so opening Zalo Web elsewhere ends this one (close code 3000).
4
+ import { ChannelError } from "./engine.js";
5
+ const USER = 0, GROUP = 1;
6
+ const loadZcaJs = async () => {
7
+ const { Zalo } = (await import("zca-js"));
8
+ return new Zalo({ selfListen: false, checkUpdate: false, logging: false });
9
+ };
10
+ const thread = (chatId) => ({ type: chatId.startsWith("g:") ? GROUP : USER, id: chatId.slice(2) });
11
+ export function zaloAdapter(load = loadZcaJs) {
12
+ async function signIn(secret) {
13
+ let credentials;
14
+ try {
15
+ credentials = JSON.parse(secret);
16
+ }
17
+ catch {
18
+ throw new ChannelError("auth", "Phiên Zalo hỏng. Quét mã QR lại.");
19
+ }
20
+ return (await load()).login(credentials).catch((error) => {
21
+ throw new ChannelError("auth", `Phiên Zalo đã hết hạn hoặc bị đăng xuất. Quét mã QR lại. (${error instanceof Error ? error.message : String(error)})`);
22
+ });
23
+ }
24
+ async function account(api) {
25
+ const info = await api.fetchAccountInfo().catch(() => null);
26
+ const name = info?.profile?.displayName ?? info?.profile?.zaloName ?? "";
27
+ return { username: api.getOwnId(), name };
28
+ }
29
+ return {
30
+ kind: "zalo",
31
+ label: "Zalo",
32
+ textMax: 2000,
33
+ quietToStrangers: true,
34
+ paceMs: [400, 1_200],
35
+ async check(secret) { return account(await signIn(secret)); },
36
+ async open(secret, io) {
37
+ const api = await signIn(secret);
38
+ const self = api.getOwnId();
39
+ const done = new Promise((resolve, reject) => {
40
+ const stop = () => { try {
41
+ api.listener.stop();
42
+ }
43
+ catch { } };
44
+ io.signal.addEventListener("abort", () => { stop(); resolve(); }, { once: true });
45
+ api.listener.on("connected", () => io.healthy());
46
+ api.listener.on("error", () => { });
47
+ api.listener.on("closed", (code) => {
48
+ if (io.signal.aborted)
49
+ return resolve();
50
+ if (code === 3000 || code === 3003)
51
+ return reject(new ChannelError("auth", "Tài khoản Zalo của bot vừa mở ở nơi khác (Zalo Web hoặc máy khác) nên bot đã dừng. Đóng nơi đó rồi tắt và bật lại Zalo ở đây."));
52
+ reject(new ChannelError("retry", `Zalo ngắt kết nối (${code}).`));
53
+ });
54
+ api.listener.on("message", (event) => {
55
+ if (event.isSelf || event.data.uidFrom === self)
56
+ return;
57
+ const direct = event.type === USER;
58
+ const tag = (event.data.mentions ?? []).find((mention) => mention.uid === self);
59
+ if (!direct && !tag)
60
+ return;
61
+ const content = event.data.content;
62
+ const said = typeof content !== "string" ? "" : tag && !direct ? content.slice(0, tag.pos) + content.slice(tag.pos + tag.len) : content;
63
+ const message = {
64
+ id: String(event.data.msgId), chatId: `${direct ? "u" : "g"}:${event.threadId}`, direct,
65
+ from: { id: String(event.data.uidFrom), name: event.data.dName || String(event.data.uidFrom) },
66
+ text: said.trim(),
67
+ ...(typeof content === "string" ? {} : { media: true }),
68
+ };
69
+ io.deliver(message);
70
+ });
71
+ api.listener.start({ retryOnClose: true });
72
+ });
73
+ return {
74
+ done,
75
+ send: async (chatId, text) => {
76
+ const target = thread(chatId);
77
+ await api.sendMessage({ msg: text }, target.id, target.type).catch((error) => { throw new ChannelError("retry", `Zalo: ${error instanceof Error ? error.message : String(error)}`); });
78
+ },
79
+ typing: async (chatId) => { const target = thread(chatId); await api.sendTypingEvent(target.id, target.type); },
80
+ };
81
+ },
82
+ };
83
+ }
84
+ /** Signs a Zalo account in by QR: the image goes to the settings card, the session cookies come back as the secret. */
85
+ export function zaloLogin(load = loadZcaJs) {
86
+ return {
87
+ async start(update, signal) {
88
+ const client = await load();
89
+ let credentials;
90
+ let abortLogin;
91
+ signal.addEventListener("abort", () => abortLogin?.(), { once: true });
92
+ const expired = "Mã QR đã hết hạn hoặc bị từ chối. Bấm tạo mã mới.";
93
+ await client.loginQR({}, (event) => {
94
+ if (event.actions)
95
+ abortLogin = event.actions.abort;
96
+ if (event.type === 0)
97
+ update({ qr: `data:image/png;base64,${String(event.data?.image ?? "")}` });
98
+ else if (event.type === 1)
99
+ event.actions?.abort();
100
+ else if (event.type === 2)
101
+ update({ scanned: String(event.data?.display_name ?? "") });
102
+ else if (event.type === 4)
103
+ credentials = { cookie: event.data?.cookie, imei: event.data?.imei, userAgent: event.data?.userAgent };
104
+ }).catch(() => { if (!credentials)
105
+ throw new Error(expired); });
106
+ if (signal.aborted || !credentials)
107
+ throw new Error(expired);
108
+ return JSON.stringify(credentials);
109
+ },
110
+ };
111
+ }
@@ -1,5 +1,6 @@
1
1
  import { imageConnectorRefusal } from "./limix-image-routing.js";
2
- import { createLimixTelegram } from "./limix-telegram.js";
2
+ import { botChannelParts } from "./bot-channels/adapters.js";
3
+ import { createBotChannels } from "./bot-channels/engine.js";
3
4
  // Import first: it reads a Cloud home's secrets off the launcher's pipe before any module can start a process.
4
5
  import { BOOT_CLOUD_SECRETS } from "./cloud-secrets-boot.js";
5
6
  import { startFailureText } from "./start-failure-text.js";
@@ -9881,11 +9882,11 @@ const webhookIngressStatus = () => ({
9881
9882
  ...(webhookIngressError ? { error: webhookIngressError } : {}),
9882
9883
  });
9883
9884
  ROUTES.push(createWebhookRoutes({ webhooks, ingress: webhookIngressStatus, visible: (auth) => visibleTo(viewerFor(auth)) }), botApi.routes);
9884
- // Limix Bot: a bot answers on Telegram once its owner pastes a @BotFather token in its settings (server/limix-telegram.ts).
9885
- const limixTelegram = createLimixTelegram({ dataDir: DATA_DIR, ask: botApi.askFromChannel, botExists: (botId) => Boolean(store.bot(botId)), log: (line) => console.log(line),
9886
- manageRefusal: (auth, botId) => auth.scopes.includes("admin") || (CLOUD_TEAM && levelOf(auth, botId) === "edit") ? null : refusalFor(store.bot(botId)?.name ?? "this bot", "edit").error });
9887
- ROUTES.push(limixTelegram.routes);
9888
- limixTelegram.start();
9885
+ // Limix Bot: a bot answers on Telegram, Discord, Zalo or a Facebook Page once its owner connects it in the bot's settings.
9886
+ const channelRefusal = (auth, botId) => auth.scopes.includes("admin") || (CLOUD_TEAM && levelOf(auth, botId) === "edit") ? null : refusalFor(store.bot(botId)?.name ?? "this bot", "edit").error, channelParts = botChannelParts(channelRefusal);
9887
+ const botChannels = createBotChannels({ dataDir: DATA_DIR, ...channelParts, ask: botApi.askFromChannel, botExists: (botId) => Boolean(store.bot(botId)), log: (line) => console.log(line), manageRefusal: channelRefusal });
9888
+ ROUTES.push(botChannels.routes, channelParts.bridgeRoutes);
9889
+ botChannels.start();
9889
9890
  const RUNTIME_KEEP_MS = 30 * 24 * 60 * 60_000;
9890
9891
  let runtimePrunedAt = 0;
9891
9892
  handoffTicks.start({ pace: () => enginesRead || parkedNodesToReconcile.size > 0 ? "busy" : coordinator.pace(), tick: () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limixbot",
3
- "version": "0.3.80",
3
+ "version": "0.3.82",
4
4
  "description": "Run the Limix Bot server anywhere and pair your devices to it (Leox ৹ Limix AI)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",