@resolveio/server-lib 22.3.124 → 22.3.126

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 (711) hide show
  1. package/.nodemon.json +5 -0
  2. package/.vscode/settings.json +21 -0
  3. package/AGENTS.md +195 -0
  4. package/README.md +22 -0
  5. package/build_package.sh +5 -0
  6. package/compileDTS.pl +64 -0
  7. package/docs/ai-assistant-nightly-eval.md +65 -0
  8. package/docs/ai-assistant-preflight-checklist.md +23 -0
  9. package/docs/ai-assistant-report-builder-bridge-playbook.md +115 -0
  10. package/eslint-plugin-custom/index.js +7 -0
  11. package/eslint-plugin-custom/rules/no-filter-zero-index.js +44 -0
  12. package/eslint.config.js +103 -0
  13. package/gulpfile.js +216 -0
  14. package/methodAndPublicationListGenerator.py +375 -0
  15. package/mongodbensurers.js +2 -0
  16. package/mongostop.js +3 -0
  17. package/package.json +3 -1
  18. package/scripts/cleanup-bypassed-callmethod-logs.js +616 -0
  19. package/settings.development.json +25 -0
  20. package/settings.development.redacted.json +25 -0
  21. package/src/.env +12 -0
  22. package/src/ai/assistant-core-heuristics.ts +379 -0
  23. package/src/ai/resolveio-platform-intelligence-memory-corpus.ts +185 -0
  24. package/src/ai/resolveio-platform-intelligence-memory.ts +325 -0
  25. package/{ai/resolveio-platform-intelligence-types.d.ts → src/ai/resolveio-platform-intelligence-types.ts} +20 -15
  26. package/src/ai/resolveio-platform-intelligence.ts +462 -0
  27. package/src/client-server-app.ts +12 -0
  28. package/src/collections/ai-run.collection.ts +117 -0
  29. package/src/collections/ai-terminal-conversation.collection.ts +91 -0
  30. package/src/collections/ai-terminal-issue-report.collection.ts +99 -0
  31. package/src/collections/ai-terminal-message.collection.ts +77 -0
  32. package/src/collections/app-setting.collection.ts +104 -0
  33. package/src/collections/app-status.collection.ts +58 -0
  34. package/src/collections/communication-metric.collection.ts +84 -0
  35. package/src/collections/counter.collection.ts +56 -0
  36. package/src/collections/cron-job-history.collection.ts +94 -0
  37. package/src/collections/cron-job.collection.ts +92 -0
  38. package/src/collections/customer-notification.collection.ts +131 -0
  39. package/src/collections/customer-portal-password.collection.ts +76 -0
  40. package/src/collections/email-history.collection.ts +134 -0
  41. package/src/collections/email-verified.collection.ts +62 -0
  42. package/src/collections/file.collection.ts +74 -0
  43. package/src/collections/flag-update.collection.ts +57 -0
  44. package/src/collections/flag.collection.ts +57 -0
  45. package/src/collections/log-method-latency.collection.ts +77 -0
  46. package/src/collections/log-subscription.collection.ts +80 -0
  47. package/src/collections/log.collection.ts +93 -0
  48. package/src/collections/logged-in-users.collection.ts +67 -0
  49. package/src/collections/monitor-cpu.collection.ts +65 -0
  50. package/src/collections/monitor-function.collection.ts +74 -0
  51. package/src/collections/monitor-memory.collection.ts +77 -0
  52. package/src/collections/monitor-mongo.collection.ts +71 -0
  53. package/src/collections/notification.collection.ts +57 -0
  54. package/src/collections/openai-usage-ledger.collection.ts +77 -0
  55. package/src/collections/report-builder-dashboard-builder.collection.ts +109 -0
  56. package/src/collections/report-builder-library.collection.ts +89 -0
  57. package/src/collections/report-builder-report.collection.ts +184 -0
  58. package/src/collections/user-group.collection.ts +89 -0
  59. package/src/collections/user-guide.collection.ts +57 -0
  60. package/src/collections/user.collection.ts +181 -0
  61. package/src/cron/cron.ts +117 -0
  62. package/src/fixtures/cron-jobs.ts +95 -0
  63. package/src/fixtures/init.ts +35 -0
  64. package/src/http/auth.ts +818 -0
  65. package/src/http/health.ts +7 -0
  66. package/src/http/home.ts +90 -0
  67. package/src/http/slow-query-publication.ts +49 -0
  68. package/src/index.ts +1 -0
  69. package/src/managers/ai-assistant-codex-manager.manager.ts +1131 -0
  70. package/src/managers/ai-run-evidence.manager.ts +264 -0
  71. package/src/managers/communication-metric.manager.ts +82 -0
  72. package/src/managers/cron.manager.ts +333 -0
  73. package/src/managers/customer-notification-content.manager.ts +236 -0
  74. package/src/managers/diagnostic-manager-bootstrap.ts +165 -0
  75. package/src/managers/error-auto-fix.manager.ts +2767 -0
  76. package/src/managers/local-log.manager.ts +113 -0
  77. package/src/managers/method.manager.ts +1857 -0
  78. package/src/managers/mongo.manager.ts +4575 -0
  79. package/src/managers/monitor.manager.ts +507 -0
  80. package/src/managers/openai-usage-ledger.manager.ts +57 -0
  81. package/src/managers/slow-query-verifier.manager.ts +3590 -0
  82. package/src/managers/slow-query.manager.ts +519 -0
  83. package/src/managers/subscription.manager.ts +3128 -0
  84. package/src/managers/websocket.manager.ts +746 -0
  85. package/src/managers/worker-dispatcher.manager.ts +1360 -0
  86. package/src/managers/worker-server.manager.ts +536 -0
  87. package/src/methods/accounts.ts +532 -0
  88. package/src/methods/ai-terminal.ts +23497 -0
  89. package/src/methods/app-settings.ts +114 -0
  90. package/src/methods/aws.ts +649 -0
  91. package/src/methods/collections.ts +641 -0
  92. package/src/methods/counters.ts +69 -0
  93. package/src/methods/cron-jobs.ts +2614 -0
  94. package/src/methods/customer-notifications.ts +458 -0
  95. package/src/methods/diagnostics.ts +616 -0
  96. package/src/methods/flag-updates.ts +7 -0
  97. package/src/methods/flags.ts +7 -0
  98. package/src/methods/logs.ts +657 -0
  99. package/src/methods/mongo-explorer.ts +1880 -0
  100. package/src/methods/monitor.ts +540 -0
  101. package/src/methods/pdf.ts +1236 -0
  102. package/src/methods/publications.ts +129 -0
  103. package/src/methods/report-builder.ts +3300 -0
  104. package/src/methods/support.ts +335 -0
  105. package/src/models/ai-run.model.ts +27 -0
  106. package/src/models/ai-terminal-conversation.model.ts +19 -0
  107. package/src/models/ai-terminal-issue-report.model.ts +21 -0
  108. package/src/models/ai-terminal-message.model.ts +24 -0
  109. package/src/models/app-setting.model.ts +17 -0
  110. package/{models/app-status.model.d.ts → src/models/app-status.model.ts} +3 -2
  111. package/{models/billing-logged-in-users.model.d.ts → src/models/billing-logged-in-users.model.ts} +5 -4
  112. package/src/models/collection-document.model.ts +24 -0
  113. package/src/models/communication-metric.model.ts +23 -0
  114. package/{models/counter.model.d.ts → src/models/counter.model.ts} +4 -3
  115. package/src/models/cron-job-history.model.ts +16 -0
  116. package/src/models/cron-job.model.ts +15 -0
  117. package/src/models/customer-notification.model.ts +28 -0
  118. package/src/models/customer-portal-password.model.ts +12 -0
  119. package/src/models/dialog.model.ts +25 -0
  120. package/{models/email-history.model.js → src/models/email-history.model.ts} +36 -4
  121. package/{models/email-verified.model.d.ts → src/models/email-verified.model.ts} +6 -5
  122. package/{models/file.model.d.ts → src/models/file.model.ts} +8 -7
  123. package/{models/flag-update.model.d.ts → src/models/flag-update.model.ts} +4 -3
  124. package/{models/flag.model.d.ts → src/models/flag.model.ts} +4 -3
  125. package/src/models/log-method-latency.model.ts +11 -0
  126. package/{models/log-subscription.model.d.ts → src/models/log-subscription.model.ts} +11 -9
  127. package/src/models/log.model.ts +19 -0
  128. package/{models/logged-in-users.model.d.ts → src/models/logged-in-users.model.ts} +6 -5
  129. package/{models/method-response.model.d.ts → src/models/method-response.model.ts} +7 -6
  130. package/src/models/method.model.ts +25 -0
  131. package/{models/monitor-cpu.model.d.ts → src/models/monitor-cpu.model.ts} +9 -7
  132. package/src/models/monitor-function.model.ts +16 -0
  133. package/src/models/monitor-memory.model.ts +17 -0
  134. package/src/models/monitor-mongo.model.ts +15 -0
  135. package/{models/notification.model.d.ts → src/models/notification.model.ts} +6 -4
  136. package/src/models/openai-usage-ledger.model.ts +16 -0
  137. package/src/models/pagination.model.ts +35 -0
  138. package/src/models/permission.model.ts +14 -0
  139. package/src/models/report-builder-dashboard-builder.model.ts +29 -0
  140. package/src/models/report-builder-library.model.ts +20 -0
  141. package/src/models/report-builder-report.model.ts +136 -0
  142. package/src/models/report-builder.model.ts +68 -0
  143. package/src/models/select-data-label.model.ts +9 -0
  144. package/src/models/server-message.model.ts +31 -0
  145. package/src/models/slow-query-report.model.ts +23 -0
  146. package/src/models/subscription.model.ts +73 -0
  147. package/src/models/support-ticket.model.ts +104 -0
  148. package/src/models/user-group.model.ts +24 -0
  149. package/{models/user-guide.model.d.ts → src/models/user-guide.model.ts} +5 -4
  150. package/src/models/user.model.ts +96 -0
  151. package/src/private/images/ResolveIO.png +0 -0
  152. package/{public_api.d.ts → src/public_api.ts} +7 -0
  153. package/src/publications/ai-terminal.ts +73 -0
  154. package/src/publications/app-settings.ts +25 -0
  155. package/src/publications/app-status.ts +13 -0
  156. package/src/publications/cron-jobs.ts +40 -0
  157. package/src/publications/customer-notifications.ts +101 -0
  158. package/src/publications/files.ts +33 -0
  159. package/src/publications/flags-update.ts +19 -0
  160. package/src/publications/flags.ts +19 -0
  161. package/src/publications/logs.ts +163 -0
  162. package/src/publications/notifications.ts +13 -0
  163. package/src/publications/report-builder-dashboard-builders.ts +39 -0
  164. package/src/publications/report-builder-libraries.ts +41 -0
  165. package/src/publications/report-builder-reports.ts +47 -0
  166. package/src/publications/super-admin.ts +13 -0
  167. package/src/publications/user-groups.ts +12 -0
  168. package/src/publications/user-guides.ts +12 -0
  169. package/src/resolveio-server-app.ts +617 -0
  170. package/src/server-app.ts +3354 -0
  171. package/src/services/codex-client.ts +1231 -0
  172. package/src/services/openai-client.ts +265 -0
  173. package/src/types/error-report.ts +26 -0
  174. package/src/types/js-tiktoken.d.ts +11 -0
  175. package/src/types/slow-query-report.ts +28 -0
  176. package/src/util/ai-qa-policy.ts +925 -0
  177. package/src/util/ai-run-evidence-adapters.ts +521 -0
  178. package/src/util/ai-run-evidence-dashboard.ts +271 -0
  179. package/src/util/ai-run-evidence-eval.ts +885 -0
  180. package/src/util/ai-run-evidence.ts +964 -0
  181. package/src/util/ai-runner-artifacts.ts +586 -0
  182. package/src/util/ai-runner-qa-auth.ts +821 -0
  183. package/src/util/ai-runner-qa-tools.ts +3045 -0
  184. package/src/util/aicoder-runner-v6.ts +526 -0
  185. package/src/util/common.ts +649 -0
  186. package/src/util/customer-portal-password.ts +183 -0
  187. package/src/util/error-reporter.ts +332 -0
  188. package/src/util/error-tracking.ts +79 -0
  189. package/src/util/openai-usage-cost.ts +114 -0
  190. package/src/util/report-builder-unwinds.ts +180 -0
  191. package/src/util/runner-process-janitor.ts +219 -0
  192. package/src/util/schema-report-builder.ts +448 -0
  193. package/src/util/slow-query-reporter.ts +216 -0
  194. package/src/util/subscription-dependency-context.ts +1096 -0
  195. package/src/util/support-runner-v5.ts +897 -0
  196. package/src/util/tokenizer.ts +38 -0
  197. package/src/workers/codex-runner.worker.ts +142 -0
  198. package/start_server.sh +5 -0
  199. package/tests/ai-assistant-corpus-build.ts +484 -0
  200. package/tests/ai-assistant-corpus-replay-e2e.ts +774 -0
  201. package/tests/ai-assistant-data-parity-e2e.ts +1989 -0
  202. package/tests/ai-assistant-eval-triage.ts +831 -0
  203. package/tests/ai-assistant-openai-e2e.ts +1061 -0
  204. package/tests/ai-assistant-openai-git-e2e.ts +155 -0
  205. package/tests/ai-assistant-preflight-matrix.ts +215 -0
  206. package/tests/ai-assistant-routing-eval.test.ts +560 -0
  207. package/tests/ai-assistant-snf-live-eval.ts +975 -0
  208. package/tests/ai-assistant-utils.test.ts +2968 -0
  209. package/tests/ai-run-eval.test.ts +88 -0
  210. package/tests/ai-run-evidence.test.ts +232 -0
  211. package/tests/ai-runner-contract.test.ts +488 -0
  212. package/tests/aicoder-runner-v6.test.ts +92 -0
  213. package/tests/error-reporter.test.ts +145 -0
  214. package/tests/method-publication-generator.test.ts +46 -0
  215. package/tests/report-builder-linking.test.ts +79 -0
  216. package/tests/resolveio-platform-intelligence.test.ts +352 -0
  217. package/tests/server-app-cron-owner.test.ts +127 -0
  218. package/tests/subscription-connect-race.test.ts +158 -0
  219. package/tests/subscription-dependency-context.test.ts +324 -0
  220. package/tests/subscription-manager-collection-tracking.test.ts +86 -0
  221. package/tests/subscription-manager-invalidation.test.ts +86 -0
  222. package/tests/support-runner-v5.test.ts +191 -0
  223. package/tsconfig.json +34 -0
  224. package/ai/assistant-core-heuristics.d.ts +0 -11
  225. package/ai/assistant-core-heuristics.js +0 -356
  226. package/ai/assistant-core-heuristics.js.map +0 -1
  227. package/ai/resolveio-platform-intelligence-memory-corpus.d.ts +0 -3
  228. package/ai/resolveio-platform-intelligence-memory-corpus.js +0 -214
  229. package/ai/resolveio-platform-intelligence-memory-corpus.js.map +0 -1
  230. package/ai/resolveio-platform-intelligence-memory.d.ts +0 -20
  231. package/ai/resolveio-platform-intelligence-memory.js +0 -341
  232. package/ai/resolveio-platform-intelligence-memory.js.map +0 -1
  233. package/ai/resolveio-platform-intelligence-types.js +0 -4
  234. package/ai/resolveio-platform-intelligence-types.js.map +0 -1
  235. package/ai/resolveio-platform-intelligence.d.ts +0 -6
  236. package/ai/resolveio-platform-intelligence.js +0 -463
  237. package/ai/resolveio-platform-intelligence.js.map +0 -1
  238. package/client-server-app.d.ts +0 -1
  239. package/client-server-app.js +0 -68
  240. package/client-server-app.js.map +0 -1
  241. package/collections/ai-terminal-conversation.collection.d.ts +0 -2
  242. package/collections/ai-terminal-conversation.collection.js +0 -140
  243. package/collections/ai-terminal-conversation.collection.js.map +0 -1
  244. package/collections/ai-terminal-issue-report.collection.d.ts +0 -2
  245. package/collections/ai-terminal-issue-report.collection.js +0 -148
  246. package/collections/ai-terminal-issue-report.collection.js.map +0 -1
  247. package/collections/ai-terminal-message.collection.d.ts +0 -2
  248. package/collections/ai-terminal-message.collection.js +0 -121
  249. package/collections/ai-terminal-message.collection.js.map +0 -1
  250. package/collections/app-setting.collection.d.ts +0 -3
  251. package/collections/app-setting.collection.js +0 -103
  252. package/collections/app-setting.collection.js.map +0 -1
  253. package/collections/app-status.collection.d.ts +0 -3
  254. package/collections/app-status.collection.js +0 -57
  255. package/collections/app-status.collection.js.map +0 -1
  256. package/collections/communication-metric.collection.d.ts +0 -2
  257. package/collections/communication-metric.collection.js +0 -133
  258. package/collections/communication-metric.collection.js.map +0 -1
  259. package/collections/counter.collection.d.ts +0 -3
  260. package/collections/counter.collection.js +0 -56
  261. package/collections/counter.collection.js.map +0 -1
  262. package/collections/cron-job-history.collection.d.ts +0 -3
  263. package/collections/cron-job-history.collection.js +0 -137
  264. package/collections/cron-job-history.collection.js.map +0 -1
  265. package/collections/cron-job.collection.d.ts +0 -3
  266. package/collections/cron-job.collection.js +0 -92
  267. package/collections/cron-job.collection.js.map +0 -1
  268. package/collections/customer-notification.collection.d.ts +0 -3
  269. package/collections/customer-notification.collection.js +0 -130
  270. package/collections/customer-notification.collection.js.map +0 -1
  271. package/collections/customer-portal-password.collection.d.ts +0 -3
  272. package/collections/customer-portal-password.collection.js +0 -75
  273. package/collections/customer-portal-password.collection.js.map +0 -1
  274. package/collections/email-history.collection.d.ts +0 -3
  275. package/collections/email-history.collection.js +0 -134
  276. package/collections/email-history.collection.js.map +0 -1
  277. package/collections/email-verified.collection.d.ts +0 -3
  278. package/collections/email-verified.collection.js +0 -62
  279. package/collections/email-verified.collection.js.map +0 -1
  280. package/collections/file.collection.d.ts +0 -3
  281. package/collections/file.collection.js +0 -74
  282. package/collections/file.collection.js.map +0 -1
  283. package/collections/flag-update.collection.d.ts +0 -3
  284. package/collections/flag-update.collection.js +0 -57
  285. package/collections/flag-update.collection.js.map +0 -1
  286. package/collections/flag.collection.d.ts +0 -3
  287. package/collections/flag.collection.js +0 -57
  288. package/collections/flag.collection.js.map +0 -1
  289. package/collections/log-method-latency.collection.d.ts +0 -3
  290. package/collections/log-method-latency.collection.js +0 -77
  291. package/collections/log-method-latency.collection.js.map +0 -1
  292. package/collections/log-subscription.collection.d.ts +0 -3
  293. package/collections/log-subscription.collection.js +0 -80
  294. package/collections/log-subscription.collection.js.map +0 -1
  295. package/collections/log.collection.d.ts +0 -3
  296. package/collections/log.collection.js +0 -93
  297. package/collections/log.collection.js.map +0 -1
  298. package/collections/logged-in-users.collection.d.ts +0 -3
  299. package/collections/logged-in-users.collection.js +0 -67
  300. package/collections/logged-in-users.collection.js.map +0 -1
  301. package/collections/monitor-cpu.collection.d.ts +0 -3
  302. package/collections/monitor-cpu.collection.js +0 -65
  303. package/collections/monitor-cpu.collection.js.map +0 -1
  304. package/collections/monitor-function.collection.d.ts +0 -3
  305. package/collections/monitor-function.collection.js +0 -74
  306. package/collections/monitor-function.collection.js.map +0 -1
  307. package/collections/monitor-memory.collection.d.ts +0 -3
  308. package/collections/monitor-memory.collection.js +0 -77
  309. package/collections/monitor-memory.collection.js.map +0 -1
  310. package/collections/monitor-mongo.collection.d.ts +0 -3
  311. package/collections/monitor-mongo.collection.js +0 -71
  312. package/collections/monitor-mongo.collection.js.map +0 -1
  313. package/collections/notification.collection.d.ts +0 -3
  314. package/collections/notification.collection.js +0 -57
  315. package/collections/notification.collection.js.map +0 -1
  316. package/collections/openai-usage-ledger.collection.d.ts +0 -2
  317. package/collections/openai-usage-ledger.collection.js +0 -124
  318. package/collections/openai-usage-ledger.collection.js.map +0 -1
  319. package/collections/report-builder-dashboard-builder.collection.d.ts +0 -3
  320. package/collections/report-builder-dashboard-builder.collection.js +0 -109
  321. package/collections/report-builder-dashboard-builder.collection.js.map +0 -1
  322. package/collections/report-builder-library.collection.d.ts +0 -3
  323. package/collections/report-builder-library.collection.js +0 -87
  324. package/collections/report-builder-library.collection.js.map +0 -1
  325. package/collections/report-builder-report.collection.d.ts +0 -4
  326. package/collections/report-builder-report.collection.js +0 -184
  327. package/collections/report-builder-report.collection.js.map +0 -1
  328. package/collections/user-group.collection.d.ts +0 -4
  329. package/collections/user-group.collection.js +0 -89
  330. package/collections/user-group.collection.js.map +0 -1
  331. package/collections/user-guide.collection.d.ts +0 -3
  332. package/collections/user-guide.collection.js +0 -57
  333. package/collections/user-guide.collection.js.map +0 -1
  334. package/collections/user.collection.d.ts +0 -4
  335. package/collections/user.collection.js +0 -180
  336. package/collections/user.collection.js.map +0 -1
  337. package/cron/cron.d.ts +0 -14
  338. package/cron/cron.js +0 -216
  339. package/cron/cron.js.map +0 -1
  340. package/fixtures/cron-jobs.d.ts +0 -1
  341. package/fixtures/cron-jobs.js +0 -150
  342. package/fixtures/cron-jobs.js.map +0 -1
  343. package/fixtures/init.d.ts +0 -1
  344. package/fixtures/init.js +0 -91
  345. package/fixtures/init.js.map +0 -1
  346. package/http/auth.d.ts +0 -2
  347. package/http/auth.js +0 -951
  348. package/http/auth.js.map +0 -1
  349. package/http/health.d.ts +0 -1
  350. package/http/health.js +0 -11
  351. package/http/health.js.map +0 -1
  352. package/http/home.d.ts +0 -1
  353. package/http/home.js +0 -134
  354. package/http/home.js.map +0 -1
  355. package/http/slow-query-publication.d.ts +0 -2
  356. package/http/slow-query-publication.js +0 -99
  357. package/http/slow-query-publication.js.map +0 -1
  358. package/index.d.ts +0 -1
  359. package/index.js +0 -19
  360. package/index.js.map +0 -1
  361. package/managers/ai-assistant-codex-manager.manager.d.ts +0 -67
  362. package/managers/ai-assistant-codex-manager.manager.js +0 -1113
  363. package/managers/ai-assistant-codex-manager.manager.js.map +0 -1
  364. package/managers/communication-metric.manager.d.ts +0 -16
  365. package/managers/communication-metric.manager.js +0 -134
  366. package/managers/communication-metric.manager.js.map +0 -1
  367. package/managers/cron.manager.d.ts +0 -20
  368. package/managers/cron.manager.js +0 -534
  369. package/managers/cron.manager.js.map +0 -1
  370. package/managers/customer-notification-content.manager.d.ts +0 -55
  371. package/managers/customer-notification-content.manager.js +0 -158
  372. package/managers/customer-notification-content.manager.js.map +0 -1
  373. package/managers/diagnostic-manager-bootstrap.d.ts +0 -9
  374. package/managers/diagnostic-manager-bootstrap.js +0 -260
  375. package/managers/diagnostic-manager-bootstrap.js.map +0 -1
  376. package/managers/error-auto-fix.manager.d.ts +0 -149
  377. package/managers/error-auto-fix.manager.js +0 -3064
  378. package/managers/error-auto-fix.manager.js.map +0 -1
  379. package/managers/local-log.manager.d.ts +0 -18
  380. package/managers/local-log.manager.js +0 -88
  381. package/managers/local-log.manager.js.map +0 -1
  382. package/managers/method.manager.d.ts +0 -84
  383. package/managers/method.manager.js +0 -1964
  384. package/managers/method.manager.js.map +0 -1
  385. package/managers/mongo.manager.d.ts +0 -224
  386. package/managers/mongo.manager.js +0 -5000
  387. package/managers/mongo.manager.js.map +0 -1
  388. package/managers/monitor.manager.d.ts +0 -70
  389. package/managers/monitor.manager.js +0 -550
  390. package/managers/monitor.manager.js.map +0 -1
  391. package/managers/openai-usage-ledger.manager.d.ts +0 -15
  392. package/managers/openai-usage-ledger.manager.js +0 -144
  393. package/managers/openai-usage-ledger.manager.js.map +0 -1
  394. package/managers/slow-query-verifier.manager.d.ts +0 -144
  395. package/managers/slow-query-verifier.manager.js +0 -3857
  396. package/managers/slow-query-verifier.manager.js.map +0 -1
  397. package/managers/slow-query.manager.d.ts +0 -28
  398. package/managers/slow-query.manager.js +0 -468
  399. package/managers/slow-query.manager.js.map +0 -1
  400. package/managers/subscription.manager.d.ts +0 -169
  401. package/managers/subscription.manager.js +0 -3434
  402. package/managers/subscription.manager.js.map +0 -1
  403. package/managers/websocket.manager.d.ts +0 -73
  404. package/managers/websocket.manager.js +0 -673
  405. package/managers/websocket.manager.js.map +0 -1
  406. package/managers/worker-dispatcher.manager.d.ts +0 -120
  407. package/managers/worker-dispatcher.manager.js +0 -1266
  408. package/managers/worker-dispatcher.manager.js.map +0 -1
  409. package/managers/worker-server.manager.d.ts +0 -35
  410. package/managers/worker-server.manager.js +0 -582
  411. package/managers/worker-server.manager.js.map +0 -1
  412. package/methods/accounts.d.ts +0 -2
  413. package/methods/accounts.js +0 -624
  414. package/methods/accounts.js.map +0 -1
  415. package/methods/ai-terminal.d.ts +0 -337
  416. package/methods/ai-terminal.js +0 -23166
  417. package/methods/ai-terminal.js.map +0 -1
  418. package/methods/app-settings.d.ts +0 -2
  419. package/methods/app-settings.js +0 -169
  420. package/methods/app-settings.js.map +0 -1
  421. package/methods/aws.d.ts +0 -2
  422. package/methods/aws.js +0 -877
  423. package/methods/aws.js.map +0 -1
  424. package/methods/collections.d.ts +0 -2
  425. package/methods/collections.js +0 -719
  426. package/methods/collections.js.map +0 -1
  427. package/methods/counters.d.ts +0 -2
  428. package/methods/counters.js +0 -113
  429. package/methods/counters.js.map +0 -1
  430. package/methods/cron-jobs.d.ts +0 -2
  431. package/methods/cron-jobs.js +0 -2475
  432. package/methods/cron-jobs.js.map +0 -1
  433. package/methods/customer-notifications.d.ts +0 -2
  434. package/methods/customer-notifications.js +0 -528
  435. package/methods/customer-notifications.js.map +0 -1
  436. package/methods/diagnostics.d.ts +0 -2
  437. package/methods/diagnostics.js +0 -703
  438. package/methods/diagnostics.js.map +0 -1
  439. package/methods/flag-updates.d.ts +0 -2
  440. package/methods/flag-updates.js +0 -8
  441. package/methods/flag-updates.js.map +0 -1
  442. package/methods/flags.d.ts +0 -2
  443. package/methods/flags.js +0 -8
  444. package/methods/flags.js.map +0 -1
  445. package/methods/logs.d.ts +0 -2
  446. package/methods/logs.js +0 -751
  447. package/methods/logs.js.map +0 -1
  448. package/methods/mongo-explorer.d.ts +0 -2
  449. package/methods/mongo-explorer.js +0 -1808
  450. package/methods/mongo-explorer.js.map +0 -1
  451. package/methods/monitor.d.ts +0 -2
  452. package/methods/monitor.js +0 -543
  453. package/methods/monitor.js.map +0 -1
  454. package/methods/pdf.d.ts +0 -2
  455. package/methods/pdf.js +0 -1216
  456. package/methods/pdf.js.map +0 -1
  457. package/methods/publications.d.ts +0 -1
  458. package/methods/publications.js +0 -183
  459. package/methods/publications.js.map +0 -1
  460. package/methods/report-builder.d.ts +0 -2
  461. package/methods/report-builder.js +0 -3094
  462. package/methods/report-builder.js.map +0 -1
  463. package/methods/support.d.ts +0 -2
  464. package/methods/support.js +0 -430
  465. package/methods/support.js.map +0 -1
  466. package/models/ai-terminal-conversation.model.d.ts +0 -17
  467. package/models/ai-terminal-conversation.model.js +0 -4
  468. package/models/ai-terminal-conversation.model.js.map +0 -1
  469. package/models/ai-terminal-issue-report.model.d.ts +0 -19
  470. package/models/ai-terminal-issue-report.model.js +0 -4
  471. package/models/ai-terminal-issue-report.model.js.map +0 -1
  472. package/models/ai-terminal-message.model.d.ts +0 -22
  473. package/models/ai-terminal-message.model.js +0 -4
  474. package/models/ai-terminal-message.model.js.map +0 -1
  475. package/models/app-setting.model.d.ts +0 -16
  476. package/models/app-setting.model.js +0 -4
  477. package/models/app-setting.model.js.map +0 -1
  478. package/models/app-status.model.js +0 -4
  479. package/models/app-status.model.js.map +0 -1
  480. package/models/billing-logged-in-users.model.js +0 -4
  481. package/models/billing-logged-in-users.model.js.map +0 -1
  482. package/models/collection-document.model.d.ts +0 -21
  483. package/models/collection-document.model.js +0 -4
  484. package/models/collection-document.model.js.map +0 -1
  485. package/models/communication-metric.model.d.ts +0 -20
  486. package/models/communication-metric.model.js +0 -4
  487. package/models/communication-metric.model.js.map +0 -1
  488. package/models/counter.model.js +0 -4
  489. package/models/counter.model.js.map +0 -1
  490. package/models/cron-job-history.model.d.ts +0 -15
  491. package/models/cron-job-history.model.js +0 -4
  492. package/models/cron-job-history.model.js.map +0 -1
  493. package/models/cron-job.model.d.ts +0 -14
  494. package/models/cron-job.model.js +0 -4
  495. package/models/cron-job.model.js.map +0 -1
  496. package/models/customer-notification.model.d.ts +0 -26
  497. package/models/customer-notification.model.js +0 -4
  498. package/models/customer-notification.model.js.map +0 -1
  499. package/models/customer-portal-password.model.d.ts +0 -11
  500. package/models/customer-portal-password.model.js +0 -4
  501. package/models/customer-portal-password.model.js.map +0 -1
  502. package/models/dialog.model.d.ts +0 -23
  503. package/models/dialog.model.js +0 -4
  504. package/models/dialog.model.js.map +0 -1
  505. package/models/email-history.model.d.ts +0 -32
  506. package/models/email-history.model.js.map +0 -1
  507. package/models/email-verified.model.js +0 -4
  508. package/models/email-verified.model.js.map +0 -1
  509. package/models/file.model.js +0 -4
  510. package/models/file.model.js.map +0 -1
  511. package/models/flag-update.model.js +0 -4
  512. package/models/flag-update.model.js.map +0 -1
  513. package/models/flag.model.js +0 -4
  514. package/models/flag.model.js.map +0 -1
  515. package/models/log-method-latency.model.d.ts +0 -10
  516. package/models/log-method-latency.model.js +0 -4
  517. package/models/log-method-latency.model.js.map +0 -1
  518. package/models/log-subscription.model.js +0 -4
  519. package/models/log-subscription.model.js.map +0 -1
  520. package/models/log.model.d.ts +0 -17
  521. package/models/log.model.js +0 -4
  522. package/models/log.model.js.map +0 -1
  523. package/models/logged-in-users.model.js +0 -4
  524. package/models/logged-in-users.model.js.map +0 -1
  525. package/models/method-response.model.js +0 -4
  526. package/models/method-response.model.js.map +0 -1
  527. package/models/method.model.d.ts +0 -26
  528. package/models/method.model.js +0 -4
  529. package/models/method.model.js.map +0 -1
  530. package/models/monitor-cpu.model.js +0 -4
  531. package/models/monitor-cpu.model.js.map +0 -1
  532. package/models/monitor-function.model.d.ts +0 -14
  533. package/models/monitor-function.model.js +0 -4
  534. package/models/monitor-function.model.js.map +0 -1
  535. package/models/monitor-memory.model.d.ts +0 -15
  536. package/models/monitor-memory.model.js +0 -4
  537. package/models/monitor-memory.model.js.map +0 -1
  538. package/models/monitor-mongo.model.d.ts +0 -13
  539. package/models/monitor-mongo.model.js +0 -4
  540. package/models/monitor-mongo.model.js.map +0 -1
  541. package/models/notification.model.js +0 -4
  542. package/models/notification.model.js.map +0 -1
  543. package/models/openai-usage-ledger.model.d.ts +0 -15
  544. package/models/openai-usage-ledger.model.js +0 -4
  545. package/models/openai-usage-ledger.model.js.map +0 -1
  546. package/models/pagination.model.d.ts +0 -11
  547. package/models/pagination.model.js +0 -28
  548. package/models/pagination.model.js.map +0 -1
  549. package/models/permission.model.d.ts +0 -12
  550. package/models/permission.model.js +0 -4
  551. package/models/permission.model.js.map +0 -1
  552. package/models/report-builder-dashboard-builder.model.d.ts +0 -25
  553. package/models/report-builder-dashboard-builder.model.js +0 -4
  554. package/models/report-builder-dashboard-builder.model.js.map +0 -1
  555. package/models/report-builder-library.model.d.ts +0 -17
  556. package/models/report-builder-library.model.js +0 -4
  557. package/models/report-builder-library.model.js.map +0 -1
  558. package/models/report-builder-report.model.d.ts +0 -121
  559. package/models/report-builder-report.model.js +0 -4
  560. package/models/report-builder-report.model.js.map +0 -1
  561. package/models/report-builder.model.d.ts +0 -61
  562. package/models/report-builder.model.js +0 -4
  563. package/models/report-builder.model.js.map +0 -1
  564. package/models/select-data-label.model.d.ts +0 -9
  565. package/models/select-data-label.model.js +0 -4
  566. package/models/select-data-label.model.js.map +0 -1
  567. package/models/server-message.model.d.ts +0 -32
  568. package/models/server-message.model.js +0 -4
  569. package/models/server-message.model.js.map +0 -1
  570. package/models/slow-query-report.model.d.ts +0 -23
  571. package/models/slow-query-report.model.js +0 -4
  572. package/models/slow-query-report.model.js.map +0 -1
  573. package/models/subscription.model.d.ts +0 -31
  574. package/models/subscription.model.js +0 -4
  575. package/models/subscription.model.js.map +0 -1
  576. package/models/support-ticket.model.d.ts +0 -87
  577. package/models/support-ticket.model.js +0 -4
  578. package/models/support-ticket.model.js.map +0 -1
  579. package/models/user-group.model.d.ts +0 -20
  580. package/models/user-group.model.js +0 -4
  581. package/models/user-group.model.js.map +0 -1
  582. package/models/user-guide.model.js +0 -4
  583. package/models/user-guide.model.js.map +0 -1
  584. package/models/user.model.d.ts +0 -84
  585. package/models/user.model.js +0 -4
  586. package/models/user.model.js.map +0 -1
  587. package/private/images/ResolveIO.png +0 -0
  588. package/public_api.js +0 -118
  589. package/public_api.js.map +0 -1
  590. package/publications/ai-terminal.d.ts +0 -1
  591. package/publications/ai-terminal.js +0 -122
  592. package/publications/ai-terminal.js.map +0 -1
  593. package/publications/app-settings.d.ts +0 -2
  594. package/publications/app-settings.js +0 -28
  595. package/publications/app-settings.js.map +0 -1
  596. package/publications/app-status.d.ts +0 -2
  597. package/publications/app-status.js +0 -16
  598. package/publications/app-status.js.map +0 -1
  599. package/publications/cron-jobs.d.ts +0 -2
  600. package/publications/cron-jobs.js +0 -88
  601. package/publications/cron-jobs.js.map +0 -1
  602. package/publications/customer-notifications.d.ts +0 -2
  603. package/publications/customer-notifications.js +0 -161
  604. package/publications/customer-notifications.js.map +0 -1
  605. package/publications/files.d.ts +0 -2
  606. package/publications/files.js +0 -36
  607. package/publications/files.js.map +0 -1
  608. package/publications/flags-update.d.ts +0 -2
  609. package/publications/flags-update.js +0 -22
  610. package/publications/flags-update.js.map +0 -1
  611. package/publications/flags.d.ts +0 -2
  612. package/publications/flags.js +0 -22
  613. package/publications/flags.js.map +0 -1
  614. package/publications/logs.d.ts +0 -2
  615. package/publications/logs.js +0 -164
  616. package/publications/logs.js.map +0 -1
  617. package/publications/notifications.d.ts +0 -2
  618. package/publications/notifications.js +0 -16
  619. package/publications/notifications.js.map +0 -1
  620. package/publications/report-builder-dashboard-builders.d.ts +0 -2
  621. package/publications/report-builder-dashboard-builders.js +0 -42
  622. package/publications/report-builder-dashboard-builders.js.map +0 -1
  623. package/publications/report-builder-libraries.d.ts +0 -2
  624. package/publications/report-builder-libraries.js +0 -90
  625. package/publications/report-builder-libraries.js.map +0 -1
  626. package/publications/report-builder-reports.d.ts +0 -2
  627. package/publications/report-builder-reports.js +0 -50
  628. package/publications/report-builder-reports.js.map +0 -1
  629. package/publications/super-admin.d.ts +0 -2
  630. package/publications/super-admin.js +0 -16
  631. package/publications/super-admin.js.map +0 -1
  632. package/publications/user-groups.d.ts +0 -1
  633. package/publications/user-groups.js +0 -16
  634. package/publications/user-groups.js.map +0 -1
  635. package/publications/user-guides.d.ts +0 -1
  636. package/publications/user-guides.js +0 -16
  637. package/publications/user-guides.js.map +0 -1
  638. package/resolveio-server-app.d.ts +0 -70
  639. package/resolveio-server-app.js +0 -801
  640. package/resolveio-server-app.js.map +0 -1
  641. package/server-app.d.ts +0 -228
  642. package/server-app.js +0 -3566
  643. package/server-app.js.map +0 -1
  644. package/services/codex-client.d.ts +0 -128
  645. package/services/codex-client.js +0 -1629
  646. package/services/codex-client.js.map +0 -1
  647. package/services/openai-client.d.ts +0 -46
  648. package/services/openai-client.js +0 -318
  649. package/services/openai-client.js.map +0 -1
  650. package/types/error-report.d.ts +0 -25
  651. package/types/error-report.js +0 -4
  652. package/types/error-report.js.map +0 -1
  653. package/types/slow-query-report.d.ts +0 -27
  654. package/types/slow-query-report.js +0 -6
  655. package/types/slow-query-report.js.map +0 -1
  656. package/util/ai-qa-policy.d.ts +0 -124
  657. package/util/ai-qa-policy.js +0 -736
  658. package/util/ai-qa-policy.js.map +0 -1
  659. package/util/ai-runner-artifacts.d.ts +0 -82
  660. package/util/ai-runner-artifacts.js +0 -713
  661. package/util/ai-runner-artifacts.js.map +0 -1
  662. package/util/ai-runner-qa-auth.d.ts +0 -5
  663. package/util/ai-runner-qa-auth.js +0 -822
  664. package/util/ai-runner-qa-auth.js.map +0 -1
  665. package/util/ai-runner-qa-tools.d.ts +0 -25
  666. package/util/ai-runner-qa-tools.js +0 -2910
  667. package/util/ai-runner-qa-tools.js.map +0 -1
  668. package/util/aicoder-runner-v6.d.ts +0 -168
  669. package/util/aicoder-runner-v6.js +0 -347
  670. package/util/aicoder-runner-v6.js.map +0 -1
  671. package/util/common.d.ts +0 -31
  672. package/util/common.js +0 -683
  673. package/util/common.js.map +0 -1
  674. package/util/customer-portal-password.d.ts +0 -13
  675. package/util/customer-portal-password.js +0 -209
  676. package/util/customer-portal-password.js.map +0 -1
  677. package/util/error-reporter.d.ts +0 -52
  678. package/util/error-reporter.js +0 -326
  679. package/util/error-reporter.js.map +0 -1
  680. package/util/error-tracking.d.ts +0 -13
  681. package/util/error-tracking.js +0 -120
  682. package/util/error-tracking.js.map +0 -1
  683. package/util/report-builder-unwinds.d.ts +0 -15
  684. package/util/report-builder-unwinds.js +0 -156
  685. package/util/report-builder-unwinds.js.map +0 -1
  686. package/util/runner-process-janitor.d.ts +0 -27
  687. package/util/runner-process-janitor.js +0 -208
  688. package/util/runner-process-janitor.js.map +0 -1
  689. package/util/schema-report-builder.d.ts +0 -6
  690. package/util/schema-report-builder.js +0 -481
  691. package/util/schema-report-builder.js.map +0 -1
  692. package/util/slow-query-reporter.d.ts +0 -28
  693. package/util/slow-query-reporter.js +0 -226
  694. package/util/slow-query-reporter.js.map +0 -1
  695. package/util/subscription-dependency-context.d.ts +0 -34
  696. package/util/subscription-dependency-context.js +0 -1283
  697. package/util/subscription-dependency-context.js.map +0 -1
  698. package/util/support-runner-v5.d.ts +0 -250
  699. package/util/support-runner-v5.js +0 -634
  700. package/util/support-runner-v5.js.map +0 -1
  701. package/util/tokenizer.d.ts +0 -5
  702. package/util/tokenizer.js +0 -41
  703. package/util/tokenizer.js.map +0 -1
  704. package/workers/codex-runner.worker.d.ts +0 -1
  705. package/workers/codex-runner.worker.js +0 -192
  706. package/workers/codex-runner.worker.js.map +0 -1
  707. /package/{private → src/private}/email-templates/enrollment.html +0 -0
  708. /package/{private → src/private}/email-templates/forgot-password.html +0 -0
  709. /package/{private → src/private}/email-templates/support-ticket-deleted.html +0 -0
  710. /package/{private → src/private}/email-templates/support-ticket-modified.html +0 -0
  711. /package/{private → src/private}/email-templates/support-ticket.html +0 -0
@@ -1,1808 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
- var __values = (this && this.__values) || function(o) {
66
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
67
- if (m) return m.call(o);
68
- if (o && typeof o.length === "number") return {
69
- next: function () {
70
- if (o && i >= o.length) o = void 0;
71
- return { value: o && o[i++], done: !o };
72
- }
73
- };
74
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
75
- };
76
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
77
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
78
- if (ar || !(i in from)) {
79
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
80
- ar[i] = from[i];
81
- }
82
- }
83
- return to.concat(ar || Array.prototype.slice.call(from));
84
- };
85
- Object.defineProperty(exports, "__esModule", { value: true });
86
- exports.loadMongoExplorerMethods = loadMongoExplorerMethods;
87
- var simpl_schema_1 = require("simpl-schema");
88
- var user_collection_1 = require("../collections/user.collection");
89
- var openai_usage_ledger_manager_1 = require("../managers/openai-usage-ledger.manager");
90
- var resolveio_server_app_1 = require("../resolveio-server-app");
91
- var codex_client_1 = require("../services/codex-client");
92
- var common_1 = require("../util/common");
93
- var tokenizer_1 = require("../util/tokenizer");
94
- var DEFAULT_LIMIT = 100;
95
- var MAX_LIMIT = 2000;
96
- var ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
97
- var MAX_REVIEW_STRING_LENGTH = 500;
98
- var MAX_REVIEW_ARRAY_ITEMS = 10;
99
- var MAX_REVIEW_OBJECT_KEYS = 40;
100
- var MAX_REVIEW_DEPTH = 4;
101
- var MAX_REVIEW_LIST_ITEMS = 6;
102
- var MAX_REVIEW_CHANGED_FIELDS = 60;
103
- var DEFAULT_RISK_REVIEW_TIMEOUT_MS = 30000;
104
- var DEFAULT_RISK_REVIEW_MAX_TOKENS = 700;
105
- var SENSITIVE_REVIEW_FIELD_REGEX = /(password|secret|token|api[_-]?key|salt|hash|email|phone|address|ssn|services|roles)/i;
106
- var DEFAULT_AI_SUGGEST_TIMEOUT_MS = 60000;
107
- var DEFAULT_AI_SUGGEST_MAX_TOKENS = 1000;
108
- var MAX_AI_SUGGEST_FIELDS = 700;
109
- var MAX_AI_SUGGEST_COLLECTIONS = 800;
110
- var MAX_AI_SUGGEST_RESULTS = 500;
111
- var RESTRICTED_AGGREGATE_STAGES = new Set(['$out', '$merge']);
112
- function parseMongoExplorerWriteUsers() {
113
- var raw = typeof process.env.MONGO_EXPLORER_WRITE_USERS === 'string' ? process.env.MONGO_EXPLORER_WRITE_USERS.trim() : '';
114
- if (!raw) {
115
- return [];
116
- }
117
- try {
118
- var parsed = JSON.parse(raw);
119
- if (Array.isArray(parsed)) {
120
- return parsed.map(function (value) { return String(value); }).filter(function (value) { return value.trim().length; });
121
- }
122
- if (typeof parsed === 'string') {
123
- return [parsed.trim()].filter(Boolean);
124
- }
125
- }
126
- catch (_a) {
127
- // Fall back to comma-separated list.
128
- }
129
- return raw
130
- .split(',')
131
- .map(function (value) { return value.trim(); })
132
- .filter(Boolean);
133
- }
134
- function normalizeExplorerMode(mode) {
135
- var normalizedMode = String(mode || '').trim().toLowerCase();
136
- if (normalizedMode === 'resolveio') {
137
- return 'resolveio';
138
- }
139
- return 'aicoder';
140
- }
141
- function allowUnschemaizedWrites() {
142
- return process.env.MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE === 'true';
143
- }
144
- function resolveDatabaseName(database) {
145
- var _a, _b;
146
- var defaultDb = ((_a = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _a === void 0 ? void 0 : _a.DATABASE) || '';
147
- var dbName = typeof database === 'string' && database.trim().length ? database.trim() : defaultDb;
148
- if (!dbName) {
149
- throw new Error('Mongo Explorer: Database is required');
150
- }
151
- var allowedDatabases = ((_b = resolveio_server_app_1.ResolveIOServer.getMongoManager()) === null || _b === void 0 ? void 0 : _b.getWatchedDatabases()) || [];
152
- if (allowedDatabases.length && !allowedDatabases.includes(dbName)) {
153
- throw new Error('Mongo Explorer: Database access denied');
154
- }
155
- return dbName;
156
- }
157
- function resolveDatabase(database) {
158
- var dbName = resolveDatabaseName(database);
159
- return resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
160
- }
161
- function resolveCollectionHandle(database, collection) {
162
- var _a, _b;
163
- var mainDb = ((_a = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _a === void 0 ? void 0 : _a.DATABASE) || '';
164
- var isMainDb = database === mainDb;
165
- var managerCollection = isMainDb ? (_b = resolveio_server_app_1.ResolveIOServer.getMongoManager()) === null || _b === void 0 ? void 0 : _b.collection(collection) : null;
166
- var db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(database);
167
- return {
168
- managerCollection: managerCollection,
169
- dbCollection: db.collection(collection)
170
- };
171
- }
172
- function getSchemaDefinition(collectionRef) {
173
- if (!collectionRef || !collectionRef.simplschema || typeof collectionRef.simplschema.schema !== 'function') {
174
- return {};
175
- }
176
- var schema = collectionRef.simplschema.schema();
177
- return schema && typeof schema === 'object' ? schema : {};
178
- }
179
- function getSchemaTypeName(definition) {
180
- var _a, _b;
181
- var typeDefs = (_a = definition === null || definition === void 0 ? void 0 : definition.type) === null || _a === void 0 ? void 0 : _a.definitions;
182
- if (!Array.isArray(typeDefs) || !typeDefs.length) {
183
- return 'Any';
184
- }
185
- var firstType = (_b = typeDefs[0]) === null || _b === void 0 ? void 0 : _b.type;
186
- if (!firstType) {
187
- return 'Any';
188
- }
189
- if (firstType === String) {
190
- return 'String';
191
- }
192
- if (firstType === Number) {
193
- return 'Number';
194
- }
195
- if (firstType === Boolean) {
196
- return 'Boolean';
197
- }
198
- if (firstType === Date) {
199
- return 'Date';
200
- }
201
- if (firstType === Object) {
202
- return 'Object';
203
- }
204
- if (firstType === Array) {
205
- return 'Array';
206
- }
207
- var typeName = firstType.name || String(firstType);
208
- if (typeName === 'Integer') {
209
- return 'Number';
210
- }
211
- return typeName;
212
- }
213
- function toLabel(path) {
214
- var last = path.split('.').pop() || path;
215
- return last
216
- .replace(/\$/g, '')
217
- .replace(/_/g, ' ')
218
- .replace(/\s+/g, ' ')
219
- .trim();
220
- }
221
- function isProtectedFieldSegment(segment) {
222
- if (!segment) {
223
- return false;
224
- }
225
- if (segment === '_id') {
226
- return true;
227
- }
228
- var normalizedSegment = segment.replace(/\[\d+\]/g, '');
229
- return normalizedSegment.toLowerCase().startsWith('id_');
230
- }
231
- function isProtectedFieldPath(path) {
232
- var segments = String(path || '').split('.').filter(Boolean);
233
- return segments.some(function (segment) { return isProtectedFieldSegment(segment); });
234
- }
235
- function safeStringify(value) {
236
- try {
237
- return JSON.stringify(value);
238
- }
239
- catch (_a) {
240
- return String(value);
241
- }
242
- }
243
- function collectProtectedFieldPaths(value, prefix, out) {
244
- if (prefix === void 0) { prefix = ''; }
245
- if (out === void 0) { out = {}; }
246
- if (Array.isArray(value)) {
247
- value.forEach(function (item, index) {
248
- var nextPrefix = prefix ? "".concat(prefix, "[").concat(index, "]") : "[".concat(index, "]");
249
- collectProtectedFieldPaths(item, nextPrefix, out);
250
- });
251
- return out;
252
- }
253
- if (!value || typeof value !== 'object') {
254
- return out;
255
- }
256
- Object.keys(value).forEach(function (key) {
257
- var nextPrefix = prefix ? "".concat(prefix, ".").concat(key) : key;
258
- if (isProtectedFieldSegment(key)) {
259
- out[nextPrefix] = value[key];
260
- }
261
- collectProtectedFieldPaths(value[key], nextPrefix, out);
262
- });
263
- return out;
264
- }
265
- function ensureProtectedFieldsUnchanged(originalDoc, updatedDoc) {
266
- var originalProtected = collectProtectedFieldPaths(originalDoc || {});
267
- var updatedProtected = collectProtectedFieldPaths(updatedDoc || {});
268
- var violations = [];
269
- Object.keys(originalProtected).forEach(function (path) {
270
- if (!Object.prototype.hasOwnProperty.call(updatedProtected, path)) {
271
- violations.push(path);
272
- return;
273
- }
274
- var originalValue = safeStringify(originalProtected[path]);
275
- var updatedValue = safeStringify(updatedProtected[path]);
276
- if (originalValue !== updatedValue) {
277
- violations.push(path);
278
- }
279
- });
280
- Object.keys(updatedProtected).forEach(function (path) {
281
- if (!Object.prototype.hasOwnProperty.call(originalProtected, path)) {
282
- violations.push(path);
283
- }
284
- });
285
- if (violations.length) {
286
- var preview = violations.slice(0, 4).join(', ');
287
- throw new Error("Mongo Explorer: Protected fields cannot be edited (".concat(preview).concat(violations.length > 4 ? ', ...' : '', ")"));
288
- }
289
- }
290
- function coerceDateValue(value) {
291
- if (value instanceof Date) {
292
- return value;
293
- }
294
- if (typeof value !== 'string' || !ISO_DATE_REGEX.test(value)) {
295
- return value;
296
- }
297
- var parsed = new Date(value);
298
- return Number.isNaN(parsed.getTime()) ? value : parsed;
299
- }
300
- function coerceDatePath(target, segments) {
301
- if (!target || !segments.length) {
302
- return;
303
- }
304
- var _a = __read(segments), segment = _a[0], rest = _a.slice(1);
305
- if (segment === '$') {
306
- if (Array.isArray(target)) {
307
- target.forEach(function (item) { return coerceDatePath(item, rest); });
308
- }
309
- return;
310
- }
311
- if (!Object.prototype.hasOwnProperty.call(target, segment)) {
312
- return;
313
- }
314
- if (rest.length === 0) {
315
- var updatedValue = coerceDateValue(target[segment]);
316
- if (updatedValue !== target[segment]) {
317
- target[segment] = updatedValue;
318
- }
319
- return;
320
- }
321
- coerceDatePath(target[segment], rest);
322
- }
323
- function coerceDateFields(collectionRef, doc) {
324
- if (!collectionRef || !collectionRef.simplschema || !doc) {
325
- return;
326
- }
327
- var schema = getSchemaDefinition(collectionRef);
328
- Object.keys(schema).forEach(function (schemaKey) {
329
- var _a;
330
- var definition = schema[schemaKey];
331
- var typeDefs = (_a = definition === null || definition === void 0 ? void 0 : definition.type) === null || _a === void 0 ? void 0 : _a.definitions;
332
- if (!Array.isArray(typeDefs) || !typeDefs.some(function (typeDef) { return typeDef.type === Date; })) {
333
- return;
334
- }
335
- coerceDatePath(doc, schemaKey.split('.'));
336
- });
337
- }
338
- function normalizeFindOptions(options) {
339
- var normalized = options || {};
340
- var projection = normalized.projection && Object.keys(normalized.projection).length ? normalized.projection : undefined;
341
- var sort = normalized.sort && Object.keys(normalized.sort).length ? normalized.sort : undefined;
342
- var limit = typeof normalized.limit === 'number' ? Math.min(Math.max(normalized.limit, 0), MAX_LIMIT) : DEFAULT_LIMIT;
343
- var skip = typeof normalized.skip === 'number' ? Math.max(normalized.skip, 0) : 0;
344
- return {
345
- findOptions: {
346
- projection: projection,
347
- sort: sort,
348
- limit: limit,
349
- skip: skip
350
- },
351
- includeTotal: normalized.includeTotal === true
352
- };
353
- }
354
- function userHasView(user, view) {
355
- var _a, _b, _c;
356
- if (!user || !view) {
357
- return false;
358
- }
359
- if ((_a = user.roles) === null || _a === void 0 ? void 0 : _a.super_admin) {
360
- return true;
361
- }
362
- var groups = Array.isArray((_b = user.roles) === null || _b === void 0 ? void 0 : _b.groups) ? user.roles.groups : [];
363
- var miscs = Array.isArray((_c = user.roles) === null || _c === void 0 ? void 0 : _c.miscs) ? user.roles.miscs : [];
364
- if (groups.some(function (group) { return Array.isArray(group.views) && group.views.some(function (v) { return v.startsWith(view); }); })) {
365
- return true;
366
- }
367
- if (miscs.some(function (v) { return v.startsWith(view); })) {
368
- return true;
369
- }
370
- if (groups.some(function (group) { return group.name === view; })) {
371
- return true;
372
- }
373
- return false;
374
- }
375
- function ensureWriteAccess(context, permissionView, mode) {
376
- return __awaiter(this, void 0, void 0, function () {
377
- var idUser, user, normalizedMode, allowedUsers, username_1, email_1, id_1, isAllowed, normalizedPermission;
378
- var _a;
379
- return __generator(this, function (_b) {
380
- switch (_b.label) {
381
- case 0:
382
- idUser = context === null || context === void 0 ? void 0 : context.id_user;
383
- if (!idUser) {
384
- throw new Error('Mongo Explorer: Unauthorized');
385
- }
386
- return [4 /*yield*/, user_collection_1.Users.findOne({ _id: idUser })];
387
- case 1:
388
- user = _b.sent();
389
- if (!user) {
390
- throw new Error('Mongo Explorer: Unauthorized');
391
- }
392
- if (user.readonly) {
393
- throw new Error('Mongo Explorer: Readonly user');
394
- }
395
- normalizedMode = normalizeExplorerMode(mode);
396
- if (normalizedMode === 'resolveio') {
397
- throw new Error('Mongo Explorer: ResolveIO mode is read only');
398
- }
399
- allowedUsers = parseMongoExplorerWriteUsers();
400
- if (allowedUsers.length) {
401
- username_1 = String(user.username || '').trim().toLowerCase();
402
- email_1 = String(user.email || '').trim().toLowerCase();
403
- id_1 = String(user._id || '').trim();
404
- isAllowed = allowedUsers.some(function (entry) {
405
- var normalized = String(entry || '').trim().toLowerCase();
406
- if (!normalized) {
407
- return false;
408
- }
409
- return normalized === username_1 || (email_1 && normalized === email_1) || (id_1 && entry === id_1);
410
- });
411
- if (!isAllowed) {
412
- throw new Error('Mongo Explorer: Write access denied');
413
- }
414
- }
415
- if ((_a = user.roles) === null || _a === void 0 ? void 0 : _a.super_admin) {
416
- return [2 /*return*/];
417
- }
418
- normalizedPermission = typeof permissionView === 'string' ? permissionView.trim() : '';
419
- if (!normalizedPermission) {
420
- return [2 /*return*/];
421
- }
422
- if (userHasView(user, normalizedPermission)) {
423
- return [2 /*return*/];
424
- }
425
- throw new Error('Mongo Explorer: Write access denied');
426
- }
427
- });
428
- });
429
- }
430
- function buildDeleteSafetyCollections(collectionRef) {
431
- var schema = getSchemaDefinition(collectionRef);
432
- return Object.keys(schema).filter(function (path) { return isProtectedFieldPath(path) && path !== '_id'; });
433
- }
434
- function buildDeleteImpact(database, sourceCollection, docId) {
435
- return __awaiter(this, void 0, void 0, function () {
436
- var mainDb, mongoManager, collections, impacts, unresolved, collections_1, collections_1_1, collectionRef, collectionName, referencePaths, query, docs, _a, e_1_1;
437
- var e_1, _b;
438
- var _c;
439
- return __generator(this, function (_d) {
440
- switch (_d.label) {
441
- case 0:
442
- mainDb = ((_c = resolveio_server_app_1.ResolveIOServer.getServerConfig()) === null || _c === void 0 ? void 0 : _c.DATABASE) || '';
443
- if (database !== mainDb) {
444
- return [2 /*return*/, {
445
- has_references: false,
446
- unresolved: true,
447
- collections: []
448
- }];
449
- }
450
- mongoManager = resolveio_server_app_1.ResolveIOServer.getMongoManager();
451
- collections = (mongoManager === null || mongoManager === void 0 ? void 0 : mongoManager.collections) ? mongoManager.collections() : [];
452
- impacts = [];
453
- unresolved = false;
454
- _d.label = 1;
455
- case 1:
456
- _d.trys.push([1, 8, 9, 10]);
457
- collections_1 = __values(collections), collections_1_1 = collections_1.next();
458
- _d.label = 2;
459
- case 2:
460
- if (!!collections_1_1.done) return [3 /*break*/, 7];
461
- collectionRef = collections_1_1.value;
462
- collectionName = collectionRef === null || collectionRef === void 0 ? void 0 : collectionRef.collectionName;
463
- if (!collectionName) {
464
- return [3 /*break*/, 6];
465
- }
466
- if (collectionName === "".concat(sourceCollection, ".versions")) {
467
- return [3 /*break*/, 6];
468
- }
469
- referencePaths = buildDeleteSafetyCollections(collectionRef);
470
- if (!referencePaths.length) {
471
- return [3 /*break*/, 6];
472
- }
473
- query = {
474
- $or: referencePaths.map(function (path) {
475
- var _a;
476
- return (_a = {}, _a[path] = docId, _a);
477
- })
478
- };
479
- _d.label = 3;
480
- case 3:
481
- _d.trys.push([3, 5, , 6]);
482
- return [4 /*yield*/, collectionRef.find(query, { projection: { _id: 1 }, limit: 3 })];
483
- case 4:
484
- docs = _d.sent();
485
- if (Array.isArray(docs) && docs.length) {
486
- impacts.push({
487
- collection: collectionName,
488
- references: docs.length,
489
- sample_ids: docs.map(function (doc) { return String((doc === null || doc === void 0 ? void 0 : doc._id) || ''); }).filter(Boolean)
490
- });
491
- }
492
- return [3 /*break*/, 6];
493
- case 5:
494
- _a = _d.sent();
495
- unresolved = true;
496
- return [3 /*break*/, 6];
497
- case 6:
498
- collections_1_1 = collections_1.next();
499
- return [3 /*break*/, 2];
500
- case 7: return [3 /*break*/, 10];
501
- case 8:
502
- e_1_1 = _d.sent();
503
- e_1 = { error: e_1_1 };
504
- return [3 /*break*/, 10];
505
- case 9:
506
- try {
507
- if (collections_1_1 && !collections_1_1.done && (_b = collections_1.return)) _b.call(collections_1);
508
- }
509
- finally { if (e_1) throw e_1.error; }
510
- return [7 /*endfinally*/];
511
- case 10: return [2 /*return*/, {
512
- has_references: impacts.length > 0,
513
- unresolved: unresolved,
514
- collections: impacts.sort(function (a, b) { return a.collection.localeCompare(b.collection); })
515
- }];
516
- }
517
- });
518
- });
519
- }
520
- function normalizeOptionalString(value) {
521
- if (typeof value === 'string') {
522
- var trimmed = value.trim();
523
- return trimmed.length ? trimmed : undefined;
524
- }
525
- if (value === null || value === undefined) {
526
- return undefined;
527
- }
528
- var normalized = String(value).trim();
529
- return normalized.length ? normalized : undefined;
530
- }
531
- function normalizePositiveNumber(value, fallback) {
532
- var parsed = Number(value);
533
- if (!Number.isFinite(parsed) || parsed <= 0) {
534
- return fallback;
535
- }
536
- return parsed;
537
- }
538
- function parseBooleanValue(value, fallback) {
539
- if (typeof value === 'boolean') {
540
- return value;
541
- }
542
- var normalized = String(value || '').trim().toLowerCase();
543
- if (!normalized.length) {
544
- return fallback;
545
- }
546
- if (['1', 'true', 'yes', 'on'].includes(normalized)) {
547
- return true;
548
- }
549
- if (['0', 'false', 'no', 'off'].includes(normalized)) {
550
- return false;
551
- }
552
- return fallback;
553
- }
554
- function truncateForRiskReview(value, maxLength) {
555
- if (maxLength === void 0) { maxLength = MAX_REVIEW_STRING_LENGTH; }
556
- var normalized = String(value || '');
557
- if (normalized.length <= maxLength) {
558
- return normalized;
559
- }
560
- var diff = normalized.length - maxLength;
561
- return "".concat(normalized.slice(0, maxLength), "...[+").concat(diff, " chars]");
562
- }
563
- function sanitizeForRiskReview(value, depth) {
564
- if (depth === void 0) { depth = 0; }
565
- if (value === null || value === undefined) {
566
- return value;
567
- }
568
- if (depth > MAX_REVIEW_DEPTH) {
569
- return '[Truncated depth]';
570
- }
571
- if (value instanceof Date) {
572
- return value.toISOString();
573
- }
574
- if (typeof value === 'string') {
575
- return truncateForRiskReview(value);
576
- }
577
- if (typeof value === 'number' || typeof value === 'boolean') {
578
- return value;
579
- }
580
- if (Array.isArray(value)) {
581
- var sanitized = value
582
- .slice(0, MAX_REVIEW_ARRAY_ITEMS)
583
- .map(function (item) { return sanitizeForRiskReview(item, depth + 1); });
584
- if (value.length > MAX_REVIEW_ARRAY_ITEMS) {
585
- sanitized.push("[".concat(value.length - MAX_REVIEW_ARRAY_ITEMS, " more item(s)]"));
586
- }
587
- return sanitized;
588
- }
589
- if (typeof value === 'object') {
590
- var output_1 = {};
591
- var keys = Object.keys(value);
592
- var limitedKeys = keys.slice(0, MAX_REVIEW_OBJECT_KEYS);
593
- limitedKeys.forEach(function (key) {
594
- if (SENSITIVE_REVIEW_FIELD_REGEX.test(key)) {
595
- output_1[key] = '[REDACTED]';
596
- return;
597
- }
598
- output_1[key] = sanitizeForRiskReview(value[key], depth + 1);
599
- });
600
- if (keys.length > MAX_REVIEW_OBJECT_KEYS) {
601
- output_1.__truncated_keys = keys.length - MAX_REVIEW_OBJECT_KEYS;
602
- }
603
- return output_1;
604
- }
605
- return truncateForRiskReview(String(value));
606
- }
607
- function pickChangedFields(beforeDocument, afterDocument) {
608
- var e_2, _a;
609
- if (!beforeDocument || typeof beforeDocument !== 'object' || !afterDocument || typeof afterDocument !== 'object') {
610
- return [];
611
- }
612
- var changed = [];
613
- var fieldNames = new Set(__spreadArray(__spreadArray([], __read(Object.keys(beforeDocument)), false), __read(Object.keys(afterDocument)), false));
614
- try {
615
- for (var fieldNames_1 = __values(fieldNames), fieldNames_1_1 = fieldNames_1.next(); !fieldNames_1_1.done; fieldNames_1_1 = fieldNames_1.next()) {
616
- var field = fieldNames_1_1.value;
617
- if (changed.length >= MAX_REVIEW_CHANGED_FIELDS) {
618
- break;
619
- }
620
- var beforeValue = safeStringify(beforeDocument[field]);
621
- var afterValue = safeStringify(afterDocument[field]);
622
- if (beforeValue !== afterValue) {
623
- changed.push(field);
624
- }
625
- }
626
- }
627
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
628
- finally {
629
- try {
630
- if (fieldNames_1_1 && !fieldNames_1_1.done && (_a = fieldNames_1.return)) _a.call(fieldNames_1);
631
- }
632
- finally { if (e_2) throw e_2.error; }
633
- }
634
- return changed;
635
- }
636
- function normalizeRiskLevel(value) {
637
- var normalized = String(value || '').trim().toLowerCase();
638
- if (normalized === 'low') {
639
- return 'low';
640
- }
641
- if (normalized === 'medium') {
642
- return 'medium';
643
- }
644
- if (normalized === 'high') {
645
- return 'high';
646
- }
647
- if (normalized === 'critical') {
648
- return 'critical';
649
- }
650
- return 'high';
651
- }
652
- function normalizeRiskList(value) {
653
- if (!Array.isArray(value)) {
654
- return [];
655
- }
656
- return value
657
- .map(function (item) { return normalizeOptionalString(item); })
658
- .filter(function (item) { return !!item; })
659
- .slice(0, MAX_REVIEW_LIST_ITEMS)
660
- .map(function (item) { return truncateForRiskReview(item, 220); });
661
- }
662
- function buildFallbackRiskReview(operation, summary, model) {
663
- if (model === void 0) { model = ''; }
664
- return {
665
- operation: operation,
666
- risk_level: 'high',
667
- should_block: true,
668
- summary: truncateForRiskReview(summary, 220),
669
- reasons: [
670
- 'AI review could not produce a reliable result.',
671
- 'Proceed only with explicit approval and manual dependency checks.'
672
- ],
673
- suggested_checks: [
674
- 'Confirm related records and id_* references before writing.',
675
- 'Validate that schema-required fields and date values remain valid.'
676
- ],
677
- confidence: 0,
678
- model: model || '',
679
- request_id: '',
680
- review_status: 'fallback',
681
- reviewed_at: new Date().toISOString()
682
- };
683
- }
684
- function buildDisabledRiskReview(operation) {
685
- return {
686
- operation: operation,
687
- risk_level: 'low',
688
- should_block: false,
689
- summary: 'AI risk review is disabled by configuration.',
690
- reasons: [],
691
- suggested_checks: [],
692
- confidence: 1,
693
- model: '',
694
- request_id: '',
695
- review_status: 'disabled',
696
- reviewed_at: new Date().toISOString()
697
- };
698
- }
699
- function parseRiskReviewPayload(content) {
700
- var normalized = String(content || '').trim();
701
- if (!normalized.length) {
702
- return {};
703
- }
704
- try {
705
- return JSON.parse(normalized);
706
- }
707
- catch (_a) {
708
- // Fall through and try to parse a JSON object embedded in plain text.
709
- }
710
- var start = normalized.indexOf('{');
711
- var end = normalized.lastIndexOf('}');
712
- if (start !== -1 && end > start) {
713
- var candidate = normalized.slice(start, end + 1);
714
- try {
715
- return JSON.parse(candidate);
716
- }
717
- catch (_b) {
718
- return {};
719
- }
720
- }
721
- return {};
722
- }
723
- function normalizeRiskReview(operation, payload, model, requestId) {
724
- var riskLevel = normalizeRiskLevel(payload === null || payload === void 0 ? void 0 : payload.risk_level);
725
- var normalizedConfidence = Number(payload === null || payload === void 0 ? void 0 : payload.confidence);
726
- var confidence = Number.isFinite(normalizedConfidence)
727
- ? Math.max(0, Math.min(1, normalizedConfidence))
728
- : 0.6;
729
- var summary = normalizeOptionalString(payload === null || payload === void 0 ? void 0 : payload.summary)
730
- || "AI review marked this operation as ".concat(riskLevel, " risk.");
731
- var reasons = normalizeRiskList(payload === null || payload === void 0 ? void 0 : payload.reasons);
732
- var suggestedChecks = normalizeRiskList(payload === null || payload === void 0 ? void 0 : payload.suggested_checks);
733
- var shouldBlock = (payload === null || payload === void 0 ? void 0 : payload.should_block) === true || riskLevel === 'critical';
734
- return {
735
- operation: operation,
736
- risk_level: riskLevel,
737
- should_block: !!shouldBlock,
738
- summary: truncateForRiskReview(summary, 220),
739
- reasons: reasons,
740
- suggested_checks: suggestedChecks,
741
- confidence: confidence,
742
- model: model || '',
743
- request_id: requestId || '',
744
- review_status: 'ok',
745
- reviewed_at: new Date().toISOString()
746
- };
747
- }
748
- function resolveRiskReviewSettings() {
749
- var _a, _b, _c, _d, _e;
750
- var serverConfig = resolveio_server_app_1.ResolveIOServer.getServerConfig() || {};
751
- var enabled = parseBooleanValue((_a = serverConfig['MONGO_EXPLORER_ENABLE_AI_RISK_REVIEW']) !== null && _a !== void 0 ? _a : process.env.MONGO_EXPLORER_ENABLE_AI_RISK_REVIEW, true);
752
- var model = normalizeOptionalString(serverConfig['MONGO_EXPLORER_RISK_REVIEW_MODEL']
753
- || process.env.MONGO_EXPLORER_RISK_REVIEW_MODEL
754
- || serverConfig['AI_ASSISTANT_CODEX_MODEL']
755
- || process.env.AI_ASSISTANT_CODEX_MODEL
756
- || serverConfig['AI_DASHBOARD_CODEX_MODEL']
757
- || process.env.AI_DASHBOARD_CODEX_MODEL);
758
- var fallbackModel = normalizeOptionalString(serverConfig['MONGO_EXPLORER_RISK_REVIEW_FALLBACK_MODEL']
759
- || process.env.MONGO_EXPLORER_RISK_REVIEW_FALLBACK_MODEL
760
- || serverConfig['AI_ASSISTANT_CODEX_FALLBACK_MODEL']
761
- || process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL
762
- || serverConfig['AI_DASHBOARD_CODEX_FALLBACK_MODEL']
763
- || process.env.AI_DASHBOARD_CODEX_FALLBACK_MODEL);
764
- var timeoutMs = normalizePositiveNumber((_b = serverConfig['MONGO_EXPLORER_RISK_REVIEW_TIMEOUT_MS']) !== null && _b !== void 0 ? _b : process.env.MONGO_EXPLORER_RISK_REVIEW_TIMEOUT_MS, DEFAULT_RISK_REVIEW_TIMEOUT_MS);
765
- var maxTokens = normalizePositiveNumber((_c = serverConfig['MONGO_EXPLORER_RISK_REVIEW_MAX_TOKENS']) !== null && _c !== void 0 ? _c : process.env.MONGO_EXPLORER_RISK_REVIEW_MAX_TOKENS, DEFAULT_RISK_REVIEW_MAX_TOKENS);
766
- var maxRetries = normalizePositiveNumber((_d = serverConfig['OPENAI_MAX_RETRIES']) !== null && _d !== void 0 ? _d : process.env.OPENAI_MAX_RETRIES, 1);
767
- var retryDelayMs = normalizePositiveNumber((_e = serverConfig['OPENAI_RETRY_DELAY_MS']) !== null && _e !== void 0 ? _e : process.env.OPENAI_RETRY_DELAY_MS, 750);
768
- var apiKey = normalizeOptionalString(serverConfig['OPENAI_API_KEY'] || process.env.OPENAI_API_KEY) || '';
769
- var baseUrl = normalizeOptionalString(serverConfig['OPENAI_BASE_URL'] || process.env.OPENAI_BASE_URL);
770
- return {
771
- enabled: enabled,
772
- apiKey: apiKey,
773
- baseUrl: baseUrl,
774
- model: model,
775
- fallbackModel: fallbackModel,
776
- timeoutMs: timeoutMs,
777
- maxTokens: maxTokens,
778
- maxRetries: maxRetries,
779
- retryDelayMs: retryDelayMs
780
- };
781
- }
782
- function buildCodexPrompt(systemPrompt, userPrompt) {
783
- return "System:\n".concat(systemPrompt, "\n\nUser:\n").concat(userPrompt).trim();
784
- }
785
- function buildCodexClient(settings) {
786
- var fallbackModels = [];
787
- var fallback = normalizeOptionalString(settings.fallbackModel);
788
- if (fallback && fallback !== settings.model) {
789
- fallbackModels.push(fallback);
790
- }
791
- return new codex_client_1.CodexClient(__assign(__assign(__assign({ apiKey: settings.apiKey, baseUrl: settings.baseUrl }, (settings.model ? { model: settings.model } : {})), (fallbackModels.length ? { fallbackModel: fallbackModels[0], fallbackModels: fallbackModels } : {})), { maxRetries: (0, common_1.round)(settings.maxRetries || 0), retryDelayMs: (0, common_1.round)(settings.retryDelayMs || 0) }));
792
- }
793
- function estimateCodexUsage(messages, responseText, model) {
794
- var inputTokens = (0, tokenizer_1.countChatTokens)(messages, model);
795
- var outputTokens = (0, tokenizer_1.countTokens)(responseText || '', model);
796
- return {
797
- inputTokens: inputTokens,
798
- outputTokens: outputTokens,
799
- totalTokens: inputTokens + outputTokens
800
- };
801
- }
802
- function buildRiskReviewPrompt(input) {
803
- var payload = {
804
- database: input.database,
805
- collection: input.collection,
806
- operation: input.operation,
807
- mode: input.mode,
808
- changed_fields: pickChangedFields(input.before_document, input.after_document),
809
- delete_impact: sanitizeForRiskReview(input.delete_impact || null),
810
- before_document: sanitizeForRiskReview(input.before_document || null),
811
- after_document: sanitizeForRiskReview(input.after_document || null)
812
- };
813
- return [
814
- 'Review this MongoDB write operation for runtime and data integrity risk.',
815
- 'Focus on foreign-key style id_* dependencies, schema compatibility, destructive impact, and financial/operational record safety.',
816
- 'Return JSON only.',
817
- JSON.stringify(payload, null, 2)
818
- ].join('\n');
819
- }
820
- function reviewOperationRisk(input) {
821
- return __awaiter(this, void 0, void 0, function () {
822
- var settings, client, systemPrompt, userPrompt, prompt, responseText, payload, err_1, detail;
823
- return __generator(this, function (_a) {
824
- switch (_a.label) {
825
- case 0:
826
- settings = resolveRiskReviewSettings();
827
- if (!settings.enabled) {
828
- return [2 /*return*/, buildDisabledRiskReview(input.operation)];
829
- }
830
- if (!settings.apiKey) {
831
- return [2 /*return*/, buildFallbackRiskReview(input.operation, 'AI risk review unavailable: AI API key is missing.')];
832
- }
833
- client = buildCodexClient(settings);
834
- systemPrompt = [
835
- 'You are a MongoDB operation safety reviewer for a production SaaS application.',
836
- 'Respond with a single JSON object only.',
837
- 'Required keys:',
838
- 'risk_level ("low" | "medium" | "high" | "critical"),',
839
- 'should_block (boolean),',
840
- 'summary (string),',
841
- 'reasons (string[]),',
842
- 'suggested_checks (string[]),',
843
- 'confidence (number between 0 and 1).',
844
- 'Keep summary concise (<= 220 chars).'
845
- ].join(' ');
846
- userPrompt = buildRiskReviewPrompt(input);
847
- prompt = buildCodexPrompt(systemPrompt, userPrompt);
848
- _a.label = 1;
849
- case 1:
850
- _a.trys.push([1, 3, , 4]);
851
- return [4 /*yield*/, client.run(prompt, {
852
- timeoutMs: (0, common_1.round)(settings.timeoutMs),
853
- threadOptions: {
854
- model: settings.model,
855
- sandboxMode: 'read-only',
856
- skipGitRepoCheck: true,
857
- networkAccessEnabled: false,
858
- webSearchMode: 'disabled',
859
- webSearchEnabled: false,
860
- approvalPolicy: 'never'
861
- }
862
- })];
863
- case 2:
864
- responseText = _a.sent();
865
- payload = parseRiskReviewPayload(responseText);
866
- return [2 /*return*/, normalizeRiskReview(input.operation, payload, settings.model, '')];
867
- case 3:
868
- err_1 = _a.sent();
869
- detail = (err_1 === null || err_1 === void 0 ? void 0 : err_1.message) ? String(err_1.message) : 'Unknown AI review error';
870
- return [2 /*return*/, buildFallbackRiskReview(input.operation, "AI risk review failed: ".concat(truncateForRiskReview(detail, 160)), settings.model)];
871
- case 4: return [2 /*return*/];
872
- }
873
- });
874
- });
875
- }
876
- function normalizeAiAction(value) {
877
- var normalized = normalizeOptionalString(value) || '';
878
- return normalized.toLowerCase() === 'aggregate' ? 'aggregate' : 'find';
879
- }
880
- function sanitizeAiCollections(raw) {
881
- var values = [];
882
- var seen = new Set();
883
- (raw || []).forEach(function (entry) {
884
- var normalized = normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.collection) || (entry === null || entry === void 0 ? void 0 : entry.name) || entry);
885
- if (!normalized) {
886
- return;
887
- }
888
- var key = normalized.toLowerCase();
889
- if (seen.has(key)) {
890
- return;
891
- }
892
- seen.add(key);
893
- values.push(normalized);
894
- });
895
- return values.slice(0, MAX_AI_SUGGEST_COLLECTIONS);
896
- }
897
- function sanitizeAiFields(raw, fallbackCollection) {
898
- var fields = [];
899
- var seen = new Set();
900
- (raw || []).forEach(function (entry) {
901
- var path = normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.path) || (entry === null || entry === void 0 ? void 0 : entry.field_path) || (entry === null || entry === void 0 ? void 0 : entry.fieldPath));
902
- if (!path) {
903
- return;
904
- }
905
- var collection = normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.collection) || (entry === null || entry === void 0 ? void 0 : entry.collection_name) || (entry === null || entry === void 0 ? void 0 : entry.collectionName)) || fallbackCollection || '';
906
- var key = "".concat(collection.toLowerCase(), "::").concat(path.toLowerCase());
907
- if (seen.has(key)) {
908
- return;
909
- }
910
- seen.add(key);
911
- fields.push({
912
- path: path,
913
- label: normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.label) || (entry === null || entry === void 0 ? void 0 : entry.field_path_name) || (entry === null || entry === void 0 ? void 0 : entry.fieldPathName)) || path,
914
- type: normalizeOptionalString((entry === null || entry === void 0 ? void 0 : entry.type) || (entry === null || entry === void 0 ? void 0 : entry.field_type) || (entry === null || entry === void 0 ? void 0 : entry.fieldType)) || 'Any',
915
- collection: collection
916
- });
917
- });
918
- return fields.slice(0, MAX_AI_SUGGEST_FIELDS);
919
- }
920
- function deriveAiFieldsFromCollection(database, collection) {
921
- if (!collection) {
922
- return [];
923
- }
924
- var managerCollection = resolveCollectionHandle(database, collection).managerCollection;
925
- if (!managerCollection) {
926
- return [];
927
- }
928
- var schema = getSchemaDefinition(managerCollection);
929
- return Object.keys(schema)
930
- .sort(function (a, b) { return a.localeCompare(b); })
931
- .slice(0, MAX_AI_SUGGEST_FIELDS)
932
- .map(function (path) {
933
- var definition = schema[path];
934
- return {
935
- path: path,
936
- label: toLabel(path),
937
- type: getSchemaTypeName(definition),
938
- collection: collection
939
- };
940
- });
941
- }
942
- function resolveCollectionFromList(value, collections, fallback) {
943
- if (fallback === void 0) { fallback = ''; }
944
- var normalized = normalizeOptionalString(value);
945
- if (normalized) {
946
- var matched = (collections || []).find(function (entry) { return entry.toLowerCase() === normalized.toLowerCase(); });
947
- if (matched) {
948
- return matched;
949
- }
950
- }
951
- if (fallback) {
952
- return fallback;
953
- }
954
- return (collections === null || collections === void 0 ? void 0 : collections[0]) || '';
955
- }
956
- function normalizeAiResultLimit(value, fallback) {
957
- if (fallback === void 0) { fallback = 100; }
958
- var fallbackValue = Math.min(Math.max(fallback, 1), MAX_AI_SUGGEST_RESULTS);
959
- var parsed = Number(value);
960
- if (!Number.isFinite(parsed) || parsed <= 0) {
961
- return fallbackValue;
962
- }
963
- return Math.min(Math.max((0, common_1.round)(parsed), 1), MAX_AI_SUGGEST_RESULTS);
964
- }
965
- function normalizeAiSkip(value) {
966
- var parsed = Number(value);
967
- if (!Number.isFinite(parsed) || parsed < 0) {
968
- return 0;
969
- }
970
- return Math.max(0, (0, common_1.round)(parsed));
971
- }
972
- function normalizeAiObject(value) {
973
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
974
- return {};
975
- }
976
- return value;
977
- }
978
- function hasObjectKeys(value) {
979
- return !!value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
980
- }
981
- function parseAiPlanPayload(content) {
982
- var normalized = String(content || '').trim();
983
- if (!normalized.length) {
984
- return {};
985
- }
986
- try {
987
- return JSON.parse(normalized);
988
- }
989
- catch (_a) {
990
- // Fall through and parse embedded JSON object.
991
- }
992
- var start = normalized.indexOf('{');
993
- var end = normalized.lastIndexOf('}');
994
- if (start !== -1 && end > start) {
995
- try {
996
- return JSON.parse(normalized.slice(start, end + 1));
997
- }
998
- catch (_b) {
999
- return {};
1000
- }
1001
- }
1002
- return {};
1003
- }
1004
- function resolveMongoExplorerAiSettings() {
1005
- var _a, _b, _c, _d;
1006
- var serverConfig = resolveio_server_app_1.ResolveIOServer.getServerConfig() || {};
1007
- var apiKey = normalizeOptionalString(serverConfig['OPENAI_API_KEY'] || process.env.OPENAI_API_KEY) || '';
1008
- var baseUrl = normalizeOptionalString(serverConfig['OPENAI_BASE_URL'] || process.env.OPENAI_BASE_URL);
1009
- var model = normalizeOptionalString(serverConfig['MONGO_EXPLORER_AI_MODEL']
1010
- || process.env.MONGO_EXPLORER_AI_MODEL
1011
- || serverConfig['AI_ASSISTANT_CODEX_MODEL']
1012
- || process.env.AI_ASSISTANT_CODEX_MODEL);
1013
- var fallbackModel = normalizeOptionalString(serverConfig['MONGO_EXPLORER_AI_FALLBACK_MODEL']
1014
- || process.env.MONGO_EXPLORER_AI_FALLBACK_MODEL
1015
- || serverConfig['AI_ASSISTANT_CODEX_FALLBACK_MODEL']
1016
- || process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL);
1017
- var timeoutMs = normalizePositiveNumber((_a = serverConfig['MONGO_EXPLORER_AI_TIMEOUT_MS']) !== null && _a !== void 0 ? _a : process.env.MONGO_EXPLORER_AI_TIMEOUT_MS, DEFAULT_AI_SUGGEST_TIMEOUT_MS);
1018
- var maxTokens = normalizePositiveNumber((_b = serverConfig['MONGO_EXPLORER_AI_MAX_TOKENS']) !== null && _b !== void 0 ? _b : process.env.MONGO_EXPLORER_AI_MAX_TOKENS, DEFAULT_AI_SUGGEST_MAX_TOKENS);
1019
- var maxRetries = normalizePositiveNumber((_c = serverConfig['OPENAI_MAX_RETRIES']) !== null && _c !== void 0 ? _c : process.env.OPENAI_MAX_RETRIES, 1);
1020
- var retryDelayMs = normalizePositiveNumber((_d = serverConfig['OPENAI_RETRY_DELAY_MS']) !== null && _d !== void 0 ? _d : process.env.OPENAI_RETRY_DELAY_MS, 750);
1021
- return {
1022
- apiKey: apiKey,
1023
- baseUrl: baseUrl,
1024
- model: model,
1025
- fallbackModel: fallbackModel,
1026
- timeoutMs: timeoutMs,
1027
- maxTokens: maxTokens,
1028
- maxRetries: maxRetries,
1029
- retryDelayMs: retryDelayMs
1030
- };
1031
- }
1032
- function buildMongoExplorerAiSystemPrompt() {
1033
- return [
1034
- 'You are a MongoDB query planner for a read-only Mongo Explorer UI.',
1035
- 'Return a single JSON object and nothing else.',
1036
- 'Supported schema:',
1037
- '{',
1038
- ' "action": "find|aggregate",',
1039
- ' "collection": "string",',
1040
- ' "query": { ... },',
1041
- ' "pipeline": [{ ... }],',
1042
- ' "options": {',
1043
- ' "projection": { "field": 1 },',
1044
- ' "sort": { "field": -1 },',
1045
- ' "limit": 100,',
1046
- ' "skip": 0,',
1047
- ' "includeTotal": true,',
1048
- ' "allowDiskUse": true',
1049
- ' },',
1050
- ' "notes": "short summary"',
1051
- '}',
1052
- 'Rules:',
1053
- '- Use only provided collection names and field paths.',
1054
- '- Read-only only. Never output write operations, update/delete commands, or aggregation stages $out/$merge.',
1055
- '- Prefer action=find for direct lookups and simple filters.',
1056
- '- Use action=aggregate for grouped totals, rankings, or trend buckets.',
1057
- '- Keep options.limit between 1 and 500.',
1058
- '- If request is ambiguous, use selected_collection and a conservative limit.'
1059
- ].join('\n');
1060
- }
1061
- function buildMongoExplorerAiUserPrompt(input) {
1062
- var payload = {
1063
- request: input.prompt,
1064
- selected_collection: input.selectedCollection || '',
1065
- max_results: input.maxResults,
1066
- available_collections: input.availableCollections || [],
1067
- available_fields: input.availableFields || []
1068
- };
1069
- return JSON.stringify(payload);
1070
- }
1071
- function sanitizeAggregatePipeline(rawPipeline, limit) {
1072
- var source = Array.isArray(rawPipeline) ? rawPipeline : [];
1073
- var sanitized = [];
1074
- var removedRestricted = false;
1075
- source.forEach(function (stage) {
1076
- if (!stage || typeof stage !== 'object' || Array.isArray(stage)) {
1077
- return;
1078
- }
1079
- var keys = Object.keys(stage);
1080
- if (!keys.length) {
1081
- return;
1082
- }
1083
- var stageName = keys[0];
1084
- if (RESTRICTED_AGGREGATE_STAGES.has(String(stageName).toLowerCase())) {
1085
- removedRestricted = true;
1086
- return;
1087
- }
1088
- if (stageName === '$limit') {
1089
- sanitized.push({ $limit: normalizeAiResultLimit(stage.$limit, limit) });
1090
- return;
1091
- }
1092
- sanitized.push(stage);
1093
- });
1094
- if (!sanitized.some(function (stage) { return Object.keys(stage || {})[0] === '$limit'; })) {
1095
- sanitized.push({ $limit: limit });
1096
- }
1097
- return {
1098
- pipeline: sanitized,
1099
- removedRestricted: removedRestricted
1100
- };
1101
- }
1102
- function sanitizeFindOptions(raw, fallbackLimit) {
1103
- var options = normalizeAiObject(raw);
1104
- return {
1105
- projection: hasObjectKeys(options.projection) ? options.projection : undefined,
1106
- sort: hasObjectKeys(options.sort) ? options.sort : undefined,
1107
- limit: normalizeAiResultLimit(options.limit, fallbackLimit),
1108
- skip: normalizeAiSkip(options.skip),
1109
- includeTotal: options.includeTotal === true
1110
- };
1111
- }
1112
- function buildMongoExplorerAiNotes(rawNotes, action, collection, rowCount, total, removedRestricted) {
1113
- var notes = [];
1114
- var base = normalizeOptionalString(rawNotes);
1115
- if (base) {
1116
- notes.push(base);
1117
- }
1118
- var actionLabel = action === 'aggregate' ? 'aggregate pipeline' : 'query';
1119
- if (typeof total === 'number' && total >= 0) {
1120
- notes.push("Applied ".concat(actionLabel, " on ").concat(collection, ". Loaded ").concat(rowCount, " of ").concat(total, " rows."));
1121
- }
1122
- else {
1123
- notes.push("Applied ".concat(actionLabel, " on ").concat(collection, ". Loaded ").concat(rowCount, " rows."));
1124
- }
1125
- if (removedRestricted) {
1126
- notes.push('Removed restricted write stages from the generated pipeline.');
1127
- }
1128
- return notes.join(' ').trim();
1129
- }
1130
- function resolveUsageClientId(idClientInput, idUser) {
1131
- return __awaiter(this, void 0, void 0, function () {
1132
- var normalized, user, _a;
1133
- var _b, _c;
1134
- return __generator(this, function (_d) {
1135
- switch (_d.label) {
1136
- case 0:
1137
- normalized = normalizeOptionalString(idClientInput);
1138
- if (normalized) {
1139
- return [2 /*return*/, normalized];
1140
- }
1141
- if (!idUser) {
1142
- return [2 /*return*/, ''];
1143
- }
1144
- _d.label = 1;
1145
- case 1:
1146
- _d.trys.push([1, 3, , 4]);
1147
- return [4 /*yield*/, user_collection_1.Users.findById(idUser)];
1148
- case 2:
1149
- user = _d.sent();
1150
- return [2 /*return*/, normalizeOptionalString(((_b = user === null || user === void 0 ? void 0 : user.other) === null || _b === void 0 ? void 0 : _b.id_client) || ((_c = user === null || user === void 0 ? void 0 : user.other) === null || _c === void 0 ? void 0 : _c.idClient)) || ''];
1151
- case 3:
1152
- _a = _d.sent();
1153
- return [2 /*return*/, ''];
1154
- case 4: return [2 /*return*/];
1155
- }
1156
- });
1157
- });
1158
- }
1159
- function executeMongoExplorerAi(payload, context) {
1160
- return __awaiter(this, void 0, void 0, function () {
1161
- var input, prompt, database, db, availableCollections, listed, selectedCollection, availableFields, settings, maxResults, client, messages, responseText, parsed, action, collection, plan, removedRestrictedStages, optionsRaw, aggregateLimit, pipelineResult, aggregateOptions, aggregateRows, rows, query, options, findOptions, rows, total, _a, usage, idClient;
1162
- var _b;
1163
- return __generator(this, function (_c) {
1164
- switch (_c.label) {
1165
- case 0:
1166
- input = payload || {};
1167
- prompt = normalizeOptionalString(input.prompt);
1168
- if (!prompt) {
1169
- throw new Error('Prompt is required.');
1170
- }
1171
- database = resolveDatabaseName(input.database);
1172
- db = resolveDatabase(database);
1173
- availableCollections = sanitizeAiCollections(input.available_collections || []);
1174
- if (!!availableCollections.length) return [3 /*break*/, 2];
1175
- return [4 /*yield*/, db.listCollections().toArray()];
1176
- case 1:
1177
- listed = _c.sent();
1178
- availableCollections = listed
1179
- .map(function (collection) { return normalizeOptionalString(collection === null || collection === void 0 ? void 0 : collection.name); })
1180
- .filter(function (collection) { return !!collection; })
1181
- .slice(0, MAX_AI_SUGGEST_COLLECTIONS);
1182
- _c.label = 2;
1183
- case 2:
1184
- if (!availableCollections.length) {
1185
- throw new Error('Mongo Explorer AI assistant: no collections available.');
1186
- }
1187
- selectedCollection = resolveCollectionFromList(input.selected_collection, availableCollections, availableCollections[0]);
1188
- availableFields = sanitizeAiFields(input.available_fields || [], selectedCollection);
1189
- if (!availableFields.length && selectedCollection) {
1190
- availableFields = deriveAiFieldsFromCollection(database, selectedCollection);
1191
- }
1192
- settings = resolveMongoExplorerAiSettings();
1193
- if (!settings.apiKey) {
1194
- throw new Error('AI API key missing. Add an AI API key to server config.');
1195
- }
1196
- maxResults = normalizeAiResultLimit(input.max_results, 100);
1197
- client = buildCodexClient(settings);
1198
- messages = [
1199
- { role: 'system', content: buildMongoExplorerAiSystemPrompt() },
1200
- {
1201
- role: 'user',
1202
- content: buildMongoExplorerAiUserPrompt({
1203
- prompt: prompt,
1204
- selectedCollection: selectedCollection,
1205
- availableCollections: availableCollections,
1206
- availableFields: availableFields,
1207
- maxResults: maxResults
1208
- })
1209
- }
1210
- ];
1211
- return [4 /*yield*/, client.run(buildCodexPrompt(messages[0].content, messages[1].content), {
1212
- timeoutMs: (0, common_1.round)(settings.timeoutMs),
1213
- threadOptions: {
1214
- model: settings.model,
1215
- sandboxMode: 'read-only',
1216
- skipGitRepoCheck: true,
1217
- networkAccessEnabled: false,
1218
- webSearchMode: 'disabled',
1219
- webSearchEnabled: false,
1220
- approvalPolicy: 'never'
1221
- }
1222
- })];
1223
- case 3:
1224
- responseText = _c.sent();
1225
- parsed = parseAiPlanPayload(responseText);
1226
- action = normalizeAiAction((parsed === null || parsed === void 0 ? void 0 : parsed.action) || (Array.isArray(parsed === null || parsed === void 0 ? void 0 : parsed.pipeline) ? 'aggregate' : 'find'));
1227
- collection = resolveCollectionFromList((parsed === null || parsed === void 0 ? void 0 : parsed.collection) || (parsed === null || parsed === void 0 ? void 0 : parsed.collection_name), availableCollections, selectedCollection || availableCollections[0]);
1228
- if (!collection) {
1229
- throw new Error('Mongo Explorer AI assistant could not resolve a collection.');
1230
- }
1231
- plan = {
1232
- action: action,
1233
- collection: collection,
1234
- options: {}
1235
- };
1236
- removedRestrictedStages = false;
1237
- if (!(action === 'aggregate')) return [3 /*break*/, 5];
1238
- optionsRaw = normalizeAiObject(parsed === null || parsed === void 0 ? void 0 : parsed.options);
1239
- aggregateLimit = normalizeAiResultLimit((_b = optionsRaw.limit) !== null && _b !== void 0 ? _b : parsed === null || parsed === void 0 ? void 0 : parsed.limit, maxResults);
1240
- pipelineResult = sanitizeAggregatePipeline(parsed === null || parsed === void 0 ? void 0 : parsed.pipeline, aggregateLimit);
1241
- removedRestrictedStages = pipelineResult.removedRestricted;
1242
- aggregateOptions = {
1243
- allowDiskUse: optionsRaw.allowDiskUse === true
1244
- };
1245
- return [4 /*yield*/, db.collection(collection).aggregate(pipelineResult.pipeline, aggregateOptions).toArray()];
1246
- case 4:
1247
- aggregateRows = _c.sent();
1248
- rows = (aggregateRows || []).slice(0, aggregateLimit);
1249
- plan = {
1250
- action: action,
1251
- collection: collection,
1252
- pipeline: pipelineResult.pipeline,
1253
- options: {
1254
- allowDiskUse: aggregateOptions.allowDiskUse,
1255
- limit: aggregateLimit
1256
- },
1257
- documents: rows,
1258
- total: null
1259
- };
1260
- return [3 /*break*/, 10];
1261
- case 5:
1262
- query = normalizeAiObject(parsed === null || parsed === void 0 ? void 0 : parsed.query);
1263
- options = sanitizeFindOptions(parsed === null || parsed === void 0 ? void 0 : parsed.options, maxResults);
1264
- findOptions = {
1265
- limit: options.limit,
1266
- skip: options.skip
1267
- };
1268
- if (options.projection) {
1269
- findOptions.projection = options.projection;
1270
- }
1271
- if (options.sort) {
1272
- findOptions.sort = options.sort;
1273
- }
1274
- return [4 /*yield*/, db.collection(collection).find(query, findOptions).toArray()];
1275
- case 6:
1276
- rows = _c.sent();
1277
- if (!options.includeTotal) return [3 /*break*/, 8];
1278
- return [4 /*yield*/, db.collection(collection).countDocuments(query)];
1279
- case 7:
1280
- _a = _c.sent();
1281
- return [3 /*break*/, 9];
1282
- case 8:
1283
- _a = null;
1284
- _c.label = 9;
1285
- case 9:
1286
- total = _a;
1287
- plan = {
1288
- action: action,
1289
- collection: collection,
1290
- query: query,
1291
- options: __assign(__assign(__assign({}, (options.projection ? { projection: options.projection } : {})), (options.sort ? { sort: options.sort } : {})), { limit: options.limit, skip: options.skip, includeTotal: options.includeTotal }),
1292
- documents: rows,
1293
- total: total
1294
- };
1295
- _c.label = 10;
1296
- case 10:
1297
- plan.notes = buildMongoExplorerAiNotes(parsed === null || parsed === void 0 ? void 0 : parsed.notes, plan.action, plan.collection, Array.isArray(plan.documents) ? plan.documents.length : 0, typeof plan.total === 'number' ? plan.total : null, removedRestrictedStages);
1298
- usage = estimateCodexUsage(messages, responseText, settings.model);
1299
- return [4 /*yield*/, resolveUsageClientId(input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
1300
- case 11:
1301
- idClient = _c.sent();
1302
- if (!usage.totalTokens) return [3 /*break*/, 13];
1303
- return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
1304
- id_client: idClient || '',
1305
- model: settings.model || 'unknown',
1306
- input_tokens: usage.inputTokens || 0,
1307
- output_tokens: usage.outputTokens || 0,
1308
- total_tokens: usage.totalTokens || 0,
1309
- category: 'mongo-explorer-ai',
1310
- id_request: ''
1311
- })];
1312
- case 12:
1313
- _c.sent();
1314
- _c.label = 13;
1315
- case 13: return [2 /*return*/, {
1316
- notes: plan.notes,
1317
- plan: plan,
1318
- model: settings.model,
1319
- usage: {
1320
- input_tokens: usage.inputTokens || 0,
1321
- output_tokens: usage.outputTokens || 0,
1322
- total_tokens: usage.totalTokens || 0
1323
- }
1324
- }];
1325
- }
1326
- });
1327
- });
1328
- }
1329
- function loadMongoExplorerMethods(methodManager) {
1330
- methodManager.methods({
1331
- mongoExplorerAiSuggest: {
1332
- check: new simpl_schema_1.default({
1333
- payload: {
1334
- type: Object,
1335
- blackbox: true
1336
- }
1337
- }),
1338
- function: function (payload) {
1339
- return __awaiter(this, void 0, void 0, function () {
1340
- return __generator(this, function (_a) {
1341
- return [2 /*return*/, executeMongoExplorerAi(payload || {}, this)];
1342
- });
1343
- });
1344
- }
1345
- },
1346
- mongoExplorerListCollections: {
1347
- check: new simpl_schema_1.default({
1348
- database: {
1349
- type: String,
1350
- optional: true
1351
- }
1352
- }),
1353
- function: function (database) {
1354
- return __awaiter(this, void 0, void 0, function () {
1355
- var db, collections;
1356
- return __generator(this, function (_a) {
1357
- switch (_a.label) {
1358
- case 0:
1359
- db = resolveDatabase(database);
1360
- return [4 /*yield*/, db.listCollections().toArray()];
1361
- case 1:
1362
- collections = _a.sent();
1363
- return [2 /*return*/, collections
1364
- .map(function (col) { return ({
1365
- name: col.name,
1366
- type: col.type || 'collection'
1367
- }); })
1368
- .sort(function (a, b) { return a.name.localeCompare(b.name); })];
1369
- }
1370
- });
1371
- });
1372
- }
1373
- },
1374
- mongoExplorerFind: {
1375
- bypassSession: true,
1376
- check: new simpl_schema_1.default({
1377
- database: {
1378
- type: String,
1379
- optional: true
1380
- },
1381
- collection: {
1382
- type: String
1383
- },
1384
- query: {
1385
- type: Object,
1386
- blackbox: true,
1387
- optional: true
1388
- },
1389
- options: {
1390
- type: Object,
1391
- blackbox: true,
1392
- optional: true
1393
- }
1394
- }),
1395
- function: function (database_1, collection_1) {
1396
- return __awaiter(this, arguments, void 0, function (database, collection, query, options) {
1397
- var db, normalized, documents, total;
1398
- if (query === void 0) { query = {}; }
1399
- return __generator(this, function (_a) {
1400
- switch (_a.label) {
1401
- case 0:
1402
- db = resolveDatabase(database);
1403
- normalized = normalizeFindOptions(options);
1404
- return [4 /*yield*/, db.collection(collection).find(query || {}, normalized.findOptions).toArray()];
1405
- case 1:
1406
- documents = _a.sent();
1407
- total = null;
1408
- if (!normalized.includeTotal) return [3 /*break*/, 3];
1409
- return [4 /*yield*/, db.collection(collection).countDocuments(query || {})];
1410
- case 2:
1411
- total = _a.sent();
1412
- _a.label = 3;
1413
- case 3: return [2 /*return*/, {
1414
- documents: documents,
1415
- total: total
1416
- }];
1417
- }
1418
- });
1419
- });
1420
- }
1421
- },
1422
- mongoExplorerGetCollectionSchema: {
1423
- check: new simpl_schema_1.default({
1424
- database: {
1425
- type: String,
1426
- optional: true
1427
- },
1428
- collection: {
1429
- type: String
1430
- }
1431
- }),
1432
- function: function (database, collection) {
1433
- var dbName = resolveDatabaseName(database);
1434
- var managerCollection = resolveCollectionHandle(dbName, collection).managerCollection;
1435
- if (!managerCollection) {
1436
- return Promise.resolve({
1437
- collection: collection,
1438
- has_schema: false,
1439
- fields: []
1440
- });
1441
- }
1442
- var schema = getSchemaDefinition(managerCollection);
1443
- var fields = Object.keys(schema)
1444
- .sort(function (a, b) { return a.localeCompare(b); })
1445
- .map(function (path) {
1446
- var definition = schema[path];
1447
- return {
1448
- path: path,
1449
- label: toLabel(path),
1450
- type: getSchemaTypeName(definition),
1451
- optional: (definition === null || definition === void 0 ? void 0 : definition.optional) === true,
1452
- protected: isProtectedFieldPath(path),
1453
- depth: path.split('.').filter(function (segment) { return segment !== '$'; }).length - 1
1454
- };
1455
- });
1456
- return Promise.resolve({
1457
- collection: collection,
1458
- has_schema: true,
1459
- fields: fields
1460
- });
1461
- }
1462
- },
1463
- mongoExplorerAggregate: {
1464
- bypassSession: true,
1465
- check: new simpl_schema_1.default({
1466
- database: {
1467
- type: String,
1468
- optional: true
1469
- },
1470
- collection: {
1471
- type: String
1472
- },
1473
- pipeline: {
1474
- type: Array
1475
- },
1476
- 'pipeline.$': {
1477
- type: Object,
1478
- blackbox: true
1479
- },
1480
- options: {
1481
- type: Object,
1482
- optional: true,
1483
- blackbox: true
1484
- }
1485
- }),
1486
- function: function (database_1, collection_1, pipeline_1) {
1487
- return __awaiter(this, arguments, void 0, function (database, collection, pipeline, options) {
1488
- var db;
1489
- if (options === void 0) { options = {}; }
1490
- return __generator(this, function (_a) {
1491
- db = resolveDatabase(database);
1492
- return [2 /*return*/, db.collection(collection).aggregate(pipeline || [], options || undefined).toArray()];
1493
- });
1494
- });
1495
- }
1496
- },
1497
- mongoExplorerCommand: {
1498
- check: new simpl_schema_1.default({
1499
- database: {
1500
- type: String,
1501
- optional: true
1502
- },
1503
- command: {
1504
- type: Object,
1505
- blackbox: true
1506
- },
1507
- permissionView: {
1508
- type: String,
1509
- optional: true
1510
- },
1511
- mode: {
1512
- type: String,
1513
- optional: true
1514
- }
1515
- }),
1516
- function: function (database, command, permissionView, mode) {
1517
- return __awaiter(this, void 0, void 0, function () {
1518
- var db;
1519
- return __generator(this, function (_a) {
1520
- switch (_a.label) {
1521
- case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1522
- case 1:
1523
- _a.sent();
1524
- db = resolveDatabase(database);
1525
- return [2 /*return*/, db.command(command)];
1526
- }
1527
- });
1528
- });
1529
- }
1530
- },
1531
- mongoExplorerInsertDocument: {
1532
- check: new simpl_schema_1.default({
1533
- database: {
1534
- type: String,
1535
- optional: true
1536
- },
1537
- collection: {
1538
- type: String
1539
- },
1540
- document: {
1541
- type: Object,
1542
- blackbox: true
1543
- },
1544
- permissionView: {
1545
- type: String,
1546
- optional: true
1547
- },
1548
- mode: {
1549
- type: String,
1550
- optional: true
1551
- }
1552
- }),
1553
- function: function (database, collection, document, permissionView, mode) {
1554
- return __awaiter(this, void 0, void 0, function () {
1555
- var dbName, _a, managerCollection, dbCollection;
1556
- return __generator(this, function (_b) {
1557
- switch (_b.label) {
1558
- case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1559
- case 1:
1560
- _b.sent();
1561
- dbName = resolveDatabaseName(database);
1562
- _a = resolveCollectionHandle(dbName, collection), managerCollection = _a.managerCollection, dbCollection = _a.dbCollection;
1563
- if (!document || typeof document !== 'object') {
1564
- throw new Error('Mongo Explorer: Document is required');
1565
- }
1566
- if (!managerCollection && !allowUnschemaizedWrites()) {
1567
- throw new Error('Mongo Explorer: Writes require schema-backed collections. Set MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE=true to bypass.');
1568
- }
1569
- if (!document._id) {
1570
- document._id = (0, common_1.objectIdHexString)();
1571
- }
1572
- if (document.__v === undefined) {
1573
- document.__v = 0;
1574
- }
1575
- if (!managerCollection) return [3 /*break*/, 3];
1576
- coerceDateFields(managerCollection, document);
1577
- return [4 /*yield*/, managerCollection.insertOne(document)];
1578
- case 2:
1579
- _b.sent();
1580
- return [3 /*break*/, 5];
1581
- case 3: return [4 /*yield*/, dbCollection.insertOne(document)];
1582
- case 4:
1583
- _b.sent();
1584
- _b.label = 5;
1585
- case 5: return [2 /*return*/, document._id];
1586
- }
1587
- });
1588
- });
1589
- }
1590
- },
1591
- mongoExplorerReplaceDocument: {
1592
- check: new simpl_schema_1.default({
1593
- database: {
1594
- type: String,
1595
- optional: true
1596
- },
1597
- collection: {
1598
- type: String
1599
- },
1600
- document: {
1601
- type: Object,
1602
- blackbox: true
1603
- },
1604
- permissionView: {
1605
- type: String,
1606
- optional: true
1607
- },
1608
- mode: {
1609
- type: String,
1610
- optional: true
1611
- }
1612
- }),
1613
- function: function (database, collection, document, permissionView, mode) {
1614
- return __awaiter(this, void 0, void 0, function () {
1615
- var dbName, _a, managerCollection, dbCollection, currentDoc, _b;
1616
- return __generator(this, function (_c) {
1617
- switch (_c.label) {
1618
- case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1619
- case 1:
1620
- _c.sent();
1621
- dbName = resolveDatabaseName(database);
1622
- _a = resolveCollectionHandle(dbName, collection), managerCollection = _a.managerCollection, dbCollection = _a.dbCollection;
1623
- if (!document || typeof document !== 'object' || !document._id) {
1624
- throw new Error('Mongo Explorer: Document with _id is required');
1625
- }
1626
- if (!managerCollection) return [3 /*break*/, 3];
1627
- return [4 /*yield*/, managerCollection.findOne({ _id: document._id })];
1628
- case 2:
1629
- _b = _c.sent();
1630
- return [3 /*break*/, 5];
1631
- case 3: return [4 /*yield*/, dbCollection.findOne({ _id: document._id })];
1632
- case 4:
1633
- _b = _c.sent();
1634
- _c.label = 5;
1635
- case 5:
1636
- currentDoc = _b;
1637
- if (!currentDoc) {
1638
- throw new Error('Mongo Explorer: Document not found');
1639
- }
1640
- ensureProtectedFieldsUnchanged(currentDoc, document);
1641
- if (!managerCollection && !allowUnschemaizedWrites()) {
1642
- throw new Error('Mongo Explorer: Writes require schema-backed collections. Set MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE=true to bypass.');
1643
- }
1644
- if (!managerCollection) return [3 /*break*/, 7];
1645
- coerceDateFields(managerCollection, document);
1646
- return [4 /*yield*/, managerCollection.replaceOne({ _id: document._id }, document)];
1647
- case 6:
1648
- _c.sent();
1649
- return [3 /*break*/, 9];
1650
- case 7: return [4 /*yield*/, dbCollection.replaceOne({ _id: document._id }, document)];
1651
- case 8:
1652
- _c.sent();
1653
- _c.label = 9;
1654
- case 9: return [2 /*return*/, true];
1655
- }
1656
- });
1657
- });
1658
- }
1659
- },
1660
- mongoExplorerReviewOperationRisk: {
1661
- check: new simpl_schema_1.default({
1662
- database: {
1663
- type: String,
1664
- optional: true
1665
- },
1666
- collection: {
1667
- type: String
1668
- },
1669
- operation: {
1670
- type: String,
1671
- allowedValues: ['insert', 'replace', 'delete', 'command']
1672
- },
1673
- before_document: {
1674
- type: Object,
1675
- blackbox: true,
1676
- optional: true
1677
- },
1678
- after_document: {
1679
- type: Object,
1680
- blackbox: true,
1681
- optional: true
1682
- },
1683
- delete_impact: {
1684
- type: Object,
1685
- blackbox: true,
1686
- optional: true
1687
- },
1688
- permissionView: {
1689
- type: String,
1690
- optional: true
1691
- },
1692
- mode: {
1693
- type: String,
1694
- optional: true
1695
- }
1696
- }),
1697
- function: function (database, collection, operation, before_document, after_document, delete_impact, permissionView, mode) {
1698
- return __awaiter(this, void 0, void 0, function () {
1699
- var dbName;
1700
- return __generator(this, function (_a) {
1701
- switch (_a.label) {
1702
- case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1703
- case 1:
1704
- _a.sent();
1705
- dbName = resolveDatabaseName(database);
1706
- return [2 /*return*/, reviewOperationRisk({
1707
- database: dbName,
1708
- collection: collection,
1709
- operation: operation,
1710
- mode: normalizeExplorerMode(mode),
1711
- before_document: before_document,
1712
- after_document: after_document,
1713
- delete_impact: delete_impact
1714
- })];
1715
- }
1716
- });
1717
- });
1718
- }
1719
- },
1720
- mongoExplorerDeleteDocument: {
1721
- check: new simpl_schema_1.default({
1722
- database: {
1723
- type: String,
1724
- optional: true
1725
- },
1726
- collection: {
1727
- type: String
1728
- },
1729
- doc_id: {
1730
- type: String
1731
- },
1732
- permissionView: {
1733
- type: String,
1734
- optional: true
1735
- },
1736
- force: {
1737
- type: Boolean,
1738
- optional: true
1739
- },
1740
- mode: {
1741
- type: String,
1742
- optional: true
1743
- }
1744
- }),
1745
- function: function (database_1, collection_1, doc_id_1, permissionView_1) {
1746
- return __awaiter(this, arguments, void 0, function (database, collection, doc_id, permissionView, force, mode) {
1747
- var dbName, impact, collectionPreview, _a, managerCollection, dbCollection, deleteFilter;
1748
- if (force === void 0) { force = false; }
1749
- return __generator(this, function (_b) {
1750
- switch (_b.label) {
1751
- case 0: return [4 /*yield*/, ensureWriteAccess(this, permissionView, mode)];
1752
- case 1:
1753
- _b.sent();
1754
- dbName = resolveDatabaseName(database);
1755
- return [4 /*yield*/, buildDeleteImpact(dbName, collection, doc_id)];
1756
- case 2:
1757
- impact = _b.sent();
1758
- if (!force && (impact.unresolved || impact.has_references)) {
1759
- collectionPreview = impact.collections.slice(0, 3).map(function (item) { return item.collection; }).join(', ');
1760
- if (impact.unresolved) {
1761
- throw new Error('Mongo Explorer: Delete blocked because dependency checks could not complete. Use force delete after review.');
1762
- }
1763
- throw new Error("Mongo Explorer: Delete blocked. Document is referenced by ".concat(collectionPreview).concat(impact.collections.length > 3 ? ', ...' : ''));
1764
- }
1765
- _a = resolveCollectionHandle(dbName, collection), managerCollection = _a.managerCollection, dbCollection = _a.dbCollection;
1766
- deleteFilter = { _id: doc_id };
1767
- if (!managerCollection) return [3 /*break*/, 4];
1768
- return [4 /*yield*/, managerCollection.deleteOne(deleteFilter)];
1769
- case 3:
1770
- _b.sent();
1771
- return [3 /*break*/, 6];
1772
- case 4: return [4 /*yield*/, dbCollection.deleteOne(deleteFilter)];
1773
- case 5:
1774
- _b.sent();
1775
- _b.label = 6;
1776
- case 6: return [2 /*return*/, true];
1777
- }
1778
- });
1779
- });
1780
- }
1781
- },
1782
- mongoExplorerDeleteImpact: {
1783
- check: new simpl_schema_1.default({
1784
- database: {
1785
- type: String,
1786
- optional: true
1787
- },
1788
- collection: {
1789
- type: String
1790
- },
1791
- doc_id: {
1792
- type: String
1793
- }
1794
- }),
1795
- function: function (database, collection, doc_id) {
1796
- return __awaiter(this, void 0, void 0, function () {
1797
- var dbName;
1798
- return __generator(this, function (_a) {
1799
- dbName = resolveDatabaseName(database);
1800
- return [2 /*return*/, buildDeleteImpact(dbName, collection, doc_id)];
1801
- });
1802
- });
1803
- }
1804
- }
1805
- });
1806
- }
1807
-
1808
- //# sourceMappingURL=mongo-explorer.js.map