levix-bot 4.9.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -0,0 +1,172 @@
1
+ // Panel routes for Levix Plus. Mounted by the panel bootstrap under
2
+ // `/dashboard/api`. Responses carry state only: no token, installation id,
3
+ // sequence, or purchase token.
4
+
5
+ import { Router } from "express";
6
+ import { createRequire } from "node:module";
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const { TRUSTED_KEYS } = require("../extensions/entitlement/keys.cjs");
10
+ const { validateClaimBody } = require("../extensions/entitlement/client.cjs");
11
+
12
+ const CLAIM_BODY_MAX = 4096;
13
+ const REFRESH_INTERVAL_MS = 30_000;
14
+ const STATES = new Set([
15
+ "none",
16
+ "active",
17
+ "grace",
18
+ "canceled",
19
+ "inactive",
20
+ "expired",
21
+ "clock",
22
+ "unverified",
23
+ ]);
24
+ const UNTIL_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
25
+ const REASON_RE = /^[a-z0-9_]{1,32}$/;
26
+ const INSTALLATION_RE = /^[A-Za-z0-9_-]{43}$/;
27
+ const CODE_RE = /^[A-Z0-9_]{1,64}$/;
28
+
29
+ function pickStatus(value) {
30
+ const state = STATES.has(value?.state) ? value.state : "none";
31
+ const until = typeof value?.until === "string" && UNTIL_RE.test(value.until) ? value.until : null;
32
+ const reason =
33
+ typeof value?.reason === "string" && REASON_RE.test(value.reason) ? value.reason : null;
34
+ return { state, until, reason };
35
+ }
36
+
37
+ function readStatus(entitlement) {
38
+ try {
39
+ return pickStatus(entitlement.status());
40
+ } catch {
41
+ return { state: "unverified", until: null, reason: null };
42
+ }
43
+ }
44
+
45
+ function publicResult(result, entitlement) {
46
+ const body = {
47
+ ok: result?.ok === true,
48
+ entitlement: pickStatus(result?.entitlement ?? readStatus(entitlement)),
49
+ };
50
+ if (!body.ok && typeof result?.code === "string" && CODE_RE.test(result.code))
51
+ body.code = result.code;
52
+ if (
53
+ Number.isSafeInteger(result?.retryAfter) &&
54
+ result.retryAfter >= 0 &&
55
+ result.retryAfter <= 86400
56
+ ) {
57
+ body.retryAfter = result.retryAfter;
58
+ }
59
+ return body;
60
+ }
61
+
62
+ function claimTooLarge(req) {
63
+ const header = req.headers?.["content-length"];
64
+ if (header != null && /^\d+$/.test(String(header).trim()) && Number(header) > CLAIM_BODY_MAX)
65
+ return true;
66
+ if (req.body == null) return false;
67
+ try {
68
+ return Buffer.byteLength(JSON.stringify(req.body)) > CLAIM_BODY_MAX;
69
+ } catch {
70
+ return true;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * @param {{ entitlement: object, extensionStatus?: () => unknown, keys?: Array<unknown>, now?: () => number, clock?: () => number }} options
76
+ */
77
+ export function createPlusRouter(options = {}) {
78
+ const { entitlement, extensionStatus = () => ({ state: "absent" }), keys } = options;
79
+ const now = options.now ?? options.clock ?? (() => Date.now());
80
+ if (!entitlement || typeof extensionStatus !== "function") {
81
+ throw new Error("createPlusRouter requires entitlement and extensionStatus");
82
+ }
83
+ const router = Router();
84
+ let lastRefreshAt = null;
85
+
86
+ function isConfigured() {
87
+ if (Array.isArray(keys)) return keys.length > 0;
88
+ if (typeof entitlement.isConfigured === "function") return Boolean(entitlement.isConfigured());
89
+ return TRUSTED_KEYS.length > 0;
90
+ }
91
+
92
+ router.get("/plus/status", (_req, res) => {
93
+ try {
94
+ return res.json({
95
+ configured: isConfigured(),
96
+ entitlement: readStatus(entitlement),
97
+ extension: extensionStatus(),
98
+ });
99
+ } catch {
100
+ return res.status(500).json({ ok: false, code: "UNAVAILABLE" });
101
+ }
102
+ });
103
+
104
+ router.post("/plus/prepare", async (_req, res) => {
105
+ try {
106
+ const result = await entitlement.prepare();
107
+ if (
108
+ typeof result?.installationId !== "string" ||
109
+ !INSTALLATION_RE.test(result.installationId)
110
+ ) {
111
+ return res.status(500).json({ ok: false, code: "UNAVAILABLE" });
112
+ }
113
+ return res.json({ installationId: result.installationId });
114
+ } catch {
115
+ return res.status(500).json({ ok: false, code: "UNAVAILABLE" });
116
+ }
117
+ });
118
+
119
+ router.post("/plus/claim", async (req, res) => {
120
+ const entitlementStatus = readStatus(entitlement);
121
+ if (claimTooLarge(req)) {
122
+ return res
123
+ .status(413)
124
+ .json({ ok: false, code: "BAD_REQUEST", entitlement: entitlementStatus });
125
+ }
126
+ if (!validateClaimBody(req.body)) {
127
+ return res
128
+ .status(400)
129
+ .json({ ok: false, code: "BAD_REQUEST", entitlement: entitlementStatus });
130
+ }
131
+ try {
132
+ const result = await entitlement.claim({
133
+ purchaseToken: req.body.purchaseToken,
134
+ productId: req.body.productId,
135
+ packageName: req.body.packageName,
136
+ });
137
+ return res.status(200).json(publicResult(result, entitlement));
138
+ } catch {
139
+ return res
140
+ .status(500)
141
+ .json({ ok: false, code: "UNAVAILABLE", entitlement: entitlementStatus });
142
+ }
143
+ });
144
+
145
+ router.post("/plus/refresh", async (_req, res) => {
146
+ const current = now();
147
+ if (lastRefreshAt != null && current - lastRefreshAt < REFRESH_INTERVAL_MS) {
148
+ const retryAfter = Math.max(
149
+ 1,
150
+ Math.ceil((REFRESH_INTERVAL_MS - (current - lastRefreshAt)) / 1000),
151
+ );
152
+ res.set("Retry-After", String(retryAfter));
153
+ return res.status(429).json({
154
+ ok: false,
155
+ code: "RATE_LIMITED",
156
+ retryAfter,
157
+ entitlement: readStatus(entitlement),
158
+ });
159
+ }
160
+ lastRefreshAt = current;
161
+ try {
162
+ const result = await entitlement.refresh({ force: true });
163
+ return res.status(200).json(publicResult(result, entitlement));
164
+ } catch {
165
+ return res
166
+ .status(500)
167
+ .json({ ok: false, code: "UNAVAILABLE", entitlement: readStatus(entitlement) });
168
+ }
169
+ });
170
+
171
+ return router;
172
+ }
@@ -0,0 +1,60 @@
1
+ import { createRequire } from "node:module";
2
+ import { Router } from "express";
3
+ import * as manage from "../automation/manage.js";
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const logger = require("../utils/logger.cjs");
7
+ const router = Router();
8
+ export const setSession = manage.setSession;
9
+
10
+ function route(handler, status = 200) {
11
+ return (req, res) => {
12
+ try {
13
+ res.status(status).json({ success: true, ...handler(req) });
14
+ } catch (error) {
15
+ if (error instanceof manage.ReactionManageError) {
16
+ return res.status(error.status).json({
17
+ success: false,
18
+ error: error.code,
19
+ ...(error.issues ? { issues: error.issues } : {}),
20
+ });
21
+ }
22
+ logger.error({ err: error }, "[Reactions] management failed");
23
+ res.status(500).json({ success: false, error: "INTERNAL" });
24
+ }
25
+ };
26
+ }
27
+
28
+ router.get(
29
+ "/reactions",
30
+ route(() => manage.overview()),
31
+ );
32
+ router.post(
33
+ "/reactions/rules/check",
34
+ route((req) => manage.checkDraft(req.body)),
35
+ );
36
+ router.post(
37
+ "/reactions/rules",
38
+ route((req) => ({ rule: manage.createRule(req.body) }), 201),
39
+ );
40
+ router.put(
41
+ "/reactions/rules/:id",
42
+ route((req) => ({ rule: manage.updateRule(req.params.id, req.body) })),
43
+ );
44
+ router.post(
45
+ "/reactions/rules/:id/enabled",
46
+ route((req) => ({ rule: manage.setRuleEnabled(req.params.id, req.body) })),
47
+ );
48
+ router.delete(
49
+ "/reactions/rules/:id",
50
+ route((req) => {
51
+ manage.deleteRule(req.params.id, req.query.revision);
52
+ return {};
53
+ }),
54
+ );
55
+ router.put(
56
+ "/reactions/automation",
57
+ route((req) => ({ automation: manage.setAutomation(req.body) })),
58
+ );
59
+
60
+ export default router;
@@ -15,6 +15,7 @@
15
15
 
16
16
  const fs = require("fs");
17
17
  const { GoogleGenAI, FunctionCallingConfigMode } = require("@google/genai");
18
+ const { geminiHttpOptions } = require("../utils/geminiHttpOptions.cjs");
18
19
 
19
20
  const logger = require("../utils/logger.cjs");
20
21
  const {
@@ -23,15 +24,14 @@ const {
23
24
  downloadMedia,
24
25
  geminiMediaPart,
25
26
  } = require("../utils/geminiMedia.cjs");
26
- const { tr } = require("../utils/i18n.cjs");
27
+ const { t } = require("../utils/i18n.cjs");
27
28
  const aiIdentity = require("../config/ai-identity.cjs");
28
29
  const settings = require("../config/settings.cjs");
29
30
  const memory = require("../utils/memory.cjs");
30
- const {
31
- assertProviderBaseUrl,
32
- assertProviderRequestUrl,
33
- } = require("../utils/providerUrl.cjs");
34
- const { toolDeclarations, describeCall, runTool } = require("./aiTools.cjs");
31
+ const { globalMemoryAccess } = require("./memoryPolicy.cjs");
32
+ const { assertProviderBaseUrl, assertProviderRequestUrl } = require("../utils/providerUrl.cjs");
33
+ const { toolDeclarations, describeCall, runToolWithDeadline } = require("./aiTools.cjs");
34
+ const { docSourcesFromTool } = require("./aiDocs.cjs");
35
35
  const {
36
36
  BaseAIProvider,
37
37
  registerProvider,
@@ -65,7 +65,7 @@ function geminiClient() {
65
65
  clientCache = {
66
66
  key,
67
67
  baseUrl,
68
- client: new GoogleGenAI({ apiKey: key, httpOptions: { baseUrl } }),
68
+ client: new GoogleGenAI({ apiKey: key, apiVersion: "v1beta", httpOptions: geminiHttpOptions(baseUrl) }),
69
69
  };
70
70
  }
71
71
  return clientCache.client;
@@ -99,7 +99,14 @@ use your tools instead of guessing when something needs to be looked up.`;
99
99
  // A copy of ai-persona.md from before that split still carries them, and an
100
100
  // operator can type one back in: both are dropped here, so the rules are stated
101
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"]);
102
+ const SEALED_HEADINGS = new Set([
103
+ "tools",
104
+ "levix help",
105
+ "media",
106
+ "memory",
107
+ "chats and groups",
108
+ "boundaries",
109
+ ]);
103
110
 
104
111
  function stripSealedSections(text) {
105
112
  const kept = [];
@@ -158,7 +165,10 @@ function nowLabel() {
158
165
  }
159
166
 
160
167
  function botLangDirective() {
161
- const botLang = settings.get("bot_language") || "auto";
168
+ const aiLang = settings.get("ai_reply_language");
169
+ const botLang = ["auto", "ar", "en", "pt-BR", "es-419"].includes(aiLang)
170
+ ? aiLang
171
+ : settings.get("bot_language") || "auto";
162
172
  // The dialect rule lives here on purpose, not in the persona: the operator
163
173
  // owns src/config/ai-persona.md and can rewrite every line of it, and this
164
174
  // one must survive every edit (Levix users worldwide; Levix is built in
@@ -169,6 +179,12 @@ function botLangDirective() {
169
179
  if (botLang === "en") {
170
180
  return "- Language instruction: Always reply in English, clear, professional, natural, and direct.";
171
181
  }
182
+ if (botLang === "pt-BR") {
183
+ return "- Language instruction: Always reply in Brazilian Portuguese, clear, natural, and direct.";
184
+ }
185
+ if (botLang === "es-419") {
186
+ return "- Language instruction: Always reply in Latin American Spanish, clear, natural, and direct.";
187
+ }
172
188
  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.";
173
189
  }
174
190
 
@@ -195,7 +211,9 @@ function buildSystemInstruction(context = {}) {
195
211
  botLangDirective(),
196
212
  ].join("\n");
197
213
 
198
- const memoryBlock = memory.buildMemoryContext(chatId);
214
+ const memoryBlock = memory.buildMemoryContext(chatId, {
215
+ includeGlobal: globalMemoryAccess(context).read,
216
+ });
199
217
 
200
218
  return [aiIdentity.systemBlock, loadPersona(), runtime, memoryBlock].filter(Boolean).join("\n\n");
201
219
  }
@@ -218,6 +236,10 @@ function trimHistory(history) {
218
236
  const out = Array.isArray(history) ? [...history] : [];
219
237
  while (out.length > maxEntries) out.shift();
220
238
  while (out.length && !isOpeningTurn(out[0])) out.shift();
239
+ // A budget-exhausted model call has no response. Drop the whole turn so
240
+ // retained parts (including Gemini thought signatures) remain untouched.
241
+ while (out.at(-1)?.role === "model" && out.at(-1).parts?.some((part) => part?.functionCall))
242
+ out.pop();
221
243
  return out;
222
244
  }
223
245
 
@@ -259,27 +281,6 @@ function sanitizeHistoryForFiles(history) {
259
281
  .filter(Boolean);
260
282
  }
261
283
 
262
- function withTimeout(promise, ms, label) {
263
- let timer;
264
- return Promise.race([
265
- promise,
266
- new Promise((_, reject) => {
267
- timer = setTimeout(
268
- () =>
269
- reject(
270
- new Error(
271
- tr(
272
- `${label} took longer than ${Math.round(ms / 1000)} seconds`,
273
- `${label} تأخرت أكتر من ${Math.round(ms / 1000)} ثانية`,
274
- ),
275
- ),
276
- ),
277
- ms,
278
- );
279
- }),
280
- ]).finally(() => clearTimeout(timer));
281
- }
282
-
283
284
  function isAgentEnabled() {
284
285
  // The key that matters is the active provider's: a panel switch from gemini
285
286
  // to openai must not keep the agent gated on (or running on) a Gemini key.
@@ -413,14 +414,25 @@ const MAX_SOURCES = 5;
413
414
  function formatSources(sources) {
414
415
  const seen = new Set();
415
416
  const lines = [];
416
- for (const source of sources || []) {
417
+ const ordered = [
418
+ ...(sources || []).filter((source) => source?.kind === "levix-doc"),
419
+ ...(sources || []).filter((source) => source?.kind !== "levix-doc"),
420
+ ];
421
+ for (const source of ordered) {
422
+ if (source?.kind === "levix-doc") {
423
+ if (seen.has(source.id)) continue;
424
+ seen.add(source.id);
425
+ lines.push(`• ${source.citation}`);
426
+ if (lines.length >= MAX_SOURCES) break;
427
+ continue;
428
+ }
417
429
  if (!source?.uri || seen.has(source.uri)) continue;
418
430
  seen.add(source.uri);
419
431
  const label = String(source.title || hostOf(source.uri) || "source").trim();
420
432
  lines.push(`• ${label} — ${source.uri}`);
421
433
  if (lines.length >= MAX_SOURCES) break;
422
434
  }
423
- return lines.length ? `\n\n${tr("*Sources:*", "*المصادر:*")}\n${lines.join("\n")}` : "";
435
+ return lines.length ? `\n\n${t("bot.ai.aiAgent.sources")}\n${lines.join("\n")}` : "";
424
436
  }
425
437
 
426
438
  /**
@@ -521,9 +533,10 @@ async function runGeminiTurn({
521
533
  maxSteps = null,
522
534
  systemInstruction = null,
523
535
  search = null,
536
+ signal,
524
537
  } = {}) {
525
538
  const genAI = geminiClient();
526
- if (!genAI) throw new Error(tr("No Gemini API key is set", "لم يُضبط مفتاح Gemini API"));
539
+ if (!genAI) throw new Error(t("bot.ai.aiAgent.noGeminiKey"));
527
540
  await assertProviderRequestUrl(settings.get("gemini_base_url"), { allowLoopback: true });
528
541
 
529
542
  const stepBudget = maxSteps ?? settings.get("ai_max_tool_steps");
@@ -546,6 +559,7 @@ async function runGeminiTurn({
546
559
  history: trimmed,
547
560
  config: {
548
561
  systemInstruction: instruction,
562
+ ...(signal ? { abortSignal: signal } : {}),
549
563
  ...(tools.length ? { tools } : {}),
550
564
  ...(toolConfig ? { toolConfig } : {}),
551
565
  },
@@ -598,20 +612,22 @@ async function runGeminiTurn({
598
612
  const responses = [];
599
613
  for (const call of calls) {
600
614
  toolCalls.push({ name: call.name, args: call.args });
601
- logger.info({ tool: call.name, chatId: context.chatId }, "[aiAgent] tool call");
615
+ logger.info({ tool: call.name }, "[aiAgent] tool call");
602
616
 
603
617
  // Named apart from the outer `response` on purpose: that one is the
604
618
  // model's reply and is reassigned at the bottom of this loop.
605
619
  let toolResult;
606
620
  try {
607
- toolResult = await withTimeout(
608
- runTool(call.name, call.args, context),
609
- settings.get("ai_tool_timeout_ms"),
621
+ toolResult = await runToolWithDeadline(
610
622
  call.name,
623
+ call.args,
624
+ context,
625
+ settings.get("ai_tool_timeout_ms"),
611
626
  );
612
627
  } catch (err) {
613
628
  toolResult = { error: err?.message || String(err) };
614
629
  }
630
+ sources.push(...docSourcesFromTool(call.name, toolResult));
615
631
  responses.push({
616
632
  functionResponse: {
617
633
  // Echoed back when the model supplied one: with several calls in a
@@ -623,7 +639,7 @@ async function runGeminiTurn({
623
639
  });
624
640
  }
625
641
 
626
- if (status) await status.update(tr("🤖 Writing the answer...", "🤖 بجهّز الرد..."));
642
+ if (status) await status.update(t("bot.ai.aiAgent.writingAnswer"));
627
643
  // One message carrying every functionResponse part, which is what the API
628
644
  // expects when the model asked for several calls in one turn.
629
645
  response = await chat.sendMessage({ message: responses });
@@ -641,10 +657,7 @@ async function runGeminiTurn({
641
657
  }
642
658
 
643
659
  if (!text && steps >= stepBudget) {
644
- text = tr(
645
- "I ran the tools I have but couldn't reach a final answer. Try asking more clearly.",
646
- "استخدمت الأدوات المتاحة، لكنني لم أتمكن من الوصول إلى إجابة نهائية. حاول صياغة السؤال بوضوح أكبر.",
647
- );
660
+ text = t("bot.ai.aiAgent.toolBudget");
648
661
  }
649
662
 
650
663
  let newHistory = [];
@@ -0,0 +1,187 @@
1
+ // A literal JSON require also embeds the index in SEA. No user-supplied paths.
2
+ const index = require("./levix-docs.generated.json");
3
+ const version = require("../../package.json").version;
4
+ const LANGUAGES = ["en", "ar", "pt-BR", "es-419"];
5
+ const SOURCES = [
6
+ "README.md",
7
+ "SETUP.md",
8
+ "ANDROID.md",
9
+ "PRIVACY.md",
10
+ ...LANGUAGES.map((language) => `i18n/${language}/commands.json`),
11
+ ];
12
+ const MAX_SECTION_CHARS = 4000;
13
+
14
+ function validateIndex(value, expectedVersion = version) {
15
+ if (!value || value.schema !== 1 || value.version !== expectedVersion)
16
+ throw new Error("Bundled documentation is unavailable for this release");
17
+ if (
18
+ !Array.isArray(value.sources) ||
19
+ value.sources.length !== SOURCES.length ||
20
+ new Set(value.sources.map((source) => source.file)).size !== SOURCES.length ||
21
+ value.sources.some(
22
+ (source) => !SOURCES.includes(source.file) || !/^[a-f0-9]{64}$/.test(source.sha256),
23
+ ) ||
24
+ !Array.isArray(value.sections) ||
25
+ !value.sections.length ||
26
+ value.sections.length > 2000 ||
27
+ Buffer.byteLength(JSON.stringify(value)) > 1024 * 1024
28
+ )
29
+ throw new Error("Invalid bundled documentation index");
30
+ const ids = new Set();
31
+ for (const section of value.sections) {
32
+ const locale =
33
+ typeof section.source === "string" && section.source.startsWith("i18n/")
34
+ ? section.source.split("/")[1]
35
+ : "en";
36
+ if (
37
+ !SOURCES.includes(section.source) ||
38
+ section.locale !== locale ||
39
+ typeof section.id !== "string" ||
40
+ section.id.length > 240 ||
41
+ !section.id.startsWith(`${section.source}#`) ||
42
+ ids.has(section.id) ||
43
+ typeof section.title !== "string" ||
44
+ section.title.length > 160 ||
45
+ typeof section.text !== "string" ||
46
+ !section.text ||
47
+ section.text.length > MAX_SECTION_CHARS
48
+ )
49
+ throw new Error("Invalid bundled documentation section");
50
+ ids.add(section.id);
51
+ }
52
+ return value;
53
+ }
54
+
55
+ function normalize(value) {
56
+ return value.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().replace(/[أإآ]/g, "ا");
57
+ }
58
+
59
+ // Lexical bridges for English prose; the command reference is localized.
60
+ const TOPICS = [
61
+ [
62
+ "backup restore",
63
+ "backup",
64
+ "restore",
65
+ "احتياط",
66
+ "نسخة",
67
+ "نسخه",
68
+ "استعاد",
69
+ "restaur",
70
+ "copia",
71
+ "seguridad",
72
+ ],
73
+ [
74
+ "password recovery reset",
75
+ "password",
76
+ "كلمة المرور",
77
+ "كلمه المرور",
78
+ "senha",
79
+ "contrasena",
80
+ "recuper",
81
+ ],
82
+ ["proxy whatsapp", "proxy", "بروكسي", "وكيل"],
83
+ ["battery background", "battery", "بطاري", "الخلفية", "الخلفيه", "bateria", "segundo plano"],
84
+ ["setup install", "setup", "install", "تثبيت", "اعداد", "instal", "configur"],
85
+ ["language", "language", "لغة", "لغه", "idioma", "lingua"],
86
+ ["permission roles", "permission", "صلاح", "اذن", "permis", "funcao"],
87
+ ["terms consent", "consent", "terms", "شروط", "موافق", "termos", "terminos", "consentim"],
88
+ ["privacy", "privacy", "خصوص", "privacidade", "privacidad"],
89
+ ["sticker", "sticker", "ملصق", "figurinha", "pegatina"],
90
+ ["transcribe voice speech", "transcri", "تفريغ", "صوت", "voz", "audio"],
91
+ ];
92
+ const STOP = new Set(
93
+ "how do i a an the to is are can does have levix me my this what about please como de la el en un una que eu o os as e y هل كيف ما من في على عن اعمل هذا".split(
94
+ " ",
95
+ ),
96
+ );
97
+
98
+ function metadata(section, requestedLanguage) {
99
+ return {
100
+ id: section.id,
101
+ source: section.source,
102
+ title: section.title,
103
+ version,
104
+ locale: section.locale,
105
+ requestedLanguage,
106
+ fallback: section.locale !== requestedLanguage,
107
+ citation: `${section.source} § ${section.title} (Levix ${version}, ${section.locale})`,
108
+ };
109
+ }
110
+
111
+ function searchDocs({ query, language = "en", limit = 3 } = {}) {
112
+ validateIndex(index);
113
+ if (
114
+ typeof query !== "string" ||
115
+ !query.trim() ||
116
+ query.length > 300 ||
117
+ !Number.isInteger(limit) ||
118
+ limit < 1 ||
119
+ limit > 5 ||
120
+ typeof language !== "string"
121
+ )
122
+ throw new Error("Docs search requires a query of 1–300 characters and limit 1–5");
123
+ const requested = LANGUAGES.includes(language) ? language : "en";
124
+ const normalized = normalize(query);
125
+ const terms = new Set(
126
+ normalized.split(/[^\p{L}\p{N}]+/u).filter((word) => word.length > 1 && !STOP.has(word)),
127
+ );
128
+ for (const [expansion, ...matches] of TOPICS) {
129
+ if (matches.some((match) => normalized.includes(normalize(match))))
130
+ for (const word of expansion.split(" ")) terms.add(word);
131
+ }
132
+ const ranked = [];
133
+ for (const section of index.sections) {
134
+ if (section.locale !== requested && section.locale !== "en") continue;
135
+ const title = normalize(section.title);
136
+ const text = normalize(section.text);
137
+ let score = 0;
138
+ for (const term of terms) score += title.includes(term) ? 6 : text.includes(term) ? 1 : 0;
139
+ if (score) ranked.push({ section, score: score + (section.locale === requested ? 2 : 0) });
140
+ }
141
+ ranked.sort((a, b) => b.score - a.score || a.section.id.localeCompare(b.section.id, "en"));
142
+ const seen = new Set();
143
+ const results = [];
144
+ for (const { section } of ranked) {
145
+ const key = section.source.startsWith("i18n/") ? section.title : section.id;
146
+ if (seen.has(key)) continue;
147
+ seen.add(key);
148
+ results.push({ ...metadata(section, requested), excerpt: section.text.slice(0, 450) });
149
+ if (results.length >= limit) break;
150
+ }
151
+ return { version, untrustedData: true, results };
152
+ }
153
+
154
+ function openDocSection({ id } = {}) {
155
+ validateIndex(index);
156
+ if (typeof id !== "string" || id.length > 240)
157
+ throw new Error("A documentation section ID is required");
158
+ const section = index.sections.find((item) => item.id === id);
159
+ if (!section) throw new Error("Section not found in this release's bundled documentation");
160
+ return { ...metadata(section, section.locale), untrustedData: true, text: section.text };
161
+ }
162
+
163
+ // Cite only IDs that exist in the bundled index, never a model-supplied URL or title.
164
+ function docSourcesFromTool(name, result) {
165
+ if (result?.error || result?.version !== version) return [];
166
+ const ids =
167
+ name === "search_levix_docs"
168
+ ? result.results?.map((item) => item.id)
169
+ : name === "open_levix_doc_section"
170
+ ? [result.id]
171
+ : [];
172
+ if (!Array.isArray(ids)) return [];
173
+ return ids.slice(0, 5).flatMap((id) => {
174
+ const section = index.sections.find((item) => item.id === id);
175
+ return section
176
+ ? [{ kind: "levix-doc", id, citation: metadata(section, section.locale).citation }]
177
+ : [];
178
+ });
179
+ }
180
+
181
+ module.exports = {
182
+ searchDocs,
183
+ openDocSection,
184
+ validateIndex,
185
+ docSourcesFromTool,
186
+ MAX_SECTION_CHARS,
187
+ };