levix-bot 4.8.0 → 4.9.1

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 (60) hide show
  1. package/README.md +9 -5
  2. package/SETUP.md +21 -2
  3. package/app.cjs +69 -23
  4. package/package.json +3 -2
  5. package/public/dashboard/assets/index-B1sOW2VX.js +561 -0
  6. package/public/dashboard/assets/index-CK8osB4o.css +2 -0
  7. package/public/dashboard/index.html +2 -2
  8. package/public/dashboard.css +21 -0
  9. package/public/dashboard.js +25 -2
  10. package/public/gateway-i18n.js +26 -0
  11. package/src/bootstrap/session-startup-policy.js +6 -6
  12. package/src/commands/group/antilink.cjs +82 -59
  13. package/src/commands/group/antispam.cjs +112 -0
  14. package/src/commands/group/clearwarns.cjs +6 -6
  15. package/src/commands/group/demote.cjs +11 -13
  16. package/src/commands/group/flagged.cjs +52 -0
  17. package/src/commands/group/kick.cjs +25 -15
  18. package/src/commands/group/media.cjs +65 -29
  19. package/src/commands/group/policy.cjs +215 -0
  20. package/src/commands/group/promote.cjs +11 -12
  21. package/src/commands/group/rules.cjs +9 -6
  22. package/src/commands/group/setwarn.cjs +17 -27
  23. package/src/commands/group/warn.cjs +13 -63
  24. package/src/commands/group.cjs +5 -2
  25. package/src/commands/mod.cjs +101 -26
  26. package/src/commands/translate.cjs +585 -0
  27. package/src/config/ai-identity.cjs +53 -1
  28. package/src/config/ai-persona.md +32 -73
  29. package/src/config/defaults.cjs +2 -0
  30. package/src/config/secrets.cjs +71 -3
  31. package/src/config/settings.cjs +22 -1
  32. package/src/core/socket.js +4 -5
  33. package/src/db/db.cjs +66 -0
  34. package/src/db/store.cjs +264 -16
  35. package/src/diagnostics/crashReports.cjs +35 -9
  36. package/src/diagnostics/debugLog.cjs +405 -0
  37. package/src/handlers/command.handler.js +1 -0
  38. package/src/handlers/group.handler.js +32 -1
  39. package/src/handlers/message.handler.js +53 -17
  40. package/src/middleware/antispam.middleware.js +95 -48
  41. package/src/panel/feedback.cjs +32 -5
  42. package/src/panel/one-time-code.cjs +156 -0
  43. package/src/panel/password-reset.cjs +187 -91
  44. package/src/panel/recovery-email.cjs +333 -0
  45. package/src/routes/dashboard.api.esm.js +267 -20
  46. package/src/services/aiAgent.cjs +25 -3
  47. package/src/services/moderationPolicy.cjs +895 -0
  48. package/src/services/settingsTransfer.cjs +4 -2
  49. package/src/utils/linkedCreds.cjs +22 -0
  50. package/src/utils/logger.cjs +5 -0
  51. package/src/utils/moderationAction.cjs +637 -0
  52. package/src/utils/moderationSummary.cjs +225 -0
  53. package/src/utils/permissions.cjs +70 -0
  54. package/src/utils/permissions.esm.js +48 -8
  55. package/src/utils/storage.cjs +8 -0
  56. package/src/utils/storage.esm.js +4 -0
  57. package/views/login.ejs +100 -28
  58. package/public/dashboard/assets/index-B8E5IYlB.js +0 -540
  59. package/public/dashboard/assets/index-C5D4wzm4.css +0 -2
  60. package/src/commands/group/antiSpam.cjs +0 -97
@@ -38,6 +38,7 @@ import {
38
38
  getGroupSettings,
39
39
  getRecentDebts,
40
40
  getSchedules,
41
+ listModerationFlags,
41
42
  rememberSavedName,
42
43
  resolveUserPhone,
43
44
  saveGroupSettings,
@@ -45,6 +46,24 @@ import {
45
46
 
46
47
  const require = createRequire(import.meta.url);
47
48
  const logger = require("../utils/logger.cjs");
49
+ const {
50
+ buildModerationSummaryBoth,
51
+ featureActionOf,
52
+ warnConfigOf,
53
+ normalizeWarnAction,
54
+ normalizeFeatureAction,
55
+ } = require("../utils/moderationSummary.cjs");
56
+ const {
57
+ describeModerationPolicy,
58
+ prepareGroupModeration,
59
+ commitPreparedModeration,
60
+ evaluateModerationDraft,
61
+ } = require("../services/moderationPolicy.cjs");
62
+ const {
63
+ kickGroupMember,
64
+ clearMemberModeration,
65
+ dismissMemberFlag,
66
+ } = require("../utils/moderationAction.cjs");
48
67
  const runtimeConfig = require("../config/runtime-config.cjs");
49
68
  const settings = require("../config/settings.cjs");
50
69
  const memory = require("../utils/memory.cjs");
@@ -56,16 +75,21 @@ const {
56
75
  TOPICS: FEEDBACK_TOPICS,
57
76
  MESSAGE_MAX: FEEDBACK_MESSAGE_MAX,
58
77
  MESSAGE_MIN: FEEDBACK_MESSAGE_MIN,
78
+ buildDiagnosticsAttachment,
59
79
  describeRuntime,
60
80
  feedbackRetryAfter,
61
81
  submitFeedback,
62
82
  validateFeedback,
63
83
  } = require("../panel/feedback.cjs");
64
84
  const { stampPanelSession } = require("../panel/session-auth.cjs");
85
+ const recoveryEmail = require("../panel/recovery-email.cjs");
65
86
  const { DATA_DIR } = require("../config/paths.cjs");
66
- const { buildDiagnostics } = require("../diagnostics/device.cjs");
67
87
  const crashReports = require("../diagnostics/crashReports.cjs");
68
- const { PERSONA_FILE, activeProviderKeySetting } = require("../services/aiAgent.cjs");
88
+ const {
89
+ PERSONA_FILE,
90
+ activeProviderKeySetting,
91
+ stripSealedSections,
92
+ } = require("../services/aiAgent.cjs");
69
93
  const {
70
94
  SCHEDULE_MEDIA_MAX_BYTES,
71
95
  deleteScheduledJob,
@@ -427,7 +451,7 @@ router.get("/ai/persona", (req, res) => {
427
451
  const { header, body } = splitPersona(raw);
428
452
  res.json({
429
453
  success: true,
430
- persona: { header, body, file: path.basename(PERSONA_FILE) },
454
+ persona: { header, body: stripSealedSections(body), file: path.basename(PERSONA_FILE) },
431
455
  });
432
456
  } catch (error) {
433
457
  fail(res, error, "Error reading persona");
@@ -442,10 +466,11 @@ router.put("/ai/persona", (req, res) => {
442
466
  try {
443
467
  const raw = fs.existsSync(PERSONA_FILE) ? fs.readFileSync(PERSONA_FILE, "utf8") : "";
444
468
  const { header } = splitPersona(raw);
445
- const next = `${header}\n${PERSONA_SEPARATOR}\n${body.trim()}\n`;
469
+ const clean = stripSealedSections(body);
470
+ const next = `${header}\n${PERSONA_SEPARATOR}\n${clean}\n`;
446
471
  fs.writeFileSync(PERSONA_FILE, next, "utf8");
447
472
  logger.info("[Dashboard] AI persona updated");
448
- res.json({ success: true, persona: { header, body: body.trim() } });
473
+ res.json({ success: true, persona: { header, body: clean } });
449
474
  } catch (error) {
450
475
  fail(res, error, "Error writing persona");
451
476
  }
@@ -717,6 +742,7 @@ function groupView(groupId, stored) {
717
742
  const live = groupMetadataCache.get(groupId) || null;
718
743
  const directory = getGroupDirectory(groupId) || null;
719
744
  const config = stored || {};
745
+ const described = describeModerationPolicy(config);
720
746
  const subject = live?.subject || directory?.subject || null;
721
747
  const memberCount = live?.participants?.length ?? directory?.participant_count ?? null;
722
748
  const mediaEnabled = !!config.media_control?.enabled;
@@ -733,25 +759,24 @@ function groupView(groupId, stored) {
733
759
  enabled: !!config.antilink?.enabled,
734
760
  mode: config.antilink?.mode || "ALL",
735
761
  allowed_domains: config.antilink?.allowed_domains || [],
762
+ action: featureActionOf(config, "antilink"),
736
763
  },
737
764
  antispam: {
738
765
  enabled: !!config.antispam?.enabled,
739
766
  time_window: config.antispam?.time_window ?? 10,
740
767
  message_count: config.antispam?.message_count ?? 5,
741
- action: config.antispam?.action || "WARN",
768
+ action: featureActionOf(config, "antispam"),
742
769
  },
743
770
  media_control: {
744
771
  enabled: !!config.media_control?.enabled,
745
772
  blocked_types: config.media_control?.blocked_types || [],
773
+ action: featureActionOf(config, "media"),
746
774
  },
747
775
  welcome_system: {
748
776
  enabled: !!config.welcome_system?.enabled,
749
777
  messages: config.welcome_system?.messages || [],
750
778
  },
751
- warn_system: {
752
- max_warnings: config.warn_system?.max_warnings ?? 3,
753
- action: config.warn_system?.action || "NONE",
754
- },
779
+ warn_system: warnConfigOf(config),
755
780
  join_requests: {
756
781
  auto_approve_enabled: !!config.join_requests?.auto_approve_enabled,
757
782
  },
@@ -760,9 +785,47 @@ function groupView(groupId, stored) {
760
785
  antilinkEnabled: !!config.antilink?.enabled,
761
786
  welcomeEnabled: !!config.welcome_system?.enabled,
762
787
  mediaRestriction,
788
+ forbidden_words: {
789
+ enabled: !!config.moderation?.forbiddenWords?.enabled,
790
+ count: Array.isArray(config.moderation?.forbiddenWords?.list)
791
+ ? config.moderation.forbiddenWords.list.length
792
+ : 0,
793
+ action: featureActionOf(config, "forbidden"),
794
+ },
795
+ moderation_summary: buildModerationSummaryBoth(config),
796
+ flagged_members: listModerationFlags(groupId).map((row) => {
797
+ const peer = describePeer(row.user_id);
798
+ return {
799
+ user_id: row.user_id,
800
+ name: peer.label || row.user_id,
801
+ phone: peer.phone,
802
+ warn_count: row.warn_count,
803
+ last_rule: row.last_rule,
804
+ flagged_at: row.flagged_at,
805
+ reasons: row.reasons,
806
+ };
807
+ }),
808
+ moderation_policy: described.effective,
809
+ moderation_policy_visibility: described.visibility,
763
810
  };
764
811
  }
765
812
 
813
+ router.post("/groups/moderation-preview", (req, res) => {
814
+ try {
815
+ const draft = evaluateModerationDraft(req.body || {});
816
+ const summary = buildModerationSummaryBoth(draft.settings);
817
+ res.json({
818
+ success: true,
819
+ en: summary.en,
820
+ ar: summary.ar,
821
+ visibility: draft.visibility,
822
+ errors: draft.errors || [],
823
+ });
824
+ } catch (error) {
825
+ fail(res, error, "Error building moderation preview");
826
+ }
827
+ });
828
+
766
829
  router.get("/groups", (req, res) => {
767
830
  try {
768
831
  const stored = new Map(getAllGroupSettings().map((row) => [row.group_id, row.settings || {}]));
@@ -835,6 +898,11 @@ router.patch("/groups/:id", (req, res) => {
835
898
  }
836
899
  }
837
900
  const current = getGroupSettings(groupId) || {};
901
+ const prepared = prepareGroupModeration(current, patch);
902
+ if (!prepared.ok) {
903
+ const message = prepared.errors[0]?.message || "Invalid moderation policy";
904
+ return res.status(400).json({ success: false, error: message, errors: prepared.errors });
905
+ }
838
906
 
839
907
  try {
840
908
  if (patch.antilink) {
@@ -845,6 +913,11 @@ router.patch("/groups/:id", (req, res) => {
845
913
  if (!ANTILINK_MODES.includes(mode)) throw new Error("Unknown antilink mode");
846
914
  next.mode = mode;
847
915
  }
916
+ if (patch.antilink.action !== undefined) {
917
+ const action = normalizeFeatureAction(patch.antilink.action);
918
+ if (!action) throw new Error("Unknown antilink action");
919
+ next.action = action;
920
+ }
848
921
  if (patch.antilink.allowed_domains !== undefined) {
849
922
  if (!Array.isArray(patch.antilink.allowed_domains)) {
850
923
  throw new Error("allowed_domains must be a list");
@@ -885,8 +958,8 @@ router.patch("/groups/:id", (req, res) => {
885
958
  enabled: !!next.enabled,
886
959
  time_window: next.time_window ?? 10,
887
960
  message_count: next.message_count ?? 5,
888
- action: next.action || "WARN",
889
961
  };
962
+ if (next.action === "WARN" || next.action === "KICK") current.antispam.action = next.action;
890
963
  }
891
964
 
892
965
  if (patch.media_control) {
@@ -904,10 +977,18 @@ router.patch("/groups/:id", (req, res) => {
904
977
  }
905
978
  next.blocked_types = [...new Set(types)];
906
979
  }
980
+ if (patch.media_control.action !== undefined) {
981
+ const action = normalizeFeatureAction(patch.media_control.action);
982
+ if (!action) throw new Error("Unknown media action");
983
+ next.action = action;
984
+ }
907
985
  current.media_control = {
908
986
  enabled: !!next.enabled,
909
987
  blocked_types: next.blocked_types || [],
910
988
  };
989
+ if (next.action === "DELETE" || next.action === "WARN" || next.action === "KICK") {
990
+ current.media_control.action = next.action;
991
+ }
911
992
  }
912
993
 
913
994
  if (patch.welcome_system) {
@@ -940,14 +1021,30 @@ router.patch("/groups/:id", (req, res) => {
940
1021
  next.max_warnings = Math.trunc(max);
941
1022
  }
942
1023
  if (patch.warn_system.action !== undefined) {
943
- const action = String(patch.warn_system.action).toUpperCase();
944
- if (!["KICK", "NONE"].includes(action)) throw new Error("Unknown warn action");
1024
+ const action = normalizeWarnAction(patch.warn_system.action);
1025
+ if (!action) throw new Error("Unknown warn action");
945
1026
  next.action = action;
946
1027
  }
947
- current.warn_system = {
1028
+ const stored = {
948
1029
  max_warnings: next.max_warnings ?? 3,
949
- action: next.action || "NONE",
950
1030
  };
1031
+ const existingAction = normalizeWarnAction(next.action);
1032
+ if (existingAction) stored.action = existingAction;
1033
+ current.warn_system = stored;
1034
+ }
1035
+
1036
+ if (patch.forbidden_words) {
1037
+ current.moderation ||= {};
1038
+ current.moderation.forbiddenWords ||= { enabled: false, list: [] };
1039
+ const words = current.moderation.forbiddenWords;
1040
+ if (patch.forbidden_words.enabled !== undefined) {
1041
+ words.enabled = !!patch.forbidden_words.enabled;
1042
+ }
1043
+ if (patch.forbidden_words.action !== undefined) {
1044
+ const action = normalizeFeatureAction(patch.forbidden_words.action);
1045
+ if (!action) throw new Error("Unknown forbidden-words action");
1046
+ words.action = action;
1047
+ }
951
1048
  }
952
1049
 
953
1050
  if (patch.join_requests) {
@@ -959,6 +1056,7 @@ router.patch("/groups/:id", (req, res) => {
959
1056
  if (patch.rules !== undefined) {
960
1057
  current.rules = String(patch.rules).slice(0, 4000);
961
1058
  }
1059
+ commitPreparedModeration(current, prepared);
962
1060
  } catch (error) {
963
1061
  return badRequest(res, error.message);
964
1062
  }
@@ -972,6 +1070,77 @@ router.patch("/groups/:id", (req, res) => {
972
1070
  }
973
1071
  });
974
1072
 
1073
+ function flaggedUserId(req) {
1074
+ return String(req.body?.user_id || "").trim();
1075
+ }
1076
+
1077
+ router.post(
1078
+ "/groups/:id/flagged/kick",
1079
+ asyncRoute(async (req, res) => {
1080
+ const groupId = req.params.id;
1081
+ if (!groupId?.endsWith("@g.us")) return badRequest(res, "Not a group id");
1082
+ const userId = flaggedUserId(req);
1083
+ if (!userId) return badRequest(res, "user_id is required");
1084
+ const sock = currentSocket();
1085
+ if (!sock) {
1086
+ return res.status(503).json({ success: false, error: "WhatsApp is disconnected" });
1087
+ }
1088
+ let meta = groupMetadataCache.get(groupId);
1089
+ if (!meta) {
1090
+ try {
1091
+ meta = await sock.groupMetadata(groupId);
1092
+ } catch (error) {
1093
+ return fail(res, error, "Could not load group roster", 503);
1094
+ }
1095
+ }
1096
+ try {
1097
+ const result = await kickGroupMember(sock, {
1098
+ groupId,
1099
+ groupMetadata: meta,
1100
+ targetCandidates: [userId],
1101
+ });
1102
+ if (!result.kicked) {
1103
+ const message =
1104
+ result.error === "protected"
1105
+ ? "That member can't be kicked"
1106
+ : result.error === "bot-not-admin"
1107
+ ? "The bot must be a group admin to kick"
1108
+ : "Could not kick that member";
1109
+ return badRequest(res, message);
1110
+ }
1111
+ res.json({ success: true, group: groupView(groupId, getGroupSettings(groupId)) });
1112
+ } catch (error) {
1113
+ fail(res, error, "Error kicking flagged member");
1114
+ }
1115
+ }),
1116
+ );
1117
+
1118
+ router.post("/groups/:id/flagged/clear", (req, res) => {
1119
+ const groupId = req.params.id;
1120
+ if (!groupId?.endsWith("@g.us")) return badRequest(res, "Not a group id");
1121
+ const userId = flaggedUserId(req);
1122
+ if (!userId) return badRequest(res, "user_id is required");
1123
+ try {
1124
+ clearMemberModeration(groupId, userId);
1125
+ res.json({ success: true, group: groupView(groupId, getGroupSettings(groupId)) });
1126
+ } catch (error) {
1127
+ fail(res, error, "Error clearing flagged member");
1128
+ }
1129
+ });
1130
+
1131
+ router.post("/groups/:id/flagged/dismiss", (req, res) => {
1132
+ const groupId = req.params.id;
1133
+ if (!groupId?.endsWith("@g.us")) return badRequest(res, "Not a group id");
1134
+ const userId = flaggedUserId(req);
1135
+ if (!userId) return badRequest(res, "user_id is required");
1136
+ try {
1137
+ dismissMemberFlag(groupId, userId);
1138
+ res.json({ success: true, group: groupView(groupId, getGroupSettings(groupId)) });
1139
+ } catch (error) {
1140
+ fail(res, error, "Error dismissing flag");
1141
+ }
1142
+ });
1143
+
975
1144
  // ===========================================================================
976
1145
  // Data tables
977
1146
  // ===========================================================================
@@ -1379,6 +1548,81 @@ router.post("/security/password", (req, res) => {
1379
1548
  });
1380
1549
  });
1381
1550
 
1551
+ // ===========================================================================
1552
+ // Recovery email — sealed account security, not a setting
1553
+ // ===========================================================================
1554
+ //
1555
+ // The address is never returned. `publicStatus()` is a mask plus `verified`.
1556
+ // A new address does not replace the saved one until its code is verified.
1557
+ // Same-origin and the panel session come from the /dashboard/api mount.
1558
+
1559
+ // Wrong codes and a wrong password are 400, not 401. The panel client treats
1560
+ // every 401 as a dead session and sends the operator to /login. Login-page
1561
+ // reset confirm stays 401; that page does not use this client. A wrong verify
1562
+ // code does not count toward the login lockout (the relay limits guesses); a
1563
+ // wrong password does.
1564
+ const RECOVERY_HTTP = {
1565
+ throttled: 429,
1566
+ rate_limited: 429,
1567
+ wrong_password: 400,
1568
+ invalid_email: 400,
1569
+ invalid: 400,
1570
+ unavailable: 502,
1571
+ wrong_code: 400,
1572
+ expired: 400,
1573
+ too_many_attempts: 400,
1574
+ no_pending: 400,
1575
+ };
1576
+
1577
+ function recoveryFailure(res, result) {
1578
+ const status = RECOVERY_HTTP[result.reason] ?? 400;
1579
+ if (result.retryAfter) res.set("Retry-After", String(result.retryAfter));
1580
+ const body = { success: false, error: result.reason || "unavailable" };
1581
+ if (result.retryAfter) body.retryAfter = result.retryAfter;
1582
+ if (result.attemptsLeft != null) body.attemptsLeft = result.attemptsLeft;
1583
+ return res.status(status).json(body);
1584
+ }
1585
+
1586
+ router.get("/recovery-email", (req, res) => {
1587
+ res.json({ success: true, ...recoveryEmail.publicStatus() });
1588
+ });
1589
+
1590
+ // A recovery address can reset the password, so binding one asks for the
1591
+ // password again, like changing it does. Otherwise a stolen session or an
1592
+ // unattended browser could add its own address and keep the panel after the
1593
+ // operator signs it out or changes the password.
1594
+ router.post(
1595
+ "/recovery-email/start",
1596
+ asyncRoute(async (req, res) => {
1597
+ const peer = clientAddress(req);
1598
+ const retryAfter = blockedFor(peer);
1599
+ if (retryAfter) return recoveryFailure(res, { reason: "throttled", retryAfter });
1600
+ if (!secrets.verifyDashboardPassword(req.body?.current)) {
1601
+ recordFailure(peer);
1602
+ return recoveryFailure(res, { reason: "wrong_password" });
1603
+ }
1604
+ clearAttempts(peer);
1605
+
1606
+ const result = await recoveryEmail.startVerification(req.body?.email, req.body?.lang, peer);
1607
+ if (!result.ok) return recoveryFailure(res, result);
1608
+ res.json({ success: true });
1609
+ }),
1610
+ );
1611
+
1612
+ router.post(
1613
+ "/recovery-email/verify",
1614
+ asyncRoute(async (req, res) => {
1615
+ const result = await recoveryEmail.confirmVerification(req.body?.code);
1616
+ if (!result.ok) return recoveryFailure(res, result);
1617
+ res.json({ success: true, verified: true, masked: result.masked });
1618
+ }),
1619
+ );
1620
+
1621
+ router.delete("/recovery-email", (req, res) => {
1622
+ recoveryEmail.remove();
1623
+ res.json({ success: true, verified: false });
1624
+ });
1625
+
1382
1626
  // ===========================================================================
1383
1627
  // Feedback — the operator's line to the developer
1384
1628
  // ===========================================================================
@@ -1398,13 +1642,15 @@ router.get("/feedback/meta", (req, res) => {
1398
1642
  });
1399
1643
  });
1400
1644
 
1401
- // The exact object the server would forward as `diagnostics`, so the operator
1402
- // can see what they are about to share before they send it. This is the same
1403
- // builder submitFeedback() uses, so the preview cannot lie.
1645
+ // Preview of the diagnostics object plus a frozen debug-log snapshot. Send
1646
+ // redeems `debugLogId`; it does not rebuild the tail.
1404
1647
  router.post("/feedback/diagnostics-preview", (req, res) => {
1405
1648
  const parsed = parseDiagnosticsInput(req.body?.client);
1406
1649
  if (parsed.error) return badRequest(res, parsed.error);
1407
- res.json({ success: true, diagnostics: buildDiagnostics(parsed.present ? parsed.value : {}) });
1650
+ res.json({
1651
+ success: true,
1652
+ ...buildDiagnosticsAttachment(parsed.present ? parsed.value : {}),
1653
+ });
1408
1654
  });
1409
1655
 
1410
1656
  // Leaves this machine only when the operator presses Send, and carries nothing
@@ -1460,6 +1706,7 @@ router.post(
1460
1706
  parsed.value,
1461
1707
  attachment,
1462
1708
  diagnostics.present ? diagnostics.value : undefined,
1709
+ typeof body.debugLogId === "string" ? body.debugLogId : undefined,
1463
1710
  );
1464
1711
  if (!result.ok) {
1465
1712
  return res.status(result.status).json({ success: false, error: result.error });
@@ -1768,7 +2015,7 @@ router.post("/crash-reports", (req, res) => {
1768
2015
  router.post(
1769
2016
  "/crash-reports/:id/send",
1770
2017
  asyncRoute(async (req, res) => {
1771
- const result = await crashReports.sendReport(req.params.id);
2018
+ const result = await crashReports.sendReport(req.params.id, req.body?.debugLogId);
1772
2019
  if (!result.ok) {
1773
2020
  return res.status(result.status || 502).json({ success: false, error: result.error });
1774
2021
  }
@@ -95,6 +95,23 @@ const DEFAULT_PERSONA = `You are a capable personal WhatsApp assistant.
95
95
  Be concise and direct by default, reply in the language the user writes in, and
96
96
  use your tools instead of guessing when something needs to be looked up.`;
97
97
 
98
+ // Sections the code owns now (OPERATING_RULES in src/config/ai-identity.cjs).
99
+ // A copy of ai-persona.md from before that split still carries them, and an
100
+ // operator can type one back in: both are dropped here, so the rules are stated
101
+ // once, from code, and no edit of the persona can weaken them.
102
+ const SEALED_HEADINGS = new Set(["tools", "memory", "chats and groups", "boundaries"]);
103
+
104
+ function stripSealedSections(text) {
105
+ const kept = [];
106
+ let sealed = false;
107
+ for (const line of String(text).split("\n")) {
108
+ const heading = /^#{1,3}\s+(.+?)\s*$/.exec(line);
109
+ if (heading) sealed = SEALED_HEADINGS.has(heading[1].toLowerCase());
110
+ if (!sealed) kept.push(line);
111
+ }
112
+ return kept.join("\n").trim();
113
+ }
114
+
98
115
  let personaCache = { text: null, stamp: null };
99
116
 
100
117
  /**
@@ -121,7 +138,7 @@ function loadPersona() {
121
138
  .slice(1)
122
139
  .join("\n---\n")
123
140
  : raw;
124
- personaCache = { text: body.trim() || DEFAULT_PERSONA, stamp };
141
+ personaCache = { text: stripSealedSections(body) || DEFAULT_PERSONA, stamp };
125
142
  return personaCache.text;
126
143
  } catch {
127
144
  return DEFAULT_PERSONA;
@@ -142,13 +159,17 @@ function nowLabel() {
142
159
 
143
160
  function botLangDirective() {
144
161
  const botLang = settings.get("bot_language") || "auto";
162
+ // The dialect rule lives here on purpose, not in the persona: the operator
163
+ // owns src/config/ai-persona.md and can rewrite every line of it, and this
164
+ // one must survive every edit (Levix users worldwide; Levix is built in
165
+ // Egypt, and Egyptian dialect in should mean Egyptian dialect out).
145
166
  if (botLang === "ar") {
146
- return "- Language instruction: Always reply in Modern Standard Arabic (العربية الفصحى), clear, professional, and well-phrased.";
167
+ return "- Language instruction: Always reply in Arabic. Match the dialect the user writes in: Egyptian Arabic gets natural Egyptian Arabic back; formal Arabic or any other Arabic dialect gets clear, natural Arabic matching the user's.";
147
168
  }
148
169
  if (botLang === "en") {
149
170
  return "- Language instruction: Always reply in English, clear, professional, natural, and direct.";
150
171
  }
151
- return "- Language instruction: Automatically reply in the language the user writes in (Modern Standard Arabic if Arabic, English if English).";
172
+ return "- Language instruction: Reply in the language and dialect the user writes in. Egyptian Arabic gets natural Egyptian Arabic back; formal Arabic or other Arabic dialects get clear, natural Arabic matching the user; English gets English; any other language gets that language.";
152
173
  }
153
174
 
154
175
  /**
@@ -658,6 +679,7 @@ module.exports = {
658
679
  GOOGLE_SEARCH_TOOL,
659
680
  buildSystemInstruction,
660
681
  loadPersona,
682
+ stripSealedSections,
661
683
  isAgentEnabled,
662
684
  activeProviderKeySetting,
663
685
  isFileReferenceError,