@lobu/runtime-server 24.8.0 → 24.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/dist/catalogs/automations.json +2 -2
  2. package/dist/catalogs/connectors.json +99 -10
  3. package/dist/catalogs/skills.json +1 -1
  4. package/dist/component.json +1 -1
  5. package/dist/connectors/README.md +6 -2
  6. package/dist/connectors/github.ts +16 -3
  7. package/dist/connectors/market_quotes.ts +388 -91
  8. package/dist/connectors/postgres.ts +60 -38
  9. package/dist/connectors/whatsapp-web-adapter.js +41 -10
  10. package/dist/connectors/whatsapp-web-helpers.ts +12 -2
  11. package/dist/connectors/whatsapp_web.ts +18 -2
  12. package/dist/connectors/x-dm-adapter.js +55 -21
  13. package/dist/connectors/x.ts +1 -1
  14. package/dist/db/migrations/20261109010000_workspace_navigation.sql +14 -0
  15. package/dist/db/migrations/20261110010000_view_resources.sql +11 -0
  16. package/dist/db/migrations/20261112210000_instance_identity.sql +18 -0
  17. package/dist/dependencies.bun.lock +88 -86
  18. package/dist/embeddings-server.mjs +38 -5
  19. package/dist/owletto/dist/assets/_-CYvj1y65.js +3 -0
  20. package/dist/owletto/dist/assets/_-CeLTSYYY.js +2 -0
  21. package/dist/owletto/dist/assets/_agentId-BB5E-L6T.js +2 -0
  22. package/dist/owletto/dist/assets/_agentId-DN0EwMAC.js +2 -0
  23. package/dist/owletto/dist/assets/_automationId-DvUl9CSd.js +2 -0
  24. package/dist/owletto/dist/assets/_connectorKey._connectionId-CVKfL9AG.js +2 -0
  25. package/dist/owletto/dist/assets/_connectorKey.index-Cv6FzK1v.js +2 -0
  26. package/dist/owletto/dist/assets/{_conversationId-OJrZjd0o.js → _conversationId-CPpNySjO.js} +2 -2
  27. package/dist/owletto/dist/assets/_eventId-DZKicuq6.js +2 -0
  28. package/dist/owletto/dist/assets/_owner-Dauk3YuD.js +3 -0
  29. package/dist/owletto/dist/assets/_shape-cKrEID3T.js +2 -0
  30. package/dist/owletto/dist/assets/_slug-DJx_8fsV.js +2 -0
  31. package/dist/owletto/dist/assets/_viewKey-CPVzVKEf.js +2 -0
  32. package/dist/owletto/dist/assets/_viewKey-CW8gexOQ.js +2 -0
  33. package/dist/owletto/dist/assets/accept-invitation-Dwq1GAnG.js +2 -0
  34. package/dist/owletto/dist/assets/activity-route-location-C1jcXC7v.js +2 -0
  35. package/dist/owletto/dist/assets/activity-route-view-D78Wj0RH.js +2 -0
  36. package/dist/owletto/dist/assets/agent-connect-pages-DoI9UR0a.js +4 -0
  37. package/dist/owletto/dist/assets/{agent-editor-form-CDAHRNWl.js → agent-editor-form-DlavYg2q.js} +2 -2
  38. package/dist/owletto/dist/assets/{agent-loading-shells-BupiSjR-.js → agent-loading-shells-DYqQphN7.js} +2 -2
  39. package/dist/owletto/dist/assets/agent-permissions-matrix-C1L8IcYR.js +2 -0
  40. package/dist/owletto/dist/assets/{agent-skill-context-B0ZYVE3n.js → agent-skill-context-D1nMrVod.js} +2 -2
  41. package/dist/owletto/dist/assets/{agent-subpage-shell-ByU0xhXn.js → agent-subpage-shell-2w7vTeXw.js} +2 -2
  42. package/dist/owletto/dist/assets/{agent-thread-DiVKn1WX.js → agent-thread-BopD-2k1.js} +2 -2
  43. package/dist/owletto/dist/assets/{app._appId-BQWElSoP.js → app._appId-BXeFXW1w.js} +2 -2
  44. package/dist/owletto/dist/assets/{assist-composer-igTXq3DL.js → assist-composer-CL5x8pNt.js} +2 -2
  45. package/dist/owletto/dist/assets/automation-run-now-MtxUTfzd.js +2 -0
  46. package/dist/owletto/dist/assets/{callback-Dmaio9CX.js → callback-BgfwP1Eo.js} +2 -2
  47. package/dist/owletto/dist/assets/{card-rE4Ctuy6.js → card-DtLIFq7D.js} +2 -2
  48. package/dist/owletto/dist/assets/{claim-BN17CPYh.js → claim-CT3hYVMF.js} +2 -2
  49. package/dist/owletto/dist/assets/{client-activity-scopes-B7xVaUA-.js → client-activity-scopes-BPbRX-Pe.js} +2 -2
  50. package/dist/owletto/dist/assets/{client-rows-B3LULJxW.js → client-rows-vrNA6FLs.js} +2 -2
  51. package/dist/owletto/dist/assets/clients-xnzZeEdZ.js +2 -0
  52. package/dist/owletto/dist/assets/{code-editor-UppEMWpt.js → code-editor-mrKkAfcE.js} +2 -2
  53. package/dist/owletto/dist/assets/connect-NUCSay8X.js +2 -0
  54. package/dist/owletto/dist/assets/{connect-menu-B9u86bb2.js → connect-menu-C6iVtuSo.js} +2 -2
  55. package/dist/owletto/dist/assets/connect._clientId-Cp-d9Q5b.js +2 -0
  56. package/dist/owletto/dist/assets/{connected._clientId-CaF-ZWlZ.js → connected._clientId-ROfVgp9h.js} +2 -2
  57. package/dist/owletto/dist/assets/connection-BMz740Wi.js +2 -0
  58. package/dist/owletto/dist/assets/{connection-feed-detail-CJYqryAV.js → connection-feed-detail-0VAJiZTP.js} +2 -2
  59. package/dist/owletto/dist/assets/connector-page-shell-BFv21yuv.js +2 -0
  60. package/dist/owletto/dist/assets/{connector-provenance-CW4CXtCz.js → connector-provenance-b59RfBtk.js} +2 -2
  61. package/dist/owletto/dist/assets/connectors-nYS31lO2.js +2 -0
  62. package/dist/owletto/dist/assets/consent-cPRF9JQv.js +2 -0
  63. package/dist/owletto/dist/assets/{copy-button-1ALlvZU1.js → copy-button-C3wMMv63.js} +2 -2
  64. package/dist/owletto/dist/assets/{core.esm-6koO33th.js → core.esm-C9QlSrgK.js} +3 -3
  65. package/dist/owletto/dist/assets/{create-kUevP9Xx.js → create-ASRN3Obq.js} +2 -2
  66. package/dist/owletto/dist/assets/create-CBcodaSO.js +2 -0
  67. package/dist/owletto/dist/assets/create-CGOWfMk4.js +2 -0
  68. package/dist/owletto/dist/assets/{create-automation-form-BhujNbRr.js → create-automation-form-CLicoPH5.js} +3 -3
  69. package/dist/owletto/dist/assets/create._connectorKey-s4xkktTC.js +2 -0
  70. package/dist/owletto/dist/assets/{custom-guardrail-edits-B_aCgvoZ.js → custom-guardrail-edits-BUL7nmuO.js} +2 -2
  71. package/dist/owletto/dist/assets/{definition-comparison-3zKUSTt8.js → definition-comparison-4UYMI6BK.js} +2 -2
  72. package/dist/owletto/dist/assets/{detail-page-skeleton-BmxqqIsH.js → detail-page-skeleton-C8v3rJXK.js} +2 -2
  73. package/dist/owletto/dist/assets/device-BBwsOi7q.js +2 -0
  74. package/dist/owletto/dist/assets/device-pin-tombstone-Bcpe7nAA.js +2 -0
  75. package/dist/owletto/dist/assets/{device._deviceId-Dqtmb1Xp.js → device._deviceId-DLT4jh0Z.js} +2 -2
  76. package/dist/owletto/dist/assets/{dynamic-schema-form-D3KnzCsW.js → dynamic-schema-form-BDT8x0Vg.js} +2 -2
  77. package/dist/owletto/dist/assets/entity-options-B9hm9V87.js +2 -0
  78. package/dist/owletto/dist/assets/entity-page-DZjzQ2V4.js +2 -0
  79. package/dist/owletto/dist/assets/entity-pages-BWBpttz3.js +2 -0
  80. package/dist/owletto/dist/assets/entity-schema-graph-lMMx3HhR.js +2 -0
  81. package/dist/owletto/dist/assets/{entity-type-page-CouHZbc9.js → entity-type-page-CkQm0yEu.js} +2 -2
  82. package/dist/owletto/dist/assets/event-detail-CkzfakTK.js +2 -0
  83. package/dist/owletto/dist/assets/events-feed-DmRzikZW.js +2 -0
  84. package/dist/owletto/dist/assets/filter-editors-CQoSj-20.js +3 -0
  85. package/dist/owletto/dist/assets/{full-page-spinner-B7A6Ycyi.js → full-page-spinner-CYyCnKve.js} +2 -2
  86. package/dist/owletto/dist/assets/index-BE7eb2kE.js +2 -0
  87. package/dist/owletto/dist/assets/index-BFR0uiKY.js +2 -0
  88. package/dist/owletto/dist/assets/{index-DXfYVs5m.js → index-BS5Ty3tf.js} +2 -2
  89. package/dist/owletto/dist/assets/index-C38OzBpB.js +2 -0
  90. package/dist/owletto/dist/assets/{index-BztXeLBN.js → index-C3hz9tzx.js} +2 -2
  91. package/dist/owletto/dist/assets/index-CDyFQ32o.js +2 -0
  92. package/dist/owletto/dist/assets/{index-B-dZruj6.js → index-CUndAH6o.js} +2 -2
  93. package/dist/owletto/dist/assets/index-CiKysEhV.js +2 -0
  94. package/dist/owletto/dist/assets/index-DByaMzsG.js +7906 -0
  95. package/dist/owletto/dist/assets/index-DfdinB7B.js +2 -0
  96. package/dist/owletto/dist/assets/index-DgMM4Zt5.css +1 -0
  97. package/dist/owletto/dist/assets/index-Xk711gVC.js +2 -0
  98. package/dist/owletto/dist/assets/index-ittfA0k8.js +2 -0
  99. package/dist/owletto/dist/assets/{json-diff-CJK-gzCt.js → json-diff-mcDgyct_.js} +2 -2
  100. package/dist/owletto/dist/assets/{list-skeleton-bQAZ0hQp.js → list-skeleton-DsYGUHxi.js} +2 -2
  101. package/dist/owletto/dist/assets/login-EoLq136v.js +2 -0
  102. package/dist/owletto/dist/assets/{logout-H0F3IfiO.js → logout-gLgEQOiX.js} +2 -2
  103. package/dist/owletto/dist/assets/{member-scope-gate-Doic_6qX.js → member-scope-gate-vvkgSAb2.js} +2 -2
  104. package/dist/owletto/dist/assets/memory-browse-page-DvDtwrEI.js +74 -0
  105. package/dist/owletto/dist/assets/{model-selector-BrfaDwIg.js → model-selector-D3vSMLO2.js} +2 -2
  106. package/dist/owletto/dist/assets/needs-you-list-B5Bgd05M.js +2 -0
  107. package/dist/owletto/dist/assets/new-BPW3V0Y1.js +2 -0
  108. package/dist/owletto/dist/assets/new-Bk_flKQO.js +2 -0
  109. package/dist/owletto/dist/assets/new-C5HtQdM_.js +2 -0
  110. package/dist/owletto/dist/assets/new-dLXsCHBd.js +2 -0
  111. package/dist/owletto/dist/assets/organization-DBfgBkzq.js +2 -0
  112. package/dist/owletto/dist/assets/peek-pane-content-c2PG3TEX.js +2 -0
  113. package/dist/owletto/dist/assets/{pending-seed-DYYOoCvj.js → pending-seed-CBhx2Ql-.js} +2 -2
  114. package/dist/owletto/dist/assets/{proposal-review-shell-BVwOMoq9.js → proposal-review-shell-B-jYcKfB.js} +2 -2
  115. package/dist/owletto/dist/assets/public-shell-ready-D8TijlRY.js +2 -0
  116. package/dist/owletto/dist/assets/record-activity-DnRVOrG2.js +2 -0
  117. package/dist/owletto/dist/assets/{record-session-KuEDuF3S.js → record-session-CAmGHMyM.js} +2 -2
  118. package/dist/owletto/dist/assets/{renderer-ucwCQmBk.js → renderer-olRv_HMI.js} +3 -3
  119. package/dist/owletto/dist/assets/reset-password-B9_xi8Pq.js +2 -0
  120. package/dist/owletto/dist/assets/{run-initiator-8vdkq-3o.js → run-initiator-DhE5v4z0.js} +2 -2
  121. package/dist/owletto/dist/assets/runs-C8sZQr4o.js +2 -0
  122. package/dist/owletto/dist/assets/runs-list-CwtH-wmk.js +2 -0
  123. package/dist/owletto/dist/assets/{schema-value-CefbtPIY.js → schema-value-zTJGE4eh.js} +3 -3
  124. package/dist/owletto/dist/assets/scoped-feed-bar-BKyJSa3_.js +2 -0
  125. package/dist/owletto/dist/assets/{settings-DvzkRYQy.js → settings-z02cvVS3.js} +2 -2
  126. package/dist/owletto/dist/assets/source-record-panels-CGmKIJdN.js +2 -0
  127. package/dist/owletto/dist/assets/{status-variants-BxHtpMOj.js → status-variants-DyRCXBzM.js} +2 -2
  128. package/dist/owletto/dist/assets/subDays-D8nHthaS.js +2 -0
  129. package/dist/owletto/dist/assets/{table-1O-ik4_O.js → table-C637cQxG.js} +2 -2
  130. package/dist/owletto/dist/assets/use-automations-CgWNoYio.js +2 -0
  131. package/dist/owletto/dist/assets/use-login-redirect-tDdhXTpt.js +2 -0
  132. package/dist/owletto/dist/assets/{use-mention-search-CA-evCDf.js → use-mention-search-D-kIKchD.js} +2 -2
  133. package/dist/owletto/dist/assets/view-param-filters-CUCj9Df-.js +2 -0
  134. package/dist/owletto/dist/assets/views-access-required-C35Dyt91.js +2 -0
  135. package/dist/owletto/dist/index.html +19 -12
  136. package/dist/server-main.bundle.mjs +6964 -4213
  137. package/npm-shrinkwrap.json +423 -406
  138. package/package.json +1 -1
  139. package/vendor/connector-sdk/dist/connector-types.d.ts +29 -2
  140. package/vendor/connector-sdk/dist/index.d.ts +1 -0
  141. package/vendor/connector-sdk/dist/index.js +1 -0
  142. package/vendor/connector-sdk/dist/ip-reachability.d.ts +1 -1
  143. package/vendor/connector-sdk/dist/ip-reachability.js +1 -1
  144. package/vendor/connector-sdk/dist/logger.d.ts +1 -1
  145. package/vendor/connector-sdk/dist/logger.js +1 -1
  146. package/vendor/connector-sdk/dist/reaction-client-types.d.ts +3 -1
  147. package/vendor/connector-sdk/dist/retry.d.ts +1 -1
  148. package/vendor/connector-sdk/dist/retry.js +1 -1
  149. package/vendor/connector-sdk/dist/source-withheld-error.d.ts +16 -0
  150. package/vendor/connector-sdk/dist/source-withheld-error.js +19 -0
  151. package/vendor/connector-sdk/package.json +1 -1
  152. package/vendor/core/dist/classify-error.d.ts +4 -5
  153. package/vendor/core/dist/classify-error.js +10 -10
  154. package/vendor/core/dist/contracts/tools/collection-presentation.d.ts +17 -1
  155. package/vendor/core/dist/contracts/tools/collection-presentation.js +27 -3
  156. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +67 -3
  157. package/vendor/core/dist/contracts/tools/manage-automations.js +38 -9
  158. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +1 -1
  159. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +8 -0
  160. package/vendor/core/dist/contracts/tools/manage-entity.js +11 -3
  161. package/vendor/core/dist/contracts/tools/manage-views.d.ts +249 -7
  162. package/vendor/core/dist/contracts/tools/manage-views.js +83 -21
  163. package/vendor/core/dist/contracts/tools/navigation.d.ts +248 -0
  164. package/vendor/core/dist/contracts/tools/navigation.js +284 -0
  165. package/vendor/core/dist/contracts/tools/save-memory.d.ts +11 -1
  166. package/vendor/core/dist/contracts/tools/save-memory.js +25 -3
  167. package/vendor/core/dist/contracts/tools/search-memory.js +1 -1
  168. package/vendor/core/dist/contracts/tools/view-attach.d.ts +7 -0
  169. package/vendor/core/dist/contracts/tools/view-attach.js +15 -0
  170. package/vendor/core/dist/contracts/tools/view-content-hash.d.ts +4 -1
  171. package/vendor/core/dist/contracts/tools/view-content-hash.js +4 -2
  172. package/vendor/core/dist/contracts/tools/view-definition.d.ts +2 -0
  173. package/vendor/core/dist/contracts/tools/view-definition.js +52 -0
  174. package/vendor/core/dist/contracts/tools/view-host.d.ts +68 -0
  175. package/vendor/core/dist/contracts/tools/view-host.js +28 -1
  176. package/vendor/core/dist/contracts/tools/view-scope.d.ts +31 -0
  177. package/vendor/core/dist/contracts/tools/view-scope.js +45 -0
  178. package/vendor/core/dist/credentials.d.ts +12 -0
  179. package/vendor/core/dist/credentials.js +1 -0
  180. package/vendor/core/dist/errors.d.ts +17 -24
  181. package/vendor/core/dist/errors.js +19 -26
  182. package/vendor/core/dist/types.d.ts +0 -6
  183. package/vendor/core/dist/worker/auth.d.ts +5 -0
  184. package/vendor/core/dist/worker/auth.js +15 -4
  185. package/vendor/core/package.json +11 -1
  186. package/vendor/postgres/cf/src/connection.js +7 -2
  187. package/vendor/postgres/cjs/src/connection.js +7 -2
  188. package/vendor/postgres/src/connection.js +7 -2
  189. package/vendor/views/dist/api.d.ts +30 -5
  190. package/vendor/views/dist/api.js +22 -8
  191. package/vendor/views/dist/bridge.d.ts +17 -0
  192. package/vendor/views/dist/bridge.js +49 -1
  193. package/vendor/views/dist/components.d.ts +27 -5
  194. package/vendor/views/dist/components.js +57 -7
  195. package/vendor/views/dist/embed.d.ts +98 -0
  196. package/vendor/views/dist/embed.js +418 -0
  197. package/vendor/views/dist/index.d.ts +3 -1
  198. package/vendor/views/dist/index.js +1 -0
  199. package/vendor/views/dist/native.d.ts +33 -1
  200. package/vendor/views/dist/native.js +3 -0
  201. package/vendor/views/package.json +1 -1
  202. package/dist/owletto/dist/assets/_-B0tmXZ86.js +0 -2
  203. package/dist/owletto/dist/assets/_-DwXULq4r.js +0 -3
  204. package/dist/owletto/dist/assets/_agentId-B1dNkhnr.js +0 -2
  205. package/dist/owletto/dist/assets/_agentId-sYjvnBaB.js +0 -2
  206. package/dist/owletto/dist/assets/_automationId-Bnw_CnT_.js +0 -2
  207. package/dist/owletto/dist/assets/_connectorKey._connectionId-D7Z8DQ-B.js +0 -2
  208. package/dist/owletto/dist/assets/_connectorKey.index-DM5MTO8c.js +0 -2
  209. package/dist/owletto/dist/assets/_eventId-CfB0_2zK.js +0 -2
  210. package/dist/owletto/dist/assets/_owner-BDvTUY0a.js +0 -3
  211. package/dist/owletto/dist/assets/_shape-BZidoJMB.js +0 -2
  212. package/dist/owletto/dist/assets/_slug-R989vOiM.js +0 -2
  213. package/dist/owletto/dist/assets/_viewKey-BDUSrpe5.js +0 -2
  214. package/dist/owletto/dist/assets/_viewKey-BnFqh5-t.js +0 -2
  215. package/dist/owletto/dist/assets/accept-invitation-BC-ZIsrf.js +0 -2
  216. package/dist/owletto/dist/assets/activity-route-view-CN2dOiCD.js +0 -2
  217. package/dist/owletto/dist/assets/agent-connect-pages-CdDjrHjn.js +0 -4
  218. package/dist/owletto/dist/assets/agent-permissions-matrix-ju7L2M0l.js +0 -2
  219. package/dist/owletto/dist/assets/automation-detail-content-BJwRU6qT.js +0 -2
  220. package/dist/owletto/dist/assets/clients-CydgUHrc.js +0 -2
  221. package/dist/owletto/dist/assets/connect-OdHpIVV9.js +0 -2
  222. package/dist/owletto/dist/assets/connect._clientId-EI1tcdSE.js +0 -2
  223. package/dist/owletto/dist/assets/connection-D8ZAMHBT.js +0 -2
  224. package/dist/owletto/dist/assets/connector-boxes-BWPXijAk.js +0 -2
  225. package/dist/owletto/dist/assets/connector-page-shell-C23dWdKz.js +0 -2
  226. package/dist/owletto/dist/assets/connectors-Bp08_KPq.js +0 -2
  227. package/dist/owletto/dist/assets/consent-_PpYI1cT.js +0 -2
  228. package/dist/owletto/dist/assets/create-DULVO0HS.js +0 -2
  229. package/dist/owletto/dist/assets/create-Drx9tcnG.js +0 -2
  230. package/dist/owletto/dist/assets/create._connectorKey-N6fhcIPy.js +0 -2
  231. package/dist/owletto/dist/assets/device-D2eUt_nr.js +0 -2
  232. package/dist/owletto/dist/assets/device-pin-tombstone-BFPbTM_o.js +0 -2
  233. package/dist/owletto/dist/assets/entity-options-IUdQ-64R.js +0 -2
  234. package/dist/owletto/dist/assets/entity-page-B3Im65EI.js +0 -2
  235. package/dist/owletto/dist/assets/entity-pages-DJNSQrfB.js +0 -2
  236. package/dist/owletto/dist/assets/event-detail-CvaRN1qB.js +0 -2
  237. package/dist/owletto/dist/assets/events-feed-DwOkLk6A.js +0 -2
  238. package/dist/owletto/dist/assets/filter-editors-DQ5V4Cvh.js +0 -2
  239. package/dist/owletto/dist/assets/home-stream-Bg97PUBJ.js +0 -2
  240. package/dist/owletto/dist/assets/home-toolbar-CpCcHA6z.js +0 -2
  241. package/dist/owletto/dist/assets/index-9PGnv4-5.js +0 -2
  242. package/dist/owletto/dist/assets/index-C2TCKJDP.js +0 -7901
  243. package/dist/owletto/dist/assets/index-C7QM3aqU.js +0 -2
  244. package/dist/owletto/dist/assets/index-CWn46a4y.js +0 -2
  245. package/dist/owletto/dist/assets/index-CxJONizf.js +0 -2
  246. package/dist/owletto/dist/assets/index-DJhb3li3.js +0 -2
  247. package/dist/owletto/dist/assets/index-DY-YGnCe.js +0 -2
  248. package/dist/owletto/dist/assets/index-j3v7ITPb.js +0 -2
  249. package/dist/owletto/dist/assets/index-oiy6ygaI.js +0 -2
  250. package/dist/owletto/dist/assets/index-pEgtAY1t.js +0 -2
  251. package/dist/owletto/dist/assets/index-xAvK3IyQ.css +0 -1
  252. package/dist/owletto/dist/assets/login-DLqL54Rk.js +0 -2
  253. package/dist/owletto/dist/assets/memory-browse-page-CUea2Llz.js +0 -74
  254. package/dist/owletto/dist/assets/new-5GkxlOuQ.js +0 -2
  255. package/dist/owletto/dist/assets/new-BiA4DGoN.js +0 -2
  256. package/dist/owletto/dist/assets/new-M-MX_T5C.js +0 -2
  257. package/dist/owletto/dist/assets/organization-CLrcmgNK.js +0 -2
  258. package/dist/owletto/dist/assets/peek-pane-content-B29OcHwm.js +0 -2
  259. package/dist/owletto/dist/assets/public-shell-ready-BbjPgh3k.js +0 -2
  260. package/dist/owletto/dist/assets/record-activity-BCpNKaUo.js +0 -2
  261. package/dist/owletto/dist/assets/reset-password-BkiAmXZW.js +0 -2
  262. package/dist/owletto/dist/assets/runs-B_iywKWb.js +0 -2
  263. package/dist/owletto/dist/assets/runs-list-CJJFRhTl.js +0 -2
  264. package/dist/owletto/dist/assets/schema-type-editor-panel-C4e8pq1A.js +0 -2
  265. package/dist/owletto/dist/assets/scoped-feed-bar-CapleZvS.js +0 -2
  266. package/dist/owletto/dist/assets/source-record-panels-LJIWGtHb.js +0 -2
  267. package/dist/owletto/dist/assets/subDays-DwIOMzYC.js +0 -2
  268. package/dist/owletto/dist/assets/use-automations-lV8PuE8L.js +0 -2
  269. package/dist/owletto/dist/assets/use-login-redirect-CfCbEeJR.js +0 -2
  270. package/dist/owletto/dist/assets/view-param-filters-Bp84PUMd.js +0 -2
  271. package/dist/owletto/dist/assets/views-access-required-BerT4Z1d.js +0 -2
  272. /package/vendor/postgres/{.bun-tag-c81dacd34e959a7a → .bun-tag-652f2580b8090d71} +0 -0
@@ -94,7 +94,7 @@
94
94
  {
95
95
  "id": "duplicate-identity",
96
96
  "name": "Duplicate identity resolution",
97
- "version": "4.0.0",
97
+ "version": "4.0.1",
98
98
  "description": "Associate duplicate records with reversible identity links while preserving every record. Attach one entity to select the entity type to inspect.",
99
99
  "detail": {
100
100
  "slug": "duplicate-identity",
@@ -108,7 +108,7 @@
108
108
  }
109
109
  ],
110
110
  "prompt": "Summarize the bound entity type in analysis_summary. Do not call entity tools or emit backlog tasks. The deterministic reaction discovers duplicate groups across this entity type and submits reversible identity links. Configure an identity-purpose relationship and the entity type's x-lobu-resolution rules first; there are no implicit identity rules. The server rechecks evidence, access, and approval policy for every link. Queued approvals are proposals, not completed links. Oversized groups and an incomplete sweep are reported in the reaction log.\n",
111
- "reaction_script": "export const input = {\n\ttype: \"object\",\n\tproperties: { analysis_summary: { type: \"string\" } },\n\trequired: [\"analysis_summary\"],\n\tadditionalProperties: false,\n};\n\nexport default async function reaction(ctx, client) {\n\tconst types = [...new Set((ctx.entities ?? []).map((entity) => entity.entity_type))];\n\tif (types.length !== 1 || !types[0] || types[0].startsWith(\"$\")) {\n\t\tthrow new Error(\"Attach entities of exactly one stored entity type to select the identity sweep\");\n\t}\n\tconst progress = { entity_type: types[0], applied: 0, queued: 0, suppressed: 0, oversized: 0, deferred_candidates: 0, complete: false, next_cursor: null };\n\tlet calls = 0;\n\tlet cursor;\n\tdo {\n\t\t// Reserve one call for the final progress log; a page emits at most one link per component.\n\t\tconst limit = Math.min(100, 198 - calls);\n\t\tif (limit < 1) break;\n\t\tconst page = await client.entities.discoverDuplicates({ entity_type: types[0], limit, ...(cursor ? { cursor } : {}) });\n\t\tcalls++;\n\t\tfor (const component of page.components) {\n\t\t\tprogress.oversized += Number(component.oversized);\n\t\t\tprogress.deferred_candidates += component.deferred_candidates;\n\t\t\tfor (const decision of component.decisions) {\n\t\t\t\tconst result = await client.entities.link(decision);\n\t\t\t\tcalls++;\n\t\t\t\tif (result.approval_queued) progress.queued++;\n\t\t\t\telse if (result.approval_suppressed) progress.suppressed++;\n\t\t\t\telse if (result.relationship) progress.applied++;\n\t\t\t\telse throw new Error(\"Identity link returned no applied, queued, or suppressed receipt\");\n\t\t\t}\n\t\t}\n\t\tcursor = page.next_cursor;\n\t\tprogress.next_cursor = cursor;\n\t\tprogress.complete = cursor === null;\n\t} while (cursor);\n\tawait client.log(\"Duplicate identity sweep\", progress);\n\treturn progress;\n}",
111
+ "reaction_script": "export const input = {\n\ttype: \"object\",\n\tproperties: { analysis_summary: { type: \"string\" } },\n\trequired: [\"analysis_summary\"],\n\tadditionalProperties: false,\n};\n\nexport default async function reaction(ctx, client) {\n\tconst types = [...new Set((ctx.entities ?? []).map((entity) => entity.entity_type))];\n\tif (types.length !== 1 || !types[0] || types[0].startsWith(\"$\")) {\n\t\tctx.fail(\"Attach entities of exactly one stored entity type to select the identity sweep\");\n\t}\n\tconst progress = { entity_type: types[0], applied: 0, queued: 0, suppressed: 0, oversized: 0, deferred_candidates: 0, complete: false, next_cursor: null };\n\tlet calls = 0;\n\tlet cursor;\n\tdo {\n\t\t// Reserve one call for the final progress log; a page emits at most one link per component.\n\t\tconst limit = Math.min(100, 198 - calls);\n\t\tif (limit < 1) break;\n\t\tconst page = await client.entities.discoverDuplicates({ entity_type: types[0], limit, ...(cursor ? { cursor } : {}) });\n\t\tcalls++;\n\t\tfor (const component of page.components) {\n\t\t\tprogress.oversized += Number(component.oversized);\n\t\t\tprogress.deferred_candidates += component.deferred_candidates;\n\t\t\tfor (const decision of component.decisions) {\n\t\t\t\tconst result = await client.entities.link(decision);\n\t\t\t\tcalls++;\n\t\t\t\tif (result.approval_queued) progress.queued++;\n\t\t\t\telse if (result.approval_suppressed) progress.suppressed++;\n\t\t\t\telse if (result.relationship) progress.applied++;\n\t\t\t\telse throw new Error(\"Identity link returned no applied, queued, or suppressed receipt\");\n\t\t\t}\n\t\t}\n\t\tcursor = page.next_cursor;\n\t\tprogress.next_cursor = cursor;\n\t\tprogress.complete = cursor === null;\n\t} while (cursor);\n\tawait client.log(\"Duplicate identity sweep\", progress);\n\treturn progress;\n}",
112
112
  "reactions_guidance": "Attach an entity of the type to inspect. Keep uncertain matches for human review. Each run uses at most 200 SDK calls; incomplete sweeps expose next_cursor in the log and restart from current state next run.",
113
113
  "tags": [
114
114
  "identity",
@@ -128,7 +128,7 @@
128
128
  {
129
129
  "id": "github",
130
130
  "name": "GitHub",
131
- "version": "1.5.0",
131
+ "version": "1.8.0",
132
132
  "description": "Collects GitHub issues/discussions and executes repo actions.",
133
133
  "detail": {
134
134
  "source_path": "github.ts",
@@ -198,13 +198,14 @@
198
198
  {
199
199
  "type": "env_keys",
200
200
  "required": false,
201
- "description": "Optional fallback token for sync/action calls.",
201
+ "description": "Optional fallback token for sync/action calls and generated REST reads.",
202
202
  "fields": [
203
203
  {
204
204
  "key": "GITHUB_TOKEN",
205
205
  "label": "GitHub Token",
206
206
  "description": "Personal access token used as fallback auth for API requests.",
207
- "secret": true
207
+ "secret": true,
208
+ "httpCredential": {}
208
209
  }
209
210
  ]
210
211
  }
@@ -20100,8 +20101,8 @@
20100
20101
  {
20101
20102
  "id": "market.quotes",
20102
20103
  "name": "Market Quotes",
20103
- "version": "1.0.0",
20104
- "description": "Credential-free current market marks returned on demand without a price feed.",
20104
+ "version": "1.1.0",
20105
+ "description": "Credential-free current market marks and daily close history returned on demand without a price feed.",
20105
20106
  "detail": {
20106
20107
  "source_path": "market_quotes.ts",
20107
20108
  "auth_schema": {
@@ -20188,6 +20189,82 @@
20188
20189
  }
20189
20190
  }
20190
20191
  }
20192
+ },
20193
+ "history": {
20194
+ "key": "history",
20195
+ "kind": "read",
20196
+ "name": "Daily close history",
20197
+ "description": "Return daily closes between from and to (inclusive, exchange-local dates) as a history or history_unavailable entry for every requested symbol.",
20198
+ "annotations": {
20199
+ "readOnlyHint": true,
20200
+ "idempotentHint": true,
20201
+ "openWorldHint": true
20202
+ },
20203
+ "inputSchema": {
20204
+ "type": "object",
20205
+ "required": [
20206
+ "symbols",
20207
+ "from",
20208
+ "to"
20209
+ ],
20210
+ "properties": {
20211
+ "symbols": {
20212
+ "type": "array",
20213
+ "minItems": 1,
20214
+ "maxItems": 50,
20215
+ "items": {
20216
+ "oneOf": [
20217
+ {
20218
+ "type": "string"
20219
+ },
20220
+ {
20221
+ "type": "object",
20222
+ "properties": {
20223
+ "market": {
20224
+ "type": "string"
20225
+ },
20226
+ "symbol": {
20227
+ "type": "string"
20228
+ },
20229
+ "id": {
20230
+ "type": "string"
20231
+ },
20232
+ "provider_symbol": {
20233
+ "type": "string"
20234
+ }
20235
+ }
20236
+ }
20237
+ ]
20238
+ }
20239
+ },
20240
+ "from": {
20241
+ "type": "string",
20242
+ "description": "First calendar day (YYYY-MM-DD), inclusive."
20243
+ },
20244
+ "to": {
20245
+ "type": "string",
20246
+ "description": "Last calendar day (YYYY-MM-DD), inclusive; at most 10 years after from."
20247
+ }
20248
+ }
20249
+ },
20250
+ "outputSchema": {
20251
+ "type": "object",
20252
+ "required": [
20253
+ "provider",
20254
+ "series"
20255
+ ],
20256
+ "properties": {
20257
+ "provider": {
20258
+ "type": "string"
20259
+ },
20260
+ "series": {
20261
+ "type": "array",
20262
+ "items": {
20263
+ "type": "object"
20264
+ }
20265
+ }
20266
+ }
20267
+ }
20191
20268
  }
20192
20269
  },
20193
20270
  "automation_events": null,
@@ -20530,7 +20607,7 @@
20530
20607
  {
20531
20608
  "id": "postgres",
20532
20609
  "name": "PostgreSQL",
20533
- "version": "1.1.0",
20610
+ "version": "1.1.1",
20534
20611
  "description": "Bring your own PostgreSQL database as memory, read a configured feed directly, or run governed connection-level SQL.",
20535
20612
  "detail": {
20536
20613
  "source_path": "postgres.ts",
@@ -21598,7 +21675,7 @@
21598
21675
  {
21599
21676
  "id": "whatsapp.web",
21600
21677
  "name": "WhatsApp",
21601
- "version": "2.3.0",
21678
+ "version": "2.3.1",
21602
21679
  "description": "Personal WhatsApp messages read live from WhatsApp Web in the paired Owletto Chrome without importing message history. Automations react to new-message references and read content on demand. Search, draft, send, edit, react to, and revoke messages.",
21603
21680
  "detail": {
21604
21681
  "source_path": "whatsapp_web.ts",
@@ -21616,7 +21693,7 @@
21616
21693
  ],
21617
21694
  "accountProbe": {
21618
21695
  "url": "https://web.whatsapp.com/",
21619
- "expression": "(async () => {\n (function whatsAppWebAdapterProgram() {\n const SYSTEM_TYPES = new Set([\n \"gp2\",\n \"notification_template\",\n \"e2e_notification\"\n ]);\n let readinessSignature = null, readinessStableSince = 0;\n const existing = globalThis.__owlettoWhatsAppAdapterV1;\n if (existing?.version === 27)\n return;\n existing?.detach?.(void 0, \"WhatsApp adapter was replaced; recovery is required\");\n const listeners = new Map;\n function detach(bindingId, reason) {\n const selected = bindingId ? [listeners.get(bindingId)] : [...listeners.values()];\n for (const state of selected) {\n if (!state)\n continue;\n if (reason) {\n state.error = reason;\n state.post({ sequence: ++state.sequence, record: { id: \"whatsapp-web:source-observation-error\", source_error: reason } });\n }\n for (const entry of state.pending.values())\n entry.reject?.(Error(reason ?? \"Source listener was detached\"));\n state.collection.off(\"add\", state.onAdd);\n state.collection.off(\"change\", state.onChange);\n window.removeEventListener(\"message\", state.onReply);\n listeners.delete(state.id);\n }\n }\n function assertAccount(account) {\n if (typeof account !== \"string\" || !account || widString(meUser()) !== account)\n throw Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n }\n async function digest(value) {\n const bytes = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n function listen(request) {\n assertAccount(request.account_id);\n const collection = requireFirst([\"WAWebCollections\"])?.Msg;\n if (typeof collection?.on !== \"function\" || typeof collection?.off !== \"function\")\n throw Error(\"WhatsApp message observation is unavailable in this build\");\n if (!request.bridge_id || !request.token)\n throw Error(\"A feed bridge is required\");\n const post = (state2, entry) => window.postMessage({\n type: \"lobu-feed-record\",\n token: state2.token,\n sequence: entry.sequence,\n record: entry.record\n }, location.origin), reportError = (state2, message, sequence = ++state2.sequence) => {\n state2.error = message;\n post(state2, {\n sequence,\n record: {\n id: \"whatsapp-web:source-observation-error\",\n source_error: message\n }\n });\n }, resident = listeners.get(request.bridge_id), previous = resident?.request.account_id === request.account_id && resident?.request.chat_filter === request.chat_filter && resident?.request.minimum_timestamp === request.minimum_timestamp ? resident : null;\n detach(request.bridge_id);\n const state = {\n ...previous ?? {\n id: request.bridge_id,\n collection,\n sequence: 0,\n pending: new Map,\n fingerprints: new Map,\n pendingBytes: 0,\n fingerprintBytes: 0,\n error: null\n },\n collection,\n error: null\n };\n state.token = request.token;\n state.request = request;\n state.post = (entry) => post(state, entry);\n const observe = (model) => {\n if (state.error)\n return;\n const sequence = ++state.sequence;\n new Promise((resolve) => {\n assertAccount(state.request.account_id);\n resolve(messageReference(model));\n }).then((record) => {\n if (listeners.get(state.id) !== state)\n return;\n assertAccount(state.request.account_id);\n if (!record || record.timestamp <= 0)\n return;\n if (state.request.chat_filter === \"group\" && !record.is_group)\n return;\n if (state.request.chat_filter === \"individual\" && record.is_group)\n return;\n if (state.request.minimum_timestamp != null && record.timestamp < state.request.minimum_timestamp)\n return;\n record = {\n id: record.id,\n events: [{\n id: record.id,\n event_type: \"message.created\",\n resource_ref: record.id,\n resource_type: \"message\",\n occurred_at: new Date(record.timestamp * 1000).toISOString()\n }]\n };\n const previous2 = state.pending.get(record.id), seen = state.fingerprints.get(record.id);\n if (seen && seen.sequence >= sequence)\n return;\n const fingerprint = JSON.stringify(record);\n if (seen?.fingerprint === fingerprint) {\n seen.sequence = sequence;\n return;\n }\n const bytes = new TextEncoder().encode(fingerprint).length;\n if (bytes > 131072 || state.pendingBytes - (previous2?.bytes ?? 0) + bytes > 16777216 || state.pending.size >= 1e4 && !previous2) {\n reportError(state, \"WhatsApp page observation buffer overflowed; recovery is required\", sequence);\n return;\n }\n const entry = { sequence, record, bytes };\n state.pendingBytes += bytes - (previous2?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.fingerprintBytes += bytes - (seen?.bytes ?? 0);\n state.fingerprints.delete(record.id);\n state.fingerprints.set(record.id, { fingerprint, sequence, bytes });\n while (state.fingerprints.size > 1e4 || state.fingerprintBytes > 16777216) {\n const oldest = state.fingerprints.keys().next().value;\n state.fingerprintBytes -= state.fingerprints.get(oldest).bytes;\n state.fingerprints.delete(oldest);\n }\n post(state, entry);\n }).catch(() => {\n if (listeners.get(state.id) !== state)\n return;\n reportError(state, \"WhatsApp source observation failed; recovery is required\", sequence);\n });\n };\n state.onAdd = (model) => observe(model);\n state.onChange = (model) => observe(model);\n state.onReply = (event) => {\n if (event.source !== window || event.origin !== location.origin || event.data?.token !== state.token)\n return;\n if (event.data.type === \"lobu-feed-record:stop\") {\n detach(state.id);\n return;\n }\n if (event.data.type !== \"lobu-feed-record:ack\")\n return;\n try {\n assertAccount(state.request.account_id);\n } catch {\n detach(state.id, \"WhatsApp saved account changed; recovery is required\");\n return;\n }\n for (const [id, entry] of state.pending) {\n if (entry.sequence !== event.data.sequence)\n continue;\n if (event.data.ok) {\n state.pendingBytes -= entry.bytes;\n state.pending.delete(id);\n entry.resolve?.();\n } else\n entry.reject?.(Error(\"Browser rejected the source reference batch\"));\n break;\n }\n };\n listeners.set(state.id, state);\n try {\n collection.on(\"add\", state.onAdd);\n collection.on(\"change\", state.onChange);\n window.addEventListener(\"message\", state.onReply);\n } catch (error) {\n reportError(state, \"WhatsApp source observation failed; recovery is required\");\n throw error;\n }\n if (previous?.error)\n post(state, {\n sequence: ++state.sequence,\n record: { id: \"whatsapp-web:source-observation-error\", source_error: previous.error }\n });\n for (const entry of state.pending.values())\n post(state, entry);\n return { ok: !0, listening: !0 };\n }\n async function publishChanges(request) {\n const state = listeners.get(request.bridge_id);\n if (!state || state.token !== request.token)\n throw Error(\"Source listener is unavailable\");\n assertAccount(state.request.account_id);\n const record = { ...request.batch, id: `replay:${await digest(JSON.stringify([request.transition ?? null, request.batch]))}` };\n if (listeners.get(state.id) !== state)\n throw Error(\"Source listener was replaced\");\n assertAccount(state.request.account_id);\n const bytes = new TextEncoder().encode(JSON.stringify(record)).length, previous = state.pending.get(record.id);\n if (bytes > 131072 || state.pendingBytes - (previous?.bytes ?? 0) + bytes > 16777216 || state.pending.size >= 1e4 && !previous)\n throw Error(\"Source replay buffer is full\");\n await new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(Error(\"Source replay was not accepted by the browser\")), 1e4), entry = {\n record,\n bytes,\n sequence: ++state.sequence,\n resolve: () => {\n clearTimeout(timer);\n resolve();\n },\n reject: (error) => {\n clearTimeout(timer);\n reject(error);\n }\n };\n state.pendingBytes += bytes - (previous?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.post(entry);\n });\n return { ok: !0 };\n }\n function requireFirst(names) {\n for (const name of names)\n try {\n const module2 = window.require?.(name);\n if (module2)\n return module2;\n } catch {}\n return null;\n }\n function meUser() {\n const module2 = requireFirst([\n \"WAWebUserPrefsMeUser\",\n \"WAWebUserPrefsMe\",\n \"WAWebUserPrefs\"\n ]);\n if (!module2)\n return null;\n for (const accessor of [\n \"getMaybeMePnUser\",\n \"getMaybeMeUser\",\n \"getMeUser\",\n \"getMeUserOrThrow\",\n \"getMaybeMeLidUser\"\n ])\n try {\n const value = module2[accessor]?.();\n if (value)\n return value;\n } catch {}\n try {\n return module2.me ?? null;\n } catch {}\n return null;\n }\n async function ownJids() {\n const module2 = requireFirst([\"WAWebUserPrefsMeUser\"]), candidates = [meUser()];\n for (const accessor of [\"getMaybeMePnUser\", \"getMaybeMeLidUser\"])\n try {\n candidates.push(module2?.[accessor]?.());\n } catch {}\n const forms = new Set;\n for (const value of candidates) {\n const own = await canonicalJid(value);\n if (own.jid)\n forms.add(own.jid);\n if (own.lid)\n forms.add(own.lid);\n }\n return forms;\n }\n async function mentionsOwnAccount(row) {\n const addressed = [\n ...Array.isArray(row.mentionedJidList) ? row.mentionedJidList : [],\n row.quotedParticipant\n ].filter(Boolean);\n if (addressed.length === 0)\n return !1;\n const own = await ownJids();\n for (const value of addressed) {\n const candidate = await canonicalJid(value);\n if (own.has(candidate.jid) || candidate.lid && own.has(candidate.lid))\n return !0;\n }\n return !1;\n }\n const SEND_MODULES = [\n \"WAWebSendTextMsgChatAction\",\n \"WAWebSendMsgChatAction\",\n \"WAWebSendMessage\"\n ], REACTION_MODULES = [\n \"WAWebSendReactionMsgAction\",\n \"WAWebSendReactionMsg\",\n \"WAWebReactionAction\"\n ], REVOKE_MODULES = [\n \"WAWebChatSendMessages\",\n \"WAWebRevokeMsgAction\",\n \"WAWebDeleteChatAction\",\n \"WAWebRevokeMessage\"\n ], EDIT_MODULES = [\"WAWebSendMessageEditAction\", \"WAWebEditMessage\"], DRAFT_MODULES = [\n \"WAWebChatDraftUtils\",\n \"WAWebSetDraft\",\n \"WAWebComposeBoxActions\"\n ];\n function modelData(model) {\n return model?.attributes ?? model?._data ?? model ?? {};\n }\n function messageReference(model) {\n const row = modelData(model), key = row.id ?? model?.id, id = rawId(key), remote = widString(key?.remote ?? row.chatId ?? (key?.fromMe ? row.to : row.from));\n if (!id || !remote || remote === \"status@broadcast\" || remote.endsWith(\"@newsletter\") || SYSTEM_TYPES.has(row.type))\n return null;\n return { id, timestamp: unixSeconds(row), is_group: remote.endsWith(\"@g.us\") };\n }\n async function observeMessages(input = {}) {\n const after = input.after ?? null;\n if (after !== null && (!Number.isSafeInteger(after) || after < 0))\n throw Error(\"Invalid WhatsApp observation cursor\");\n const pending = input.unresolved ?? [];\n if (!Array.isArray(pending) || pending.length > 32 || pending.some((row) => !Number.isSafeInteger(row.position) || row.position <= 0 || typeof row.id !== \"string\" || row.id.length > 512 || !Number.isSafeInteger(row.first_seen) || row.first_seen < 0))\n throw Error(\"Invalid WhatsApp pending placeholder cursor\");\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n }), now = Math.floor(Date.now() / 1000), gaps = [], gap = (reason, detail) => gaps.push({ reason, detail }), scan = (position, limit, direction = \"next\", inclusive = !1) => new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source observation aborted\"));\n const request = transaction.objectStore(\"message\").index(\"rowId\").openCursor(position === null ? null : IDBKeyRange.lowerBound(position, !inclusive), direction), page2 = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(page2);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\" || cursor.value.id.length > 512) {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n page2.push({ position: cursor.key, id: cursor.value.id, timestamp: unixSeconds(cursor.value), type: cursor.value.type });\n if (page2.length >= limit)\n resolve(page2);\n else\n cursor.continue();\n };\n });\n let rows, rechecks;\n try {\n if (after === null) {\n rows = await scan(null, 1, \"prev\");\n const head = rows[0];\n return {\n after: head?.position ?? 0,\n anchor: head?.id ?? null,\n unresolved: head?.timestamp === 0 ? [{ position: head.position, id: head.id, first_seen: now }] : [],\n references: [],\n gaps: [],\n hasMore: !1\n };\n }\n let start = after;\n if (after > 0) {\n const [anchor] = await scan(after, 1, \"next\", !0);\n if (!input.anchor || anchor?.position !== after || anchor.id !== input.anchor) {\n gap(\"history-continuity\", [after, input.anchor ?? null]);\n start = 0;\n }\n }\n rechecks = await Promise.all(pending.map(async (item) => ({ item, row: (await scan(item.position, 1, \"next\", !0))[0] })));\n rows = await scan(start, 501);\n } finally {\n database.close();\n }\n const page = rows.slice(0, 500), references = new Map, unresolved = new Map, keys = requireFirst([\"WAWebMsgKey\"]);\n if ((page.length || rechecks.length) && typeof keys?.fromString !== \"function\")\n throw Error(\"WhatsApp source message keys are unavailable\");\n const accept = (row, firstSeen = now) => {\n const reference = messageReference({ id: keys.fromString(row.id), t: row.timestamp, type: row.type });\n if (!reference)\n return;\n if (input.chat_filter === \"group\" && !reference.is_group)\n return;\n if (input.chat_filter === \"individual\" && reference.is_group)\n return;\n if (reference.timestamp <= 0) {\n if (now - firstSeen >= 604800)\n gap(\"placeholder-expired\", [row.position, row.id, firstSeen]);\n else if (unresolved.size < 32 || unresolved.has(row.id))\n unresolved.set(row.id, { position: row.position, id: row.id, first_seen: firstSeen });\n else\n gap(\"placeholder-capacity\", [row.position, row.id]);\n return;\n }\n if (reference.timestamp >= input.started_at)\n references.set(reference.id, reference);\n }, checked = new Set;\n for (const { item, row } of rechecks)\n if (!row || row.position !== item.position || row.id !== item.id)\n gap(\"placeholder-unavailable\", [item.position, item.id]);\n else {\n checked.add(item.id);\n accept(row, item.first_seen);\n }\n for (const row of page)\n if (!checked.has(row.id))\n accept(row);\n const last = page[page.length - 1], rebased = gaps.some((item) => item.reason === \"history-continuity\");\n return {\n after: last?.position ?? (rebased ? 0 : after),\n anchor: last?.id ?? (rebased ? null : input.anchor ?? null),\n unresolved: [...unresolved.values()],\n references: [...references.values()],\n hasMore: rows.length > 500,\n gaps: await Promise.all(gaps.map(async (item) => {\n const identity = await digest(JSON.stringify([input.account_id, input.started_at, input.chat_filter, item]));\n return {\n id: `gap:${identity}`,\n event_type: \"source.gap\",\n resource_type: \"message\",\n resource_ref: `whatsapp:${item.reason}:${identity}`\n };\n }))\n };\n }\n function models(collection) {\n if (Array.isArray(collection?._models))\n return collection._models;\n if (Array.isArray(collection?.models))\n return collection.models;\n if (typeof collection?.toArray === \"function\")\n try {\n return collection.toArray();\n } catch {}\n return [];\n }\n function widString(value) {\n if (typeof value === \"string\")\n return value;\n if (!value)\n return null;\n if (typeof value._serialized === \"string\")\n return value._serialized;\n try {\n const rendered = value.toString?.();\n return rendered && rendered !== \"[object Object]\" ? String(rendered) : null;\n } catch {\n return null;\n }\n }\n function rawId(value) {\n if (typeof value === \"string\")\n return value && !/^(?:true|false)_/i.test(value) ? value : null;\n if (typeof value?.id === \"string\")\n return value.id && !/^(?:true|false)_/i.test(value.id) ? value.id : null;\n return null;\n }\n function unixSeconds(row) {\n const value = Number(row?.t ?? row?.timestamp ?? row?.ephemeralStartTimestamp ?? 0);\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n }\n async function canonicalJid(value) {\n const original = widString(value);\n if (!original)\n return { jid: null, lid: null };\n let jid = original.toLowerCase();\n if (jid.endsWith(\"@c.us\"))\n jid = `${jid.slice(0, -5)}@s.whatsapp.net`;\n if (!jid.endsWith(\"@lid\"))\n return { jid, lid: null };\n const migration = requireFirst([\n \"WAWebLidMigrationUtils\",\n \"WAWebLidMigration\"\n ]), toPn = migration?.toPn ?? migration?.getPnForLid ?? migration?.lidToPhone;\n if (typeof toPn === \"function\")\n try {\n const converted = await toPn.call(migration, value), phoneJid = widString(converted);\n if (phoneJid)\n return {\n jid: phoneJid.endsWith(\"@c.us\") ? `${phoneJid.slice(0, -5)}@s.whatsapp.net` : phoneJid,\n lid: jid\n };\n } catch {}\n return { jid, lid: jid };\n }\n function collectionByRawId(collection, id) {\n if (!id)\n return null;\n for (const model of models(collection)) {\n const row = modelData(model);\n if (rawId(row.id ?? model?.id) === id)\n return model;\n }\n return null;\n }\n function reactionTargetId(row) {\n return rawId(row.reactionParentKey) ?? rawId(row.parentMsgKey) ?? rawId(row.parentMessageKey) ?? (typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : null);\n }\n function normalizeReactions(row) {\n const source = row.reactions ?? row.reactionCollection ?? row.reactionsBySender;\n return (Array.isArray(source) ? source : models(source)).map((reaction) => {\n const data = modelData(reaction);\n return {\n emoji: data.text ?? data.reactionText ?? data.emoji ?? null,\n sender_jid: widString(data.senderUserJid ?? data.sender ?? data.author),\n from_me: Boolean(data.fromMe)\n };\n }).filter((reaction) => typeof reaction.emoji === \"string\" && reaction.emoji.length > 0);\n }\n function nameIndex(collections) {\n const byId = (collection) => {\n const map = new Map;\n for (const model of models(collection)) {\n const id = widString(modelData(model).id ?? model?.id);\n if (id && !map.has(id))\n map.set(id, model);\n }\n return map;\n };\n return { chats: byId(collections?.Chat), contacts: byId(collections?.Contact) };\n }\n function contactName(names, jid) {\n if (!jid)\n return null;\n const contact = names?.contacts?.get(jid);\n if (!contact)\n return null;\n const row = modelData(contact);\n return row.name ?? row.pushname ?? row.shortName ?? row.formattedName ?? null;\n }\n function chatName(names, jid) {\n if (!jid)\n return null;\n const chat = names?.chats?.get(jid);\n if (!chat)\n return null;\n const row = modelData(chat);\n return row.name ?? row.formattedTitle ?? row.contact?.name ?? row.contact?.pushname ?? null;\n }\n async function normalizeMessage(model, eventType = \"snapshot\", collectionsOverride = null, names = null) {\n const collections = collectionsOverride ?? requireFirst([\"WAWebCollections\"]);\n if (!collections)\n return null;\n const nameLookup = names ?? nameIndex(collections);\n let row = modelData(model), key = row.id ?? model?.id, id = rawId(key);\n if (!id)\n return null;\n if (row.type === \"reaction\") {\n const targetId = reactionTargetId(row), target = collectionByRawId(collections.Msg, targetId);\n if (target) {\n model = target;\n row = modelData(model);\n key = row.id ?? model?.id;\n id = rawId(key);\n }\n }\n const fromMe = Boolean(key?.fromMe ?? row.fromMe), remoteRaw = key?.remote ?? row.chatId, fromRaw = row.from, toRaw = row.to, authorRaw = row.author ?? key?.participant, chatRaw = remoteRaw ?? (fromMe ? toRaw : fromRaw), chat = await canonicalJid(chatRaw);\n if (!chat.jid || chat.jid === \"status@broadcast\" || chat.jid.endsWith(\"@newsletter\"))\n return null;\n const senderRaw = fromMe ? fromRaw : authorRaw ?? fromRaw, sender = await canonicalJid(senderRaw), participant = await canonicalJid(key?.participant ?? row.participant ?? (fromMe ? toRaw : null)), timestamp = unixSeconds(row), body = typeof row.body === \"string\" ? row.body : \"\", caption = typeof row.caption === \"string\" ? row.caption : \"\", quotedId = typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : rawId(row.quotedMsg?.id ?? row.quotedMsgKey), type = typeof row.type === \"string\" ? row.type : \"unknown\";\n return {\n id,\n chat_jid: chat.jid,\n chat_lid: chat.lid,\n chat_name: chatName(nameLookup, widString(chatRaw)),\n sender_jid: sender.jid,\n sender_lid: sender.lid,\n push_name: contactName(nameLookup, widString(senderRaw)) ?? row.notifyName ?? null,\n participant: participant.jid,\n from_me: fromMe,\n is_group: chat.jid.endsWith(\"@g.us\"),\n timestamp,\n occurred_at: timestamp > 0 ? new Date(timestamp * 1000).toISOString() : null,\n body,\n caption,\n message_type: type,\n media_kind: type === \"ptt\" ? \"audio\" : [\"image\", \"video\", \"audio\", \"document\", \"sticker\"].includes(type) ? type : null,\n media_type: typeof row.mimetype === \"string\" ? row.mimetype : null,\n media_size: Number.isFinite(Number(row.size ?? row.fileSize)) ? Number(row.size ?? row.fileSize) : null,\n media_filename: row.filename ?? row.fileName ?? row.title ?? null,\n quoted_id: quotedId,\n mentions_me: await mentionsOwnAccount(row),\n is_forwarded: Boolean(row.isForwarded || Number(row.forwardingScore) > 0),\n is_starred: Boolean(row.star ?? row.isStarred),\n is_system_event: SYSTEM_TYPES.has(type),\n edited: Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey),\n edit_timestamp: Number(row.editTimestamp ?? row.lastEditTimestamp) || null,\n revoked: Boolean(row.isRevoked || row.revoked || type === \"revoked\"),\n reactions: normalizeReactions(row),\n event_type: eventType\n };\n }\n function readiness() {\n if (typeof window.require !== \"function\")\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"whatsapp_runtime_unavailable\"\n };\n const collections = requireFirst([\"WAWebCollections\"]);\n if (!collections?.Msg || !collections?.Chat)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"collections_unavailable\"\n };\n const me = meUser(), qrVisible = Boolean(document.querySelector('[data-testid=\"qrcode\"], canvas[aria-label*=\"Scan\" i], [data-ref] canvas'));\n if (!me && qrVisible)\n return { ready: !1, state: \"logged_out\", reason: \"qr_code_visible\" };\n if (!me)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"authenticated_self_identity_unavailable\"\n };\n const socket = requireFirst([\"WAWebSocketModel\"])?.Socket, connection = socket ?? requireFirst([\"WAWebSocketState\", \"WAWebConn\", \"WAWebConnectionState\"]), connectionState = String(connection?.getSocketState?.() ?? connection?.state ?? connection?.socketState ?? \"\").toLowerCase();\n if (!connectionState)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"connection_state_unavailable\"\n };\n if (!/^(connected|open|ready|syncing)$/.test(connectionState))\n return {\n ready: !1,\n state: \"not_ready\",\n reason: `connection_${connectionState}`\n };\n if (socket) {\n const stream = String(socket.stream ?? \"\").toLowerCase();\n if (!stream)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"stream_state_unavailable\"\n };\n if (!/^(connected|open|ready)$/.test(stream))\n return { ready: !1, state: \"not_ready\", reason: `stream_${stream}` };\n if (socket.hasSynced === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n }\n const offlineDelivery = requireFirst([\n \"WAWebOfflineDelivery\",\n \"WAWebOfflineDeliveryState\"\n ]);\n if ((offlineDelivery?.isOfflineDeliveryComplete?.() ?? offlineDelivery?.offlineDeliveryComplete ?? offlineDelivery?.isComplete) === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"offline_delivery_incomplete\"\n };\n const hydration = requireFirst([\n \"WAWebInitialSyncInfo\",\n \"WAWebHistorySync\",\n \"WAWebAppState\"\n ]);\n if ((hydration?.isInitialSyncComplete?.() ?? hydration?.initialSyncComplete ?? hydration?.isHydrated ?? !0) !== !0)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n if (!Array.isArray(collections.Chat._models) && !Array.isArray(collections.Chat.models))\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"chat_store_placeholder\"\n };\n const signature = `${widString(me)}:${models(collections.Chat).length}:${models(collections.Msg).length}`;\n if (signature !== readinessSignature) {\n readinessSignature = signature;\n readinessStableSince = Date.now();\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n }\n if (Date.now() - readinessStableSince < 500)\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n return {\n ready: !0,\n state: \"ready\",\n message_count: models(collections.Msg).length,\n chat_count: models(collections.Chat).length\n };\n }\n function operationCapabilities() {\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]), draft = requireFirst(DRAFT_MODULES), send = requireFirst(SEND_MODULES), edit = requireFirst(EDIT_MODULES), reaction = requireFirst(REACTION_MODULES), revoke = requireFirst(REVOKE_MODULES), hasFunction = (module2, names) => names.some((name) => typeof module2?.[name] === \"function\");\n return {\n read_messages: typeof indexedDB < \"u\" && typeof requireFirst([\"WAWebMsgKey\"])?.fromString === \"function\" && typeof requireFirst([\"WAWebCollections\"])?.Msg?.getMessagesById === \"function\",\n search_messages: hasFunction(search, [\"searchMessages\", \"searchMsgs\", \"search\"]) || Boolean(requireFirst([\"WAWebCollections\"])?.Msg),\n draft_message: hasFunction(draft, [\n \"setDraft\",\n \"setChatDraft\",\n \"saveDraft\"\n ]),\n send_message: hasFunction(send, [\n \"sendTextMsgToChat\",\n \"sendMessage\",\n \"addAndSendTextMsg\"\n ]),\n edit_message: hasFunction(edit, [\"sendMessageEdit\", \"editMessage\"]),\n react_message: hasFunction(reaction, [\n \"sendReactionToMsg\",\n \"sendReaction\"\n ]),\n revoke_message: hasFunction(revoke, [\"sendRevokeMsgs\", \"revokeMessage\"])\n };\n }\n function uniqueMessageModels(collections) {\n const byId = new Map;\n for (const message of models(collections.Msg)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n for (const chat of models(collections.Chat))\n for (const message of models(modelData(chat).msgs ?? chat?.msgs)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n return [...byId.values()];\n }\n async function resolveChat(collections, input) {\n if (input?.self_chat === !0) {\n const me = meUser(), selfJid = (await canonicalJid(me)).jid;\n let self = null;\n for (const chat of models(collections.Chat))\n if ((await canonicalJid(modelData(chat).id ?? chat?.id)).jid === selfJid) {\n self = chat;\n break;\n }\n if (!self)\n throw Error(\"WhatsApp self chat is not loaded\");\n return self;\n }\n const requestedJidRaw = typeof input?.chat_jid === \"string\" ? input.chat_jid.trim().toLowerCase() : null, requestedJid = requestedJidRaw ? (await canonicalJid(requestedJidRaw)).jid : null, requestedName = typeof input?.chat_name === \"string\" ? input.chat_name.trim().toLowerCase() : null, matches = [];\n for (const chat of models(collections.Chat)) {\n const row = modelData(chat), jid = (await canonicalJid(row.id ?? chat?.id)).jid, name = String(row.name ?? row.formattedTitle ?? row.contact?.name ?? \"\").trim().toLowerCase();\n if (requestedJid ? jid === requestedJid : requestedName && name === requestedName)\n matches.push(chat);\n }\n if (matches.length === 0)\n throw Error(\"WhatsApp chat not found; pass an exact canonical chat_jid or exact chat_name\");\n if (matches.length > 1)\n throw Error(\"WhatsApp chat name is ambiguous; pass chat_jid\");\n return matches[0];\n }\n async function waitForPostState(check, label, timeoutMs = 2000) {\n const deadline = Date.now() + timeoutMs;\n do {\n if (check())\n return;\n await new Promise((resolve) => setTimeout(resolve, 50));\n } while (Date.now() < deadline);\n throw Error(`WhatsApp did not confirm ${label}`);\n }\n async function readMessages(input = {}, account) {\n const query = String(input.query ?? \"\").trim(), chatFilter = input.chat_filter ?? \"all\", limit = Math.min(100, Math.max(1, Math.trunc(Number(input.limit) || 50)));\n let before = null;\n if (input.cursor) {\n const cursor = JSON.parse(input.cursor);\n if (cursor.v !== 1 || !Number.isSafeInteger(cursor.before) || cursor.before <= 0 || cursor.query !== query || cursor.chat_filter !== chatFilter || cursor.account !== account)\n throw Error(\"Invalid WhatsApp source cursor or changed query scope\");\n before = cursor.before;\n }\n const keyModule = requireFirst([\"WAWebMsgKey\"]), exactId = query.startsWith(\"id:\") ? query.slice(3) : null;\n let chatJid = null;\n if (query.startsWith(\"chat:\")) {\n const chat = await resolveChat(requireFirst([\"WAWebCollections\"]), { chat_jid: query.slice(5) });\n chatJid = (await canonicalJid(modelData(chat).id ?? chat?.id)).jid;\n }\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n });\n let sourceRows;\n try {\n sourceRows = await new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source read aborted\"));\n const index = transaction.objectStore(\"message\").index(\"rowId\"), range = before === null ? null : IDBKeyRange.upperBound(before, !0), request = index.openCursor(range, \"prev\"), rows = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(rows);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\") {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n if (exactId !== null) {\n if (keyModule.fromString(cursor.value.id).id !== exactId) {\n cursor.continue();\n return;\n }\n resolve([{ position: cursor.key, id: cursor.value.id }]);\n return;\n }\n rows.push({ position: cursor.key, id: cursor.value.id });\n if (rows.length > (chatJid === null ? limit : 20000))\n resolve(rows);\n else\n cursor.continue();\n };\n });\n } finally {\n database.close();\n }\n let hasMore = sourceRows.length > limit, page = sourceRows.slice(0, limit), last = page[page.length - 1];\n if (chatJid !== null) {\n const examined = sourceRows.slice(0, 20000), canonical = new Map, matches = [];\n for (const row of examined) {\n const remote = keyModule.fromString(row.id).remote, raw = widString(remote);\n if (!canonical.has(raw))\n canonical.set(raw, (await canonicalJid(remote)).jid);\n if (canonical.get(raw) !== chatJid)\n continue;\n matches.push(row);\n if (matches.length > limit)\n break;\n }\n page = matches.slice(0, limit);\n hasMore = matches.length > limit || sourceRows.length > 20000;\n last = matches.length > limit ? page[page.length - 1] : examined[examined.length - 1];\n }\n const collections = requireFirst([\"WAWebCollections\"]), selected = [];\n for (const row of page) {\n const key = keyModule.fromString(row.id);\n if (exactId !== null && key.id !== exactId)\n continue;\n const remote = widString(key.remote);\n if (remote === \"status@broadcast\" || remote.endsWith(\"@newsletter\"))\n continue;\n const isGroup = remote.endsWith(\"@g.us\");\n if (chatFilter === \"group\" && !isGroup || chatFilter === \"individual\" && isGroup)\n continue;\n selected.push(row);\n }\n const results = [];\n if (selected.length) {\n const loaded = await collections.Msg.getMessagesById(selected.map((row) => row.id));\n if (loaded?.canceled || !Array.isArray(loaded?.messages))\n throw Error(\"Source message loading was canceled or unavailable\");\n const byKey = new Map(loaded.messages.map((model) => [String(model.id ?? modelData(model).id), model])), names = nameIndex(collections);\n for (const row of selected) {\n const model = byKey.get(row.id);\n if (!model)\n throw Error(\"Source message could not be loaded; retry the read\");\n const message = await normalizeMessage(model, \"snapshot\", collections, names);\n if (!message || message.timestamp <= 0)\n continue;\n if (exactId === null && chatJid === null && query && !`${message.body}\n${message.caption}`.toLowerCase().includes(query.toLowerCase()))\n continue;\n results.push(message);\n }\n }\n return {\n results,\n hasMore,\n ...hasMore ? { nextCursor: JSON.stringify({ v: 1, before: last.position, query, chat_filter: chatFilter, account }) } : {}\n };\n }\n async function searchMessages(input) {\n const collections = requireFirst([\"WAWebCollections\"]), query = String(input?.query ?? \"\").trim();\n if (!query)\n throw Error(\"query is required\");\n const offset = Math.max(0, Number(input?.offset) || 0), requestedLimit = Math.max(1, Math.min(Number(input?.limit) || 50, 100));\n if (offset >= 100)\n throw Error(\"WhatsApp source search supports only the first 100 matches\");\n const limit = Math.min(requestedLimit, 100 - offset), searchSourceLimit = 100, chatFilter = [\"all\", \"individual\", \"group\"].includes(input?.chat_filter) ? input.chat_filter : \"all\", chat = input?.chat_jid || input?.chat_name || input?.self_chat === !0 ? await resolveChat(collections, input) : null;\n let scopedChats = chat ? [chat] : void 0;\n if (!chat && chatFilter !== \"all\") {\n scopedChats = [];\n for (const candidate of models(collections.Chat)) {\n const jid = (await canonicalJid(modelData(candidate).id ?? candidate?.id)).jid;\n if (!jid || jid === \"status@broadcast\" || jid.endsWith(\"@newsletter\"))\n continue;\n const isGroup = jid.endsWith(\"@g.us\");\n if (chatFilter === \"group\" ? isGroup : !isGroup)\n scopedChats.push(candidate);\n }\n }\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]);\n let found = null;\n for (const fn of [\n search?.searchMessages,\n search?.searchMsgs,\n search?.search\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n found = await fn.call(search, query, scopedChats, searchSourceLimit);\n break;\n } catch {}\n }\n let source = \"whatsapp_fts\", candidates = Array.isArray(found) ? found : models(found?.messages ?? found);\n if (!found) {\n source = \"loaded_model_fallback\";\n const needle = query.toLowerCase();\n candidates = uniqueMessageModels(collections).filter((model) => {\n const row = modelData(model);\n if (chat) {\n const chatId = widString(modelData(chat).id ?? chat?.id);\n if (widString(row.id?.remote ?? row.chatId) !== chatId)\n return !1;\n }\n return String(row.body ?? row.caption ?? \"\").toLowerCase().includes(needle);\n });\n }\n const normalized = [], names = nameIndex(collections);\n for (const candidate of candidates) {\n const model = candidate?.msg ?? candidate?.message ?? candidate, message = await normalizeMessage(model, \"search\", collections, names);\n if (!message || Number(message.timestamp) <= 0)\n continue;\n if (chatFilter === \"group\" && !message.is_group)\n continue;\n if (chatFilter === \"individual\" && message.is_group)\n continue;\n normalized.push(message);\n if (normalized.length >= searchSourceLimit)\n break;\n }\n return {\n source,\n results: normalized.slice(offset, offset + limit),\n hasMore: offset + limit < normalized.length\n };\n }\n async function draftMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const draft = {\n body: text,\n timestamp: Math.floor(Date.now() / 1000),\n type: \"chat\",\n mentionedJidList: [],\n quotedMsg: null\n }, module2 = requireFirst(DRAFT_MODULES);\n let applied = !1;\n for (const fn of [\n module2?.setDraft,\n module2?.setChatDraft,\n module2?.saveDraft\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n assertAccount(account);\n await fn.call(module2, chat, draft);\n applied = !0;\n break;\n } catch {\n try {\n assertAccount(account);\n await fn.call(module2, draft, chat);\n applied = !0;\n break;\n } catch {}\n }\n }\n if (!applied && typeof chat?.setDraft === \"function\") {\n assertAccount(account);\n await chat.setDraft(draft);\n applied = !0;\n }\n if (!applied)\n throw Error(\"WhatsApp draft capability is unavailable in this web build\");\n const stored = modelData(chat).draft ?? chat.get?.(\"draft\") ?? null;\n if (!stored || typeof stored !== \"object\" || stored.body !== text)\n throw Error(\"WhatsApp rejected the persistent draft shape\");\n return {\n drafted: !0,\n sent: !1,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n draft\n };\n }\n async function sendMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(SEND_MODULES);\n if (typeof module2?.createTextMsgData === \"function\" && typeof module2?.addAndSendTextMsg === \"function\") {\n const data = await module2.createTextMsgData(chat, text), plannedId = rawId(data?.id);\n if (!plannedId)\n throw Error(\"WhatsApp did not assign an id to the outgoing message\");\n assertAccount(account);\n await module2.addAndSendTextMsg(chat, data);\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: plannedId\n };\n }\n const fn = module2?.sendTextMsgToChat ?? module2?.sendMessage ?? chat?.sendMessage;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp send capability is unavailable in this web build\");\n assertAccount(account);\n const result = fn === chat?.sendMessage ? await fn.call(chat, text) : await fn.call(module2, chat, text), messageId = rawId(modelData(result).id ?? result?.id);\n if (!messageId)\n throw Error(\"WhatsApp send acknowledgment has no raw message ID\");\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: messageId\n };\n }\n function messageActionAllowed(message, predicateNames, legacyFlags) {\n const row = modelData(message);\n for (const flag of legacyFlags)\n if (row[flag] === !0)\n return !0;\n const capability = requireFirst([\"WAWebMsgActionCapability\"]);\n for (const name of predicateNames) {\n if (typeof capability?.[name] !== \"function\")\n continue;\n try {\n if (capability[name](message) === !0)\n return !0;\n } catch {}\n }\n return !1;\n }\n function resolveMessage(collections, id) {\n const raw = String(id ?? \"\").trim();\n if (!raw)\n throw Error(\"message_id is required\");\n const message = collectionByRawId(collections.Msg, raw);\n if (!message)\n throw Error(`WhatsApp message ${raw} is not loaded; read it with id:${raw} from the live messages feed or search it first`);\n return message;\n }\n async function editMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits editing outgoing messages\");\n if (!messageActionAllowed(message, [\"canEditText\", \"canEditCaption\", \"canEnterEditingFlow\"], [\"canEdit\", \"isEditable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently editable\");\n const text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(EDIT_MODULES), fn = module2?.sendMessageEdit ?? module2?.editMessage ?? message?.edit;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp edit capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.edit ? fn.call(message, text) : fn.call(module2, message, text, {}));\n await waitForPostState(() => {\n const row = modelData(message);\n return row.body === text && Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey);\n }, \"message edit\");\n return {\n edited: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function reactMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), emoji = input?.remove ? \"\" : String(input?.emoji ?? \"\");\n if (!input?.remove && !emoji)\n throw Error(\"emoji is required unless remove=true\");\n const module2 = requireFirst(REACTION_MODULES), fn = module2?.sendReactionToMsg ?? module2?.sendReaction ?? message?.react;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp reaction capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.react ? fn.call(message, emoji) : fn.call(module2, message, emoji));\n await waitForPostState(() => {\n const row = modelData(message), reactions = normalizeReactions(row);\n if (reactions.length > 0)\n return input?.remove ? !reactions.some((reaction) => reaction.from_me) : reactions.some((reaction) => reaction.from_me && reaction.emoji === emoji);\n return input?.remove ? !0 : row.hasReaction === !0;\n }, \"reaction state\");\n return {\n reacted: !0,\n confirmed: input?.remove ? normalizeReactions(modelData(message)).length > 0 : !0,\n removed: Boolean(input?.remove),\n emoji: emoji || null,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function revokeMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits revoking outgoing messages\");\n if (!messageActionAllowed(message, [\"canSenderRevokeMsg\", \"canAdminRevokeMsg\"], [\"canRevoke\", \"isRevokable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently revokable\");\n const module2 = requireFirst(REVOKE_MODULES), fn = module2?.sendRevokeMsgs ?? module2?.sendRevoke ?? module2?.revokeMessage ?? message?.sendRevoke ?? message?.revoke;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp revoke capability is unavailable in this web build\");\n assertAccount(account);\n if (fn === message?.sendRevoke || fn === message?.revoke)\n await fn.call(message);\n else\n await fn.call(module2, [message], modelData(message).id?.remote);\n await waitForPostState(() => {\n const row = modelData(message);\n return Boolean(row.isRevoked || row.revoked || row.type === \"revoked\");\n }, \"message revoke\");\n return {\n revoked: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function invoke(request) {\n try {\n if (Number(request?.adapter_version) !== 27)\n return {\n ok: !1,\n error: {\n state: \"adapter_mismatch\",\n reason: \"expected 27\"\n }\n };\n if (request.op === \"account_identity\") {\n const accountId = widString(meUser());\n return accountId ? { accountId } : null;\n }\n if (request.op === \"probe\") {\n const status = readiness();\n return status.ready ? { ok: !0, status, capabilities: operationCapabilities() } : { ok: !1, error: status };\n }\n assertAccount(request.account_id);\n const input = { ...request.input, account_id: request.account_id }, finish = async (promise) => {\n const value = await promise;\n assertAccount(request.account_id);\n return { ok: !0, ...value };\n };\n if (request.op === \"listen\")\n return listen(request);\n if (request.op === \"publish_changes\")\n return await publishChanges(request);\n if (request.op === \"observe_messages\")\n return await finish(observeMessages(input));\n if (operationCapabilities()[request.op] !== !0)\n return {\n ok: !1,\n error: {\n state: \"capability_unavailable\",\n reason: `${request.op} is unavailable in this WhatsApp Web build`\n }\n };\n if (request.op === \"read_messages\")\n return await finish(readMessages(input, request.account_id));\n if (request.op === \"search_messages\")\n return await finish(searchMessages(input));\n if (request.op === \"draft_message\")\n return await finish(draftMessage(input, request.account_id));\n if (request.op === \"send_message\")\n return await finish(sendMessage(input, request.account_id));\n if (request.op === \"edit_message\")\n return await finish(editMessage(input, request.account_id));\n if (request.op === \"react_message\")\n return await finish(reactMessage(input, request.account_id));\n if (request.op === \"revoke_message\")\n return await finish(revokeMessage(input, request.account_id));\n return {\n ok: !1,\n error: { state: \"unsupported_operation\", reason: String(request?.op) }\n };\n } catch (error) {\n if (request?.account_id && widString(meUser()) !== request.account_id)\n error = Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n return {\n ok: !1,\n error: {\n state: \"operation_failed\",\n reason: error instanceof Error ? error.message : String(error)\n }\n };\n }\n }\n globalThis.__owlettoWhatsAppAdapterV1 = { version: 27, invoke, detach };\n })();\n for (let i = 0; i < 40; i++) {\n const identity = await globalThis.__owlettoWhatsAppAdapterV1.invoke({ op: \"account_identity\", adapter_version: 27 });\n if (identity?.accountId) return identity;\n await new Promise(resolve => setTimeout(resolve, 250));\n }\n return null;\n })()"
21696
+ "expression": "(async () => {\n (function whatsAppWebAdapterProgram() {\n const SYSTEM_TYPES = new Set([\n \"gp2\",\n \"notification_template\",\n \"e2e_notification\"\n ]);\n let readinessSignature = null, readinessStableSince = 0;\n const existing = globalThis.__owlettoWhatsAppAdapterV1;\n if (existing?.version === 28)\n return;\n existing?.detach?.(void 0, \"WhatsApp adapter was replaced; recovery is required\");\n const listeners = new Map;\n function detach(bindingId, reason) {\n const selected = bindingId ? [listeners.get(bindingId)] : [...listeners.values()];\n for (const state of selected) {\n if (!state)\n continue;\n if (reason) {\n state.error = reason;\n state.post({ sequence: ++state.sequence, record: { id: \"whatsapp-web:source-observation-error\", source_error: reason } });\n }\n for (const entry of state.pending.values())\n entry.reject?.(Error(reason ?? \"Source listener was detached\"));\n state.collection.off(\"add\", state.onAdd);\n state.collection.off(\"change\", state.onChange);\n window.removeEventListener(\"message\", state.onReply);\n listeners.delete(state.id);\n }\n }\n function assertAccount(account) {\n if (typeof account !== \"string\" || !account || widString(meUser()) !== account)\n throw Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n }\n async function digest(value) {\n const bytes = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n function listen(request) {\n assertAccount(request.account_id);\n const collection = requireFirst([\"WAWebCollections\"])?.Msg;\n if (typeof collection?.on !== \"function\" || typeof collection?.off !== \"function\")\n throw Error(\"WhatsApp message observation is unavailable in this build\");\n if (!request.bridge_id || !request.token)\n throw Error(\"A feed bridge is required\");\n const post = (state2, entry) => window.postMessage({\n type: \"lobu-feed-record\",\n token: state2.token,\n sequence: entry.sequence,\n record: entry.record\n }, location.origin), reportError = (state2, message, sequence = ++state2.sequence) => {\n state2.error = message;\n post(state2, {\n sequence,\n record: {\n id: \"whatsapp-web:source-observation-error\",\n source_error: message\n }\n });\n }, resident = listeners.get(request.bridge_id), previous = resident?.request.account_id === request.account_id && resident?.request.chat_filter === request.chat_filter && resident?.request.minimum_timestamp === request.minimum_timestamp ? resident : null;\n detach(request.bridge_id);\n const state = {\n ...previous ?? {\n id: request.bridge_id,\n collection,\n sequence: 0,\n pending: new Map,\n fingerprints: new Map,\n pendingBytes: 0,\n fingerprintBytes: 0,\n error: null\n },\n collection,\n error: null\n };\n state.token = request.token;\n state.request = request;\n state.post = (entry) => post(state, entry);\n const observe = (model) => {\n if (state.error)\n return;\n const sequence = ++state.sequence;\n new Promise((resolve) => {\n assertAccount(state.request.account_id);\n resolve(messageReference(model));\n }).then((record) => {\n if (listeners.get(state.id) !== state)\n return;\n assertAccount(state.request.account_id);\n if (!record || record.timestamp <= 0)\n return;\n if (state.request.chat_filter === \"group\" && !record.is_group)\n return;\n if (state.request.chat_filter === \"individual\" && record.is_group)\n return;\n if (state.request.minimum_timestamp != null && record.timestamp < state.request.minimum_timestamp)\n return;\n record = {\n id: record.id,\n events: [{\n id: record.id,\n event_type: \"message.created\",\n resource_ref: record.id,\n resource_type: \"message\",\n occurred_at: new Date(record.timestamp * 1000).toISOString()\n }]\n };\n const previous2 = state.pending.get(record.id), seen = state.fingerprints.get(record.id);\n if (seen && seen.sequence >= sequence)\n return;\n const fingerprint = JSON.stringify(record);\n if (seen?.fingerprint === fingerprint) {\n seen.sequence = sequence;\n return;\n }\n const bytes = new TextEncoder().encode(fingerprint).length;\n if (bytes > 131072 || state.pendingBytes - (previous2?.bytes ?? 0) + bytes > 16777216 || state.pending.size >= 1e4 && !previous2) {\n reportError(state, \"WhatsApp page observation buffer overflowed; recovery is required\", sequence);\n return;\n }\n const entry = { sequence, record, bytes };\n state.pendingBytes += bytes - (previous2?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.fingerprintBytes += bytes - (seen?.bytes ?? 0);\n state.fingerprints.delete(record.id);\n state.fingerprints.set(record.id, { fingerprint, sequence, bytes });\n while (state.fingerprints.size > 1e4 || state.fingerprintBytes > 16777216) {\n const oldest = state.fingerprints.keys().next().value;\n state.fingerprintBytes -= state.fingerprints.get(oldest).bytes;\n state.fingerprints.delete(oldest);\n }\n post(state, entry);\n }).catch(() => {\n if (listeners.get(state.id) !== state)\n return;\n reportError(state, \"WhatsApp source observation failed; recovery is required\", sequence);\n });\n };\n state.onAdd = (model) => observe(model);\n state.onChange = (model) => observe(model);\n state.onReply = (event) => {\n if (event.source !== window || event.origin !== location.origin || event.data?.token !== state.token)\n return;\n if (event.data.type === \"lobu-feed-record:stop\") {\n detach(state.id);\n return;\n }\n if (event.data.type !== \"lobu-feed-record:ack\")\n return;\n try {\n assertAccount(state.request.account_id);\n } catch {\n detach(state.id, \"WhatsApp saved account changed; recovery is required\");\n return;\n }\n for (const [id, entry] of state.pending) {\n if (entry.sequence !== event.data.sequence)\n continue;\n if (event.data.ok) {\n state.pendingBytes -= entry.bytes;\n state.pending.delete(id);\n entry.resolve?.();\n } else\n entry.reject?.(Error(\"Browser rejected the source reference batch\"));\n break;\n }\n };\n listeners.set(state.id, state);\n try {\n collection.on(\"add\", state.onAdd);\n collection.on(\"change\", state.onChange);\n window.addEventListener(\"message\", state.onReply);\n } catch (error) {\n reportError(state, \"WhatsApp source observation failed; recovery is required\");\n throw error;\n }\n if (previous?.error)\n post(state, {\n sequence: ++state.sequence,\n record: { id: \"whatsapp-web:source-observation-error\", source_error: previous.error }\n });\n for (const entry of state.pending.values())\n post(state, entry);\n return { ok: !0, listening: !0 };\n }\n async function publishChanges(request) {\n const state = listeners.get(request.bridge_id);\n if (!state || state.token !== request.token)\n throw Error(\"Source listener is unavailable\");\n assertAccount(state.request.account_id);\n const record = { ...request.batch, id: `replay:${await digest(JSON.stringify([request.transition ?? null, request.batch]))}` };\n if (listeners.get(state.id) !== state)\n throw Error(\"Source listener was replaced\");\n assertAccount(state.request.account_id);\n const bytes = new TextEncoder().encode(JSON.stringify(record)).length, previous = state.pending.get(record.id);\n if (bytes > 131072 || state.pendingBytes - (previous?.bytes ?? 0) + bytes > 16777216 || state.pending.size >= 1e4 && !previous)\n throw Error(\"Source replay buffer is full\");\n await new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(Error(\"Source replay was not accepted by the browser\")), 1e4), entry = {\n record,\n bytes,\n sequence: ++state.sequence,\n resolve: () => {\n clearTimeout(timer);\n resolve();\n },\n reject: (error) => {\n clearTimeout(timer);\n reject(error);\n }\n };\n state.pendingBytes += bytes - (previous?.bytes ?? 0);\n state.pending.set(record.id, entry);\n state.post(entry);\n });\n return { ok: !0 };\n }\n function requireFirst(names) {\n for (const name of names)\n try {\n const module2 = window.require?.(name);\n if (module2)\n return module2;\n } catch {}\n return null;\n }\n function meUser() {\n const module2 = requireFirst([\n \"WAWebUserPrefsMeUser\",\n \"WAWebUserPrefsMe\",\n \"WAWebUserPrefs\"\n ]);\n if (!module2)\n return null;\n for (const accessor of [\n \"getMaybeMePnUser\",\n \"getMaybeMeUser\",\n \"getMeUser\",\n \"getMeUserOrThrow\",\n \"getMaybeMeLidUser\"\n ])\n try {\n const value = module2[accessor]?.();\n if (value)\n return value;\n } catch {}\n try {\n return module2.me ?? null;\n } catch {}\n return null;\n }\n async function ownJids() {\n const module2 = requireFirst([\"WAWebUserPrefsMeUser\"]), candidates = [meUser()];\n for (const accessor of [\"getMaybeMePnUser\", \"getMaybeMeLidUser\"])\n try {\n candidates.push(module2?.[accessor]?.());\n } catch {}\n const forms = new Set;\n for (const value of candidates) {\n const own = await canonicalJid(value);\n if (own.jid)\n forms.add(own.jid);\n if (own.lid)\n forms.add(own.lid);\n }\n return forms;\n }\n async function mentionsOwnAccount(row) {\n const addressed = [\n ...Array.isArray(row.mentionedJidList) ? row.mentionedJidList : [],\n row.quotedParticipant\n ].filter(Boolean);\n if (addressed.length === 0)\n return !1;\n const own = await ownJids();\n for (const value of addressed) {\n const candidate = await canonicalJid(value);\n if (own.has(candidate.jid) || candidate.lid && own.has(candidate.lid))\n return !0;\n }\n return !1;\n }\n async function ownMentionJids(row) {\n const mentions = Array.isArray(row.mentionedJidList) ? row.mentionedJidList : [];\n if (mentions.length === 0)\n return [];\n const own = await ownJids(), mentioned = new Set;\n for (const value of mentions) {\n const candidate = await canonicalJid(value);\n for (const jid of [candidate.jid, candidate.lid])\n if (typeof jid === \"string\" && /^[0-9]{5,32}@(s\\.whatsapp\\.net|lid)$/.test(jid) && own.has(jid))\n mentioned.add(jid);\n }\n return [...mentioned].slice(0, 2);\n }\n const SEND_MODULES = [\n \"WAWebSendTextMsgChatAction\",\n \"WAWebSendMsgChatAction\",\n \"WAWebSendMessage\"\n ], REACTION_MODULES = [\n \"WAWebSendReactionMsgAction\",\n \"WAWebSendReactionMsg\",\n \"WAWebReactionAction\"\n ], REVOKE_MODULES = [\n \"WAWebChatSendMessages\",\n \"WAWebRevokeMsgAction\",\n \"WAWebDeleteChatAction\",\n \"WAWebRevokeMessage\"\n ], EDIT_MODULES = [\"WAWebSendMessageEditAction\", \"WAWebEditMessage\"], DRAFT_MODULES = [\n \"WAWebChatDraftUtils\",\n \"WAWebSetDraft\",\n \"WAWebComposeBoxActions\"\n ];\n function modelData(model) {\n return model?.attributes ?? model?._data ?? model ?? {};\n }\n function messageReference(model) {\n const row = modelData(model), key = row.id ?? model?.id, id = rawId(key), remote = widString(key?.remote ?? row.chatId ?? (key?.fromMe ? row.to : row.from));\n if (!id || !remote || isBroadcastOnlyJid(remote) || SYSTEM_TYPES.has(row.type))\n return null;\n return { id, timestamp: unixSeconds(row), is_group: remote.endsWith(\"@g.us\") };\n }\n async function observeMessages(input = {}) {\n const after = input.after ?? null;\n if (after !== null && (!Number.isSafeInteger(after) || after < 0))\n throw Error(\"Invalid WhatsApp observation cursor\");\n const pending = input.unresolved ?? [];\n if (!Array.isArray(pending) || pending.length > 32 || pending.some((row) => !Number.isSafeInteger(row.position) || row.position <= 0 || typeof row.id !== \"string\" || row.id.length > 512 || !Number.isSafeInteger(row.first_seen) || row.first_seen < 0))\n throw Error(\"Invalid WhatsApp pending placeholder cursor\");\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n }), now = Math.floor(Date.now() / 1000), gaps = [], gap = (reason, detail) => gaps.push({ reason, detail }), scan = (position, limit, direction = \"next\", inclusive = !1) => new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source observation aborted\"));\n const request = transaction.objectStore(\"message\").index(\"rowId\").openCursor(position === null ? null : IDBKeyRange.lowerBound(position, !inclusive), direction), page2 = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(page2);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\" || cursor.value.id.length > 512) {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n page2.push({ position: cursor.key, id: cursor.value.id, timestamp: unixSeconds(cursor.value), type: cursor.value.type });\n if (page2.length >= limit)\n resolve(page2);\n else\n cursor.continue();\n };\n });\n let rows, rechecks;\n try {\n if (after === null) {\n rows = await scan(null, 1, \"prev\");\n const head = rows[0];\n return {\n after: head?.position ?? 0,\n anchor: head?.id ?? null,\n unresolved: head?.timestamp === 0 ? [{ position: head.position, id: head.id, first_seen: now }] : [],\n references: [],\n gaps: [],\n hasMore: !1\n };\n }\n let start = after;\n if (after > 0) {\n const [anchor] = await scan(after, 1, \"next\", !0);\n if (!input.anchor || anchor?.position !== after || anchor.id !== input.anchor) {\n gap(\"history-continuity\", [after, input.anchor ?? null]);\n start = 0;\n }\n }\n rechecks = await Promise.all(pending.map(async (item) => ({ item, row: (await scan(item.position, 1, \"next\", !0))[0] })));\n rows = await scan(start, 501);\n } finally {\n database.close();\n }\n const page = rows.slice(0, 500), references = new Map, unresolved = new Map, keys = requireFirst([\"WAWebMsgKey\"]);\n if ((page.length || rechecks.length) && typeof keys?.fromString !== \"function\")\n throw Error(\"WhatsApp source message keys are unavailable\");\n const accept = (row, firstSeen = now) => {\n const reference = messageReference({ id: keys.fromString(row.id), t: row.timestamp, type: row.type });\n if (!reference)\n return;\n if (input.chat_filter === \"group\" && !reference.is_group)\n return;\n if (input.chat_filter === \"individual\" && reference.is_group)\n return;\n if (reference.timestamp <= 0) {\n if (now - firstSeen >= 604800)\n gap(\"placeholder-expired\", [row.position, row.id, firstSeen]);\n else if (unresolved.size < 32 || unresolved.has(row.id))\n unresolved.set(row.id, { position: row.position, id: row.id, first_seen: firstSeen });\n else\n gap(\"placeholder-capacity\", [row.position, row.id]);\n return;\n }\n if (reference.timestamp >= input.started_at)\n references.set(reference.id, reference);\n }, checked = new Set;\n for (const { item, row } of rechecks)\n if (!row || row.position !== item.position || row.id !== item.id)\n gap(\"placeholder-unavailable\", [item.position, item.id]);\n else {\n checked.add(item.id);\n accept(row, item.first_seen);\n }\n for (const row of page)\n if (!checked.has(row.id))\n accept(row);\n const last = page[page.length - 1], rebased = gaps.some((item) => item.reason === \"history-continuity\");\n return {\n after: last?.position ?? (rebased ? 0 : after),\n anchor: last?.id ?? (rebased ? null : input.anchor ?? null),\n unresolved: [...unresolved.values()],\n references: [...references.values()],\n hasMore: rows.length > 500,\n gaps: await Promise.all(gaps.map(async (item) => {\n const identity = await digest(JSON.stringify([input.account_id, input.started_at, input.chat_filter, item]));\n return {\n id: `gap:${identity}`,\n event_type: \"source.gap\",\n resource_type: \"message\",\n resource_ref: `whatsapp:${item.reason}:${identity}`\n };\n }))\n };\n }\n function models(collection) {\n if (Array.isArray(collection?._models))\n return collection._models;\n if (Array.isArray(collection?.models))\n return collection.models;\n if (typeof collection?.toArray === \"function\")\n try {\n return collection.toArray();\n } catch {}\n return [];\n }\n function isBroadcastOnlyJid(jid) {\n return jid === \"status@broadcast\" || jid.endsWith(\"@newsletter\") || jid === \"0@c.us\" || jid === \"0@s.whatsapp.net\";\n }\n function widString(value) {\n if (typeof value === \"string\")\n return value;\n if (!value)\n return null;\n if (typeof value._serialized === \"string\")\n return value._serialized;\n try {\n const rendered = value.toString?.();\n return rendered && rendered !== \"[object Object]\" ? String(rendered) : null;\n } catch {\n return null;\n }\n }\n function rawId(value) {\n if (typeof value === \"string\")\n return value && !/^(?:true|false)_/i.test(value) ? value : null;\n if (typeof value?.id === \"string\")\n return value.id && !/^(?:true|false)_/i.test(value.id) ? value.id : null;\n return null;\n }\n function unixSeconds(row) {\n const value = Number(row?.t ?? row?.timestamp ?? row?.ephemeralStartTimestamp ?? 0);\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n }\n async function canonicalJid(value) {\n const original = widString(value);\n if (!original)\n return { jid: null, lid: null };\n let jid = original.toLowerCase();\n if (jid.endsWith(\"@c.us\"))\n jid = `${jid.slice(0, -5)}@s.whatsapp.net`;\n if (!jid.endsWith(\"@lid\"))\n return { jid, lid: null };\n const migration = requireFirst([\n \"WAWebLidMigrationUtils\",\n \"WAWebLidMigration\"\n ]), toPn = migration?.toPn ?? migration?.getPnForLid ?? migration?.lidToPhone;\n if (typeof toPn === \"function\")\n try {\n const converted = await toPn.call(migration, value), phoneJid = widString(converted);\n if (phoneJid)\n return {\n jid: phoneJid.endsWith(\"@c.us\") ? `${phoneJid.slice(0, -5)}@s.whatsapp.net` : phoneJid,\n lid: jid\n };\n } catch {}\n return { jid, lid: jid };\n }\n function collectionByRawId(collection, id) {\n if (!id)\n return null;\n for (const model of models(collection)) {\n const row = modelData(model);\n if (rawId(row.id ?? model?.id) === id)\n return model;\n }\n return null;\n }\n function reactionTargetId(row) {\n return rawId(row.reactionParentKey) ?? rawId(row.parentMsgKey) ?? rawId(row.parentMessageKey) ?? (typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : null);\n }\n function normalizeReactions(row) {\n const source = row.reactions ?? row.reactionCollection ?? row.reactionsBySender;\n return (Array.isArray(source) ? source : models(source)).map((reaction) => {\n const data = modelData(reaction);\n return {\n emoji: data.text ?? data.reactionText ?? data.emoji ?? null,\n sender_jid: widString(data.senderUserJid ?? data.sender ?? data.author),\n from_me: Boolean(data.fromMe)\n };\n }).filter((reaction) => typeof reaction.emoji === \"string\" && reaction.emoji.length > 0);\n }\n function nameIndex(collections) {\n const byId = (collection) => {\n const map = new Map;\n for (const model of models(collection)) {\n const id = widString(modelData(model).id ?? model?.id);\n if (id && !map.has(id))\n map.set(id, model);\n }\n return map;\n };\n return { chats: byId(collections?.Chat), contacts: byId(collections?.Contact) };\n }\n function contactName(names, jid) {\n if (!jid)\n return null;\n const contact = names?.contacts?.get(jid);\n if (!contact)\n return null;\n const row = modelData(contact);\n return row.name ?? row.pushname ?? row.shortName ?? row.formattedName ?? null;\n }\n function chatName(names, jid) {\n if (!jid)\n return null;\n const chat = names?.chats?.get(jid);\n if (!chat)\n return null;\n const row = modelData(chat);\n return row.name ?? row.formattedTitle ?? row.contact?.name ?? row.contact?.pushname ?? null;\n }\n async function normalizeMessage(model, eventType = \"snapshot\", collectionsOverride = null, names = null) {\n const collections = collectionsOverride ?? requireFirst([\"WAWebCollections\"]);\n if (!collections)\n return null;\n const nameLookup = names ?? nameIndex(collections);\n let row = modelData(model), key = row.id ?? model?.id, id = rawId(key);\n if (!id)\n return null;\n if (row.type === \"reaction\") {\n const targetId = reactionTargetId(row), target = collectionByRawId(collections.Msg, targetId);\n if (target) {\n model = target;\n row = modelData(model);\n key = row.id ?? model?.id;\n id = rawId(key);\n }\n }\n const fromMe = Boolean(key?.fromMe ?? row.fromMe), remoteRaw = key?.remote ?? row.chatId, fromRaw = row.from, toRaw = row.to, authorRaw = row.author ?? key?.participant, chatRaw = remoteRaw ?? (fromMe ? toRaw : fromRaw), chat = await canonicalJid(chatRaw);\n if (!chat.jid || isBroadcastOnlyJid(chat.jid))\n return null;\n const senderRaw = fromMe ? fromRaw : authorRaw ?? fromRaw, sender = await canonicalJid(senderRaw), participant = await canonicalJid(key?.participant ?? row.participant ?? (fromMe ? toRaw : null)), timestamp = unixSeconds(row), body = typeof row.body === \"string\" ? row.body : \"\", caption = typeof row.caption === \"string\" ? row.caption : \"\", quotedId = typeof row.quotedStanzaID === \"string\" ? row.quotedStanzaID : rawId(row.quotedMsg?.id ?? row.quotedMsgKey), type = typeof row.type === \"string\" ? row.type : \"unknown\";\n return {\n id,\n chat_jid: chat.jid,\n chat_lid: chat.lid,\n chat_name: chatName(nameLookup, widString(chatRaw)),\n sender_jid: sender.jid,\n sender_lid: sender.lid,\n push_name: contactName(nameLookup, widString(senderRaw)) ?? row.notifyName ?? null,\n participant: participant.jid,\n from_me: fromMe,\n is_group: chat.jid.endsWith(\"@g.us\"),\n timestamp,\n occurred_at: timestamp > 0 ? new Date(timestamp * 1000).toISOString() : null,\n body,\n caption,\n message_type: type,\n media_kind: type === \"ptt\" ? \"audio\" : [\"image\", \"video\", \"audio\", \"document\", \"sticker\"].includes(type) ? type : null,\n media_type: typeof row.mimetype === \"string\" ? row.mimetype : null,\n media_size: Number.isFinite(Number(row.size ?? row.fileSize)) ? Number(row.size ?? row.fileSize) : null,\n media_filename: row.filename ?? row.fileName ?? row.title ?? null,\n quoted_id: quotedId,\n mentions_me: await mentionsOwnAccount(row),\n own_mention_jids: await ownMentionJids(row),\n is_forwarded: Boolean(row.isForwarded || Number(row.forwardingScore) > 0),\n is_starred: Boolean(row.star ?? row.isStarred),\n is_system_event: SYSTEM_TYPES.has(type),\n edited: Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey),\n edit_timestamp: Number(row.editTimestamp ?? row.lastEditTimestamp) || null,\n revoked: Boolean(row.isRevoked || row.revoked || type === \"revoked\"),\n reactions: normalizeReactions(row),\n event_type: eventType\n };\n }\n function readiness() {\n if (typeof window.require !== \"function\")\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"whatsapp_runtime_unavailable\"\n };\n const collections = requireFirst([\"WAWebCollections\"]);\n if (!collections?.Msg || !collections?.Chat)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"collections_unavailable\"\n };\n const me = meUser(), qrVisible = Boolean(document.querySelector('[data-testid=\"qrcode\"], canvas[aria-label*=\"Scan\" i], [data-ref] canvas'));\n if (!me && qrVisible)\n return { ready: !1, state: \"logged_out\", reason: \"qr_code_visible\" };\n if (!me)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"authenticated_self_identity_unavailable\"\n };\n const socket = requireFirst([\"WAWebSocketModel\"])?.Socket, connection = socket ?? requireFirst([\"WAWebSocketState\", \"WAWebConn\", \"WAWebConnectionState\"]), connectionState = String(connection?.getSocketState?.() ?? connection?.state ?? connection?.socketState ?? \"\").toLowerCase();\n if (!connectionState)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"connection_state_unavailable\"\n };\n if (!/^(connected|open|ready|syncing)$/.test(connectionState))\n return {\n ready: !1,\n state: \"not_ready\",\n reason: `connection_${connectionState}`\n };\n if (socket) {\n const stream = String(socket.stream ?? \"\").toLowerCase();\n if (!stream)\n return {\n ready: !1,\n state: \"capability_unavailable\",\n reason: \"stream_state_unavailable\"\n };\n if (!/^(connected|open|ready)$/.test(stream))\n return { ready: !1, state: \"not_ready\", reason: `stream_${stream}` };\n if (socket.hasSynced === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n }\n const offlineDelivery = requireFirst([\n \"WAWebOfflineDelivery\",\n \"WAWebOfflineDeliveryState\"\n ]);\n if ((offlineDelivery?.isOfflineDeliveryComplete?.() ?? offlineDelivery?.offlineDeliveryComplete ?? offlineDelivery?.isComplete) === !1)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"offline_delivery_incomplete\"\n };\n const hydration = requireFirst([\n \"WAWebInitialSyncInfo\",\n \"WAWebHistorySync\",\n \"WAWebAppState\"\n ]);\n if ((hydration?.isInitialSyncComplete?.() ?? hydration?.initialSyncComplete ?? hydration?.isHydrated ?? !0) !== !0)\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"initial_sync_incomplete\"\n };\n if (!Array.isArray(collections.Chat._models) && !Array.isArray(collections.Chat.models))\n return {\n ready: !1,\n state: \"hydrating\",\n reason: \"chat_store_placeholder\"\n };\n const signature = `${widString(me)}:${models(collections.Chat).length}:${models(collections.Msg).length}`;\n if (signature !== readinessSignature) {\n readinessSignature = signature;\n readinessStableSince = Date.now();\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n }\n if (Date.now() - readinessStableSince < 500)\n return { ready: !1, state: \"hydrating\", reason: \"stores_settling\" };\n return {\n ready: !0,\n state: \"ready\",\n message_count: models(collections.Msg).length,\n chat_count: models(collections.Chat).length\n };\n }\n function operationCapabilities() {\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]), draft = requireFirst(DRAFT_MODULES), send = requireFirst(SEND_MODULES), edit = requireFirst(EDIT_MODULES), reaction = requireFirst(REACTION_MODULES), revoke = requireFirst(REVOKE_MODULES), hasFunction = (module2, names) => names.some((name) => typeof module2?.[name] === \"function\");\n return {\n read_messages: typeof indexedDB < \"u\" && typeof requireFirst([\"WAWebMsgKey\"])?.fromString === \"function\" && typeof requireFirst([\"WAWebCollections\"])?.Msg?.getMessagesById === \"function\",\n search_messages: hasFunction(search, [\"searchMessages\", \"searchMsgs\", \"search\"]) || Boolean(requireFirst([\"WAWebCollections\"])?.Msg),\n draft_message: hasFunction(draft, [\n \"setDraft\",\n \"setChatDraft\",\n \"saveDraft\"\n ]),\n send_message: hasFunction(send, [\n \"sendTextMsgToChat\",\n \"sendMessage\",\n \"addAndSendTextMsg\"\n ]),\n edit_message: hasFunction(edit, [\"sendMessageEdit\", \"editMessage\"]),\n react_message: hasFunction(reaction, [\n \"sendReactionToMsg\",\n \"sendReaction\"\n ]),\n revoke_message: hasFunction(revoke, [\"sendRevokeMsgs\", \"revokeMessage\"])\n };\n }\n function uniqueMessageModels(collections) {\n const byId = new Map;\n for (const message of models(collections.Msg)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n for (const chat of models(collections.Chat))\n for (const message of models(modelData(chat).msgs ?? chat?.msgs)) {\n const id = rawId(modelData(message).id ?? message?.id);\n if (id)\n byId.set(id, message);\n }\n return [...byId.values()];\n }\n async function resolveChat(collections, input) {\n if (input?.self_chat === !0) {\n const me = meUser(), selfJid = (await canonicalJid(me)).jid;\n let self = null;\n for (const chat of models(collections.Chat))\n if ((await canonicalJid(modelData(chat).id ?? chat?.id)).jid === selfJid) {\n self = chat;\n break;\n }\n if (!self)\n throw Error(\"WhatsApp self chat is not loaded\");\n return self;\n }\n const requestedJidRaw = typeof input?.chat_jid === \"string\" ? input.chat_jid.trim().toLowerCase() : null, requestedJid = requestedJidRaw ? (await canonicalJid(requestedJidRaw)).jid : null, requestedName = typeof input?.chat_name === \"string\" ? input.chat_name.trim().toLowerCase() : null, matches = [];\n for (const chat of models(collections.Chat)) {\n const row = modelData(chat), jid = (await canonicalJid(row.id ?? chat?.id)).jid, name = String(row.name ?? row.formattedTitle ?? row.contact?.name ?? \"\").trim().toLowerCase();\n if (requestedJid ? jid === requestedJid : requestedName && name === requestedName)\n matches.push(chat);\n }\n if (matches.length === 0)\n throw Error(\"WhatsApp chat not found; pass an exact canonical chat_jid or exact chat_name\");\n if (matches.length > 1)\n throw Error(\"WhatsApp chat name is ambiguous; pass chat_jid\");\n return matches[0];\n }\n async function waitForPostState(check, label, timeoutMs = 2000) {\n const deadline = Date.now() + timeoutMs;\n do {\n if (check())\n return;\n await new Promise((resolve) => setTimeout(resolve, 50));\n } while (Date.now() < deadline);\n throw Error(`WhatsApp did not confirm ${label}`);\n }\n async function readMessages(input = {}, account) {\n const query = String(input.query ?? \"\").trim(), chatFilter = input.chat_filter ?? \"all\", limit = Math.min(100, Math.max(1, Math.trunc(Number(input.limit) || 50)));\n let before = null;\n if (input.cursor) {\n const cursor = JSON.parse(input.cursor);\n if (cursor.v !== 1 || !Number.isSafeInteger(cursor.before) || cursor.before <= 0 || cursor.query !== query || cursor.chat_filter !== chatFilter || cursor.account !== account)\n throw Error(\"Invalid WhatsApp source cursor or changed query scope\");\n before = cursor.before;\n }\n const keyModule = requireFirst([\"WAWebMsgKey\"]), exactId = query.startsWith(\"id:\") ? query.slice(3) : null;\n let chatJid = null;\n if (query.startsWith(\"chat:\")) {\n const chat = await resolveChat(requireFirst([\"WAWebCollections\"]), { chat_jid: query.slice(5) });\n chatJid = (await canonicalJid(modelData(chat).id ?? chat?.id)).jid;\n }\n const database = await new Promise((resolve, reject) => {\n const request = indexedDB.open(\"model-storage\");\n request.onupgradeneeded = () => {\n request.transaction.abort();\n reject(Error(\"WhatsApp source history database is unavailable\"));\n };\n request.onerror = () => reject(request.error);\n request.onblocked = () => reject(Error(\"WhatsApp source history database is blocked\"));\n request.onsuccess = () => resolve(request.result);\n });\n let sourceRows;\n try {\n sourceRows = await new Promise((resolve, reject) => {\n const transaction = database.transaction(\"message\", \"readonly\");\n transaction.onabort = () => reject(transaction.error ?? Error(\"WhatsApp source read aborted\"));\n const index = transaction.objectStore(\"message\").index(\"rowId\"), range = before === null ? null : IDBKeyRange.upperBound(before, !0), request = index.openCursor(range, \"prev\"), rows = [];\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) {\n resolve(rows);\n return;\n }\n if (!Number.isSafeInteger(cursor.key) || cursor.key <= 0 || typeof cursor.value.id !== \"string\") {\n reject(Error(\"WhatsApp source history has an unsupported key layout\"));\n return;\n }\n if (exactId !== null) {\n if (keyModule.fromString(cursor.value.id).id !== exactId) {\n cursor.continue();\n return;\n }\n resolve([{ position: cursor.key, id: cursor.value.id }]);\n return;\n }\n rows.push({ position: cursor.key, id: cursor.value.id });\n if (rows.length > (chatJid === null ? limit : 20000))\n resolve(rows);\n else\n cursor.continue();\n };\n });\n } finally {\n database.close();\n }\n let hasMore = sourceRows.length > limit, page = sourceRows.slice(0, limit), last = page[page.length - 1];\n if (chatJid !== null) {\n const examined = sourceRows.slice(0, 20000), canonical = new Map, matches = [];\n for (const row of examined) {\n const remote = keyModule.fromString(row.id).remote, raw = widString(remote);\n if (!canonical.has(raw))\n canonical.set(raw, (await canonicalJid(remote)).jid);\n if (canonical.get(raw) !== chatJid)\n continue;\n matches.push(row);\n if (matches.length > limit)\n break;\n }\n page = matches.slice(0, limit);\n hasMore = matches.length > limit || sourceRows.length > 20000;\n last = matches.length > limit ? page[page.length - 1] : examined[examined.length - 1];\n }\n const collections = requireFirst([\"WAWebCollections\"]), selected = [];\n for (const row of page) {\n const key = keyModule.fromString(row.id);\n if (exactId !== null && key.id !== exactId)\n continue;\n const remote = widString(key.remote);\n if (isBroadcastOnlyJid(remote))\n continue;\n const isGroup = remote.endsWith(\"@g.us\");\n if (chatFilter === \"group\" && !isGroup || chatFilter === \"individual\" && isGroup)\n continue;\n selected.push(row);\n }\n const results = [];\n if (selected.length) {\n const loaded = await collections.Msg.getMessagesById(selected.map((row) => row.id));\n if (loaded?.canceled || !Array.isArray(loaded?.messages))\n throw Error(\"Source message loading was canceled or unavailable\");\n const byKey = new Map(loaded.messages.map((model) => [String(model.id ?? modelData(model).id), model])), names = nameIndex(collections);\n for (const row of selected) {\n const model = byKey.get(row.id);\n if (!model)\n throw Error(\"Source message could not be loaded; retry the read\");\n const message = await normalizeMessage(model, \"snapshot\", collections, names);\n if (!message || message.timestamp <= 0)\n continue;\n if (exactId === null && chatJid === null && query && !`${message.body}\n${message.caption}`.toLowerCase().includes(query.toLowerCase()))\n continue;\n results.push(message);\n }\n }\n return {\n results,\n hasMore,\n ...hasMore ? { nextCursor: JSON.stringify({ v: 1, before: last.position, query, chat_filter: chatFilter, account }) } : {}\n };\n }\n async function searchMessages(input) {\n const collections = requireFirst([\"WAWebCollections\"]), query = String(input?.query ?? \"\").trim();\n if (!query)\n throw Error(\"query is required\");\n const offset = Math.max(0, Number(input?.offset) || 0), requestedLimit = Math.max(1, Math.min(Number(input?.limit) || 50, 100));\n if (offset >= 100)\n throw Error(\"WhatsApp source search supports only the first 100 matches\");\n const limit = Math.min(requestedLimit, 100 - offset), searchSourceLimit = 100, chatFilter = [\"all\", \"individual\", \"group\"].includes(input?.chat_filter) ? input.chat_filter : \"all\", chat = input?.chat_jid || input?.chat_name || input?.self_chat === !0 ? await resolveChat(collections, input) : null;\n let scopedChats = chat ? [chat] : void 0;\n if (!chat && chatFilter !== \"all\") {\n scopedChats = [];\n for (const candidate of models(collections.Chat)) {\n const jid = (await canonicalJid(modelData(candidate).id ?? candidate?.id)).jid;\n if (!jid || isBroadcastOnlyJid(jid))\n continue;\n const isGroup = jid.endsWith(\"@g.us\");\n if (chatFilter === \"group\" ? isGroup : !isGroup)\n scopedChats.push(candidate);\n }\n }\n const search = requireFirst([\n \"WAWebChatMessageSearch\",\n \"WAWebMessageSearch\",\n \"WAWebSearchMessages\"\n ]);\n let found = null;\n for (const fn of [\n search?.searchMessages,\n search?.searchMsgs,\n search?.search\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n found = await fn.call(search, query, scopedChats, searchSourceLimit);\n break;\n } catch {}\n }\n let source = \"whatsapp_fts\", candidates = Array.isArray(found) ? found : models(found?.messages ?? found);\n if (!found) {\n source = \"loaded_model_fallback\";\n const needle = query.toLowerCase();\n candidates = uniqueMessageModels(collections).filter((model) => {\n const row = modelData(model);\n if (chat) {\n const chatId = widString(modelData(chat).id ?? chat?.id);\n if (widString(row.id?.remote ?? row.chatId) !== chatId)\n return !1;\n }\n return String(row.body ?? row.caption ?? \"\").toLowerCase().includes(needle);\n });\n }\n const normalized = [], names = nameIndex(collections);\n for (const candidate of candidates) {\n const model = candidate?.msg ?? candidate?.message ?? candidate, message = await normalizeMessage(model, \"search\", collections, names);\n if (!message || Number(message.timestamp) <= 0)\n continue;\n if (chatFilter === \"group\" && !message.is_group)\n continue;\n if (chatFilter === \"individual\" && message.is_group)\n continue;\n normalized.push(message);\n if (normalized.length >= searchSourceLimit)\n break;\n }\n return {\n source,\n results: normalized.slice(offset, offset + limit),\n hasMore: offset + limit < normalized.length\n };\n }\n async function draftMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const draft = {\n body: text,\n timestamp: Math.floor(Date.now() / 1000),\n type: \"chat\",\n mentionedJidList: [],\n quotedMsg: null\n }, module2 = requireFirst(DRAFT_MODULES);\n let applied = !1;\n for (const fn of [\n module2?.setDraft,\n module2?.setChatDraft,\n module2?.saveDraft\n ]) {\n if (typeof fn !== \"function\")\n continue;\n try {\n assertAccount(account);\n await fn.call(module2, chat, draft);\n applied = !0;\n break;\n } catch {\n try {\n assertAccount(account);\n await fn.call(module2, draft, chat);\n applied = !0;\n break;\n } catch {}\n }\n }\n if (!applied && typeof chat?.setDraft === \"function\") {\n assertAccount(account);\n await chat.setDraft(draft);\n applied = !0;\n }\n if (!applied)\n throw Error(\"WhatsApp draft capability is unavailable in this web build\");\n const stored = modelData(chat).draft ?? chat.get?.(\"draft\") ?? null;\n if (!stored || typeof stored !== \"object\" || stored.body !== text)\n throw Error(\"WhatsApp rejected the persistent draft shape\");\n return {\n drafted: !0,\n sent: !1,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n draft\n };\n }\n async function sendMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), chat = await resolveChat(collections, input), chatJid = (await canonicalJid(modelData(chat).id ?? chat?.id)).jid;\n if (chatJid && isBroadcastOnlyJid(chatJid))\n throw Error(`WhatsApp chat ${chatJid} does not accept messages`);\n const text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(SEND_MODULES);\n if (typeof module2?.createTextMsgData === \"function\" && typeof module2?.addAndSendTextMsg === \"function\") {\n const data = await module2.createTextMsgData(chat, text), plannedId = rawId(data?.id);\n if (!plannedId)\n throw Error(\"WhatsApp did not assign an id to the outgoing message\");\n assertAccount(account);\n await module2.addAndSendTextMsg(chat, data);\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: plannedId\n };\n }\n const fn = module2?.sendTextMsgToChat ?? module2?.sendMessage ?? chat?.sendMessage;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp send capability is unavailable in this web build\");\n assertAccount(account);\n const result = fn === chat?.sendMessage ? await fn.call(chat, text) : await fn.call(module2, chat, text), messageId = rawId(modelData(result).id ?? result?.id);\n if (!messageId)\n throw Error(\"WhatsApp send acknowledgment has no raw message ID\");\n return {\n sent: !0,\n chat_jid: widString(modelData(chat).id ?? chat?.id),\n message_id: messageId\n };\n }\n function messageActionAllowed(message, predicateNames, legacyFlags) {\n const row = modelData(message);\n for (const flag of legacyFlags)\n if (row[flag] === !0)\n return !0;\n const capability = requireFirst([\"WAWebMsgActionCapability\"]);\n for (const name of predicateNames) {\n if (typeof capability?.[name] !== \"function\")\n continue;\n try {\n if (capability[name](message) === !0)\n return !0;\n } catch {}\n }\n return !1;\n }\n function resolveMessage(collections, id) {\n const raw = String(id ?? \"\").trim();\n if (!raw)\n throw Error(\"message_id is required\");\n const message = collectionByRawId(collections.Msg, raw);\n if (!message)\n throw Error(`WhatsApp message ${raw} is not loaded; read it with id:${raw} from the live messages feed or search it first`);\n return message;\n }\n async function editMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits editing outgoing messages\");\n if (!messageActionAllowed(message, [\"canEditText\", \"canEditCaption\", \"canEnterEditingFlow\"], [\"canEdit\", \"isEditable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently editable\");\n const text = String(input?.text ?? \"\");\n if (!text.trim())\n throw Error(\"text is required\");\n const module2 = requireFirst(EDIT_MODULES), fn = module2?.sendMessageEdit ?? module2?.editMessage ?? message?.edit;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp edit capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.edit ? fn.call(message, text) : fn.call(module2, message, text, {}));\n await waitForPostState(() => {\n const row = modelData(message);\n return row.body === text && Boolean(row.isEdited || row.editVersion || row.latestEditMsgKey);\n }, \"message edit\");\n return {\n edited: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function reactMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), emoji = input?.remove ? \"\" : String(input?.emoji ?? \"\");\n if (!input?.remove && !emoji)\n throw Error(\"emoji is required unless remove=true\");\n const module2 = requireFirst(REACTION_MODULES), fn = module2?.sendReactionToMsg ?? module2?.sendReaction ?? message?.react;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp reaction capability is unavailable in this web build\");\n assertAccount(account);\n await (fn === message?.react ? fn.call(message, emoji) : fn.call(module2, message, emoji));\n await waitForPostState(() => {\n const row = modelData(message), reactions = normalizeReactions(row);\n if (reactions.length > 0)\n return input?.remove ? !reactions.some((reaction) => reaction.from_me) : reactions.some((reaction) => reaction.from_me && reaction.emoji === emoji);\n return input?.remove ? !0 : row.hasReaction === !0;\n }, \"reaction state\");\n return {\n reacted: !0,\n confirmed: input?.remove ? normalizeReactions(modelData(message)).length > 0 : !0,\n removed: Boolean(input?.remove),\n emoji: emoji || null,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function revokeMessage(input, account) {\n const collections = requireFirst([\"WAWebCollections\"]), message = resolveMessage(collections, input?.message_id), before = modelData(message);\n if (!(before.id?.fromMe ?? before.fromMe))\n throw Error(\"WhatsApp only permits revoking outgoing messages\");\n if (!messageActionAllowed(message, [\"canSenderRevokeMsg\", \"canAdminRevokeMsg\"], [\"canRevoke\", \"isRevokable\"]))\n throw Error(\"WhatsApp did not affirm that this message is currently revokable\");\n const module2 = requireFirst(REVOKE_MODULES), fn = module2?.sendRevokeMsgs ?? module2?.sendRevoke ?? module2?.revokeMessage ?? message?.sendRevoke ?? message?.revoke;\n if (typeof fn !== \"function\")\n throw Error(\"WhatsApp revoke capability is unavailable in this web build\");\n assertAccount(account);\n if (fn === message?.sendRevoke || fn === message?.revoke)\n await fn.call(message);\n else\n await fn.call(module2, [message], modelData(message).id?.remote);\n await waitForPostState(() => {\n const row = modelData(message);\n return Boolean(row.isRevoked || row.revoked || row.type === \"revoked\");\n }, \"message revoke\");\n return {\n revoked: !0,\n message_id: rawId(modelData(message).id ?? message?.id)\n };\n }\n async function invoke(request) {\n try {\n if (Number(request?.adapter_version) !== 28)\n return {\n ok: !1,\n error: {\n state: \"adapter_mismatch\",\n reason: \"expected 28\"\n }\n };\n if (request.op === \"account_identity\") {\n const accountId = widString(meUser());\n return accountId ? { accountId } : null;\n }\n if (request.op === \"probe\") {\n const status = readiness();\n return status.ready ? { ok: !0, status, capabilities: operationCapabilities() } : { ok: !1, error: status };\n }\n assertAccount(request.account_id);\n const input = { ...request.input, account_id: request.account_id }, finish = async (promise) => {\n const value = await promise;\n assertAccount(request.account_id);\n return { ok: !0, ...value };\n };\n if (request.op === \"listen\")\n return listen(request);\n if (request.op === \"publish_changes\")\n return await publishChanges(request);\n if (request.op === \"observe_messages\")\n return await finish(observeMessages(input));\n if (operationCapabilities()[request.op] !== !0)\n return {\n ok: !1,\n error: {\n state: \"capability_unavailable\",\n reason: `${request.op} is unavailable in this WhatsApp Web build`\n }\n };\n if (request.op === \"read_messages\")\n return await finish(readMessages(input, request.account_id));\n if (request.op === \"search_messages\")\n return await finish(searchMessages(input));\n if (request.op === \"draft_message\")\n return await finish(draftMessage(input, request.account_id));\n if (request.op === \"send_message\")\n return await finish(sendMessage(input, request.account_id));\n if (request.op === \"edit_message\")\n return await finish(editMessage(input, request.account_id));\n if (request.op === \"react_message\")\n return await finish(reactMessage(input, request.account_id));\n if (request.op === \"revoke_message\")\n return await finish(revokeMessage(input, request.account_id));\n return {\n ok: !1,\n error: { state: \"unsupported_operation\", reason: String(request?.op) }\n };\n } catch (error) {\n if (request?.account_id && widString(meUser()) !== request.account_id)\n error = Error(\"WhatsApp saved account changed or is unavailable; reconnect this connection\");\n return {\n ok: !1,\n error: {\n state: \"operation_failed\",\n reason: error instanceof Error ? error.message : String(error)\n }\n };\n }\n }\n globalThis.__owlettoWhatsAppAdapterV1 = { version: 28, invoke, detach };\n })();\n for (let i = 0; i < 40; i++) {\n const identity = await globalThis.__owlettoWhatsAppAdapterV1.invoke({ op: \"account_identity\", adapter_version: 28 });\n if (identity?.accountId) return identity;\n await new Promise(resolve => setTimeout(resolve, 250));\n }\n return null;\n })()"
21620
21697
  }
21621
21698
  },
21622
21699
  "webhook": null,
@@ -21706,7 +21783,19 @@
21706
21783
  "results": {
21707
21784
  "type": "array",
21708
21785
  "items": {
21709
- "type": "object"
21786
+ "type": "object",
21787
+ "properties": {
21788
+ "own_mention_jids": {
21789
+ "type": "array",
21790
+ "maxItems": 2,
21791
+ "uniqueItems": true,
21792
+ "items": {
21793
+ "type": "string",
21794
+ "pattern": "^[0-9]{5,32}@(s\\.whatsapp\\.net|lid)$"
21795
+ },
21796
+ "description": "Verified phone/LID JIDs of the paired account actually @mentioned; empty for quotes alone. Original text is preserved."
21797
+ }
21798
+ }
21710
21799
  }
21711
21800
  },
21712
21801
  "hasMore": {
@@ -22102,7 +22191,7 @@
22102
22191
  {
22103
22192
  "id": "x",
22104
22193
  "name": "X (Twitter)",
22105
- "version": "3.17.1",
22194
+ "version": "3.17.2",
22106
22195
  "description": "Fetches tweets, browser-visible like history, bookmarks, and DMs through the X API v2 or the paired Owletto Chrome extension, reads the chronological Following timeline live through the X API, captures notification references and the accounts you follow, reads and answers DMs live in the paired browser, and likes posts or follows accounts there. Links social actors into the person and company graph.",
22107
22196
  "detail": {
22108
22197
  "source_path": "x.ts",