levix-bot 4.0.4 → 4.2.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 (96) hide show
  1. package/package.json +1 -1
  2. package/public/dashboard/assets/index-4AuqfnH5.js +431 -0
  3. package/public/dashboard/assets/index-LvfJ8ybs.css +2 -0
  4. package/public/dashboard/index.html +2 -2
  5. package/scheduler.cjs +25 -1
  6. package/src/commands/autoschedule.cjs +40 -10
  7. package/src/commands/blacklist.cjs +35 -10
  8. package/src/commands/block.cjs +18 -5
  9. package/src/commands/calc.cjs +90 -24
  10. package/src/commands/debt.cjs +59 -33
  11. package/src/commands/deleteschedule.cjs +21 -5
  12. package/src/commands/digit.cjs +34 -8
  13. package/src/commands/gemini.cjs +235 -108
  14. package/src/commands/group/add.cjs +46 -13
  15. package/src/commands/group/all.cjs +15 -5
  16. package/src/commands/group/antiSpam.cjs +11 -4
  17. package/src/commands/group/antilink.cjs +39 -19
  18. package/src/commands/group/approveall.cjs +22 -7
  19. package/src/commands/group/clearwarns.cjs +18 -5
  20. package/src/commands/group/deletenote.cjs +18 -5
  21. package/src/commands/group/demote.cjs +25 -7
  22. package/src/commands/group/kick.cjs +28 -12
  23. package/src/commands/group/media.cjs +34 -13
  24. package/src/commands/group/members.cjs +21 -6
  25. package/src/commands/group/note.cjs +14 -4
  26. package/src/commands/group/promote.cjs +22 -6
  27. package/src/commands/group/removeall.cjs +13 -3
  28. package/src/commands/group/rules.cjs +20 -5
  29. package/src/commands/group/save.cjs +20 -5
  30. package/src/commands/group/setname.cjs +19 -6
  31. package/src/commands/group/setpp.cjs +21 -6
  32. package/src/commands/group/setrules.cjs +17 -5
  33. package/src/commands/group/setwarn.cjs +23 -7
  34. package/src/commands/group/tagadmins.cjs +16 -6
  35. package/src/commands/group/warn.cjs +35 -15
  36. package/src/commands/group/warns.cjs +33 -13
  37. package/src/commands/group/welcome.cjs +34 -16
  38. package/src/commands/group.cjs +96 -70
  39. package/src/commands/help.cjs +270 -129
  40. package/src/commands/lang.cjs +46 -13
  41. package/src/commands/listschedules.cjs +28 -11
  42. package/src/commands/loop.cjs +43 -9
  43. package/src/commands/memory.cjs +90 -30
  44. package/src/commands/mod.cjs +72 -28
  45. package/src/commands/notes.cjs +15 -5
  46. package/src/commands/perm.cjs +52 -20
  47. package/src/commands/ping.cjs +15 -3
  48. package/src/commands/poll.cjs +71 -24
  49. package/src/commands/prayer.cjs +28 -12
  50. package/src/commands/qr.cjs +20 -5
  51. package/src/commands/rand.cjs +54 -12
  52. package/src/commands/restart.cjs +13 -3
  53. package/src/commands/schedule.cjs +32 -9
  54. package/src/commands/score.cjs +26 -10
  55. package/src/commands/setprefix.cjs +27 -5
  56. package/src/commands/shortlink.cjs +36 -10
  57. package/src/commands/shutdown.cjs +13 -3
  58. package/src/commands/status.cjs +32 -11
  59. package/src/commands/sticker.cjs +34 -7
  60. package/src/commands/stt.cjs +159 -107
  61. package/src/commands/todo.cjs +31 -9
  62. package/src/commands/tts.cjs +61 -36
  63. package/src/commands/unblock.cjs +17 -4
  64. package/src/commands/weather.cjs +55 -17
  65. package/src/config/baileys.config.js +5 -1
  66. package/src/config/settings.cjs +11 -3
  67. package/src/core/connection.js +21 -2
  68. package/src/core/socket.js +31 -7
  69. package/src/db/store.cjs +24 -0
  70. package/src/handlers/command.handler.js +55 -13
  71. package/src/handlers/group.handler.js +5 -1
  72. package/src/handlers/message.handler.js +9 -0
  73. package/src/middleware/antispam.middleware.js +13 -3
  74. package/src/middleware/blacklist.middleware.js +4 -1
  75. package/src/middleware/permissions.middleware.js +38 -51
  76. package/src/routes/dashboard.api.esm.js +91 -10
  77. package/src/services/aiAgent.cjs +51 -41
  78. package/src/services/aiProviders.cjs +46 -19
  79. package/src/services/aiRouter.cjs +11 -3
  80. package/src/services/aiToolAuth.cjs +114 -0
  81. package/src/services/aiTools.cjs +492 -56
  82. package/src/services/modelRegistry.cjs +20 -5
  83. package/src/utils/commandDocs.cjs +58 -0
  84. package/src/utils/geminiMedia.cjs +99 -0
  85. package/src/utils/groupMetadataCache.cjs +83 -0
  86. package/src/utils/i18n.cjs +113 -0
  87. package/src/utils/markdownParser.cjs +4 -2
  88. package/src/utils/memory.cjs +37 -21
  89. package/src/utils/permissionLevel.cjs +83 -0
  90. package/src/utils/providerUrl.cjs +29 -2
  91. package/src/utils/sendBotMessage.cjs +7 -3
  92. package/src/utils/sendBotMessage.esm.js +27 -3
  93. package/src/utils/statusMessage.cjs +11 -4
  94. package/src/utils/storage-hub.cjs +21 -0
  95. package/public/dashboard/assets/index-BnJbz8iW.css +0 -2
  96. package/public/dashboard/assets/index-Dn8ZyzsW.js +0 -426
@@ -1,16 +1,23 @@
1
1
  // The tools the AI agent can actually call.
2
2
  //
3
- // Each entry is { declaration, run(args, ctx), describe(args) }:
3
+ // Each entry is { declaration, access?, run(args, ctx), describe(args) }:
4
4
  // declaration - what Gemini sees (name + JSON schema)
5
+ // access - who may call it (see aiToolAuth.cjs): the command it stands
6
+ // in for, plus any role that command checks internally. A
7
+ // function of the arguments when the action they pick changes
8
+ // the rule (global vs chat memory). Absent = open to anyone
9
+ // who may use the AI at all.
5
10
  // run - what happens when the model calls it; ALWAYS resolves to a
6
11
  // plain object (errors included) so one bad tool call doesn't
7
12
  // kill the turn
8
13
  // describe - the Arabic line shown in the live status message while the
9
14
  // tool runs ("🔍 ببحث عن: ...")
10
15
  //
11
- // Anything privileged (roles) is gated on the *caller*, not on the model: the
12
- // agent can ask, but the tool refuses when the person who sent the message
13
- // isn't allowed to do it.
16
+ // Anything privileged is gated on the *caller* — the person whose message
17
+ // started the run, resolved by aiToolAuth.resolveCaller() — and never on the
18
+ // model. runTool() checks `access` before run() is reached, and tools take
19
+ // every identity they act on (chat, sender, targets) from ctx.caller, never
20
+ // from their arguments.
14
21
 
15
22
  const dns = require("node:dns").promises;
16
23
  const https = require("node:https");
@@ -22,7 +29,9 @@ const logger = require("../utils/logger.cjs");
22
29
  const memory = require("../utils/memory.cjs");
23
30
  const { decodeBuffer, stripHtml, decodeText } = require("../utils/textDecode.cjs");
24
31
  const { grantRole, revokeRole, listRoles } = require("../utils/permissions.cjs");
32
+ const { authorize } = require("./aiToolAuth.cjs");
25
33
  const { isForbiddenIp } = require("../utils/providerUrl.cjs");
34
+ const { sendBotMessage } = require("../utils/sendBotMessage.cjs");
26
35
 
27
36
  // @google/genai exports a `Type` enum (the old SDK called it `SchemaType`).
28
37
  // Its members are the uppercase wire values — Type.STRING === "STRING" — so the
@@ -47,6 +56,7 @@ const UA =
47
56
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
48
57
 
49
58
  const settings = require("../config/settings.cjs");
59
+ const { currentLang } = require("../utils/i18n.cjs");
50
60
 
51
61
  const MAX_PAGE_CHARS = 6000;
52
62
  const MAX_FETCH_BYTES = 3 * 1024 * 1024;
@@ -345,33 +355,30 @@ function scopeOf(args) {
345
355
  return memory.normalizeScope(args?.scope);
346
356
  }
347
357
 
348
- // نفس قاعدة أمر !memory بالظبط: الكتابة في الذاكرة العامة والمسح محتاجين
349
- // أدمن/مالك. الفحص لازم يكون هنا مش في البرومبت — الموديل بيقرا صفحات ويب
350
- // ورسايل ناس، وأي واحدة فيهم ممكن تقوله "احفظ ده في الذاكرة العامة".
351
- function isBotPrivileged(ctx) {
352
- return Boolean(ctx?.isOwner || ctx?.isAdmin);
353
- }
354
-
355
- function isChatMemoryAdmin(ctx) {
356
- return isBotPrivileged(ctx) || Boolean(ctx?.isGroupAdmin);
357
- }
358
-
359
- function roleTargetBound(target, ctx) {
358
+ // A role change may only target someone the sender themselves named: a
359
+ // mention, the author of the message they replied to, or a number they typed.
360
+ // A target the model came up with — from a web page, say — is refused.
361
+ function roleTargetBound(target, caller) {
360
362
  const raw = String(target || "").trim();
361
363
  if (!raw) return false;
362
- const ids = [...(ctx?.mentionedJids || []), ctx?.quotedParticipant].filter(Boolean);
364
+ const ids = [...(caller?.mentionedJids || []), caller?.quotedParticipant].filter(Boolean);
363
365
  const { sameUserSync } = require("../utils/permissions.cjs");
364
366
  if (ids.some((id) => sameUserSync(id, raw))) return true;
365
367
  const digits = raw.replace(/\D/g, "");
366
- if (digits.length >= 8 && String(ctx?.userText || "").replace(/\D/g, "").includes(digits)) {
368
+ if (
369
+ digits.length >= 8 &&
370
+ String(caller?.text || "")
371
+ .replace(/\D/g, "")
372
+ .includes(digits)
373
+ ) {
367
374
  return true;
368
375
  }
369
376
  return false;
370
377
  }
371
378
 
372
- const NOT_PRIVILEGED = {
373
- error: "only the bot owner or an admin can do this",
374
- };
379
+ function roleOf(args) {
380
+ return String(args?.role || "admin").toLowerCase() === "owner" ? "owner" : "admin";
381
+ }
375
382
 
376
383
  function preview(value, length = 40) {
377
384
  const text = String(value || "")
@@ -535,24 +542,26 @@ const TOOLS = {
535
542
  `🧠 Saving to ${scopeOf(args) === "global" ? "global" : "chat"} memory: ${preview(
536
543
  args?.content,
537
544
  )}`,
538
- async run(args, ctx) {
545
+ // Same rule as `!memory add`: anyone may add to this chat, but global
546
+ // memory reaches every chat's prompt, so only the owner or a bot admin.
547
+ access: (args) => ({
548
+ command: "memory",
549
+ role: scopeOf(args) === "global" ? "botPrivileged" : undefined,
550
+ }),
551
+ async run(args, { caller }) {
539
552
  const scope = scopeOf(args);
540
- // الذاكرة العامة بتتحقن في البرومبت بتاع كل الشاتات، فمش أي حد يكتب فيها.
541
- if (scope === "global" && !isBotPrivileged(ctx)) {
542
- return { ...NOT_PRIVILEGED, saved: false };
543
- }
544
553
  const entry = memory.addMemory({
545
554
  scope,
546
- chatId: ctx.chatId,
555
+ chatId: caller.chatId,
547
556
  content: args?.content,
548
- by: ctx.senderName || ctx.senderId,
549
- chatName: ctx.chatName,
557
+ by: caller.senderName || caller.senderId,
558
+ chatName: caller.chatName,
550
559
  });
551
560
  return {
552
561
  saved: true,
553
562
  id: entry.id,
554
563
  scope,
555
- file: scope === "global" ? "global.md" : `chats/${ctx.chatId}.md`,
564
+ file: scope === "global" ? "global.md" : `chats/${caller.chatId}.md`,
556
565
  };
557
566
  },
558
567
  },
@@ -578,13 +587,15 @@ const TOOLS = {
578
587
  },
579
588
  describe: () => "🧠 جاري البحث في الذاكرة...",
580
589
  describeEn: () => "🧠 Searching memory...",
581
- async run(args, ctx) {
590
+ // `!memory search` reads both scopes for anyone who may run `!memory`.
591
+ access: { command: "memory" },
592
+ async run(args, { caller }) {
582
593
  const wanted = String(args?.scope || "chat").toLowerCase();
583
594
  const scopes = wanted === "all" ? ["chat", "global"] : [scopeOf(args)];
584
595
  const out = {};
585
596
  for (const scope of scopes) {
586
597
  out[scope] = memory
587
- .searchMemory(args?.query, { scope, chatId: ctx.chatId })
598
+ .searchMemory(args?.query, { scope, chatId: caller.chatId })
588
599
  .map((entry) => ({ id: entry.id, content: entry.content, at: entry.at }));
589
600
  }
590
601
  return out;
@@ -610,13 +621,17 @@ const TOOLS = {
610
621
  },
611
622
  describe: (args) => `🗑️ جاري الحذف من الذاكرة: ${preview(args?.ref)}`,
612
623
  describeEn: (args) => `🗑️ Removing from memory: ${preview(args?.ref)}`,
613
- async run(args, ctx) {
624
+ // `!memory forget`: global needs the owner or a bot admin; chat memory
625
+ // also lets an admin of this group tidy their own chat.
626
+ access: (args) => ({
627
+ command: "memory",
628
+ role: scopeOf(args) === "global" ? "botPrivileged" : "chatModerator",
629
+ }),
630
+ async run(args, { caller }) {
614
631
  const scope = scopeOf(args);
615
- const allowed = scope === "global" ? isBotPrivileged(ctx) : isChatMemoryAdmin(ctx);
616
- if (!allowed) return { ...NOT_PRIVILEGED, removed: false };
617
632
  const removed = memory.removeMemory({
618
633
  scope,
619
- chatId: ctx.chatId,
634
+ chatId: caller.chatId,
620
635
  ref: args?.ref,
621
636
  });
622
637
  return removed
@@ -647,20 +662,20 @@ const TOOLS = {
647
662
  `🔑 جاري فحص صلاحيات: ${preview(args?.target, 25)} (${args?.role || "admin"})`,
648
663
  describeEn: (args) =>
649
664
  `🔑 Checking permissions: ${preview(args?.target, 25)} (${args?.role || "admin"})`,
650
- async run(args, ctx) {
651
- if (!ctx.isOwner) {
652
- return { error: "only the bot owner can grant roles", granted: false };
653
- }
654
- if (!roleTargetBound(args?.target, ctx)) {
665
+ // `!perm add`: that command's level (owner only unless the operator
666
+ // changed it), and the owner role is always the owner's to hand out.
667
+ access: (args) => ({ command: "perm", role: roleOf(args) === "owner" ? "owner" : undefined }),
668
+ async run(args, { caller }) {
669
+ if (!roleTargetBound(args?.target, caller)) {
655
670
  return {
656
671
  error: "mention, quote, or type the target phone number in your own request",
657
672
  granted: false,
658
673
  };
659
674
  }
660
- const role = String(args?.role || "admin").toLowerCase() === "owner" ? "owner" : "admin";
675
+ const role = roleOf(args);
661
676
  const record = await grantRole(args?.target, role);
662
677
  logger.info(
663
- { target: args?.target, role, by: ctx.senderId },
678
+ { target: args?.target, role, by: caller.senderId },
664
679
  "[aiTools] role granted by the agent",
665
680
  );
666
681
  return {
@@ -686,17 +701,16 @@ const TOOLS = {
686
701
  },
687
702
  describe: (args) => `🔑 جاري سحب الصلاحية من: ${preview(args?.target, 25)}`,
688
703
  describeEn: (args) => `🔑 Revoking permissions from: ${preview(args?.target, 25)}`,
689
- async run(args, ctx) {
690
- if (!ctx.isOwner) {
691
- return { error: "only the bot owner can revoke roles", revoked: false };
692
- }
693
- if (!roleTargetBound(args?.target, ctx)) {
704
+ // `!perm remove`, gated exactly like grant_role.
705
+ access: (args) => ({ command: "perm", role: roleOf(args) === "owner" ? "owner" : undefined }),
706
+ async run(args, { caller }) {
707
+ if (!roleTargetBound(args?.target, caller)) {
694
708
  return {
695
709
  error: "mention, quote, or type the target phone number in your own request",
696
710
  revoked: false,
697
711
  };
698
712
  }
699
- const role = String(args?.role || "admin").toLowerCase() === "owner" ? "owner" : "admin";
713
+ const role = roleOf(args);
700
714
  const record = await revokeRole(args?.target, role);
701
715
  return { revoked: true, role, user: record ? record.jid : args?.target };
702
716
  },
@@ -705,15 +719,15 @@ const TOOLS = {
705
719
  list_roles: {
706
720
  declaration: {
707
721
  name: "list_roles",
708
- description: "List who currently holds bot owner / admin roles. Owners and admins only.",
722
+ description:
723
+ "List who currently holds bot owner / admin roles. Allowed for whoever may run !perm (the owner, by default).",
709
724
  parameters: { type: T.OBJECT, properties: {} },
710
725
  },
711
726
  describe: () => "🔑 جاري جلب قائمة الصلاحيات...",
712
727
  describeEn: () => "🔑 Fetching roles list...",
713
- async run(_args, ctx) {
714
- if (!ctx.isOwner && !ctx.isAdmin) {
715
- return { error: "only owners and admins can list roles" };
716
- }
728
+ // `!perm list` — the roster is `!perm`'s to show.
729
+ access: { command: "perm" },
730
+ async run() {
717
731
  const { owners, admins } = await listRoles();
718
732
  const shape = (user) => ({
719
733
  id: user.jid,
@@ -757,6 +771,317 @@ const TOOLS = {
757
771
  return { iso: now.toISOString(), timezone: timeZone, local };
758
772
  },
759
773
  },
774
+
775
+ calculate: {
776
+ declaration: {
777
+ name: "calculate",
778
+ description:
779
+ "Evaluate a math expression EXACTLY — arithmetic, percentages ('15% من 300'), powers, factorials, sqrt/log/trig and min/max/avg/sum. Always use this for numbers instead of computing in your head.",
780
+ parameters: {
781
+ type: T.OBJECT,
782
+ properties: {
783
+ expression: {
784
+ type: T.STRING,
785
+ description: "The expression, e.g. '(12 + 8) * 3', '2^10', 'sqrt(144) + 5!', '25% من 480'.",
786
+ },
787
+ },
788
+ required: ["expression"],
789
+ },
790
+ },
791
+ describe: (args) => `🧮 جاري الحساب: ${preview(args?.expression, 40)}`,
792
+ describeEn: (args) => `🧮 Calculating: ${preview(args?.expression, 40)}`,
793
+ async run(args) {
794
+ const expression = String(args?.expression || "").trim();
795
+ if (!expression) return { error: "expression is required" };
796
+ // Same hand-written parser the !calc command uses — never eval.
797
+ const calc = require("../commands/calc.cjs");
798
+ try {
799
+ const { normalized, value } = calc._evaluate(expression);
800
+ return { expression: normalized, result: calc._format(value) };
801
+ } catch (err) {
802
+ return { error: err?.message || "could not parse the expression" };
803
+ }
804
+ },
805
+ },
806
+
807
+ create_reminder: {
808
+ declaration: {
809
+ name: "create_reminder",
810
+ description:
811
+ "Schedule a reminder message that the bot sends into THIS chat at a chosen time ('remind me in 20 minutes', 'ذكّرني بكرة الصبح'). Give EITHER in_minutes OR at_time, never both.",
812
+ parameters: {
813
+ type: T.OBJECT,
814
+ properties: {
815
+ message: {
816
+ type: T.STRING,
817
+ description: "What the reminder should say — short and standalone.",
818
+ },
819
+ in_minutes: {
820
+ type: T.NUMBER,
821
+ description: "Fire this many minutes from now (1-10080, i.e. up to 7 days).",
822
+ },
823
+ at_time: {
824
+ type: T.STRING,
825
+ description:
826
+ "Absolute time in the bot's timezone, format 'HH:mm DD-MM-YYYY' (e.g. '22:30 07-06-2026'). Use get_datetime first to convert 'tomorrow 9am' into this.",
827
+ },
828
+ },
829
+ required: ["message"],
830
+ },
831
+ },
832
+ describe: (args) => `⏰ جاري إعداد التذكير: ${preview(args?.message, 40)}`,
833
+ describeEn: (args) => `⏰ Setting a reminder: ${preview(args?.message, 40)}`,
834
+ // Posting into a chat at a later time is exactly what `!schedule` does, so
835
+ // it takes `!schedule`'s permission level — whatever the dashboard sets.
836
+ access: { command: "schedule" },
837
+ async run(args, { caller }) {
838
+ const message = String(args?.message || "").trim().slice(0, 500);
839
+ if (!message) return { error: "message is required" };
840
+
841
+ const { zonedTimeToDate } = require("../utils/datetime.cjs");
842
+ let when;
843
+ if (args?.at_time !== undefined && args?.at_time !== null && String(args.at_time).trim()) {
844
+ const match = /^(\d{1,2}):(\d{2})\s+(\d{1,2})-(\d{1,2})-(\d{4})$/.exec(
845
+ String(args.at_time).trim(),
846
+ );
847
+ if (!match) {
848
+ return { error: "at_time must be 'HH:mm DD-MM-YYYY' in the bot's timezone" };
849
+ }
850
+ const [, hour, minute, day, month, year] = match.map(Number);
851
+ when = zonedTimeToDate({ year, month, day, hour, minute });
852
+ } else {
853
+ const minutes = Number(args?.in_minutes);
854
+ if (!Number.isFinite(minutes) || minutes <= 0) {
855
+ return { error: "give either in_minutes (1-10080) or at_time ('HH:mm DD-MM-YYYY')" };
856
+ }
857
+ if (minutes > 7 * 24 * 60) return { error: "in_minutes can be at most 10080 (7 days)" };
858
+ when = new Date(Date.now() + minutes * 60_000);
859
+ }
860
+ if (Number.isNaN(when.getTime())) return { error: "that time is not a valid date" };
861
+ if (when.getTime() <= Date.now()) return { error: "that time is already in the past" };
862
+
863
+ // Same job shape the !schedule command stores, delivered by the same
864
+ // scheduler — one mechanism, two doors into it.
865
+ const scheduler = require("../../scheduler.cjs");
866
+ const job = {
867
+ id: `${Date.now()}${Math.floor(Math.random() * 90) + 10}`,
868
+ type: "once",
869
+ date: when.toISOString(),
870
+ message,
871
+ targetJid: caller.chatId,
872
+ creatorJid: caller.senderId || caller.chatId,
873
+ status: "pending",
874
+ };
875
+ const result = scheduler.scheduleJobNow(job);
876
+ if (!result.ok) {
877
+ return result.reason === "no_connection"
878
+ ? { error: "WhatsApp is not connected right now, so the reminder cannot be armed" }
879
+ : { error: "the reminder time is invalid" };
880
+ }
881
+ let local;
882
+ try {
883
+ local = new Intl.DateTimeFormat("ar-EG", {
884
+ timeZone: settings.get("bot_timezone"),
885
+ dateStyle: "full",
886
+ timeStyle: "short",
887
+ }).format(when);
888
+ } catch {
889
+ local = when.toISOString();
890
+ }
891
+ return {
892
+ scheduled: true,
893
+ id: job.id,
894
+ willFireAt: when.toISOString(),
895
+ localTime: local,
896
+ delivery: `the bot posts it in this chat, prefixed with a "رسالة مجدولة" header`,
897
+ };
898
+ },
899
+ },
900
+
901
+ cancel_reminder: {
902
+ declaration: {
903
+ name: "cancel_reminder",
904
+ description:
905
+ "Cancel one pending reminder in THIS chat, by the id create_reminder returned. Allowed for whoever may run !deleteschedule here.",
906
+ parameters: {
907
+ type: T.OBJECT,
908
+ properties: {
909
+ id: { type: T.STRING, description: "The reminder id returned by create_reminder." },
910
+ },
911
+ required: ["id"],
912
+ },
913
+ },
914
+ describe: (args) => `⏰ جاري إلغاء التذكير: ${preview(args?.id, 20)}`,
915
+ describeEn: (args) => `⏰ Cancelling reminder: ${preview(args?.id, 20)}`,
916
+ // Deleting a scheduled job is `!deleteschedule`'s job, so its level.
917
+ access: { command: "deleteschedule" },
918
+ async run(args, { caller }) {
919
+ const id = String(args?.id || "").trim();
920
+ if (!id) return { error: "id is required" };
921
+
922
+ const scheduler = require("../../scheduler.cjs");
923
+ // Only jobs posting into the chat the request came from. An id is all
924
+ // it takes to address a job, and one can reach the model from a pasted
925
+ // message or a web page; `!deleteschedule` is the door for other chats.
926
+ const job = scheduler
927
+ .getScheduledJobs()
928
+ .find((entry) => String(entry.id) === id && entry.targetJid === caller.chatId);
929
+ if (!job) return { error: "no reminder with that id in this chat", cancelled: false };
930
+
931
+ scheduler.deleteScheduledJob(id);
932
+ return { cancelled: true, id, message: job.message };
933
+ },
934
+ },
935
+
936
+ speak: {
937
+ declaration: {
938
+ name: "speak",
939
+ description:
940
+ "Send your answer as a WhatsApp VOICE NOTE (text-to-speech) instead of text. Only when the user explicitly asks to hear it — 'قولها بصوت', 'read it aloud', 'send it as voice'. The text must be ready to be read aloud; keep it short.",
941
+ parameters: {
942
+ type: T.OBJECT,
943
+ properties: {
944
+ text: {
945
+ type: T.STRING,
946
+ description: "What the voice note says. Plain spoken prose, no markdown, no links.",
947
+ },
948
+ language: {
949
+ type: T.STRING,
950
+ description: "Optional language code, e.g. 'ar' (default) or 'en'.",
951
+ },
952
+ },
953
+ required: ["text"],
954
+ },
955
+ },
956
+ describe: (args) => `🎙️ جاري تحويل الرد لرسالة صوتية: ${preview(args?.text, 40)}`,
957
+ describeEn: (args) => `🎙️ Converting the reply to a voice note: ${preview(args?.text, 40)}`,
958
+ // Posting a voice note into this chat is what `!tts` does, so its level.
959
+ access: { command: "tts" },
960
+ async run(args, { caller, sock }) {
961
+ const text = String(args?.text || "").trim();
962
+ if (!text) return { error: "text is required" };
963
+ if (text.length > 3000) {
964
+ return { error: "text is too long for one voice note (3000 characters max)" };
965
+ }
966
+ if (!sock) return { error: "no WhatsApp connection is attached to this turn" };
967
+
968
+ const lang = String(args?.language || "ar").trim() || "ar";
969
+ const tts = require("../commands/tts.cjs");
970
+ const voice = await tts._synthesizeVoice(text, lang);
971
+ await sendBotMessage(
972
+ sock,
973
+ caller.chatId,
974
+ { audio: voice.audio, mimetype: voice.mimetype, ptt: voice.ptt },
975
+ { typing: false },
976
+ );
977
+ return {
978
+ sent: true,
979
+ format: voice.ptt ? "voice-note (ogg/opus)" : "audio (mp3 fallback)",
980
+ };
981
+ },
982
+ },
983
+
984
+ create_poll: {
985
+ declaration: {
986
+ name: "create_poll",
987
+ description:
988
+ "Create a native WhatsApp poll in THIS chat — members vote with a tap. Only when the user asks for a poll/vote ('اعمل استفتاء', 'create a poll').",
989
+ parameters: {
990
+ type: T.OBJECT,
991
+ properties: {
992
+ question: { type: T.STRING, description: "The poll question." },
993
+ options: {
994
+ type: T.ARRAY,
995
+ items: { type: T.STRING },
996
+ description: "2 to 12 distinct options.",
997
+ },
998
+ multi: {
999
+ type: T.BOOLEAN,
1000
+ description: "true = members may pick several answers. Default false.",
1001
+ },
1002
+ },
1003
+ required: ["question", "options"],
1004
+ },
1005
+ },
1006
+ describe: (args) => `📊 جاري إنشاء الاستفتاء: ${preview(args?.question, 40)}`,
1007
+ describeEn: (args) => `📊 Creating a poll: ${preview(args?.question, 40)}`,
1008
+ // A poll is a group message like any other, so `!poll`'s level.
1009
+ access: { command: "poll" },
1010
+ async run(args, { caller, sock }) {
1011
+ if (!sock) return { error: "no WhatsApp connection is attached to this turn" };
1012
+ // Same builder the !poll command uses: dedupes, caps lengths, enforces
1013
+ // WhatsApp's 2-12 option ceiling, and throws the user-facing Arabic
1014
+ // message on any violation.
1015
+ const poll = require("../commands/poll.cjs");
1016
+ const content = poll._buildPollContent(args?.question, args?.options, {
1017
+ multi: Boolean(args?.multi),
1018
+ });
1019
+ await sendBotMessage(sock, caller.chatId, content, { typing: false });
1020
+ return {
1021
+ sent: true,
1022
+ question: content.poll.name,
1023
+ options: content.poll.values,
1024
+ multiAnswer: content.poll.selectableCount > 1,
1025
+ };
1026
+ },
1027
+ },
1028
+
1029
+ summarize_chat: {
1030
+ declaration: {
1031
+ name: "summarize_chat",
1032
+ description:
1033
+ "Summarize THIS chat's stored conversation window and save only the durable, useful facts to long-term memory (max 8 short facts). Only when the user asks for it — 'لخص محادثتنا واحفظ المهم', 'summarize our chat and remember the important stuff'.",
1034
+ parameters: {
1035
+ type: T.OBJECT,
1036
+ properties: {
1037
+ scope: {
1038
+ type: T.STRING,
1039
+ description:
1040
+ "'chat' (default) saves to this chat's memory only; 'global' shares with every chat and needs the owner or a bot admin.",
1041
+ },
1042
+ },
1043
+ },
1044
+ },
1045
+ describe: () => "🧠 جاري تلخيص المحادثة وحفظ المهم...",
1046
+ describeEn: () => "🧠 Summarizing the chat and saving what matters...",
1047
+ // Saving chat memory is what `!memory add` allows here; the global scope
1048
+ // reaches every chat's prompt, so it takes save_memory's owner/admin role.
1049
+ access: (args) => ({
1050
+ command: "memory",
1051
+ role: scopeOf(args) === "global" ? "botPrivileged" : undefined,
1052
+ }),
1053
+ async run(args, { caller }) {
1054
+ const scope = scopeOf(args);
1055
+ const { getChatHistoryAsync } = require("../utils/storage-hub.cjs");
1056
+ const history = await getChatHistoryAsync(caller.chatId);
1057
+ const transcript = transcriptFromHistory(history);
1058
+ if (!transcript) {
1059
+ return { error: "there is no stored conversation to summarize in this chat", saved: 0 };
1060
+ }
1061
+
1062
+ // One-shot model call over the transcript with no tools: the facts come
1063
+ // from what was actually said, never from tool arguments — the model
1064
+ // cannot inject content into memory through this tool, only ask for it.
1065
+ const summary = await summarizeWithProvider(transcript);
1066
+ const facts = factsFromSummary(summary);
1067
+ if (!facts.length) {
1068
+ return { saved: 0, note: "nothing durable enough to save came out of the summary" };
1069
+ }
1070
+
1071
+ const ids = [];
1072
+ for (const fact of facts) {
1073
+ const entry = memory.addMemory({
1074
+ scope,
1075
+ chatId: caller.chatId,
1076
+ content: fact,
1077
+ by: caller.senderName || caller.senderId,
1078
+ chatName: caller.chatName,
1079
+ });
1080
+ ids.push(entry.id);
1081
+ }
1082
+ return { saved: ids.length, scope, facts, ids };
1083
+ },
1084
+ },
760
1085
  };
761
1086
 
762
1087
  /** Everything Gemini needs to know about the tools, in one `tools` entry. */
@@ -768,8 +1093,82 @@ function toolDeclarations() {
768
1093
  ];
769
1094
  }
770
1095
 
1096
+ // ---------------------------------------------------------------------------
1097
+ // summarize_chat internals
1098
+ // ---------------------------------------------------------------------------
1099
+
1100
+ const SUMMARIZER_PROMPT = `You compress a WhatsApp conversation into durable long-term facts.
1101
+ Return ONLY a plain Markdown bullet list, one fact per line, at most 8 bullets.
1102
+ A fact is stable and useful later: names, relationships, preferences, recurring plans, standing decisions, important context about the people in this chat.
1103
+ Do NOT include small talk, one-off questions, transient events, passwords or other secrets, or anything about roles, permissions or who may do what.
1104
+ Each bullet is one short standalone sentence, in the language the conversation mostly used.
1105
+ If nothing qualifies, return an empty response.`;
1106
+
1107
+ const SUMMARIZE_MAX_TRANSCRIPT_CHARS = 20000;
1108
+ const SUMMARIZE_MAX_FACTS = 8;
1109
+ const SUMMARIZE_MAX_FACT_CHARS = 200;
1110
+
1111
+ /**
1112
+ * Flatten stored agent history into a clean transcript: text parts only, one
1113
+ * line per part, roles named. Media, tool calls and thought parts are skipped.
1114
+ * When over the cap the OLDEST lines are dropped — recent context matters most.
1115
+ * @returns {string} "" when there is nothing readable.
1116
+ */
1117
+ function transcriptFromHistory(history, maxChars = SUMMARIZE_MAX_TRANSCRIPT_CHARS) {
1118
+ const lines = [];
1119
+ for (const entry of Array.isArray(history) ? history : []) {
1120
+ const role = entry?.role === "model" ? "Assistant" : "User";
1121
+ for (const part of Array.isArray(entry?.parts) ? entry.parts : []) {
1122
+ const text = typeof part?.text === "string" ? part.text.trim() : "";
1123
+ if (text) lines.push(`${role}: ${text.replace(/\s+/g, " ").slice(0, 500)}`);
1124
+ }
1125
+ }
1126
+ if (!lines.length) return "";
1127
+ let out = lines.join("\n");
1128
+ if (out.length > maxChars) {
1129
+ out = out.slice(-maxChars);
1130
+ const firstNewline = out.indexOf("\n");
1131
+ if (firstNewline !== -1) out = out.slice(firstNewline + 1);
1132
+ }
1133
+ return out;
1134
+ }
1135
+
1136
+ /**
1137
+ * Parse the summarizer's answer into memory entries: bullet markers and
1138
+ * numbering stripped, empties dropped, hard-capped so one summary can't flood
1139
+ * a memory file.
1140
+ */
1141
+ function factsFromSummary(text, { max = SUMMARIZE_MAX_FACTS, maxChars = SUMMARIZE_MAX_FACT_CHARS } = {}) {
1142
+ const out = [];
1143
+ for (const rawLine of String(text || "").split("\n")) {
1144
+ const line = rawLine.replace(/^\s*[-*•\d.)]+\s*/, "").trim();
1145
+ if (!line) continue;
1146
+ out.push(line.slice(0, maxChars));
1147
+ if (out.length >= max) break;
1148
+ }
1149
+ return out;
1150
+ }
1151
+
1152
+ /**
1153
+ * One-shot summarization through whichever provider is active. No tools, no
1154
+ * search, no persona: a plain completion over the transcript so a summary
1155
+ * can't recurse into the agent loop or spend the caller's tool budget.
1156
+ */
1157
+ async function summarizeWithProvider(transcript) {
1158
+ const { getProvider } = require("./aiRouter.cjs");
1159
+ const result = await getProvider().runTurn({
1160
+ parts: [{ text: transcript }],
1161
+ history: [],
1162
+ useTools: false,
1163
+ search: false,
1164
+ maxSteps: 1,
1165
+ systemInstruction: SUMMARIZER_PROMPT,
1166
+ });
1167
+ return result?.text || "";
1168
+ }
1169
+
771
1170
  /** The status line for a tool call (falls back to the raw name). */
772
- function describeCall(name, args, lang = settings.get("bot_language")) {
1171
+ function describeCall(name, args, lang = currentLang()) {
773
1172
  const tool = TOOLS[name];
774
1173
  const isEn = lang === "en";
775
1174
  const fallback = isEn ? `⚙️ Running: ${name}` : `⚙️ جاري تشغيل: ${name}`;
@@ -784,16 +1183,49 @@ function describeCall(name, args, lang = settings.get("bot_language")) {
784
1183
  }
785
1184
  }
786
1185
 
1186
+ /**
1187
+ * The model's arguments, cut down to the properties the tool declares. The
1188
+ * model writes these after reading strangers' messages and web pages, so
1189
+ * nothing undeclared (a `senderId`, an `isOwner`) may ride along into run().
1190
+ * Frozen, so access() and run() are guaranteed to see the same values.
1191
+ */
1192
+ function declaredArgs(tool, args) {
1193
+ const declared = tool.declaration?.parameters?.properties || {};
1194
+ const out = {};
1195
+ if (args && typeof args === "object") {
1196
+ for (const key of Object.keys(declared)) {
1197
+ if (Object.hasOwn(args, key)) out[key] = args[key];
1198
+ }
1199
+ }
1200
+ return Object.freeze(out);
1201
+ }
1202
+
787
1203
  /**
788
1204
  * Run one tool call. Never throws — a failure comes back as `{ error }` so the
789
1205
  * model can apologise or try something else instead of the turn dying.
1206
+ *
1207
+ * `ctx.caller` must come from aiToolAuth.resolveCaller(); a tool with `access`
1208
+ * refuses anything else before run() is reached.
790
1209
  */
791
1210
  async function runTool(name, args, ctx) {
792
1211
  const tool = TOOLS[name];
793
1212
  if (!tool) return { error: `unknown tool: ${name}` };
794
1213
 
1214
+ const input = declaredArgs(tool, args);
1215
+ const caller = ctx?.caller;
1216
+
795
1217
  try {
796
- const result = await tool.run(args || {}, ctx || {});
1218
+ const access = typeof tool.access === "function" ? tool.access(input) : tool.access;
1219
+ const verdict = authorize(access || null, caller);
1220
+ if (!verdict.allowed) {
1221
+ logger.info(
1222
+ { tool: name, chatId: caller?.chatId, senderId: caller?.senderId },
1223
+ "[aiTools] tool call refused",
1224
+ );
1225
+ return { error: verdict.error, denied: true };
1226
+ }
1227
+
1228
+ const result = await tool.run(input, { caller, sock: ctx?.sock });
797
1229
  return result && typeof result === "object" ? result : { result };
798
1230
  } catch (err) {
799
1231
  logger.warn({ err: err?.message, tool: name }, "[aiTools] tool call failed");
@@ -806,6 +1238,10 @@ module.exports = {
806
1238
  toolDeclarations,
807
1239
  describeCall,
808
1240
  runTool,
1241
+ transcriptFromHistory,
1242
+ factsFromSummary,
1243
+ summarizeWithProvider,
1244
+ SUMMARIZER_PROMPT,
809
1245
  webSearch,
810
1246
  searchNews,
811
1247
  searchWikipedia,