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
@@ -10,8 +10,8 @@
10
10
  //
11
11
  // The active provider itself (gemini / openai / anthropic) is a setting, and
12
12
  // the loop it dispatches to lives in services/aiAgent.cjs +
13
- // services/aiProviders.cjs. Media and !generate/!stt stay Gemini-only — the
14
- // other providers have no Files API to upload to.
13
+ // services/aiProviders.cjs. Images use the dedicated Gemini model; ordinary
14
+ // voice attachments are read lazily by the authorized transcription tool.
15
15
  //
16
16
  // What moved out:
17
17
  // * the system prompt -> config/ai-persona.md (editable, hot-reloaded)
@@ -23,9 +23,11 @@
23
23
  // never costs four messages.
24
24
 
25
25
  const { GoogleGenAI } = require("@google/genai");
26
+ const { geminiHttpOptions } = require("../utils/geminiHttpOptions.cjs");
26
27
 
27
28
  const logger = require("../utils/logger.cjs");
28
29
  const settings = require("../config/settings.cjs");
30
+ const { accountEpoch } = require("../db/store.cjs");
29
31
  const {
30
32
  getChatHistoryAsync,
31
33
  saveChatHistoryAsync,
@@ -35,8 +37,11 @@ const {
35
37
  const { sendBotMessage, sendBotError } = require("../utils/sendBotMessage.cjs");
36
38
  const { createStatus } = require("../utils/statusMessage.cjs");
37
39
  const { formatMarkdownForWhatsApp } = require("../utils/markdownParser.cjs");
38
- const { isOwnerJidSync } = require("../utils/permissions.cjs");
39
- const { resolveCaller } = require("../services/aiToolAuth.cjs");
40
+ const { isOwnerJidSync, getSenderCandidatesSync } = require("../utils/permissions.cjs");
41
+ const { resolveCaller, isCurrentCaller } = require("../services/aiToolAuth.cjs");
42
+ const { globalMemoryAccess, stripMemoryToolParts } = require("../services/memoryPolicy.cjs");
43
+ const { resolveGroupMetadata } = require("../utils/groupMetadataCache.cjs");
44
+ const { generateImage } = require("../services/aiImage.cjs");
40
45
  const {
41
46
  runAgent,
42
47
  formatSources,
@@ -46,16 +51,15 @@ const {
46
51
  } = require("../services/aiAgent.cjs");
47
52
  const { getProvider } = require("../services/aiRouter.cjs");
48
53
  const { downloadContentFromMessage } = require("@whiskeysockets/baileys");
49
- const { unwrapMessage, visibleText } = require("../utils/messageContent.cjs");
50
- const {
51
- assertProviderBaseUrl,
52
- assertProviderRequestUrl,
53
- } = require("../utils/providerUrl.cjs");
54
- const { tr } = require("../utils/i18n.cjs");
54
+ const { unwrapMessage, visibleText, quotedOf } = require("../utils/messageContent.cjs");
55
+ const { assertProviderBaseUrl, assertProviderRequestUrl } = require("../utils/providerUrl.cjs");
56
+ const { t } = require("../utils/i18n.cjs");
55
57
 
56
58
  // Per-(chat, sender) explicit context buffer for the multi-message workflow.
57
59
  // Entries accumulate until `!gemini send` flushes them into a single call.
58
60
  // Lives in memory only — short-lived by design.
61
+ let historyRevision = 0;
62
+ const chatHistoryRevisions = new Map();
59
63
  const contextBuffers = new Map(); // key: "<chatJid>::<senderJid>" -> { entries, at }
60
64
  const MAX_BUFFER_ENTRIES = 20;
61
65
  const MAX_BUFFER_CHARS = 32_000;
@@ -127,7 +131,7 @@ function geminiClients() {
127
131
  geminiCache = {
128
132
  key,
129
133
  baseUrl,
130
- genAI: new GoogleGenAI({ apiKey: key, httpOptions: { baseUrl } }),
134
+ genAI: new GoogleGenAI({ apiKey: key, apiVersion: "v1beta", httpOptions: geminiHttpOptions(baseUrl) }),
131
135
  };
132
136
  }
133
137
  return geminiCache;
@@ -218,7 +222,7 @@ function buildPartsFromBuffer(entries) {
218
222
  const parts = [];
219
223
  for (const e of entries) {
220
224
  if (e.quotedText) {
221
- parts.push({ text: tr(`(Reference: "${e.quotedText}")`, `(مرجع: "${e.quotedText}")`) });
225
+ parts.push({ text: t("bot.ai.gemini.reference", { quotedText: e.quotedText }) });
222
226
  }
223
227
  if (e.quotedMediaParts?.length) parts.push(...e.quotedMediaParts);
224
228
  if (e.mediaParts?.length) parts.push(...e.mediaParts);
@@ -238,38 +242,30 @@ function summarizeEntry(e, idx) {
238
242
  bits.push(`↩️ "${preview}"`);
239
243
  }
240
244
  if (e.mediaParts?.length)
241
- bits.push(tr(`🖼️ media (${e.mediaParts.length})`, `🖼️ ميديا (${e.mediaParts.length})`));
245
+ bits.push(t("bot.ai.gemini.mediaCount", { count: e.mediaParts.length }));
242
246
  if (e.quotedMediaParts?.length) {
243
- bits.push(
244
- tr(
245
- `🖼️↩️ quoted media (${e.quotedMediaParts.length})`,
246
- `🖼️↩️ وسائط مقتبسة (${e.quotedMediaParts.length})`,
247
- ),
248
- );
247
+ bits.push(t("bot.ai.gemini.quotedMediaCount", { count: e.quotedMediaParts.length }));
249
248
  }
250
- return `${idx + 1}. ${bits.join(" · ") || tr("(empty)", "(فارغة)")}`;
249
+ return `${idx + 1}. ${bits.join(" · ") || t("bot.ai.gemini.emptyEntry")}`;
251
250
  }
252
251
 
253
252
  module.exports = {
254
253
  name: "gemini",
255
254
  aliases: ["ask", "ai", "resetai", "del", "delall", "generate"],
256
- description: {
257
- en: "AI assistant with tools (web search, reading links, long-term memory). Sub-commands: add/send/clear/show for context, generate for images, del/delall to clear the conversation.",
258
- ar: "مساعد ذكي بأدوات (بحث في الويب، قراءة الروابط، ذاكرة دائمة). أوامر فرعية: add/send/clear/show للسياق، وgenerate للصور، وdel/delall لمسح المحادثة.",
259
- },
260
- usage: {
261
- en: "gemini <text>\ngemini add <text>\ngemini send\ngemini show\ngemini clear\ngenerate <image description>\ndel (clear this chat's conversation)\ndelall (clear every conversation)",
262
- ar: "gemini <النص>\ngemini add <النص>\ngemini send\ngemini show\ngemini clear\ngenerate <وصف الصورة>\ndel (مسح سجل هذه المحادثة)\ndelall (مسح كل المحادثات)",
263
- },
264
255
  chat: "all",
265
256
 
266
257
  async execute(sock, msg, args, body, groupMetadata, ctx = {}) {
258
+ const epoch = ctx?.accountEpoch ?? accountEpoch();
267
259
  const chatId = msg.key.remoteJid;
268
260
  const userName = msg.pushName;
269
261
  const isGroup = chatId.endsWith("@g.us");
270
262
 
271
263
  const senderId = msg.key.fromMe ? null : isGroup ? msg.key.participant : msg.key.remoteJid;
272
- const isOwner = msg.key.fromMe || isOwnerJidSync(senderId);
264
+ const authMetadata =
265
+ ctx && Object.hasOwn(ctx, "authGroupMetadata") ? ctx.authGroupMetadata : groupMetadata;
266
+ const isOwner =
267
+ msg.key.fromMe ||
268
+ getSenderCandidatesSync(msg, sock).some((id) => isOwnerJidSync(id, authMetadata));
273
269
 
274
270
  // Resolve sub-command. Aliases like !del arrive via ctx.invokedName, while
275
271
  // `!gemini del ...` arrives as args[0].
@@ -298,20 +294,16 @@ module.exports = {
298
294
  return sendBotMessage(
299
295
  sock,
300
296
  chatId,
301
- { text: tr("🚫 Only the bot owner can use this.", "🚫 هذا الأمر مخصص للمالك فقط.") },
297
+ { text: t("bot.ai.gemini.ownerOnly") },
302
298
  { replyTo: msg },
303
299
  );
300
+ chatHistoryRevisions.set(chatId, (chatHistoryRevisions.get(chatId) || 0) + 1);
304
301
  await deleteChatHistoryAsync(chatId);
305
302
  return sendBotMessage(
306
303
  sock,
307
304
  chatId,
308
305
  {
309
- text: tr(
310
- "✅ Conversation history cleared.\n" +
311
- "_(Long-term memory isn't cleared this way — use `!memory clear` if that's what you meant.)_",
312
- "✅ تم مسح سجل المحادثة.\n" +
313
- "_(لا تُحذف الذاكرة الدائمة بهذه الطريقة. استخدم `!memory clear` إذا أردت حذفها.)_",
314
- ),
306
+ text: t("bot.ai.gemini.historyCleared"),
315
307
  },
316
308
  { replyTo: msg },
317
309
  );
@@ -321,18 +313,17 @@ module.exports = {
321
313
  return sendBotMessage(
322
314
  sock,
323
315
  chatId,
324
- { text: tr("🚫 Only the bot owner can use this.", "🚫 هذا الأمر مخصص للمالك فقط.") },
316
+ { text: t("bot.ai.gemini.ownerOnly") },
325
317
  { replyTo: msg },
326
318
  );
319
+ historyRevision += 1;
320
+ chatHistoryRevisions.clear();
327
321
  await deleteAllChatHistoriesAsync();
328
322
  return sendBotMessage(
329
323
  sock,
330
324
  chatId,
331
325
  {
332
- text: tr(
333
- "✅ Every conversation history was cleared.",
334
- "✅ تم مسح كل سجلات المحادثات بنجاح.",
335
- ),
326
+ text: t("bot.ai.gemini.allHistoryCleared"),
336
327
  },
337
328
  { replyTo: msg },
338
329
  );
@@ -348,72 +339,49 @@ module.exports = {
348
339
  sock,
349
340
  chatId,
350
341
  {
351
- text: tr(
352
- "Describe the image you want after the command. Example: !generate a cat wearing a hat",
353
- "اكتب وصفًا للصورة التي تريدها بعد الأمر. مثال: !generate قطة ترتدي قبعة",
354
- ),
342
+ text: t("bot.ai.gemini.generateUsage"),
355
343
  },
356
344
  { replyTo: msg },
357
345
  );
358
346
  }
359
347
 
360
- const status = await createStatus(
361
- sock,
362
- chatId,
363
- tr("🎨 Making the image...", "🎨 جارٍ إنشاء الصورة..."),
364
- { replyTo: msg },
365
- );
348
+ const status = await createStatus(sock, chatId, t("bot.ai.gemini.makingImage"), {
349
+ replyTo: msg,
350
+ });
366
351
 
367
352
  try {
368
- // Image generation needs a model that returns image bytes, which only
369
- // the Gemini image models do — it stays on Gemini whatever the chat
370
- // provider is.
371
- if (!geminiClients().genAI) {
372
- throw new Error(
373
- tr(
374
- "No Gemini API key is set — image generation only runs on Gemini",
375
- "لم يُضبط مفتاح Gemini API — توليد الصور يعمل على Gemini فقط",
376
- ),
377
- );
378
- }
379
- await assertProviderRequestUrl(settings.get("gemini_base_url"), {
380
- allowLoopback: true,
381
- });
353
+ // Image generation stays on the dedicated Gemini image model, whatever
354
+ // ai_provider is. generateImage owns the request, the byte checks, and
355
+ // the fixed error codes.
382
356
  const fullPrompt =
383
357
  imagePrompt && quotedMsg
384
358
  ? `Prompt: ${imagePrompt} ,using quote: ${quotedMsg}`
385
359
  : imagePrompt
386
360
  ? `Prompt: ${imagePrompt}`
387
361
  : `Prompt: ${quotedMsg}`;
388
- const response = await geminiClients().genAI.models.generateContent({
389
- model: settings.get("gemini_image_model"),
390
- contents: `Generate an image using this prompt: ${fullPrompt}`,
391
- });
392
-
393
- // The bytes come back as an inlineData part. (The previous code read
394
- // `fileData.data`, which is not a field that exists on either SDK —
395
- // this path could never have produced an image.)
396
- const image = (response.candidates?.[0]?.content?.parts || []).find(
397
- (part) => part?.inlineData?.data,
398
- );
399
- if (!image) {
400
- throw new Error(tr("The model answered without an image", "أعاد النموذج ردًا دون صورة"));
401
- }
402
- const imageBuffer = Buffer.from(image.inlineData.data, "base64");
403
-
362
+ const generated = await generateImage(fullPrompt);
404
363
  await status.remove();
405
364
  await sendBotMessage(
406
365
  sock,
407
366
  chatId,
408
367
  {
409
- image: imageBuffer,
410
- caption: tr(`🖼️ Here you go: "${imagePrompt}"`, `🖼️ تفضل، صورة لـ: "${imagePrompt}"`),
368
+ image: generated.image,
369
+ caption: t("bot.ai.gemini.imageCaption", { prompt: imagePrompt }),
411
370
  },
412
371
  { replyTo: msg },
413
372
  );
414
373
  } catch (error) {
415
- logger.error({ err: error }, `Error in !generate command`);
416
- await status.fail(error, tr("I couldn't make the image", "تعذّر إنشاء الصورة"));
374
+ const code = error?.code || error?.message;
375
+ const shown =
376
+ code === "IMAGE_KEY_REQUIRED"
377
+ ? t("bot.ai.gemini.noGeminiKeyImages")
378
+ : code === "IMAGE_OUTPUT_INVALID"
379
+ ? t("bot.ai.gemini.noImageInAnswer")
380
+ : code === "IMAGE_QUOTA"
381
+ ? t("bot.ai.stt.quota")
382
+ : t("bot.ai.gemini.imageFailed");
383
+ logger.error({ code: code || "IMAGE_FAILED" }, "Error in !generate command");
384
+ await status.fail(new Error(shown), t("bot.ai.gemini.imageFailed"));
417
385
  }
418
386
  return;
419
387
  }
@@ -421,17 +389,13 @@ module.exports = {
421
389
  // --- multi-message context buffer ---
422
390
  if (subCommand === "add") {
423
391
  const entry = await captureContextEntry(msg, args);
392
+ if (epoch !== accountEpoch()) return;
424
393
  if (!entryHasContent(entry)) {
425
394
  return sendBotMessage(
426
395
  sock,
427
396
  chatId,
428
397
  {
429
- text: tr(
430
- "📭 Nothing to add to the context.\n\n" +
431
- "Write text after the command, reply to a message, or send media with the caption `!gemini add`.",
432
- "📭 لا يوجد محتوى لإضافته إلى السياق.\n\n" +
433
- "اكتب نصًا بعد الأمر، أو ردّ على رسالة، أو أرسل ملف وسائط مع الوصف `!gemini add`.",
434
- ),
398
+ text: t("bot.ai.gemini.nothingToAdd"),
435
399
  },
436
400
  { replyTo: msg },
437
401
  );
@@ -442,10 +406,7 @@ module.exports = {
442
406
  sock,
443
407
  chatId,
444
408
  {
445
- text: tr(
446
- `The context is full (${MAX_BUFFER_ENTRIES} messages at most). Send \`!gemini send\` or \`!gemini clear\`.`,
447
- `السياق ممتلئ (حد أقصى ${MAX_BUFFER_ENTRIES} رسائل). أرسل \`!gemini send\` أو \`!gemini clear\`.`,
448
- ),
409
+ text: t("bot.ai.gemini.contextFull", { max: MAX_BUFFER_ENTRIES }),
449
410
  },
450
411
  { replyTo: msg },
451
412
  );
@@ -456,12 +417,7 @@ module.exports = {
456
417
  sock,
457
418
  chatId,
458
419
  {
459
- text: tr(
460
- "The context is too big, or too many contexts are open. " +
461
- "Send `!gemini send` or `!gemini clear` and try again.",
462
- "السياق كبير جدًا، أو بلغ عدد السياقات المفتوحة الحد الأقصى. " +
463
- "أرسل `!gemini send` أو `!gemini clear` وحاول مرة أخرى.",
464
- ),
420
+ text: t("bot.ai.gemini.contextTooBig"),
465
421
  },
466
422
  { replyTo: msg },
467
423
  );
@@ -471,12 +427,7 @@ module.exports = {
471
427
  sock,
472
428
  chatId,
473
429
  {
474
- text: tr(
475
- `✅ Added to the context. (Total now: *${stored.length}*)\n\n` +
476
- "Keep going with `!gemini add ...`, or send it all with `!gemini send`.",
477
- `✅ أُضيفت إلى السياق. (إجمالي الآن: *${stored.length}*)\n\n` +
478
- "تابع باستخدام `!gemini add ...`، أو أرسل المحتوى كله باستخدام `!gemini send`.",
479
- ),
430
+ text: t("bot.ai.gemini.contextAdded", { total: stored.length }),
480
431
  },
481
432
  { replyTo: msg },
482
433
  );
@@ -490,11 +441,8 @@ module.exports = {
490
441
  chatId,
491
442
  {
492
443
  text: had
493
- ? tr(
494
- `🗑️ Cleared *${had}* messages from the context.`,
495
- `🗑️ تم مسح *${had}* رسالة من السياق.`,
496
- )
497
- : tr("📭 The context was already empty.", "📭 السياق فارغ بالفعل."),
444
+ ? t("bot.ai.gemini.contextCleared", { count: had })
445
+ : t("bot.ai.gemini.contextAlreadyEmpty"),
498
446
  },
499
447
  { replyTo: msg },
500
448
  );
@@ -507,10 +455,7 @@ module.exports = {
507
455
  sock,
508
456
  chatId,
509
457
  {
510
- text: tr(
511
- "📭 The context is empty. Start with `!gemini add ...`.",
512
- "📭 السياق فارغ. ابدأ بـ `!gemini add ...`.",
513
- ),
458
+ text: t("bot.ai.gemini.contextEmptyHint"),
514
459
  },
515
460
  { replyTo: msg },
516
461
  );
@@ -520,15 +465,9 @@ module.exports = {
520
465
  chatId,
521
466
  {
522
467
  text:
523
- tr(
524
- `📋 *Current context:* (${buf.length} messages)\n\n`,
525
- `📋 *السياق الحالي:* (${buf.length} رسالة)\n\n`,
526
- ) +
468
+ t("bot.ai.gemini.contextHeader", { count: buf.length }) +
527
469
  buf.map((e, i) => summarizeEntry(e, i)).join("\n") +
528
- tr(
529
- "\n\nSend it all with `!gemini send` or clear it with `!gemini clear`.",
530
- "\n\nأرسل المحتوى كله باستخدام `!gemini send` أو امسحه باستخدام `!gemini clear`.",
531
- ),
470
+ t("bot.ai.gemini.contextFooter"),
532
471
  },
533
472
  { replyTo: msg },
534
473
  );
@@ -541,6 +480,7 @@ module.exports = {
541
480
  if (subCommand === "send") {
542
481
  const buf = getBuffer(msg);
543
482
  const finalEntry = await captureContextEntry(msg, args);
483
+ if (epoch !== accountEpoch()) return;
544
484
  const allEntries = [...buf];
545
485
  if (entryHasContent(finalEntry)) allEntries.push(finalEntry);
546
486
  if (!allEntries.length) {
@@ -548,12 +488,7 @@ module.exports = {
548
488
  sock,
549
489
  chatId,
550
490
  {
551
- text: tr(
552
- "📭 The context is empty and `!gemini send` has no text.\n\n" +
553
- "Start with `!gemini add ...`, or write text with `!gemini send ...`.",
554
- "📭 السياق فارغ ولا يوجد نص في `!gemini send`.\n\n" +
555
- "ابدأ بـ `!gemini add ...` أولًا، أو اكتب نصًا مع `!gemini send ...`.",
556
- ),
491
+ text: t("bot.ai.gemini.sendEmpty"),
557
492
  },
558
493
  { replyTo: msg },
559
494
  );
@@ -573,39 +508,20 @@ module.exports = {
573
508
  msg.message.imageMessage ? "image" : "video",
574
509
  );
575
510
  parts.push({
576
- text:
577
- prompt ||
578
- mediaMessage.caption ||
579
- tr("What is in this image/video?", "ماذا يوجد في هذه الصورة/الفيديو؟"),
511
+ text: prompt || mediaMessage.caption || t("bot.ai.gemini.mediaPrompt"),
580
512
  });
581
513
  } catch (error) {
582
514
  logger.error({ err: error }, "Failed to upload media to Gemini.");
583
- return sendBotError(
584
- sock,
585
- chatId,
586
- error,
587
- tr("Uploading the image/video failed", "حصلت مشكلة في رفع الصورة/الفيديو"),
588
- {
589
- replyTo: msg,
590
- },
591
- );
592
- }
593
- } else if (!parts.length && msg.message?.audioMessage) {
594
- try {
595
- await processIncomingMedia(parts, msg.message.audioMessage, "audio");
596
- parts.push({ text: prompt || tr("Analyze this recording.", "حلل لي هذا التسجيل الصوتي.") });
597
- } catch (error) {
598
- logger.error({ err: error }, "Failed to upload audio to Gemini.");
599
- return sendBotError(
600
- sock,
601
- chatId,
602
- error,
603
- tr("Uploading the recording failed", "حصلت مشكلة في رفع التسجيل الصوتي"),
604
- {
605
- replyTo: msg,
606
- },
607
- );
515
+ return sendBotError(sock, chatId, error, t("bot.ai.gemini.uploadMediaFailed"), {
516
+ replyTo: msg,
517
+ });
608
518
  }
519
+ } else if (!parts.length && unwrapMessage(msg.message).audioMessage) {
520
+ // i18n-exception: attachment metadata sent only to the model, not a reply.
521
+ parts.push({
522
+ text: "[Audio attached to this turn; transcribe_audio can read it when requested.]",
523
+ });
524
+ parts.push({ text: prompt || t("bot.ai.gemini.analyzeRecording") });
609
525
  } else if (!parts.length && msg.message?.documentMessage) {
610
526
  try {
611
527
  await processIncomingMedia(parts, msg.message.documentMessage, "document");
@@ -613,20 +529,14 @@ module.exports = {
613
529
  const text = prompt || msg.message.documentMessage.caption || "";
614
530
  parts.push({
615
531
  text: text
616
- ? tr(`${text}\n(File: ${fileName})`, `${text}\n(الملف: ${fileName})`)
617
- : tr(`Analyze/summarize the file: ${fileName}`, `حلل/لخّص الملف: ${fileName}`),
532
+ ? t("bot.ai.gemini.fileWithText", { text, fileName })
533
+ : t("bot.ai.gemini.analyzeFile", { fileName }),
618
534
  });
619
535
  } catch (error) {
620
536
  logger.error({ err: error }, "Failed to upload document to Gemini.");
621
- return sendBotError(
622
- sock,
623
- chatId,
624
- error,
625
- tr("Uploading the file failed", "حصلت مشكلة في رفع الملف"),
626
- {
627
- replyTo: msg,
628
- },
629
- );
537
+ return sendBotError(sock, chatId, error, t("bot.ai.gemini.uploadFileFailed"), {
538
+ replyTo: msg,
539
+ });
630
540
  }
631
541
  } else if (!parts.length && prompt) {
632
542
  parts.push({ text: prompt });
@@ -637,10 +547,7 @@ module.exports = {
637
547
  sock,
638
548
  chatId,
639
549
  {
640
- text: tr(
641
- "Write a question, or send an image/video/voice note/file with the command.",
642
- "يرجى كتابة سؤال أو إرسال صورة/فيديو/تسجيل صوتي/ملف مع الأمر.",
643
- ),
550
+ text: t("bot.ai.gemini.askPrompt"),
644
551
  },
645
552
  { replyTo: msg },
646
553
  );
@@ -648,8 +555,7 @@ module.exports = {
648
555
 
649
556
  // Quoted message context. Skipped for `!gemini send` — those entries
650
557
  // captured their own quotes at `add` time.
651
- const quotedMsg =
652
- subCommand === "send" ? null : msg.message?.extendedTextMessage?.contextInfo?.quotedMessage;
558
+ const quotedMsg = subCommand === "send" ? null : quotedOf(msg);
653
559
 
654
560
  if (quotedMsg) {
655
561
  let quotedMediaPart = null;
@@ -657,7 +563,12 @@ module.exports = {
657
563
  const quotedText = visibleText(quotedMsg);
658
564
  const mediaInQuote = pickMedia(quotedMsg);
659
565
 
660
- if (mediaInQuote) {
566
+ if (mediaInQuote?.type === "audio") {
567
+ // i18n-exception: attachment metadata sent only to the model.
568
+ quotedMediaPart = {
569
+ text: "[Quoted audio is available to transcribe_audio when requested.]",
570
+ };
571
+ } else if (mediaInQuote) {
661
572
  try {
662
573
  const probeParts = [];
663
574
  await processIncomingMedia(probeParts, mediaInQuote.media, mediaInQuote.type);
@@ -667,15 +578,9 @@ module.exports = {
667
578
  // AND a second reply from a model that had never seen the photo
668
579
  // ("I can't see any image") — two messages, the second one wrong.
669
580
  logger.error({ err: mediaError }, "Failed to process quoted media");
670
- return sendBotError(
671
- sock,
672
- chatId,
673
- mediaError,
674
- tr("There was a problem with the quoted message", "حدثت مشكلة في الرسالة المقتبسة"),
675
- {
676
- replyTo: msg,
677
- },
678
- );
581
+ return sendBotError(sock, chatId, mediaError, t("bot.ai.gemini.quotedProblem"), {
582
+ replyTo: msg,
583
+ });
679
584
  }
680
585
  }
681
586
 
@@ -683,18 +588,12 @@ module.exports = {
683
588
  parts.unshift(quotedMediaPart);
684
589
  if (quotedText) {
685
590
  parts.unshift({
686
- text: tr(
687
- `Using this message as a reference:\n"""\n${quotedText}\n"""\n\n`,
688
- `بالاعتماد على هذه الرسالة كمرجع:\n"""\n${quotedText}\n"""\n\n`,
689
- ),
591
+ text: t("bot.ai.gemini.referenceMessage", { quotedText }),
690
592
  });
691
593
  }
692
594
  } else if (quotedText) {
693
595
  parts.unshift({
694
- text: tr(
695
- `Using this message as a reference:\n"""\n${quotedText}\n"""\n\nAnswer the following:`,
696
- `بالاعتماد على هذه الرسالة كمرجع:\n"""\n${quotedText}\n"""\n\nأجب على التالي:`,
697
- ),
596
+ text: t("bot.ai.gemini.referenceMessageAnswer", { quotedText }),
698
597
  });
699
598
  }
700
599
  }
@@ -706,10 +605,9 @@ module.exports = {
706
605
  sock,
707
606
  chatId,
708
607
  {
709
- text: tr(
710
- `Settings problem: no API key is set for the current AI provider (${activeProvider.label || activeProvider.id}) — set it in the control panel.`,
711
- `خطأ في الإعدادات: لم يُضبط مفتاح مزوّد الذكاء الاصطناعي الحالي (${activeProvider.label || activeProvider.id}) — اضبطه من لوحة التحكم.`,
712
- ),
608
+ text: t("bot.ai.gemini.providerNotConfigured", {
609
+ provider: activeProvider.label || activeProvider.id,
610
+ }),
713
611
  },
714
612
  { replyTo: msg },
715
613
  );
@@ -719,7 +617,24 @@ module.exports = {
719
617
  // way the command dispatcher resolves them, and frozen. The tools
720
618
  // authorize against it and nothing else — not the quoted message's author,
721
619
  // not a name in a web page, not anything the model writes into arguments.
722
- const caller = await resolveCaller({ msg, sock, groupMetadata, text: body || "" });
620
+ // Group-admin tools follow the dispatcher's fresh roster. A stale copy
621
+ // keeps its subject for the prompt and loses the admin flags.
622
+ let callerRoster = groupMetadata;
623
+ if (ctx && Object.prototype.hasOwnProperty.call(ctx, "authGroupMetadata")) {
624
+ callerRoster = ctx.authGroupMetadata;
625
+ } else if (isGroup) {
626
+ callerRoster = await resolveGroupMetadata(sock, chatId, { fresh: true });
627
+ }
628
+ if (!callerRoster && groupMetadata?.subject) callerRoster = { subject: groupMetadata.subject };
629
+ const caller = await resolveCaller({
630
+ msg,
631
+ sock,
632
+ groupMetadata: callerRoster,
633
+ accountEpoch: epoch,
634
+ rosterVersion: ctx?.rosterVersion,
635
+ text: body || "",
636
+ });
637
+ if (!isCurrentCaller(caller)) return;
723
638
  const agentContext = {
724
639
  caller,
725
640
  // Infrastructure, not identity: tools that post media (speak, poll)
@@ -741,27 +656,33 @@ module.exports = {
741
656
  const targets = [...caller.mentionedJids, caller.quotedParticipant].filter(Boolean);
742
657
  if (targets.length) {
743
658
  parts.unshift({
744
- text: tr(
745
- `(IDs mentioned in the message: ${[...new Set(targets)].join(", ")})`,
746
- `(معرفات مذكورة في الرسالة: ${[...new Set(targets)].join(", ")})`,
747
- ),
659
+ text: t("bot.ai.gemini.mentionedIds", { ids: [...new Set(targets)].join(", ") }),
748
660
  });
749
661
  }
750
662
 
751
663
  // The one message that will carry the whole run.
752
- const status = await createStatus(sock, chatId, tr("🤖 Thinking...", "🤖 جارٍ التفكير..."), {
664
+ const status = await createStatus(sock, chatId, t("bot.ai.gemini.thinking"), {
753
665
  replyTo: msg,
754
666
  });
755
667
 
668
+ const revision = historyRevision;
669
+ const chatRevision = chatHistoryRevisions.get(chatId) || 0;
670
+ const canSaveHistory = () =>
671
+ epoch === accountEpoch() &&
672
+ revision === historyRevision &&
673
+ chatRevision === (chatHistoryRevisions.get(chatId) || 0);
674
+
756
675
  async function attempt(historyOverride) {
676
+ if (!isCurrentCaller(caller)) return;
757
677
  const history = historyOverride ?? ((await getChatHistoryAsync(chatId)) || []);
678
+ if (!isCurrentCaller(caller)) return;
758
679
  const result = await runAgent({
759
680
  parts,
760
- history,
681
+ history: globalMemoryAccess(agentContext).read ? history : stripMemoryToolParts(history),
761
682
  status,
762
683
  context: agentContext,
763
684
  });
764
- if (result.history?.length) {
685
+ if (canSaveHistory() && result.history?.length) {
765
686
  await saveChatHistoryAsync(chatId, result.history);
766
687
  }
767
688
  return result;
@@ -772,25 +693,24 @@ module.exports = {
772
693
  try {
773
694
  result = await attempt();
774
695
  } catch (firstErr) {
696
+ if (!isCurrentCaller(caller)) return;
775
697
  // A dead fileData URI in the history poisons every later call — scrub
776
698
  // it once and retry so the user never sees the expiry.
777
- if (!isFileReferenceError(firstErr)) throw firstErr;
699
+ if (!isFileReferenceError(firstErr) || !canSaveHistory()) throw firstErr;
778
700
 
779
701
  const oldHistory = (await getChatHistoryAsync(chatId)) || [];
702
+ if (!isCurrentCaller(caller)) return;
780
703
  const cleaned = sanitizeHistoryForFiles(oldHistory);
704
+ if (!canSaveHistory()) throw firstErr;
781
705
  await saveChatHistoryAsync(chatId, cleaned);
782
706
  logger.info(
783
- `[Gemini] sanitized history for chat ${chatId}: ${oldHistory.length} -> ${cleaned.length}; retrying once`,
707
+ `[Gemini] sanitized history: ${oldHistory.length} -> ${cleaned.length}; retrying once`,
784
708
  );
785
709
  result = await attempt(cleaned);
786
710
  }
787
711
 
788
- const text =
789
- result.text?.trim() ||
790
- tr(
791
- "The model sent no answer. Try asking another way.",
792
- "لم يردّ النموذج. حاول صياغة السؤال بطريقة أخرى.",
793
- );
712
+ if (!result) return;
713
+ const text = result.text?.trim() || t("bot.ai.gemini.noAnswer");
794
714
  // Appended only when Gemini really grounded the answer on a search —
795
715
  // formatSources() returns "" for an answer the model gave from its own
796
716
  // knowledge, so there is never a Sources block with nothing behind it.
@@ -798,10 +718,7 @@ module.exports = {
798
718
  await status.finish(responseText);
799
719
  } catch (error) {
800
720
  logger.error({ err: error }, "Error in !gemini command");
801
- await status.fail(
802
- error,
803
- tr("Something went wrong while talking to the AI", "حصلت مشكلة وأنا بكلم الذكاء الاصطناعي"),
804
- );
721
+ await status.fail(error, t("bot.ai.gemini.chatFailed"));
805
722
  }
806
723
  },
807
724
  };