levix-bot 4.9.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -0,0 +1,521 @@
1
+ // Core-owned Auto Reply intake and AI turn. The extension only considers a
2
+ // frozen event; this module owns forwarding, rate limits, the caller, and send.
3
+
4
+ const { visibleText, unwrapMessage } = require("../utils/messageContent.cjs");
5
+ const { isLinkedSelf, linkedIdentity } = require("../messaging/identity.cjs");
6
+ const { getSenderCandidates } = require("../utils/permissions.esm.js");
7
+ const normalizeJid = require("../utils/normalizeJid.cjs");
8
+
9
+ const MAX_TEXT = 4000;
10
+ const MAX_INSTRUCTIONS = 1000;
11
+ const PENDING_MAX = 50;
12
+ const PENDING_TTL_MS = 2 * 60 * 1000;
13
+ const INTAKE_MAX = 5000;
14
+ const INTAKE_TTL_MS = 10 * 60 * 1000;
15
+ // The Core backstop admits at most 30 * 60 * 24 = 43,200 turns per 24 hours.
16
+ const EXECUTION_MAX = 50_000;
17
+ const EXECUTION_TTL_MS = 24 * 60 * 60 * 1000;
18
+ const GLOBAL_CONCURRENT = 2;
19
+ const CHAT_CONCURRENT = 1;
20
+ const CHAT_PER_MINUTE = 6;
21
+ const GLOBAL_PER_MINUTE = 30;
22
+ const WINDOW_MS = 60_000;
23
+ const AI_TIMEOUT_CAP_MS = 120_000;
24
+
25
+ const injected = {};
26
+ const pending = new Map();
27
+ const intake = new Map();
28
+ const executions = new Map();
29
+ let executionCapacityWarned = false;
30
+ const inflightAbort = new Map();
31
+ const chatInFlight = new Map();
32
+ let globalInFlight = 0;
33
+ const globalHits = [];
34
+ const chatHits = new Map();
35
+
36
+ function setAutoReplyDeps(partial) {
37
+ Object.assign(injected, partial || {});
38
+ }
39
+
40
+ function resetAutoReplyDeps() {
41
+ for (const key of Object.keys(injected)) delete injected[key];
42
+ pending.clear();
43
+ intake.clear();
44
+ executions.clear();
45
+ executionCapacityWarned = false;
46
+ inflightAbort.clear();
47
+ chatInFlight.clear();
48
+ globalInFlight = 0;
49
+ globalHits.length = 0;
50
+ chatHits.clear();
51
+ }
52
+
53
+ function dep(name, loader) {
54
+ if (Object.hasOwn(injected, name) && injected[name] != null) {
55
+ return injected[name];
56
+ }
57
+ return loader();
58
+ }
59
+
60
+ function nowMs() {
61
+ const fn = injected.now;
62
+ return typeof fn === "function" ? fn() : Date.now();
63
+ }
64
+
65
+ function accountEpochNow() {
66
+ const fn = injected.accountEpoch;
67
+ if (typeof fn === "function") return fn();
68
+ return require("../db/store.cjs").accountEpoch();
69
+ }
70
+
71
+ function withDeadline(promise, ms) {
72
+ return new Promise((resolve, reject) => {
73
+ const timer = setTimeout(() => {
74
+ const err = new Error("deadline");
75
+ err.code = "DEADLINE";
76
+ reject(err);
77
+ }, ms);
78
+ Promise.resolve(promise).then(
79
+ (value) => {
80
+ clearTimeout(timer);
81
+ resolve(value);
82
+ },
83
+ (error) => {
84
+ clearTimeout(timer);
85
+ reject(error);
86
+ },
87
+ );
88
+ });
89
+ }
90
+
91
+ function prunePending(now) {
92
+ for (const [id, entry] of pending) {
93
+ if (entry.expiresAt <= now) {
94
+ entry.controller.abort();
95
+ pending.delete(id);
96
+ }
97
+ }
98
+ while (pending.size > PENDING_MAX) {
99
+ const oldest = pending.keys().next().value;
100
+ pending.get(oldest).controller.abort();
101
+ pending.delete(oldest);
102
+ }
103
+ }
104
+
105
+ function abortAccountJobs() {
106
+ for (const entry of pending.values()) entry.controller.abort();
107
+ pending.clear();
108
+ for (const controller of inflightAbort.keys()) {
109
+ try {
110
+ controller.abort();
111
+ } catch {}
112
+ }
113
+ inflightAbort.clear();
114
+ }
115
+
116
+ function abortOutOfScope(scope) {
117
+ for (const [key, entry] of pending) {
118
+ if (inScope(entry.event.chatJid, scope)) continue;
119
+ entry.controller.abort();
120
+ pending.delete(key);
121
+ }
122
+ for (const [controller, chatJid] of inflightAbort) {
123
+ if (!inScope(chatJid, scope)) controller.abort();
124
+ }
125
+ }
126
+
127
+ function jobKey(epoch, chatJid, messageId) {
128
+ return `${epoch}:${chatJid}:${messageId}`;
129
+ }
130
+
131
+ function pruneClaims(claims, now) {
132
+ for (const [key, expiresAt] of claims) {
133
+ if (expiresAt <= now) claims.delete(key);
134
+ }
135
+ }
136
+
137
+ function rememberClaim(claims, key, expiresAt, max) {
138
+ claims.delete(key);
139
+ claims.set(key, expiresAt);
140
+ if (claims.size > max) claims.delete(claims.keys().next().value);
141
+ }
142
+
143
+ function hasBotMetadata(msg) {
144
+ const inner = unwrapMessage(msg?.message);
145
+ if (!inner || typeof inner !== "object") return false;
146
+ const top = inner.messageContextInfo;
147
+ if (top?.botMetadata || top?.botMessageSecret) return true;
148
+ for (const key of Object.keys(inner)) {
149
+ const ctx = inner[key]?.contextInfo;
150
+ if (!ctx) continue;
151
+ if (
152
+ ctx.botMetadata ||
153
+ ctx.botMessageSecret ||
154
+ ctx.botMessageSharingInfo ||
155
+ ctx.botMessageInvokerJid
156
+ ) {
157
+ return true;
158
+ }
159
+ }
160
+ return false;
161
+ }
162
+
163
+ function contextInfoOf(msg) {
164
+ const inner = unwrapMessage(msg?.message);
165
+ if (!inner || typeof inner !== "object") return null;
166
+ for (const key of [
167
+ "extendedTextMessage",
168
+ "imageMessage",
169
+ "videoMessage",
170
+ "audioMessage",
171
+ "documentMessage",
172
+ ]) {
173
+ if (inner[key]?.contextInfo) return inner[key].contextInfo;
174
+ }
175
+ return inner.messageContextInfo || null;
176
+ }
177
+
178
+ function inScope(chatJid, scope) {
179
+ if (!scope || typeof scope.has !== "function") return false;
180
+ if (scope.has(chatJid)) return true;
181
+ const norm = normalizeJid(chatJid);
182
+ return Boolean(norm) && scope.has(norm);
183
+ }
184
+
185
+ function pruneHits(list, now) {
186
+ while (list.length && now - list[0] >= WINDOW_MS) list.shift();
187
+ return list;
188
+ }
189
+
190
+ function admit(chatJid, now) {
191
+ if (globalInFlight >= GLOBAL_CONCURRENT) return false;
192
+ if ((chatInFlight.get(chatJid) || 0) >= CHAT_CONCURRENT) return false;
193
+ pruneHits(globalHits, now);
194
+ if (globalHits.length >= GLOBAL_PER_MINUTE) return false;
195
+ let chatList = chatHits.get(chatJid);
196
+ if (!chatList) {
197
+ chatList = [];
198
+ chatHits.set(chatJid, chatList);
199
+ }
200
+ pruneHits(chatList, now);
201
+ if (chatList.length >= CHAT_PER_MINUTE) return false;
202
+ return true;
203
+ }
204
+
205
+ function beginTurn(chatJid, now) {
206
+ globalInFlight += 1;
207
+ chatInFlight.set(chatJid, (chatInFlight.get(chatJid) || 0) + 1);
208
+ globalHits.push(now);
209
+ const chatList = chatHits.get(chatJid) || [];
210
+ chatList.push(now);
211
+ chatHits.set(chatJid, chatList);
212
+ }
213
+
214
+ function endTurn(chatJid) {
215
+ globalInFlight = Math.max(0, globalInFlight - 1);
216
+ const n = (chatInFlight.get(chatJid) || 1) - 1;
217
+ if (n <= 0) chatInFlight.delete(chatJid);
218
+ else chatInFlight.set(chatJid, n);
219
+ }
220
+
221
+ function anySignal(signals) {
222
+ return AbortSignal.any(signals.filter(Boolean));
223
+ }
224
+
225
+ function liveSignal(runtime) {
226
+ return typeof runtime.signal === "function" ? runtime.signal() : runtime.signal;
227
+ }
228
+
229
+ async function ownRecent(msg) {
230
+ const fn = injected.getMessageFromRecent;
231
+ if (typeof fn === "function") return fn(msg.key);
232
+ const cache = require("../utils/recentMessageCache.esm.js");
233
+ return cache.getMessageFromRecent(msg.key);
234
+ }
235
+
236
+ function rosterHelpers() {
237
+ return dep("groupMetadataCache", () => require("../utils/groupMetadataCache.cjs"));
238
+ }
239
+
240
+ async function runAiReply(runtime, job = {}) {
241
+ const messageId = job?.messageId;
242
+ const key = jobKey(accountEpochNow(), job?.chatJid, messageId);
243
+ const entry = messageId && job?.chatJid ? pending.get(key) : null;
244
+ if (!entry) return { sent: false };
245
+ pending.delete(key);
246
+ if (entry.expiresAt <= nowMs()) return { sent: false };
247
+
248
+ const instructions = job.instructions == null ? "" : String(job.instructions);
249
+ if (instructions.length > MAX_INSTRUCTIONS) return { sent: false };
250
+ const quote = job.quote === true;
251
+ const autoReplyGlobal = Object.freeze({ read: job.globalMemory?.read === true });
252
+ const { sock, msg, event, epoch, generation } = entry;
253
+ const chatJid = event.chatJid;
254
+ const isGroup = event.isGroup;
255
+ const started = nowMs();
256
+ pruneClaims(executions, started);
257
+ if (executions.has(key)) return { sent: false };
258
+ if (!admit(chatJid, started)) return { sent: false };
259
+ if (typeof runtime.isActive === "function" && !runtime.isActive()) return { sent: false };
260
+ if (typeof runtime.generation === "function" && runtime.generation() !== generation) {
261
+ return { sent: false };
262
+ }
263
+ if (accountEpochNow() !== epoch) return { sent: false };
264
+ if (!inScope(chatJid, runtime.getScope?.())) return { sent: false };
265
+
266
+ if (executions.size >= EXECUTION_MAX) {
267
+ if (!executionCapacityWarned) {
268
+ executionCapacityWarned = true;
269
+ try {
270
+ runtime.log?.warn?.("Auto Reply execution claim capacity reached; new turns refused");
271
+ } catch {}
272
+ }
273
+ return { sent: false };
274
+ }
275
+ executionCapacityWarned = false;
276
+ executions.set(key, started + EXECUTION_TTL_MS);
277
+ beginTurn(chatJid, started);
278
+ const jobAbort = entry.controller;
279
+ inflightAbort.set(jobAbort, chatJid);
280
+ const timeoutMs = Math.max(
281
+ 1,
282
+ Math.min(
283
+ AI_TIMEOUT_CAP_MS,
284
+ Number(
285
+ dep(
286
+ "settingsGet",
287
+ () => (key) => require("../config/settings.cjs").get(key),
288
+ )("ai_tool_timeout_ms"),
289
+ ) || 30_000,
290
+ ),
291
+ );
292
+ const timeoutAbort = new AbortController();
293
+ const timer = setTimeout(() => timeoutAbort.abort(), timeoutMs);
294
+ const signal = anySignal([liveSignal(runtime), jobAbort.signal, timeoutAbort.signal]);
295
+
296
+ try {
297
+ if (signal.aborted) return { sent: false };
298
+
299
+ const cache = rosterHelpers();
300
+ let groupMetadata = null;
301
+ let rosterVersion;
302
+ if (isGroup) {
303
+ groupMetadata = await cache.resolveGroupMetadata(sock, chatJid, { fresh: true });
304
+ rosterVersion = cache.getRosterVersion(chatJid);
305
+ }
306
+
307
+ const resolveCaller = dep(
308
+ "resolveCaller",
309
+ () => require("../services/aiToolAuth.cjs").resolveCaller,
310
+ );
311
+ const caller = await resolveCaller({
312
+ msg,
313
+ sock,
314
+ groupMetadata,
315
+ accountEpoch: epoch,
316
+ rosterVersion,
317
+ text: event.text,
318
+ });
319
+
320
+ const runAgent = dep("runAgent", () => require("../services/aiAgent.cjs").runAgent);
321
+ const parts = [{ text: event.text }];
322
+ if (instructions) parts.push({ text: instructions });
323
+ const deliveryGuard = {
324
+ async refresh() {
325
+ if (!isGroup) return;
326
+ await rosterHelpers().resolveGroupMetadata(sock, chatJid, { fresh: true });
327
+ },
328
+ assert() {
329
+ signal.throwIfAborted();
330
+ if (accountEpochNow() !== epoch) throw new Error("epoch");
331
+ if (typeof runtime.generation === "function" && runtime.generation() !== generation) {
332
+ throw new Error("generation");
333
+ }
334
+ if (typeof runtime.isActive === "function" && !runtime.isActive())
335
+ throw new Error("inactive");
336
+ if (!inScope(chatJid, runtime.getScope?.())) throw new Error("scope");
337
+ if (isGroup && rosterHelpers().isRosterStale(chatJid)) throw new Error("roster");
338
+ },
339
+ };
340
+ deliveryGuard.assert();
341
+ const result = await runAgent({
342
+ parts,
343
+ history: [],
344
+ status: null,
345
+ signal,
346
+ context: {
347
+ signal,
348
+ deliveryGuard,
349
+ caller,
350
+ sock,
351
+ chatId: chatJid,
352
+ senderId: caller.senderId,
353
+ senderName: caller.senderName,
354
+ isOwner: caller.isOwner,
355
+ isAdmin: caller.isOwner || caller.isBotAdmin,
356
+ isGroup: caller.isGroup,
357
+ chatName: caller.chatName,
358
+ memoryScope: "chat",
359
+ autoReplyGlobal,
360
+ },
361
+ });
362
+
363
+ let text = String(result?.text || "").trim();
364
+ if (!text) return { sent: false };
365
+ if (result?.sources?.length) {
366
+ try {
367
+ const { formatSources } = require("../services/aiAgent.cjs");
368
+ text = `${text}${formatSources(result.sources)}`;
369
+ } catch {}
370
+ }
371
+ try {
372
+ const { formatMarkdownForWhatsApp } = require("../utils/markdownParser.cjs");
373
+ text = formatMarkdownForWhatsApp(text);
374
+ } catch {}
375
+
376
+ const sendBotMessage = dep(
377
+ "sendBotMessage",
378
+ () => require("../utils/sendBotMessage.cjs").sendBotMessage,
379
+ );
380
+ await sendBotMessage(
381
+ sock,
382
+ chatJid,
383
+ { text },
384
+ {
385
+ replyTo: msg,
386
+ quote,
387
+ typing: false,
388
+ delayMs: 0,
389
+ signal,
390
+ deliveryGuard,
391
+ },
392
+ );
393
+ return { sent: true };
394
+ } catch {
395
+ return { sent: false };
396
+ } finally {
397
+ clearTimeout(timer);
398
+ inflightAbort.delete(jobAbort);
399
+ endTurn(chatJid);
400
+ }
401
+ }
402
+
403
+ async function dispatch(runtime, sock, msg, epoch) {
404
+ if (!runtime || typeof runtime.isActive !== "function" || !runtime.isActive()) return;
405
+ if (typeof runtime.consider !== "function") return;
406
+ if (msg?.key?.fromMe !== false) return;
407
+ const chatJid = msg.key.remoteJid;
408
+ if (!chatJid || chatJid.endsWith("@broadcast") || chatJid.endsWith("@newsletter")) return;
409
+ if (accountEpochNow() !== epoch) return;
410
+
411
+ try {
412
+ if (await ownRecent(msg)) return;
413
+ } catch {
414
+ return;
415
+ }
416
+
417
+ if (hasBotMetadata(msg)) return;
418
+
419
+ const identity =
420
+ typeof injected.linkedIdentity === "function" ? injected.linkedIdentity() : linkedIdentity();
421
+ const selfCheck =
422
+ typeof injected.isLinkedSelf === "function" ? injected.isLinkedSelf : isLinkedSelf;
423
+ const candidates = getSenderCandidates(msg, sock) || [];
424
+ if (candidates.some((id) => selfCheck(id, identity))) return;
425
+
426
+ const scope = typeof runtime.getScope === "function" ? runtime.getScope() : null;
427
+ if (!inScope(chatJid, scope)) return;
428
+
429
+ const text = String(visibleText(msg.message) || "").trim();
430
+ if (!text || text.length > MAX_TEXT) return;
431
+
432
+ const messageId = msg.key.id;
433
+ if (typeof messageId !== "string" || !messageId) return;
434
+
435
+ const ctxInfo = contextInfoOf(msg);
436
+ const mentioned = Array.isArray(ctxInfo?.mentionedJid) ? ctxInfo.mentionedJid : [];
437
+ const mentionsMe = mentioned.some((jid) => selfCheck(jid, identity));
438
+ const quotesMe = Boolean(ctxInfo?.participant && selfCheck(ctxInfo.participant, identity));
439
+
440
+ const event = Object.freeze({
441
+ chatJid,
442
+ isGroup: chatJid.endsWith("@g.us"),
443
+ sender: Object.freeze({
444
+ primary: candidates[0] || null,
445
+ candidates: Object.freeze([...candidates]),
446
+ }),
447
+ text,
448
+ messageId,
449
+ timestamp: Number(msg.messageTimestamp) || nowMs(),
450
+ mentionsMe,
451
+ quotesMe,
452
+ });
453
+
454
+ const generation = typeof runtime.generation === "function" ? runtime.generation() : 0;
455
+ const t = nowMs();
456
+ const key = jobKey(epoch, chatJid, messageId);
457
+ pruneClaims(intake, t);
458
+ pruneClaims(executions, t);
459
+ if (executions.has(key)) return;
460
+ if (intake.has(key)) {
461
+ rememberClaim(intake, key, intake.get(key), INTAKE_MAX);
462
+ return;
463
+ }
464
+ if (accountEpochNow() !== epoch || !runtime.isActive()) return;
465
+ if (!inScope(chatJid, runtime.getScope?.())) return;
466
+ rememberClaim(intake, key, t + INTAKE_TTL_MS, INTAKE_MAX);
467
+ prunePending(t);
468
+ const controller = new AbortController();
469
+ pending.set(key, {
470
+ sock,
471
+ msg,
472
+ event,
473
+ epoch,
474
+ generation,
475
+ controller,
476
+ expiresAt: t + PENDING_TTL_MS,
477
+ });
478
+ prunePending(t);
479
+
480
+ let decision;
481
+ try {
482
+ const timeout =
483
+ typeof runtime.considerTimeoutMs === "function" ? runtime.considerTimeoutMs() : 2000;
484
+ decision = await withDeadline(
485
+ runtime.consider(event, { signal: anySignal([liveSignal(runtime), controller.signal]) }),
486
+ timeout,
487
+ );
488
+ } catch (error) {
489
+ pending.delete(key);
490
+ try {
491
+ runtime.recordFailure?.(error);
492
+ } catch {}
493
+ return;
494
+ }
495
+
496
+ if (decision?.reply !== true) {
497
+ pending.delete(key);
498
+ return;
499
+ }
500
+ if (decision.instructions != null && String(decision.instructions).length > MAX_INSTRUCTIONS) {
501
+ pending.delete(key);
502
+ return;
503
+ }
504
+
505
+ await runAiReply(runtime, {
506
+ chatJid,
507
+ messageId,
508
+ instructions: decision.instructions,
509
+ quote: decision.quote === true,
510
+ globalMemory: decision.globalMemory,
511
+ });
512
+ }
513
+
514
+ module.exports = {
515
+ dispatch,
516
+ runAiReply,
517
+ abortAccountJobs,
518
+ abortOutOfScope,
519
+ setAutoReplyDeps,
520
+ resetAutoReplyDeps,
521
+ };
@@ -0,0 +1,73 @@
1
+ // Frozen ctx handed to activate(). Holds only what declared capabilities need.
2
+
3
+ const catalog = require("../i18n/catalog.generated.cjs");
4
+ const templateKeys = require("./templateKeys.cjs");
5
+
6
+ function makeStorage(id, kind) {
7
+ return Object.freeze({
8
+ get(name) {
9
+ return require("../db/store.cjs").getExtStorage(id, kind, name);
10
+ },
11
+ set(name, value) {
12
+ require("../db/store.cjs").setExtStorage(id, kind, name, value);
13
+ },
14
+ delete(name) {
15
+ require("../db/store.cjs").deleteExtStorage(id, kind, name);
16
+ },
17
+ });
18
+ }
19
+
20
+ function linkedAccount() {
21
+ const { linkedIdentity } = require("../messaging/identity.cjs");
22
+ const identity = linkedIdentity();
23
+ if (!identity.phone && !identity.lid) return null;
24
+ return Object.freeze({ lid: identity.lid || null, phone: identity.phone || null });
25
+ }
26
+
27
+ function childLog(log, id) {
28
+ if (log && typeof log.child === "function") return log.child({ extension: id });
29
+ return log;
30
+ }
31
+
32
+ function buildContext({
33
+ id,
34
+ signal,
35
+ generation,
36
+ capabilities,
37
+ log,
38
+ invalidateScope,
39
+ aiReply,
40
+ } = {}) {
41
+ const caps = new Set(Array.isArray(capabilities) ? capabilities : []);
42
+ const ctx = {
43
+ apiVersion: 1,
44
+ signal,
45
+ generation,
46
+ log: childLog(log, id),
47
+ storage: makeStorage(id, "cfg"),
48
+ };
49
+ if (caps.has("autoReply")) {
50
+ ctx.accountStorage = makeStorage(id, "acct");
51
+ ctx.ai = Object.freeze({
52
+ reply(job) {
53
+ return aiReply(job);
54
+ },
55
+ });
56
+ ctx.linkedAccount = linkedAccount;
57
+ ctx.invalidateScope = typeof invalidateScope === "function" ? invalidateScope : () => {};
58
+ }
59
+ if (caps.has("templates")) {
60
+ ctx.i18n = Object.freeze({
61
+ locales: Object.freeze((catalog.locales || []).map((entry) => entry.code)),
62
+ isCustomizable: templateKeys.isCustomizable,
63
+ catalogTemplate: templateKeys.catalogTemplate,
64
+ placeholders: templateKeys.placeholders,
65
+ customizableKeys: templateKeys.customizableKeys,
66
+ });
67
+ ctx.translate = (text, targetLocale) =>
68
+ require("../commands/translate.cjs").translateForExtension(text, targetLocale);
69
+ }
70
+ return Object.freeze(ctx);
71
+ }
72
+
73
+ module.exports = { buildContext };
@@ -0,0 +1,69 @@
1
+ // Public Levix Plus extension contract v1.
2
+ //
3
+ // The host loads one optional module from a fixed path and talks to it only
4
+ // through this shape. A mismatch leaves Core in Free state.
5
+
6
+ const API_VERSION = 1;
7
+ const CAPABILITIES = Object.freeze(["templates", "watermark", "progress", "autoReply", "panelApi"]);
8
+
9
+ const ID_RE = /^[a-z][a-z0-9-]{1,31}$/;
10
+ const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
11
+
12
+ const HANDLER_FIELDS = Object.freeze({
13
+ templates: ["resolve"],
14
+ watermark: ["hide"],
15
+ progress: ["hide"],
16
+ autoReply: ["scope", "consider"],
17
+ panelApi: ["handle"],
18
+ });
19
+
20
+ function validateManifest(mod) {
21
+ if (!mod || typeof mod !== "object") return { ok: false, reason: "module" };
22
+ if (mod.apiVersion !== API_VERSION) return { ok: false, reason: "apiVersion" };
23
+ if (typeof mod.id !== "string" || !ID_RE.test(mod.id)) return { ok: false, reason: "id" };
24
+ if (typeof mod.version !== "string" || !SEMVER_RE.test(mod.version)) {
25
+ return { ok: false, reason: "version" };
26
+ }
27
+ if (mod.requiresEntitlement !== "plus") return { ok: false, reason: "requiresEntitlement" };
28
+ if (!Array.isArray(mod.capabilities)) return { ok: false, reason: "capabilities" };
29
+ const seen = new Set();
30
+ for (const cap of mod.capabilities) {
31
+ if (!CAPABILITIES.includes(cap)) return { ok: false, reason: `capability:${cap}` };
32
+ if (seen.has(cap)) return { ok: false, reason: `duplicate:${cap}` };
33
+ seen.add(cap);
34
+ }
35
+ if (typeof mod.activate !== "function") return { ok: false, reason: "activate" };
36
+ if (typeof mod.deactivate !== "function") return { ok: false, reason: "deactivate" };
37
+ if (mod.onAccountReset != null && typeof mod.onAccountReset !== "function") {
38
+ return { ok: false, reason: "onAccountReset" };
39
+ }
40
+ return { ok: true };
41
+ }
42
+
43
+ function validateHandlers(capabilities, handlers) {
44
+ if (!handlers || typeof handlers !== "object" || Array.isArray(handlers)) {
45
+ return { ok: false, reason: "handlers" };
46
+ }
47
+ const declared = new Set(Array.isArray(capabilities) ? capabilities : []);
48
+ for (const cap of declared) {
49
+ if (!CAPABILITIES.includes(cap)) return { ok: false, reason: `capability:${cap}` };
50
+ const handler = handlers[cap];
51
+ if (!handler || typeof handler !== "object") return { ok: false, reason: `missing:${cap}` };
52
+ for (const field of HANDLER_FIELDS[cap] || []) {
53
+ if (typeof handler[field] !== "function")
54
+ return { ok: false, reason: `missing:${cap}.${field}` };
55
+ }
56
+ }
57
+ for (const key of Object.keys(handlers)) {
58
+ if (!CAPABILITIES.includes(key)) return { ok: false, reason: `unknown:${key}` };
59
+ if (!declared.has(key)) return { ok: false, reason: `undeclared:${key}` };
60
+ }
61
+ return { ok: true };
62
+ }
63
+
64
+ module.exports = {
65
+ API_VERSION,
66
+ CAPABILITIES,
67
+ validateManifest,
68
+ validateHandlers,
69
+ };