@openclaw/matrix 2026.10.10 → 2026.11.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (695) hide show
  1. package/dist/.setup/{account-selection-Co94mKNj.mjs → account-selection-Cow3TMFO.mjs} +11 -11
  2. package/dist/.setup/{approval-handler.runtime-DtNvJpfB.mjs → approval-handler.runtime-_0gqiVgR.mjs} +16 -51
  3. package/dist/.setup/{approval-reactions-DMDBJos0.mjs → approval-reactions-Bz_8XB01.mjs} +2 -2
  4. package/dist/.setup/{channel-CNjJyBS_.mjs → channel-ByHcZU28.mjs} +292 -357
  5. package/dist/.setup/channel.runtime-sNicWjmD.mjs +71 -0
  6. package/dist/.setup/{channel.setup-IjRB0ymg.mjs → channel.setup-Bmba21y9.mjs} +28 -39
  7. package/dist/.setup/{cli-CuEJNM3c.mjs → cli-B26pps0Q.mjs} +250 -308
  8. package/dist/.setup/{cli-metadata-rWmD_rzx.mjs → cli-metadata-CKGwVfmT.mjs} +1 -1
  9. package/dist/.setup/{client-7eyTX0cu.mjs → client-Bqu801rH.mjs} +88 -174
  10. package/dist/.setup/{client-CV0MkCZG.mjs → client-N8TEwtmk.mjs} +6 -6
  11. package/dist/.setup/{client-bootstrap-BjcmTmyR.mjs → client-bootstrap-k6Zm1M8Y.mjs} +5 -10
  12. package/dist/.setup/{client-support-CFofPPPm.mjs → client-support-CqXAOZp3.mjs} +1 -14
  13. package/dist/.setup/{create-client-C4Lnqs2C.mjs → create-client-DaGljdrk.mjs} +6 -6
  14. package/dist/.setup/{credentials-B0vpXvcB.mjs → credentials-DVmY0miU.mjs} +6 -20
  15. package/dist/.setup/{credentials-read-WCQSEvI8.mjs → credentials-read-rPqEpuxv.mjs} +3 -3
  16. package/dist/.setup/{crypto-runtime-Crp1is7m.mjs → crypto-runtime-KQupbxSM.mjs} +74 -158
  17. package/dist/.setup/{crypto-state-store-CM57gchf.mjs → crypto-state-store-p1mdYTWH.mjs} +14 -9
  18. package/dist/.setup/{crypto-store-ownership-Bratn-Np.mjs → crypto-store-ownership-7lVHeXWL.mjs} +1 -1
  19. package/dist/.setup/{crypto-unsafe-state-doctor-Brv4bIyx.mjs → crypto-unsafe-state-doctor-CG2nJk8P.mjs} +7 -6
  20. package/dist/.setup/{deps-O7rEnklr.mjs → deps-CVPT2Ros.mjs} +4 -3
  21. package/dist/.setup/device-health-D7n-lPeb.mjs +7 -0
  22. package/dist/.setup/{direct-management-DDaWVbQI.mjs → direct-management-D59C1WO-.mjs} +22 -28
  23. package/dist/.setup/{directory-live-B-csizuK.mjs → directory-live-YixmpyLW.mjs} +5 -5
  24. package/dist/.setup/doctor-contract-GiXgCj7k.mjs +37 -0
  25. package/dist/.setup/{draft-stream-dmhBHufd.mjs → draft-stream-C09OtoJZ.mjs} +10 -16
  26. package/dist/.setup/{encryption-guidance-Cn6-Tlx0.mjs → encryption-guidance-DfbEaKct.mjs} +1 -1
  27. package/dist/.setup/{exec-approvals-D7vv3AZS.mjs → exec-approvals-C3rCm0Sn.mjs} +31 -41
  28. package/dist/.setup/{file-sync-store-q5KCV2Lp.mjs → file-sync-store-NW6eDuai.mjs} +52 -8
  29. package/dist/.setup/{http-client-CxTmU1kT.mjs → http-client-CqnKFKUH.mjs} +19 -31
  30. package/dist/.setup/{idb-persistence-BF0MZglD.mjs → idb-persistence-CmoPtwDD.mjs} +22 -15
  31. package/dist/.setup/{joined-room-encryption-Dl7Sb9FF.mjs → joined-room-encryption-9sJK1kM-.mjs} +4 -3
  32. package/dist/.setup/{logger-BX5kXvh1.mjs → logger-B9TwnY6C.mjs} +2 -2
  33. package/dist/.setup/{logging-BLcaOSRD.mjs → logging-Bnsn7s4r.mjs} +20 -14
  34. package/dist/.setup/{messages-BiHM0DM3.mjs → messages-BjzsVgS6.mjs} +39 -22
  35. package/dist/.setup/{monitor-CPwDgRFY.mjs → monitor-D4vhbNUM.mjs} +647 -816
  36. package/dist/.setup/{onboarding-DiVtpjNu.mjs → onboarding-DKmt3jpW.mjs} +116 -128
  37. package/dist/.setup/{outbound-DwP97VpQ.mjs → outbound-wsXTF0z_.mjs} +2 -2
  38. package/dist/.setup/{profile-update-DnNA9mEa.mjs → profile-update-DX060MnL.mjs} +14 -14
  39. package/dist/.setup/{reaction-events-ClY9h_FC.mjs → reaction-events-BMsatzs4.mjs} +74 -99
  40. package/dist/.setup/{resolve-targets-B8PAwHVS.mjs → resolve-targets-Yz_3aN_2.mjs} +2 -2
  41. package/dist/.setup/{retired-state-vIr2IB90.mjs → retired-state-Bs3Gqkge.mjs} +6 -3
  42. package/dist/.setup/{room-info-T_PR_liR.mjs → room-info-OGKjk422.mjs} +21 -8
  43. package/dist/.setup/{doctor-contract-DybEjJcd.mjs → runtime-doctor-migrations-CSvRANPN.mjs} +12 -47
  44. package/dist/.setup/{sdk-Cj3ggJHG.mjs → sdk-BXcIyN-I.mjs} +95 -107
  45. package/dist/.setup/{send-C1qeMQAy.mjs → send-CWjH-l-T.mjs} +169 -251
  46. package/dist/.setup/{send-currentness-CAUVR-f3.mjs → send-currentness-D1x6YP9O.mjs} +9 -15
  47. package/dist/.setup/{setup-bootstrap-DDhwWvDs.mjs → setup-bootstrap-yKeGh4Iy.mjs} +2 -2
  48. package/dist/.setup/{setup-core-D2r4BivQ.mjs → setup-core-BaKffgBi.mjs} +19 -42
  49. package/dist/.setup/setup-plugin-api-B_t4waBw.mjs +2 -0
  50. package/dist/.setup/{startup-verification-B3LEbW33.mjs → startup-verification-C-lhD0gk.mjs} +9 -22
  51. package/dist/.setup/{storage-CxN4jqKI.mjs → storage-BLLN9jYG.mjs} +18 -22
  52. package/dist/.setup/{subagent-hooks-CT-rdJmh.mjs → subagent-hooks-D-lCcLGQ.mjs} +1 -1
  53. package/dist/.setup/{sync-cache-state-qYrd2EEh.mjs → sync-cache-state-B4hJFIPw.mjs} +10 -10
  54. package/dist/.setup/sync-state-Cu1nagBV.mjs +11 -0
  55. package/dist/.setup/task-runner-CYyGHdNW.mjs +51 -0
  56. package/dist/.setup/{thread-bindings-D2ZR6mEZ.mjs → thread-bindings-BA2xESjV.mjs} +34 -49
  57. package/dist/.setup/{thread-bindings-shared-FMu_szTm.mjs → thread-bindings-shared-CBlJu3Wz.mjs} +2 -2
  58. package/dist/.setup/{tool-actions-CdKa0DC4.mjs → tool-actions-CRuiVbqj.mjs} +59 -67
  59. package/dist/.setup/{url-validation-C77p4qT9.mjs → url-validation-DesoKUns.mjs} +1 -2
  60. package/dist/.setup/{verification-jP3tm-xD.mjs → verification-C5x4Hy5Y.mjs} +7 -7
  61. package/dist/.source-module-urls/1cd4d4ff8d44e1c8b830932b44d7cf8a7f3350e09e169910e1d7a85e131b7bea.json +1 -1
  62. package/dist/api.js +6 -6
  63. package/dist/auth-presence.js +1 -1
  64. package/dist/channel-plugin-api.js +1 -1
  65. package/dist/cli-metadata.js +1 -1
  66. package/dist/contract-api.js +2 -2
  67. package/dist/doctor-contract-api.js +149 -127
  68. package/dist/helper-api.js +1 -1
  69. package/dist/index.js +1 -1
  70. package/dist/plugin-entry.handlers.runtime.js +2 -2
  71. package/dist/runtime-api.js +3 -3
  72. package/dist/session-binding-contract-api.js +1 -1
  73. package/dist/setup-entry.js +1 -1
  74. package/dist/setup-plugin-api.js +1 -1
  75. package/dist/subagent-hooks-api.js +1 -1
  76. package/dist/thread-bindings-runtime.js +1 -1
  77. package/node_modules/@babel/runtime/helpers/asyncIterator.js +1 -1
  78. package/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js +12 -6
  79. package/node_modules/@babel/runtime/helpers/esm/asyncIterator.js +1 -1
  80. package/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js +12 -6
  81. package/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js +16 -19
  82. package/node_modules/@babel/runtime/helpers/esm/toPrimitive.js +5 -5
  83. package/node_modules/@babel/runtime/helpers/interopRequireWildcard.js +16 -19
  84. package/node_modules/@babel/runtime/helpers/toPrimitive.js +5 -5
  85. package/node_modules/@babel/runtime/package.json +1 -1
  86. package/node_modules/@openclaw/fs-safe/CHANGELOG.md +94 -0
  87. package/node_modules/@openclaw/fs-safe/dist/archive-parser.wasm +0 -0
  88. package/node_modules/@openclaw/fs-safe/dist/copy-file-input.d.ts +1 -1
  89. package/node_modules/@openclaw/fs-safe/dist/copy-file-input.js +3 -1
  90. package/node_modules/@openclaw/fs-safe/dist/copy-path-admission.js +2 -2
  91. package/node_modules/@openclaw/fs-safe/dist/copy-root-file-sync.js +8 -1
  92. package/node_modules/@openclaw/fs-safe/dist/file-open-error.d.ts +2 -0
  93. package/node_modules/@openclaw/fs-safe/dist/file-open-error.js +14 -0
  94. package/node_modules/@openclaw/fs-safe/dist/file-sync.d.ts +2 -1
  95. package/node_modules/@openclaw/fs-safe/dist/file-sync.js +6 -1
  96. package/node_modules/@openclaw/fs-safe/dist/guest-native-python.js +3 -0
  97. package/node_modules/@openclaw/fs-safe/dist/native-binding.d.ts +1 -0
  98. package/node_modules/@openclaw/fs-safe/dist/native-config.js +14 -3
  99. package/node_modules/@openclaw/fs-safe/dist/native-operations.js +2 -0
  100. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write-windows.js +9 -2
  101. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.js +40 -32
  102. package/node_modules/@openclaw/fs-safe/dist/output.js +6 -0
  103. package/node_modules/@openclaw/fs-safe/dist/owner-dacl.d.ts +2 -0
  104. package/node_modules/@openclaw/fs-safe/dist/owner-dacl.js +1 -0
  105. package/node_modules/@openclaw/fs-safe/dist/path.js +5 -1
  106. package/node_modules/@openclaw/fs-safe/dist/pinned-write-staged.js +25 -2
  107. package/node_modules/@openclaw/fs-safe/dist/publication-handle.d.ts +4 -0
  108. package/node_modules/@openclaw/fs-safe/dist/publication-handle.js +32 -0
  109. package/node_modules/@openclaw/fs-safe/dist/publish-copy-stage.d.ts +2 -1
  110. package/node_modules/@openclaw/fs-safe/dist/publish-copy-stage.js +19 -9
  111. package/node_modules/@openclaw/fs-safe/dist/publish-file.js +23 -24
  112. package/node_modules/@openclaw/fs-safe/dist/publish-rename-fallback.d.ts +21 -0
  113. package/node_modules/@openclaw/fs-safe/dist/publish-rename-fallback.js +102 -0
  114. package/node_modules/@openclaw/fs-safe/dist/root-create-native.js +2 -0
  115. package/node_modules/@openclaw/fs-safe/dist/root-directory-entry.d.ts +3 -1
  116. package/node_modules/@openclaw/fs-safe/dist/root-directory-entry.js +8 -5
  117. package/node_modules/@openclaw/fs-safe/dist/root-directory-list-types.d.ts +3 -0
  118. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.d.ts +2 -1
  119. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.js +19 -9
  120. package/node_modules/@openclaw/fs-safe/dist/root-file-final-admission.js +3 -3
  121. package/node_modules/@openclaw/fs-safe/dist/root-path-existing.d.ts +2 -2
  122. package/node_modules/@openclaw/fs-safe/dist/root-path-existing.js +27 -13
  123. package/node_modules/@openclaw/fs-safe/dist/root-path.js +2 -2
  124. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.d.ts +3 -0
  125. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.js +18 -3
  126. package/node_modules/@openclaw/fs-safe/dist/watch-hints.d.ts +1 -1
  127. package/node_modules/@openclaw/fs-safe/dist/watch-hints.js +68 -21
  128. package/node_modules/@openclaw/fs-safe/dist/watch-io-error.d.ts +2 -0
  129. package/node_modules/@openclaw/fs-safe/dist/watch-io-error.js +27 -0
  130. package/node_modules/@openclaw/fs-safe/dist/watch-io-worker.d.ts +1 -0
  131. package/node_modules/@openclaw/fs-safe/dist/watch-io-worker.js +93 -0
  132. package/node_modules/@openclaw/fs-safe/dist/watch-io.d.ts +47 -0
  133. package/node_modules/@openclaw/fs-safe/dist/watch-io.js +236 -0
  134. package/node_modules/@openclaw/fs-safe/dist/watch-native.d.ts +1 -1
  135. package/node_modules/@openclaw/fs-safe/dist/watch-native.js +3 -3
  136. package/node_modules/@openclaw/fs-safe/dist/watch-probe.d.ts +16 -0
  137. package/node_modules/@openclaw/fs-safe/dist/watch-probe.js +135 -0
  138. package/node_modules/@openclaw/fs-safe/dist/watch-rescan.d.ts +1 -1
  139. package/node_modules/@openclaw/fs-safe/dist/watch-rescan.js +86 -24
  140. package/node_modules/@openclaw/fs-safe/dist/watch-scan.d.ts +4 -0
  141. package/node_modules/@openclaw/fs-safe/dist/watch-scan.js +78 -16
  142. package/node_modules/@openclaw/fs-safe/dist/watch-stream.d.ts +2 -0
  143. package/node_modules/@openclaw/fs-safe/dist/watch-stream.js +23 -0
  144. package/node_modules/@openclaw/fs-safe/dist/watch-types.d.ts +3 -1
  145. package/node_modules/@openclaw/fs-safe/dist/watch.js +60 -13
  146. package/node_modules/@openclaw/fs-safe/dist/windows-security-facts.d.ts +1 -1
  147. package/node_modules/@openclaw/fs-safe/dist/windows-security-facts.js +1 -0
  148. package/node_modules/@openclaw/fs-safe/dist/windows-security-helper.exe +0 -0
  149. package/node_modules/@openclaw/fs-safe/docs/advanced.md +5 -2
  150. package/node_modules/@openclaw/fs-safe/docs/compiler-qualification.md +392 -0
  151. package/node_modules/@openclaw/fs-safe/docs/config.md +7 -1
  152. package/node_modules/@openclaw/fs-safe/docs/contributing.md +25 -5
  153. package/node_modules/@openclaw/fs-safe/docs/copy.md +10 -0
  154. package/node_modules/@openclaw/fs-safe/docs/durability.md +9 -3
  155. package/node_modules/@openclaw/fs-safe/docs/errors.md +13 -0
  156. package/node_modules/@openclaw/fs-safe/docs/migrating-to-0.5.md +6 -4
  157. package/node_modules/@openclaw/fs-safe/docs/native-helper.md +6 -4
  158. package/node_modules/@openclaw/fs-safe/docs/output.md +4 -2
  159. package/node_modules/@openclaw/fs-safe/docs/path.md +5 -2
  160. package/node_modules/@openclaw/fs-safe/docs/permissions.md +15 -0
  161. package/node_modules/@openclaw/fs-safe/docs/security-model.md +9 -0
  162. package/node_modules/@openclaw/fs-safe/docs/staged-file.md +2 -0
  163. package/node_modules/@openclaw/fs-safe/docs/testing.md +1 -1
  164. package/node_modules/@openclaw/fs-safe/docs/watch.md +62 -5
  165. package/node_modules/@openclaw/fs-safe/docs/writing.md +6 -1
  166. package/node_modules/@openclaw/fs-safe/package.json +18 -16
  167. package/node_modules/@openclaw/fs-safe-darwin-arm64/fs-safe-native.node +0 -0
  168. package/node_modules/@openclaw/fs-safe-darwin-arm64/package.json +1 -1
  169. package/node_modules/@openclaw/fs-safe-darwin-x64/fs-safe-native.node +0 -0
  170. package/node_modules/@openclaw/fs-safe-darwin-x64/package.json +1 -1
  171. package/node_modules/@openclaw/fs-safe-freebsd-arm64/fs-safe-native.node +0 -0
  172. package/node_modules/@openclaw/fs-safe-freebsd-arm64/package.json +1 -1
  173. package/node_modules/@openclaw/fs-safe-freebsd-x64/fs-safe-native.node +0 -0
  174. package/node_modules/@openclaw/fs-safe-freebsd-x64/package.json +1 -1
  175. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/fs-safe-native.node +0 -0
  176. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/package.json +1 -1
  177. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/fs-safe-native.node +0 -0
  178. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/package.json +1 -1
  179. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/fs-safe-native.node +0 -0
  180. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/package.json +1 -1
  181. package/node_modules/@openclaw/fs-safe-linux-x64-musl/fs-safe-native.node +0 -0
  182. package/node_modules/@openclaw/fs-safe-linux-x64-musl/package.json +1 -1
  183. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/fs-safe-native.node +0 -0
  184. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/package.json +1 -1
  185. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/fs-safe-native.node +0 -0
  186. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/package.json +1 -1
  187. package/node_modules/@tokenizer/inflate/README.md +30 -1
  188. package/node_modules/@tokenizer/inflate/lib/GzipHandler.js +1 -1
  189. package/node_modules/@tokenizer/inflate/lib/ZipHandler.d.ts +8 -3
  190. package/node_modules/@tokenizer/inflate/lib/ZipHandler.js +101 -26
  191. package/node_modules/@tokenizer/inflate/lib/ZipLimitError.d.ts +16 -0
  192. package/node_modules/@tokenizer/inflate/lib/ZipLimitError.js +10 -0
  193. package/node_modules/@tokenizer/inflate/lib/ZipToken.d.ts +1 -1
  194. package/node_modules/@tokenizer/inflate/lib/ZipToken.js +11 -7
  195. package/node_modules/@tokenizer/inflate/lib/index.d.ts +2 -1
  196. package/node_modules/@tokenizer/inflate/lib/index.js +2 -1
  197. package/node_modules/@tokenizer/inflate/package.json +16 -15
  198. package/node_modules/argparse/lib/argparse.js +1 -1
  199. package/node_modules/argparse/package.json +1 -1
  200. package/node_modules/fake-indexeddb/build/cjs/FDBCursor.js +20 -18
  201. package/node_modules/fake-indexeddb/build/cjs/FDBKeyRange.js +6 -6
  202. package/node_modules/fake-indexeddb/build/cjs/FDBTransaction.js +20 -2
  203. package/node_modules/fake-indexeddb/build/cjs/lib/RecordStore.js +3 -3
  204. package/node_modules/fake-indexeddb/build/cjs/lib/binarySearchTree.js +11 -13
  205. package/node_modules/fake-indexeddb/build/cjs/lib/cmp.js +44 -14
  206. package/node_modules/fake-indexeddb/build/cjs/test/fakeIndexedDB/auto.js +54 -0
  207. package/node_modules/fake-indexeddb/build/cjs/test/fakeIndexedDB/binarySearchTree.js +413 -0
  208. package/node_modules/fake-indexeddb/build/cjs/test/fakeIndexedDB/fakeIndexedDB.js +1018 -0
  209. package/node_modules/fake-indexeddb/build/cjs/test/fakeIndexedDB/forceCloseDatabase.js +99 -0
  210. package/node_modules/fake-indexeddb/build/cjs/test/fakeIndexedDB/getAll.js +707 -0
  211. package/node_modules/fake-indexeddb/build/cjs/test/fakeIndexedDB/memoryLeaks.js +42 -0
  212. package/node_modules/fake-indexeddb/build/esm/FDBCursor.js +19 -18
  213. package/node_modules/fake-indexeddb/build/esm/FDBKeyRange.js +6 -6
  214. package/node_modules/fake-indexeddb/build/esm/FDBTransaction.js +20 -2
  215. package/node_modules/fake-indexeddb/build/esm/lib/RecordStore.js +3 -3
  216. package/node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js +11 -13
  217. package/node_modules/fake-indexeddb/build/esm/lib/cmp.js +41 -11
  218. package/node_modules/fake-indexeddb/build/esm/test/fakeIndexedDB/auto.js +52 -0
  219. package/node_modules/fake-indexeddb/build/esm/test/fakeIndexedDB/binarySearchTree.js +409 -0
  220. package/node_modules/fake-indexeddb/build/esm/test/fakeIndexedDB/fakeIndexedDB.js +1014 -0
  221. package/node_modules/fake-indexeddb/build/esm/test/fakeIndexedDB/forceCloseDatabase.js +95 -0
  222. package/node_modules/fake-indexeddb/build/esm/test/fakeIndexedDB/getAll.js +703 -0
  223. package/node_modules/fake-indexeddb/build/esm/test/fakeIndexedDB/memoryLeaks.js +38 -0
  224. package/node_modules/fake-indexeddb/package.json +1 -1
  225. package/node_modules/file-type/node_modules/strtok3/LICENSE.txt +21 -0
  226. package/node_modules/file-type/node_modules/strtok3/README.md +591 -0
  227. package/node_modules/file-type/node_modules/strtok3/lib/AbortSignal.d.ts +2 -0
  228. package/node_modules/file-type/node_modules/strtok3/lib/AbortSignal.js +7 -0
  229. package/node_modules/file-type/node_modules/strtok3/lib/AbstractTokenizer.d.ts +114 -0
  230. package/node_modules/file-type/node_modules/strtok3/lib/AbstractTokenizer.js +196 -0
  231. package/node_modules/file-type/node_modules/strtok3/lib/BlobTokenizer.d.ts +29 -0
  232. package/node_modules/file-type/node_modules/strtok3/lib/BlobTokenizer.js +56 -0
  233. package/node_modules/file-type/node_modules/strtok3/lib/BufferSizeError.d.ts +19 -0
  234. package/node_modules/file-type/node_modules/strtok3/lib/BufferSizeError.js +27 -0
  235. package/node_modules/file-type/node_modules/strtok3/lib/BufferTokenizer.d.ts +29 -0
  236. package/node_modules/file-type/node_modules/strtok3/lib/BufferTokenizer.js +50 -0
  237. package/node_modules/file-type/node_modules/strtok3/lib/FileTokenizer.d.ts +47 -0
  238. package/node_modules/file-type/node_modules/strtok3/lib/FileTokenizer.js +83 -0
  239. package/node_modules/file-type/node_modules/strtok3/lib/NotRegularFileError.d.ts +5 -0
  240. package/node_modules/file-type/node_modules/strtok3/lib/NotRegularFileError.js +8 -0
  241. package/node_modules/file-type/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts +34 -0
  242. package/node_modules/file-type/node_modules/strtok3/lib/ReadStreamTokenizer.js +125 -0
  243. package/node_modules/file-type/node_modules/strtok3/lib/core.d.ts +41 -0
  244. package/node_modules/file-type/node_modules/strtok3/lib/core.js +69 -0
  245. package/node_modules/file-type/node_modules/strtok3/lib/index.d.ts +17 -0
  246. package/node_modules/file-type/node_modules/strtok3/lib/index.js +23 -0
  247. package/node_modules/file-type/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts +54 -0
  248. package/node_modules/file-type/node_modules/strtok3/lib/stream/AbstractStreamReader.js +73 -0
  249. package/node_modules/file-type/node_modules/strtok3/lib/stream/Deferred.d.ts +6 -0
  250. package/node_modules/file-type/node_modules/strtok3/lib/stream/Deferred.js +10 -0
  251. package/node_modules/file-type/node_modules/strtok3/lib/stream/Errors.d.ts +10 -0
  252. package/node_modules/file-type/node_modules/strtok3/lib/stream/Errors.js +16 -0
  253. package/node_modules/file-type/node_modules/strtok3/lib/stream/StreamReader.d.ts +30 -0
  254. package/node_modules/file-type/node_modules/strtok3/lib/stream/StreamReader.js +104 -0
  255. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts +14 -0
  256. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamByobReader.js +29 -0
  257. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts +19 -0
  258. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js +67 -0
  259. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamReader.d.ts +14 -0
  260. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamReader.js +13 -0
  261. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts +5 -0
  262. package/node_modules/file-type/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js +19 -0
  263. package/node_modules/file-type/node_modules/strtok3/lib/stream/index.d.ts +6 -0
  264. package/node_modules/file-type/node_modules/strtok3/lib/stream/index.js +5 -0
  265. package/node_modules/file-type/node_modules/strtok3/lib/types.d.ts +146 -0
  266. package/node_modules/file-type/node_modules/strtok3/lib/types.js +1 -0
  267. package/node_modules/file-type/node_modules/strtok3/package.json +95 -0
  268. package/node_modules/file-type/package.json +28 -27
  269. package/node_modules/file-type/readme.md +32 -3
  270. package/node_modules/file-type/source/detectors/ebml.js +2 -2
  271. package/node_modules/file-type/source/detectors/png.js +1 -0
  272. package/node_modules/file-type/source/detectors/zip.js +71 -112
  273. package/node_modules/file-type/source/index.d.ts +18 -8
  274. package/node_modules/file-type/source/index.js +75 -49
  275. package/node_modules/file-type/source/index.test-d.ts +29 -21
  276. package/node_modules/file-type/source/supported.js +4 -0
  277. package/node_modules/file-type/source/tokens.js +2 -2
  278. package/node_modules/markdown-it/dist/browser/markdown-it.esm.min.mjs +737 -686
  279. package/node_modules/markdown-it/dist/browser/markdown-it.esm.min.mjs.map +1 -1
  280. package/node_modules/markdown-it/dist/browser/markdown-it.umd.min.js +8 -8
  281. package/node_modules/markdown-it/dist/browser/markdown-it.umd.min.js.map +1 -1
  282. package/node_modules/markdown-it/dist/markdown-it.cjs.js +660 -518
  283. package/node_modules/markdown-it/dist/markdown-it.cjs.js.map +1 -1
  284. package/node_modules/markdown-it/dist/markdown-it.d.mts +1 -0
  285. package/node_modules/markdown-it/dist/markdown-it.mjs +179 -124
  286. package/node_modules/markdown-it/dist/markdown-it.mjs.map +1 -1
  287. package/node_modules/markdown-it/package.json +11 -11
  288. package/node_modules/matrix-js-sdk/CHANGELOG.md +23 -0
  289. package/node_modules/matrix-js-sdk/lib/@types/PushRules.d.ts +3 -1
  290. package/node_modules/matrix-js-sdk/lib/@types/PushRules.d.ts.map +1 -1
  291. package/node_modules/matrix-js-sdk/lib/@types/PushRules.js +2 -0
  292. package/node_modules/matrix-js-sdk/lib/@types/PushRules.js.map +1 -1
  293. package/node_modules/matrix-js-sdk/lib/@types/event.d.ts +1 -0
  294. package/node_modules/matrix-js-sdk/lib/@types/event.d.ts.map +1 -1
  295. package/node_modules/matrix-js-sdk/lib/@types/event.js.map +1 -1
  296. package/node_modules/matrix-js-sdk/lib/@types/matrix-sdk-crypto-wasm.d.js.map +1 -1
  297. package/node_modules/matrix-js-sdk/lib/client.d.ts +88 -37
  298. package/node_modules/matrix-js-sdk/lib/client.d.ts.map +1 -1
  299. package/node_modules/matrix-js-sdk/lib/client.js +72 -47
  300. package/node_modules/matrix-js-sdk/lib/client.js.map +1 -1
  301. package/node_modules/matrix-js-sdk/lib/crypto-api/index.d.ts +3 -3
  302. package/node_modules/matrix-js-sdk/lib/crypto-api/index.d.ts.map +1 -1
  303. package/node_modules/matrix-js-sdk/lib/crypto-api/index.js.map +1 -1
  304. package/node_modules/matrix-js-sdk/lib/embedded.d.ts +17 -1
  305. package/node_modules/matrix-js-sdk/lib/embedded.d.ts.map +1 -1
  306. package/node_modules/matrix-js-sdk/lib/embedded.js +46 -1
  307. package/node_modules/matrix-js-sdk/lib/embedded.js.map +1 -1
  308. package/node_modules/matrix-js-sdk/lib/errors.d.ts +1 -1
  309. package/node_modules/matrix-js-sdk/lib/errors.d.ts.map +1 -1
  310. package/node_modules/matrix-js-sdk/lib/errors.js +2 -2
  311. package/node_modules/matrix-js-sdk/lib/errors.js.map +1 -1
  312. package/node_modules/matrix-js-sdk/lib/http-api/fetch.d.ts +7 -1
  313. package/node_modules/matrix-js-sdk/lib/http-api/fetch.d.ts.map +1 -1
  314. package/node_modules/matrix-js-sdk/lib/http-api/fetch.js +14 -5
  315. package/node_modules/matrix-js-sdk/lib/http-api/fetch.js.map +1 -1
  316. package/node_modules/matrix-js-sdk/lib/http-api/interface.d.ts +34 -8
  317. package/node_modules/matrix-js-sdk/lib/http-api/interface.d.ts.map +1 -1
  318. package/node_modules/matrix-js-sdk/lib/http-api/interface.js +10 -3
  319. package/node_modules/matrix-js-sdk/lib/http-api/interface.js.map +1 -1
  320. package/node_modules/matrix-js-sdk/lib/http-api/refresh.d.ts +30 -11
  321. package/node_modules/matrix-js-sdk/lib/http-api/refresh.d.ts.map +1 -1
  322. package/node_modules/matrix-js-sdk/lib/http-api/refresh.js +72 -5
  323. package/node_modules/matrix-js-sdk/lib/http-api/refresh.js.map +1 -1
  324. package/node_modules/matrix-js-sdk/lib/http-api/utils.js +1 -3
  325. package/node_modules/matrix-js-sdk/lib/matrix.d.ts +1 -1
  326. package/node_modules/matrix-js-sdk/lib/matrix.d.ts.map +1 -1
  327. package/node_modules/matrix-js-sdk/lib/matrix.js.map +1 -1
  328. package/node_modules/matrix-js-sdk/lib/matrixrtc/CallMembership.d.ts.map +1 -1
  329. package/node_modules/matrix-js-sdk/lib/matrixrtc/CallMembership.js +20 -6
  330. package/node_modules/matrix-js-sdk/lib/matrixrtc/CallMembership.js.map +1 -1
  331. package/node_modules/matrix-js-sdk/lib/matrixrtc/IMembershipManager.d.ts +5 -0
  332. package/node_modules/matrix-js-sdk/lib/matrixrtc/IMembershipManager.d.ts.map +1 -1
  333. package/node_modules/matrix-js-sdk/lib/matrixrtc/IMembershipManager.js.map +1 -1
  334. package/node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSession.d.ts +27 -1
  335. package/node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  336. package/node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSession.js +58 -36
  337. package/node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  338. package/node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSessionManager.js +1 -1
  339. package/node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  340. package/node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManager.d.ts +76 -0
  341. package/node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManager.d.ts.map +1 -1
  342. package/node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManager.js +264 -47
  343. package/node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManager.js.map +1 -1
  344. package/node_modules/matrix-js-sdk/lib/matrixrtc/index.d.ts +1 -1
  345. package/node_modules/matrix-js-sdk/lib/matrixrtc/index.d.ts.map +1 -1
  346. package/node_modules/matrix-js-sdk/lib/matrixrtc/index.js +1 -1
  347. package/node_modules/matrix-js-sdk/lib/matrixrtc/index.js.map +1 -1
  348. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/common.d.ts +8 -0
  349. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/common.d.ts.map +1 -1
  350. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/common.js +10 -0
  351. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/common.js.map +1 -1
  352. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/index.d.ts +1 -1
  353. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/index.d.ts.map +1 -1
  354. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/index.js +1 -1
  355. package/node_modules/matrix-js-sdk/lib/matrixrtc/membershipData/index.js.map +1 -1
  356. package/node_modules/matrix-js-sdk/lib/matrixrtc/types.d.ts +104 -11
  357. package/node_modules/matrix-js-sdk/lib/matrixrtc/types.d.ts.map +1 -1
  358. package/node_modules/matrix-js-sdk/lib/matrixrtc/types.js +263 -19
  359. package/node_modules/matrix-js-sdk/lib/matrixrtc/types.js.map +1 -1
  360. package/node_modules/matrix-js-sdk/lib/matrixrtc/utils.d.ts +22 -1
  361. package/node_modules/matrix-js-sdk/lib/matrixrtc/utils.d.ts.map +1 -1
  362. package/node_modules/matrix-js-sdk/lib/matrixrtc/utils.js +38 -0
  363. package/node_modules/matrix-js-sdk/lib/matrixrtc/utils.js.map +1 -1
  364. package/node_modules/matrix-js-sdk/lib/models/room-sticky-events.d.ts +7 -0
  365. package/node_modules/matrix-js-sdk/lib/models/room-sticky-events.d.ts.map +1 -1
  366. package/node_modules/matrix-js-sdk/lib/models/room-sticky-events.js +27 -0
  367. package/node_modules/matrix-js-sdk/lib/models/room-sticky-events.js.map +1 -1
  368. package/node_modules/matrix-js-sdk/lib/models/thread.d.ts.map +1 -1
  369. package/node_modules/matrix-js-sdk/lib/models/thread.js +8 -0
  370. package/node_modules/matrix-js-sdk/lib/models/thread.js.map +1 -1
  371. package/node_modules/matrix-js-sdk/lib/oauth/authorize.js +1 -1
  372. package/node_modules/matrix-js-sdk/lib/oauth/authorize.js.map +1 -1
  373. package/node_modules/matrix-js-sdk/lib/oauth/index.d.ts +3 -5
  374. package/node_modules/matrix-js-sdk/lib/oauth/index.d.ts.map +1 -1
  375. package/node_modules/matrix-js-sdk/lib/oauth/index.js +7 -7
  376. package/node_modules/matrix-js-sdk/lib/oauth/index.js.map +1 -1
  377. package/node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.d.ts +10 -4
  378. package/node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.d.ts.map +1 -1
  379. package/node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.js +34 -24
  380. package/node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.js.map +1 -1
  381. package/node_modules/matrix-js-sdk/lib/receipt-accumulator.d.ts +10 -11
  382. package/node_modules/matrix-js-sdk/lib/receipt-accumulator.d.ts.map +1 -1
  383. package/node_modules/matrix-js-sdk/lib/receipt-accumulator.js +26 -25
  384. package/node_modules/matrix-js-sdk/lib/receipt-accumulator.js.map +1 -1
  385. package/node_modules/matrix-js-sdk/lib/room-summary-api.d.ts +71 -0
  386. package/node_modules/matrix-js-sdk/lib/room-summary-api.d.ts.map +1 -0
  387. package/node_modules/matrix-js-sdk/lib/room-summary-api.js +82 -0
  388. package/node_modules/matrix-js-sdk/lib/room-summary-api.js.map +1 -0
  389. package/node_modules/matrix-js-sdk/lib/rust-crypto/backup.d.ts +7 -0
  390. package/node_modules/matrix-js-sdk/lib/rust-crypto/backup.d.ts.map +1 -1
  391. package/node_modules/matrix-js-sdk/lib/rust-crypto/backup.js +41 -25
  392. package/node_modules/matrix-js-sdk/lib/rust-crypto/backup.js.map +1 -1
  393. package/node_modules/matrix-js-sdk/lib/rust-crypto/rust-crypto.js +1 -7
  394. package/node_modules/matrix-js-sdk/lib/sync.d.ts.map +1 -1
  395. package/node_modules/matrix-js-sdk/lib/sync.js +6 -1
  396. package/node_modules/matrix-js-sdk/lib/sync.js.map +1 -1
  397. package/node_modules/matrix-js-sdk/package.json +6 -6
  398. package/node_modules/matrix-js-sdk/src/@types/PushRules.ts +2 -0
  399. package/node_modules/matrix-js-sdk/src/@types/event.ts +1 -1
  400. package/node_modules/matrix-js-sdk/src/@types/matrix-sdk-crypto-wasm.d.ts +15 -12
  401. package/node_modules/matrix-js-sdk/src/client.ts +105 -62
  402. package/node_modules/matrix-js-sdk/src/crypto-api/index.ts +3 -3
  403. package/node_modules/matrix-js-sdk/src/embedded.ts +61 -2
  404. package/node_modules/matrix-js-sdk/src/errors.ts +2 -1
  405. package/node_modules/matrix-js-sdk/src/http-api/fetch.ts +14 -5
  406. package/node_modules/matrix-js-sdk/src/http-api/interface.ts +36 -8
  407. package/node_modules/matrix-js-sdk/src/http-api/refresh.ts +101 -17
  408. package/node_modules/matrix-js-sdk/src/http-api/utils.ts +1 -5
  409. package/node_modules/matrix-js-sdk/src/matrix.ts +1 -1
  410. package/node_modules/matrix-js-sdk/src/matrixrtc/CallMembership.ts +22 -4
  411. package/node_modules/matrix-js-sdk/src/matrixrtc/IMembershipManager.ts +6 -0
  412. package/node_modules/matrix-js-sdk/src/matrixrtc/MatrixRTCSession.ts +72 -49
  413. package/node_modules/matrix-js-sdk/src/matrixrtc/MatrixRTCSessionManager.ts +1 -1
  414. package/node_modules/matrix-js-sdk/src/matrixrtc/MembershipManager.ts +284 -61
  415. package/node_modules/matrix-js-sdk/src/matrixrtc/index.ts +7 -1
  416. package/node_modules/matrix-js-sdk/src/matrixrtc/membershipData/common.ts +12 -0
  417. package/node_modules/matrix-js-sdk/src/matrixrtc/membershipData/index.ts +1 -1
  418. package/node_modules/matrix-js-sdk/src/matrixrtc/types.ts +351 -23
  419. package/node_modules/matrix-js-sdk/src/matrixrtc/utils.ts +54 -1
  420. package/node_modules/matrix-js-sdk/src/models/room-sticky-events.ts +26 -1
  421. package/node_modules/matrix-js-sdk/src/models/thread.ts +9 -0
  422. package/node_modules/matrix-js-sdk/src/oauth/authorize.ts +1 -1
  423. package/node_modules/matrix-js-sdk/src/oauth/index.ts +7 -8
  424. package/node_modules/matrix-js-sdk/src/oauth/tokenRefresher.ts +15 -5
  425. package/node_modules/matrix-js-sdk/src/receipt-accumulator.ts +30 -26
  426. package/node_modules/matrix-js-sdk/src/room-summary-api.ts +114 -0
  427. package/node_modules/matrix-js-sdk/src/rust-crypto/backup.ts +46 -33
  428. package/node_modules/matrix-js-sdk/src/rust-crypto/rust-crypto.ts +1 -7
  429. package/node_modules/matrix-js-sdk/src/sync.ts +9 -1
  430. package/node_modules/music-metadata/README.md +125 -37
  431. package/node_modules/music-metadata/lib/ParseError.d.ts +10 -3
  432. package/node_modules/music-metadata/lib/ParseError.js +2 -0
  433. package/node_modules/music-metadata/lib/ParserFactory.d.ts +1 -1
  434. package/node_modules/music-metadata/lib/ParserFactory.js +20 -8
  435. package/node_modules/music-metadata/lib/aiff/AiffParser.d.ts +1 -0
  436. package/node_modules/music-metadata/lib/aiff/AiffParser.js +25 -17
  437. package/node_modules/music-metadata/lib/aiff/AiffToken.d.ts +9 -3
  438. package/node_modules/music-metadata/lib/aiff/AiffToken.js +10 -0
  439. package/node_modules/music-metadata/lib/apev2/APEv2Parser.d.ts +4 -3
  440. package/node_modules/music-metadata/lib/apev2/APEv2Parser.js +6 -30
  441. package/node_modules/music-metadata/lib/asf/AsfGuid.js +49 -49
  442. package/node_modules/music-metadata/lib/asf/AsfObject.d.ts +12 -6
  443. package/node_modules/music-metadata/lib/asf/AsfObject.js +201 -58
  444. package/node_modules/music-metadata/lib/asf/AsfParser.d.ts +4 -0
  445. package/node_modules/music-metadata/lib/asf/AsfParser.js +119 -27
  446. package/node_modules/music-metadata/lib/caf/CafLoader.d.ts +2 -0
  447. package/node_modules/music-metadata/lib/caf/CafLoader.js +8 -0
  448. package/node_modules/music-metadata/lib/caf/CafParser.d.ts +37 -0
  449. package/node_modules/music-metadata/lib/caf/CafParser.js +253 -0
  450. package/node_modules/music-metadata/lib/caf/CafTagMap.d.ts +8 -0
  451. package/node_modules/music-metadata/lib/caf/CafTagMap.js +38 -0
  452. package/node_modules/music-metadata/lib/caf/CafToken.d.ts +75 -0
  453. package/node_modules/music-metadata/lib/caf/CafToken.js +135 -0
  454. package/node_modules/music-metadata/lib/common/Allocation.d.ts +14 -0
  455. package/node_modules/music-metadata/lib/common/Allocation.js +70 -0
  456. package/node_modules/music-metadata/lib/common/BasicParser.d.ts +2 -0
  457. package/node_modules/music-metadata/lib/common/BasicParser.js +8 -0
  458. package/node_modules/music-metadata/lib/common/CaseInsensitiveTagMap.d.ts +1 -1
  459. package/node_modules/music-metadata/lib/common/CaseInsensitiveTagMap.js +3 -3
  460. package/node_modules/music-metadata/lib/common/CombinedTagMapper.js +4 -3
  461. package/node_modules/music-metadata/lib/common/GenericTagMapper.d.ts +1 -1
  462. package/node_modules/music-metadata/lib/common/GenericTagMapper.js +4 -2
  463. package/node_modules/music-metadata/lib/common/GenericTagTypes.d.ts +2 -2
  464. package/node_modules/music-metadata/lib/common/MetadataCollector.d.ts +6 -5
  465. package/node_modules/music-metadata/lib/common/MetadataCollector.js +57 -30
  466. package/node_modules/music-metadata/lib/common/TrackInfo.d.ts +8 -0
  467. package/node_modules/music-metadata/lib/common/TrackInfo.js +68 -0
  468. package/node_modules/music-metadata/lib/common/Util.d.ts +1 -1
  469. package/node_modules/music-metadata/lib/common/Util.js +6 -12
  470. package/node_modules/music-metadata/lib/core.d.ts +1 -1
  471. package/node_modules/music-metadata/lib/core.js +10 -18
  472. package/node_modules/music-metadata/lib/dsdiff/DsdiffLoader.js +1 -1
  473. package/node_modules/music-metadata/lib/dsdiff/DsdiffParser.d.ts +7 -3
  474. package/node_modules/music-metadata/lib/dsdiff/DsdiffParser.js +69 -33
  475. package/node_modules/music-metadata/lib/dsf/DsfParser.d.ts +4 -3
  476. package/node_modules/music-metadata/lib/dsf/DsfParser.js +1 -1
  477. package/node_modules/music-metadata/lib/ebml/EbmlIterator.d.ts +28 -19
  478. package/node_modules/music-metadata/lib/ebml/EbmlIterator.js +97 -67
  479. package/node_modules/music-metadata/lib/ebml/types.d.ts +36 -8
  480. package/node_modules/music-metadata/lib/ebml/types.js +2 -1
  481. package/node_modules/music-metadata/lib/flac/FlacParser.js +10 -18
  482. package/node_modules/music-metadata/lib/id3v1/ID3v1Parser.d.ts +1 -1
  483. package/node_modules/music-metadata/lib/id3v1/ID3v1Parser.js +5 -1
  484. package/node_modules/music-metadata/lib/id3v2/AbstractID3Parser.js +1 -4
  485. package/node_modules/music-metadata/lib/id3v2/EmbeddedID3v2.d.ts +5 -0
  486. package/node_modules/music-metadata/lib/id3v2/EmbeddedID3v2.js +29 -0
  487. package/node_modules/music-metadata/lib/id3v2/FrameParser.d.ts +5 -3
  488. package/node_modules/music-metadata/lib/id3v2/FrameParser.js +59 -33
  489. package/node_modules/music-metadata/lib/id3v2/ID3v2Parser.js +15 -8
  490. package/node_modules/music-metadata/lib/index.d.ts +2 -0
  491. package/node_modules/music-metadata/lib/index.js +8 -4
  492. package/node_modules/music-metadata/lib/matroska/MatroskaDtd.d.ts +630 -2
  493. package/node_modules/music-metadata/lib/matroska/MatroskaDtd.js +58 -40
  494. package/node_modules/music-metadata/lib/matroska/MatroskaParser.d.ts +4 -0
  495. package/node_modules/music-metadata/lib/matroska/MatroskaParser.js +211 -68
  496. package/node_modules/music-metadata/lib/matroska/types.d.ts +33 -131
  497. package/node_modules/music-metadata/lib/matroska/types.js +1 -18
  498. package/node_modules/music-metadata/lib/mp4/Atom.js +7 -0
  499. package/node_modules/music-metadata/lib/mp4/AtomToken.d.ts +17 -4
  500. package/node_modules/music-metadata/lib/mp4/AtomToken.js +124 -21
  501. package/node_modules/music-metadata/lib/mp4/MP4Parser.d.ts +12 -3
  502. package/node_modules/music-metadata/lib/mp4/MP4Parser.js +559 -242
  503. package/node_modules/music-metadata/lib/mpeg/AdtsFrameHeader.d.ts +17 -0
  504. package/node_modules/music-metadata/lib/mpeg/AdtsFrameHeader.js +44 -0
  505. package/node_modules/music-metadata/lib/mpeg/MpegFrameHeader.d.ts +41 -0
  506. package/node_modules/music-metadata/lib/mpeg/MpegFrameHeader.js +84 -0
  507. package/node_modules/music-metadata/lib/mpeg/MpegParser.d.ts +11 -24
  508. package/node_modules/music-metadata/lib/mpeg/MpegParser.js +77 -337
  509. package/node_modules/music-metadata/lib/musepack/MusepackConentError.d.ts +4 -3
  510. package/node_modules/music-metadata/lib/musepack/sv7/BitReader.js +3 -2
  511. package/node_modules/music-metadata/lib/musepack/sv7/MpcSv7Parser.js +3 -6
  512. package/node_modules/music-metadata/lib/musepack/sv8/MpcSv8Parser.js +1 -4
  513. package/node_modules/music-metadata/lib/musepack/sv8/StreamVersion8.js +1 -0
  514. package/node_modules/music-metadata/lib/ogg/OggLoader.js +1 -1
  515. package/node_modules/music-metadata/lib/ogg/OggParser.d.ts +4 -3
  516. package/node_modules/music-metadata/lib/ogg/OggParser.js +54 -9
  517. package/node_modules/music-metadata/lib/ogg/OggStreamMetadata.d.ts +14 -0
  518. package/node_modules/music-metadata/lib/ogg/OggStreamMetadata.js +27 -0
  519. package/node_modules/music-metadata/lib/ogg/OggToken.d.ts +1 -0
  520. package/node_modules/music-metadata/lib/ogg/OggToken.js +3 -1
  521. package/node_modules/music-metadata/lib/ogg/flac/FlacStream.d.ts +3 -1
  522. package/node_modules/music-metadata/lib/ogg/flac/FlacStream.js +21 -3
  523. package/node_modules/music-metadata/lib/ogg/opus/Opus.d.ts +4 -3
  524. package/node_modules/music-metadata/lib/ogg/opus/Opus.js +1 -0
  525. package/node_modules/music-metadata/lib/ogg/opus/OpusStream.js +4 -2
  526. package/node_modules/music-metadata/lib/ogg/speex/SpeexStream.js +2 -1
  527. package/node_modules/music-metadata/lib/ogg/theora/Theora.d.ts +5 -0
  528. package/node_modules/music-metadata/lib/ogg/theora/Theora.js +7 -2
  529. package/node_modules/music-metadata/lib/ogg/theora/TheoraStream.d.ts +5 -2
  530. package/node_modules/music-metadata/lib/ogg/theora/TheoraStream.js +43 -3
  531. package/node_modules/music-metadata/lib/ogg/vorbis/Vorbis.js +4 -3
  532. package/node_modules/music-metadata/lib/ogg/vorbis/VorbisDecoder.d.ts +11 -0
  533. package/node_modules/music-metadata/lib/ogg/vorbis/VorbisDecoder.js +29 -0
  534. package/node_modules/music-metadata/lib/ogg/vorbis/VorbisStream.d.ts +6 -4
  535. package/node_modules/music-metadata/lib/ogg/vorbis/VorbisStream.js +24 -18
  536. package/node_modules/music-metadata/lib/riff/RiffChunk.js +3 -0
  537. package/node_modules/music-metadata/lib/type.d.ts +49 -6
  538. package/node_modules/music-metadata/lib/type.js +22 -1
  539. package/node_modules/music-metadata/lib/wav/WaveChunk.d.ts +4 -3
  540. package/node_modules/music-metadata/lib/wav/WaveChunk.js +2 -0
  541. package/node_modules/music-metadata/lib/wav/WaveParser.d.ts +0 -1
  542. package/node_modules/music-metadata/lib/wav/WaveParser.js +21 -23
  543. package/node_modules/music-metadata/lib/wavpack/WavPackParser.d.ts +4 -3
  544. package/node_modules/music-metadata/lib/wavpack/WavPackParser.js +6 -6
  545. package/node_modules/music-metadata/package.json +26 -22
  546. package/node_modules/strtok3/LICENSE.txt +21 -21
  547. package/node_modules/strtok3/README.md +712 -399
  548. package/node_modules/strtok3/lib/AbortSignal.d.ts +2 -0
  549. package/node_modules/strtok3/lib/AbortSignal.js +7 -0
  550. package/node_modules/strtok3/lib/AbstractTokenizer.d.ts +40 -2
  551. package/node_modules/strtok3/lib/AbstractTokenizer.js +101 -16
  552. package/node_modules/strtok3/lib/BlobTokenizer.d.ts +1 -1
  553. package/node_modules/strtok3/lib/BlobTokenizer.js +14 -11
  554. package/node_modules/strtok3/lib/BufferSizeError.d.ts +19 -0
  555. package/node_modules/strtok3/lib/BufferSizeError.js +27 -0
  556. package/node_modules/strtok3/lib/BufferTokenizer.d.ts +1 -1
  557. package/node_modules/strtok3/lib/BufferTokenizer.js +7 -9
  558. package/node_modules/strtok3/lib/FileTokenizer.d.ts +13 -3
  559. package/node_modules/strtok3/lib/FileTokenizer.js +29 -7
  560. package/node_modules/strtok3/lib/NotRegularFileError.d.ts +5 -0
  561. package/node_modules/strtok3/lib/NotRegularFileError.js +8 -0
  562. package/node_modules/strtok3/lib/ReadStreamTokenizer.js +32 -9
  563. package/node_modules/strtok3/lib/TokenizerBoundaryError.d.ts +7 -0
  564. package/node_modules/strtok3/lib/TokenizerBoundaryError.js +10 -0
  565. package/node_modules/strtok3/lib/TokenizerView.d.ts +9 -0
  566. package/node_modules/strtok3/lib/TokenizerView.js +184 -0
  567. package/node_modules/strtok3/lib/core.d.ts +10 -6
  568. package/node_modules/strtok3/lib/core.js +16 -22
  569. package/node_modules/strtok3/lib/index.d.ts +5 -4
  570. package/node_modules/strtok3/lib/index.js +3 -2
  571. package/node_modules/strtok3/lib/isRandomAccessTokenizer.d.ts +6 -0
  572. package/node_modules/strtok3/lib/isRandomAccessTokenizer.js +10 -0
  573. package/node_modules/strtok3/lib/stream/AbstractStreamReader.js +5 -3
  574. package/node_modules/strtok3/lib/stream/Errors.js +3 -3
  575. package/node_modules/strtok3/lib/stream/StreamReader.d.ts +4 -3
  576. package/node_modules/strtok3/lib/stream/StreamReader.js +46 -25
  577. package/node_modules/strtok3/lib/stream/WebStreamByobReader.js +5 -3
  578. package/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts +1 -1
  579. package/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js +9 -4
  580. package/node_modules/strtok3/lib/stream/WebStreamReader.d.ts +13 -3
  581. package/node_modules/strtok3/lib/stream/WebStreamReader.js +1 -1
  582. package/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js +1 -1
  583. package/node_modules/strtok3/lib/stream/index.d.ts +1 -1
  584. package/node_modules/strtok3/lib/types.d.ts +25 -1
  585. package/node_modules/strtok3/package.json +97 -94
  586. package/node_modules/typebox/build/format/duration.d.mts +2 -2
  587. package/node_modules/typebox/build/format/duration.mjs +2 -2
  588. package/node_modules/typebox/build/format/idn_email.d.mts +1 -0
  589. package/node_modules/typebox/build/format/idn_email.mjs +1 -0
  590. package/node_modules/typebox/build/format/idn_hostname.d.mts +1 -1
  591. package/node_modules/typebox/build/format/idn_hostname.mjs +1 -1
  592. package/node_modules/typebox/build/format/ipv4.d.mts +2 -2
  593. package/node_modules/typebox/build/format/ipv4.mjs +2 -2
  594. package/node_modules/typebox/build/format/ipv6.d.mts +1 -1
  595. package/node_modules/typebox/build/format/ipv6.mjs +1 -1
  596. package/node_modules/typebox/build/format/relative_json_pointer.d.mts +2 -2
  597. package/node_modules/typebox/build/format/relative_json_pointer.mjs +2 -2
  598. package/node_modules/typebox/build/schema/build.mjs +1 -0
  599. package/node_modules/typebox/build/schema/engine/_unique.d.mts +4 -2
  600. package/node_modules/typebox/build/schema/engine/_unique.mjs +7 -3
  601. package/node_modules/typebox/build/schema/engine/additionalItems.mjs +3 -3
  602. package/node_modules/typebox/build/schema/engine/additionalProperties.d.mts +0 -3
  603. package/node_modules/typebox/build/schema/engine/additionalProperties.mjs +15 -17
  604. package/node_modules/typebox/build/schema/engine/contains.mjs +3 -3
  605. package/node_modules/typebox/build/schema/engine/index.d.mts +1 -0
  606. package/node_modules/typebox/build/schema/engine/index.mjs +1 -0
  607. package/node_modules/typebox/build/schema/engine/items.mjs +7 -4
  608. package/node_modules/typebox/build/schema/engine/maxContains.mjs +2 -2
  609. package/node_modules/typebox/build/schema/engine/minContains.mjs +3 -3
  610. package/node_modules/typebox/build/schema/engine/oneOf.mjs +2 -2
  611. package/node_modules/typebox/build/schema/engine/patternProperties.mjs +2 -2
  612. package/node_modules/typebox/build/schema/engine/propertyNames.mjs +2 -2
  613. package/node_modules/typebox/build/schema/engine/unevaluatedItems.mjs +2 -2
  614. package/node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs +2 -2
  615. package/node_modules/typebox/build/system/hashing/hash.mjs +63 -34
  616. package/node_modules/typebox/build/system/locale/en_US.mjs +2 -1
  617. package/node_modules/typebox/build/system/memory/assign.d.mts +2 -8
  618. package/node_modules/typebox/build/system/memory/assign.mjs +13 -6
  619. package/node_modules/typebox/build/system/memory/clone.d.mts +4 -5
  620. package/node_modules/typebox/build/system/memory/clone.mjs +8 -96
  621. package/node_modules/typebox/build/system/memory/create.d.mts +1 -5
  622. package/node_modules/typebox/build/system/memory/create.mjs +18 -13
  623. package/node_modules/typebox/build/system/memory/deep.d.mts +2 -0
  624. package/node_modules/typebox/build/system/memory/deep.mjs +108 -0
  625. package/node_modules/typebox/build/system/memory/discard.d.mts +1 -1
  626. package/node_modules/typebox/build/system/memory/discard.mjs +9 -8
  627. package/node_modules/typebox/build/system/memory/finalize.d.mts +4 -0
  628. package/node_modules/typebox/build/system/memory/finalize.mjs +30 -0
  629. package/node_modules/typebox/build/system/memory/keys.d.mts +2 -0
  630. package/node_modules/typebox/build/system/memory/keys.mjs +8 -0
  631. package/node_modules/typebox/build/system/memory/update.d.mts +1 -4
  632. package/node_modules/typebox/build/system/memory/update.mjs +43 -16
  633. package/node_modules/typebox/build/type/engine/call/index.d.mts +1 -0
  634. package/node_modules/typebox/build/type/engine/call/index.mjs +1 -0
  635. package/node_modules/typebox/build/type/engine/evaluate/composite.d.mts +2 -24
  636. package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +2 -29
  637. package/node_modules/typebox/build/type/engine/evaluate/index.d.mts +1 -0
  638. package/node_modules/typebox/build/type/engine/evaluate/index.mjs +1 -0
  639. package/node_modules/typebox/build/type/engine/evaluate/narrow.d.mts +5 -1
  640. package/node_modules/typebox/build/type/engine/evaluate/narrow.mjs +6 -1
  641. package/node_modules/typebox/build/type/engine/evaluate/property.d.mts +30 -0
  642. package/node_modules/typebox/build/type/engine/evaluate/property.mjs +29 -0
  643. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.d.mts +1 -3
  644. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs +1 -4
  645. package/node_modules/typebox/build/type/engine/object/from_intersect.d.mts +2 -2
  646. package/node_modules/typebox/build/type/engine/object/from_intersect.mjs +2 -2
  647. package/node_modules/typebox/build/type/engine/object/from_union.d.mts +2 -2
  648. package/node_modules/typebox/build/type/engine/object/from_union.mjs +2 -2
  649. package/node_modules/typebox/build/type/engine/optional/instantiate_add.d.mts +1 -3
  650. package/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs +1 -4
  651. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.d.mts +1 -3
  652. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs +1 -4
  653. package/node_modules/typebox/build/type/engine/this/index.d.mts +1 -0
  654. package/node_modules/typebox/build/type/engine/this/index.mjs +1 -0
  655. package/node_modules/typebox/build/value/clone/clone.d.mts +4 -3
  656. package/node_modules/typebox/build/value/clone/clone.mjs +5 -7
  657. package/node_modules/typebox/build/value/repair/from_cyclic.d.mts +2 -0
  658. package/node_modules/typebox/build/value/repair/from_cyclic.mjs +6 -0
  659. package/node_modules/typebox/build/value/shared/union_priority_sort.mjs +25 -14
  660. package/node_modules/typebox/package.json +1 -1
  661. package/node_modules/typebox/readme.md +1 -1
  662. package/node_modules/zod/package.json +1 -1
  663. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  664. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  665. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  666. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  667. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  668. package/node_modules/zod/src/v4/core/util.ts +13 -0
  669. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  670. package/node_modules/zod/v4/core/compile.cjs +8 -0
  671. package/node_modules/zod/v4/core/compile.js +8 -0
  672. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  673. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  674. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  675. package/node_modules/zod/v4/core/schemas.js +30 -0
  676. package/node_modules/zod/v4/core/util.cjs +15 -0
  677. package/node_modules/zod/v4/core/util.d.cts +2 -0
  678. package/node_modules/zod/v4/core/util.d.ts +2 -0
  679. package/node_modules/zod/v4/core/util.js +14 -0
  680. package/node_modules/zod/v4/core/versions.cjs +1 -1
  681. package/node_modules/zod/v4/core/versions.js +1 -1
  682. package/openclaw.plugin.json +11 -0
  683. package/package.json +11 -11
  684. package/dist/.setup/channel.runtime-DaGbm27q.mjs +0 -74
  685. package/dist/.setup/device-health-DnKAXW1v.mjs +0 -20
  686. package/dist/.setup/inbound-dedupe-CZnOq0ja.mjs +0 -47
  687. package/dist/.setup/setup-plugin-api-SO1hdrsT.mjs +0 -2
  688. package/node_modules/music-metadata/node_modules/content-type/LICENSE +0 -22
  689. package/node_modules/music-metadata/node_modules/content-type/README.md +0 -71
  690. package/node_modules/music-metadata/node_modules/content-type/dist/index.d.ts +0 -46
  691. package/node_modules/music-metadata/node_modules/content-type/dist/index.js +0 -176
  692. package/node_modules/music-metadata/node_modules/content-type/dist/index.js.map +0 -1
  693. package/node_modules/music-metadata/node_modules/content-type/package.json +0 -52
  694. package/node_modules/typebox/build/system/memory/freeze.d.mts +0 -4
  695. package/node_modules/typebox/build/system/memory/freeze.mjs +0 -6
@@ -1,36 +1,38 @@
1
1
  import { t as getMatrixRuntime } from "./runtime-Ck8TjD7L.mjs";
2
2
  import { a as resolveMatrixAccountConfig, i as resolveMatrixAccountAllowlistConfig } from "./account-config-CVM2a28p.mjs";
3
- import { h as resolveConfiguredMatrixBotUserIds } from "./setup-core-D2r4BivQ.mjs";
4
- import { a as resolveMatrixThreadRouting, i as resolveMatrixInboundRouteAsync, n as resolveMatrixStoredSessionMeta, o as resolveMatrixRoomConfig } from "./channel-CNjJyBS_.mjs";
5
- import { a as resolveMatrixAllowListMatch, i as normalizeMatrixUserId, r as normalizeMatrixAllowList } from "./channel.setup-IjRB0ymg.mjs";
3
+ import { h as resolveConfiguredMatrixBotUserIds } from "./setup-core-BaKffgBi.mjs";
4
+ import { a as resolveMatrixInboundRouteAsync, i as resolveMatrixRoomConfig, n as resolveMatrixStoredSessionMeta, o as resolveMatrixThreadRouting } from "./channel-ByHcZU28.mjs";
5
+ import { a as resolveMatrixAllowListMatch, i as normalizeMatrixUserId, r as normalizeMatrixAllowList } from "./channel.setup-Bmba21y9.mjs";
6
6
  import { n as isMatrixQualifiedUserId, r as isMatrixRoomId, t as isMatrixInviteAutoJoinTarget } from "./target-ids-DltG_ZHJ.mjs";
7
- import { a as MATRIX_REACTION_EVENT_TYPE } from "./send-currentness-CAUVR-f3.mjs";
8
- import { c as isStrictDirectMembership, f as resolveMatrixReplyToEventId, h as MATRIX_OPENCLAW_FINALIZED_PREVIEW_KEY, i as promoteMatrixDirectRoomCandidate, p as resolveMatrixThreadRootId, s as hasDirectMatrixMemberFlag, u as readJoinedMatrixMembers, v as RelationType } from "./direct-management-DDaWVbQI.mjs";
9
- import { _ as isPollEventType, c as formatMatrixMessageText, d as resolveMatrixReplacementContent, h as formatPollAsText, l as isLikelyBareFilename, r as sendMessageMatrix, u as resolveMatrixMessageAttachment, v as isPollStartType, w as setBoundedMap, y as parsePollStart } from "./send-C1qeMQAy.mjs";
10
- import { t as createMatrixThreadBindingManager } from "./thread-bindings-D2ZR6mEZ.mjs";
11
- import { a as isMatrixStartupAbortError, c as getMatrixMonitorTaskSignal, d as resolveMatrixAuthContext, l as backfillMatrixAuthDeviceIdAfterStartup, n as acquireSharedMatrixClient, o as throwIfMatrixStartupAborted, s as createMatrixMonitorTaskRunner, u as resolveMatrixAuth } from "./client-7eyTX0cu.mjs";
12
- import { i as readMatrixMessages, l as fetchMatrixPollSnapshot } from "./messages-BiHM0DM3.mjs";
13
- import { i as isMatrixMediaSizeLimitError, r as MatrixMediaSizeLimitError } from "./http-client-CxTmU1kT.mjs";
14
- import { n as prepareMatrixReplyPayload, r as resolveMatrixExtraContent } from "./outbound-DwP97VpQ.mjs";
15
- import { t as resolveMatrixTargets } from "./resolve-targets-B8PAwHVS.mjs";
16
- import { t as formatMatrixEncryptedEventDisabledWarning } from "./encryption-guidance-Cn6-Tlx0.mjs";
17
- import { createMatrixInboundEventDeduper } from "./inbound-dedupe-CZnOq0ja.mjs";
18
- import { a as isMatrixAccessTokenInvalidatedError, d as isMatrixDisconnectedSyncState, f as isMatrixReadySyncState, p as isMatrixTerminalSyncState } from "./client-support-CFofPPPm.mjs";
19
- import { r as getMatrixRoomInfo, t as createMatrixRoomInfoResolver } from "./room-info-T_PR_liR.mjs";
7
+ import { a as MATRIX_REACTION_EVENT_TYPE, n as withMatrixSendCurrentness } from "./send-currentness-D1x6YP9O.mjs";
8
+ import { c as isStrictDirectMembership, f as resolveMatrixReplyToEventId, h as MATRIX_OPENCLAW_FINALIZED_PREVIEW_KEY, i as promoteMatrixDirectRoomCandidate, p as resolveMatrixThreadRootId, s as hasDirectMatrixMemberFlag, u as readJoinedMatrixMembers, v as RelationType } from "./direct-management-D59C1WO-.mjs";
9
+ import { n as getMatrixMonitorTaskSignal, t as createMatrixMonitorTaskRunner } from "./task-runner-CYyGHdNW.mjs";
10
+ import { _ as isPollEventType, c as formatMatrixMessageText, d as resolveMatrixReplacementContent, h as formatPollAsText, l as isLikelyBareFilename, r as sendMessageMatrix, u as resolveMatrixMessageAttachment, v as isPollStartType, w as setBoundedMap, y as parsePollStart } from "./send-CWjH-l-T.mjs";
11
+ import { n as getMatrixEventProjection } from "./event-helpers-DDUjVVf7.mjs";
12
+ import { t as createMatrixThreadBindingManager } from "./thread-bindings-BA2xESjV.mjs";
13
+ import { a as isMatrixAccessTokenInvalidatedError } from "./client-support-CqXAOZp3.mjs";
14
+ import { a as isMatrixStartupAbortError, c as resolveMatrixAuth, l as resolveMatrixAuthContext, n as acquireSharedMatrixClient, o as throwIfMatrixStartupAborted, s as backfillMatrixAuthDeviceIdAfterStartup } from "./client-Bqu801rH.mjs";
15
+ import { i as readMatrixMessages, l as fetchMatrixPollSnapshot } from "./messages-BjzsVgS6.mjs";
16
+ import { a as isMatrixMediaSizeLimitError, i as MatrixMediaSizeLimitError } from "./http-client-CqnKFKUH.mjs";
17
+ import { n as prepareMatrixReplyPayload, r as resolveMatrixExtraContent } from "./outbound-wsXTF0z_.mjs";
18
+ import { t as resolveMatrixTargets } from "./resolve-targets-Yz_3aN_2.mjs";
19
+ import { t as formatMatrixEncryptedEventDisabledWarning } from "./encryption-guidance-DfbEaKct.mjs";
20
+ import { n as isMatrixReadySyncState, r as isMatrixTerminalSyncState, t as isMatrixDisconnectedSyncState } from "./sync-state-Cu1nagBV.mjs";
21
+ import { r as getMatrixRoomInfo, t as createMatrixRoomInfoResolver } from "./room-info-OGKjk422.mjs";
20
22
  import { channelBlockedPatch, channelReadyPatch, channelStoppedPatch, createTransportActivityStatusPatch } from "openclaw/plugin-sdk/gateway-runtime";
21
23
  import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
22
- import { createChannelDeliveryAccumulator, createChannelProgressDraftCompositor, createLivePreviewLifecycle, createPreviewMessageReceipt, createReplyPrefixOptions, createTypingCallbacks, logTypingFailure, resolveChannelStreamingBlockEnabled, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
24
+ import { createChannelDeliveryAccumulator, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createLivePreviewLifecycle, createPreviewMessageReceipt, createReplyPrefixOptions, createTypingCallbacks, logTypingFailure, resolveChannelStreamingBlockEnabled, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
23
25
  import { extractErrorCode, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
24
26
  import { normalizeLowercaseStringOrEmpty, normalizeNullableString, normalizeOptionalString, normalizeStringifiedEntries, normalizeUniqueTrimmedStringList, readStringValue, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
25
27
  import { stripReasoningTagsFromText } from "openclaw/plugin-sdk/text-chunking";
26
28
  import { CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "openclaw/plugin-sdk/approval-handler-adapter-runtime";
27
29
  import { addAllowlistUserEntriesFromConfigEntry, buildAllowlistResolutionSummary, canonicalizeAllowlistWithResolvedIds, patchAllowlistUsersInConfigEntries, summarizeMapping } from "openclaw/plugin-sdk/allow-from";
28
- import { normalizeStringEntries as normalizeStringEntries$1 } from "openclaw/plugin-sdk/string-normalization-runtime";
29
- import { isFutureDateTimestampMs, parseStrictFiniteNumber, resolveExpiresAtMsFromDurationMs, resolveOptionalIntegerOption, resolvePromptHistoryLimit } from "openclaw/plugin-sdk/number-runtime";
30
+ import { normalizeStringEntries as normalizeStringEntries$1, truncateWithMarker } from "openclaw/plugin-sdk/string-normalization-runtime";
31
+ import { parseStrictFiniteNumber, resolveOptionalIntegerOption, resolvePromptHistoryLimit } from "openclaw/plugin-sdk/number-runtime";
30
32
  import { resolveAgentRoute, resolveInboundLastRouteSessionKey } from "openclaw/plugin-sdk/routing";
31
33
  import { getSessionEntryAsync, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
32
34
  import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
33
- import { escapeRegExp, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
35
+ import { escapeRegExp, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
34
36
  import { buildTtsSupplementMediaPayload, getReplyPayloadTtsSupplement, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
35
37
  import { format } from "node:util";
36
38
  import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
@@ -65,14 +67,13 @@ function registerMatrixAutoJoin(params) {
65
67
  const allowedAliases = rawAllowlist.filter((entry) => entry.startsWith("#"));
66
68
  const resolvedAliasRoomIds = /* @__PURE__ */ new Map();
67
69
  if (autoJoin === "off") return () => {};
68
- if (autoJoin === "always") logVerbose("matrix: auto-join enabled for all invites");
69
- else {
70
- logVerbose("matrix: auto-join enabled for allowlist invites");
70
+ if (autoJoin === "allowlist") {
71
71
  const inertEntries = rawAllowlist.filter((entry) => !isMatrixInviteAutoJoinTarget(entry));
72
72
  if (inertEntries.length > 0) core.logging.getChildLogger({ module: "matrix-auto-join" }).warn(`matrix: autoJoinAllowlist entries cannot match an invited room and are ignored: ${inertEntries.join(", ")}`);
73
73
  }
74
74
  const resolveAllowedAliasRoomId = async (alias) => {
75
- if (resolvedAliasRoomIds.has(alias)) return resolvedAliasRoomIds.get(alias) ?? null;
75
+ const cached = resolvedAliasRoomIds.get(alias);
76
+ if (cached !== void 0) return cached;
76
77
  const resolved = await params.client.resolveRoom(alias);
77
78
  if (resolved) resolvedAliasRoomIds.set(alias, resolved);
78
79
  return resolved;
@@ -89,17 +90,23 @@ function registerMatrixAutoJoin(params) {
89
90
  };
90
91
  const onInvite = (roomId, _inviteEvent) => {
91
92
  params.runDetachedTask(`auto-join invite handler room=${roomId}`, async () => {
93
+ const monitorSignal = getMatrixMonitorTaskSignal();
92
94
  if (autoJoin === "allowlist") {
93
95
  const allowedAliasRoomIds = await resolveAllowedAliasRoomIds();
96
+ if (monitorSignal?.aborted) return;
94
97
  if (!(autoJoinAllowlist.has("*") || allowedRoomIds.has(roomId) || allowedAliasRoomIds.some((resolvedRoomId) => resolvedRoomId === roomId))) {
95
98
  logVerbose(`matrix: invite ignored (not in allowlist) room=${roomId}`);
96
99
  return;
97
100
  }
98
101
  }
102
+ if (monitorSignal?.aborted) return;
99
103
  try {
100
- await client.joinRoom(roomId);
104
+ await withMatrixSendCurrentness(client, () => {
105
+ monitorSignal?.throwIfAborted();
106
+ }, () => client.joinRoom(roomId));
101
107
  logVerbose(`matrix: joined room ${roomId}`);
102
108
  } catch (err) {
109
+ if (monitorSignal?.aborted) return;
103
110
  runtime.error?.(`matrix: failed to join room ${roomId}: ${String(err)}`);
104
111
  }
105
112
  });
@@ -178,7 +185,7 @@ async function resolveMatrixMonitorUserEntries(params) {
178
185
  resolved: false
179
186
  });
180
187
  }
181
- (pending.length === 0 ? [] : await params.resolveTargets({
188
+ (pending.length === 0 ? [] : await resolveMatrixTargets({
182
189
  cfg: params.cfg,
183
190
  accountId: params.accountId,
184
191
  inputs: pending.map((entry) => entry.query),
@@ -207,7 +214,6 @@ async function resolveMatrixMonitorUserAllowlist(params) {
207
214
  accountId: params.accountId,
208
215
  entries: allowList,
209
216
  runtime: params.runtime,
210
- resolveTargets: params.resolveTargets,
211
217
  allowNameMatching
212
218
  });
213
219
  const canonicalized = canonicalizeAllowlistWithResolvedIds({
@@ -275,7 +281,6 @@ async function resolveMatrixMonitorLiveUserAllowlist(params) {
275
281
  accountId: params.accountId,
276
282
  entries: pending,
277
283
  runtime: params.runtime,
278
- resolveTargets: params.resolveTargets ?? resolveMatrixTargets,
279
284
  allowNameMatching
280
285
  });
281
286
  const resolvedEntries = filterMatrixAllowlistEntries(canonicalizeAllowlistWithResolvedIds({
@@ -286,93 +291,90 @@ async function resolveMatrixMonitorLiveUserAllowlist(params) {
286
291
  for (const entry of resolvedEntries) addEntry(entry);
287
292
  return effective;
288
293
  }
289
- async function resolveMatrixMonitorRoomsConfig(params) {
290
- const roomsConfig = params.roomsConfig;
291
- if (!roomsConfig || Object.keys(roomsConfig).length === 0) return roomsConfig;
292
- const mapping = [];
293
- const unresolved = [];
294
- const nextRooms = {};
295
- const allowNameMatching = isMatrixDangerousNameMatchingEnabled({
296
- cfg: params.cfg,
297
- accountId: params.accountId
298
- });
299
- if (roomsConfig["*"]) nextRooms["*"] = roomsConfig["*"];
300
- const pending = [];
301
- for (const [entry, roomConfig] of Object.entries(roomsConfig)) {
302
- if (entry === "*") continue;
303
- const input = entry.trim();
304
- if (!input) continue;
305
- const cleaned = normalizeMatrixRoomLookupEntry(input);
306
- if (!cleaned) {
307
- unresolved.push(entry);
308
- continue;
309
- }
310
- if (isMatrixRoomId(cleaned)) {
311
- if (!nextRooms[cleaned]) nextRooms[cleaned] = roomConfig;
312
- if (cleaned !== input) mapping.push(`${input}→${cleaned}`);
313
- continue;
314
- }
315
- if (!cleaned.startsWith("#") && !allowNameMatching) {
316
- unresolved.push(input);
317
- continue;
294
+ async function resolveMatrixMonitorConfig(params) {
295
+ async function resolveMatrixMonitorRoomsConfig() {
296
+ const sourceRooms = params.roomsConfig;
297
+ if (!sourceRooms || Object.keys(sourceRooms).length === 0) return sourceRooms;
298
+ const mapping = [];
299
+ const unresolved = [];
300
+ const nextRooms = {};
301
+ const allowNameMatching = isMatrixDangerousNameMatchingEnabled({
302
+ cfg: params.cfg,
303
+ accountId: params.accountId
304
+ });
305
+ if (sourceRooms["*"]) nextRooms["*"] = sourceRooms["*"];
306
+ const pending = [];
307
+ for (const [entry, roomConfig] of Object.entries(sourceRooms)) {
308
+ if (entry === "*") continue;
309
+ const input = entry.trim();
310
+ if (!input) continue;
311
+ const cleaned = normalizeMatrixRoomLookupEntry(input);
312
+ if (!cleaned) {
313
+ unresolved.push(entry);
314
+ continue;
315
+ }
316
+ if (isMatrixRoomId(cleaned)) {
317
+ if (!nextRooms[cleaned]) nextRooms[cleaned] = roomConfig;
318
+ if (cleaned !== input) mapping.push(`${input}→${cleaned}`);
319
+ continue;
320
+ }
321
+ if (!cleaned.startsWith("#") && !allowNameMatching) {
322
+ unresolved.push(input);
323
+ continue;
324
+ }
325
+ pending.push({
326
+ input,
327
+ query: cleaned,
328
+ config: roomConfig
329
+ });
318
330
  }
319
- pending.push({
320
- input,
321
- query: cleaned,
322
- config: roomConfig
331
+ if (pending.length > 0) (await resolveMatrixTargets({
332
+ cfg: params.cfg,
333
+ accountId: params.accountId,
334
+ inputs: pending.map((entry) => entry.query),
335
+ kind: "group",
336
+ runtime: params.runtime
337
+ })).forEach((entry, index) => {
338
+ const source = pending[index];
339
+ if (!source) return;
340
+ if (entry.resolved && entry.id) {
341
+ const roomKey = normalizeMatrixRoomLookupEntry(entry.id);
342
+ if (!nextRooms[roomKey]) nextRooms[roomKey] = source.config;
343
+ mapping.push(`${source.input}→${roomKey}`);
344
+ } else unresolved.push(source.input);
345
+ });
346
+ summarizeMapping("matrix rooms", mapping, unresolved, params.runtime);
347
+ if (unresolved.length > 0) params.runtime.log?.("matrix rooms must be room IDs or aliases (example: !room:server, the suffixless !room form on room version 12+, or #alias:server). Unresolved entries are ignored.");
348
+ const roomUsers = /* @__PURE__ */ new Set();
349
+ for (const roomConfig of Object.values(nextRooms)) addAllowlistUserEntriesFromConfigEntry(roomUsers, roomConfig);
350
+ if (roomUsers.size === 0) return nextRooms;
351
+ const resolution = await resolveMatrixMonitorUserEntries({
352
+ cfg: params.cfg,
353
+ accountId: params.accountId,
354
+ entries: Array.from(roomUsers),
355
+ runtime: params.runtime,
356
+ allowNameMatching
357
+ });
358
+ logMatrixAllowlistResolution({
359
+ label: "matrix room users",
360
+ resolution,
361
+ allowNameMatching,
362
+ runtime: params.runtime
363
+ });
364
+ return patchAllowlistUsersInConfigEntries({
365
+ entries: nextRooms,
366
+ resolvedMap: resolution.resolvedMap,
367
+ strategy: "canonicalize",
368
+ entryKey: normalizeMatrixUserId
323
369
  });
324
370
  }
325
- if (pending.length > 0) (await params.resolveTargets({
326
- cfg: params.cfg,
327
- accountId: params.accountId,
328
- inputs: pending.map((entry) => entry.query),
329
- kind: "group",
330
- runtime: params.runtime
331
- })).forEach((entry, index) => {
332
- const source = pending[index];
333
- if (!source) return;
334
- if (entry.resolved && entry.id) {
335
- const roomKey = normalizeMatrixRoomLookupEntry(entry.id);
336
- if (!nextRooms[roomKey]) nextRooms[roomKey] = source.config;
337
- mapping.push(`${source.input}→${roomKey}`);
338
- } else unresolved.push(source.input);
339
- });
340
- summarizeMapping("matrix rooms", mapping, unresolved, params.runtime);
341
- if (unresolved.length > 0) params.runtime.log?.("matrix rooms must be room IDs or aliases (example: !room:server, the suffixless !room form on room version 12+, or #alias:server). Unresolved entries are ignored.");
342
- const roomUsers = /* @__PURE__ */ new Set();
343
- for (const roomConfig of Object.values(nextRooms)) addAllowlistUserEntriesFromConfigEntry(roomUsers, roomConfig);
344
- if (roomUsers.size === 0) return nextRooms;
345
- const resolution = await resolveMatrixMonitorUserEntries({
346
- cfg: params.cfg,
347
- accountId: params.accountId,
348
- entries: Array.from(roomUsers),
349
- runtime: params.runtime,
350
- resolveTargets: params.resolveTargets,
351
- allowNameMatching
352
- });
353
- logMatrixAllowlistResolution({
354
- label: "matrix room users",
355
- resolution,
356
- allowNameMatching,
357
- runtime: params.runtime
358
- });
359
- return patchAllowlistUsersInConfigEntries({
360
- entries: nextRooms,
361
- resolvedMap: resolution.resolvedMap,
362
- strategy: "canonicalize",
363
- entryKey: normalizeMatrixUserId
364
- });
365
- }
366
- async function resolveMatrixMonitorConfig(params) {
367
- const resolveTargets = params.resolveTargets ?? resolveMatrixTargets;
368
371
  const [allowFrom, groupAllowFrom, roomsConfig] = await Promise.all([
369
372
  resolveMatrixMonitorUserAllowlist({
370
373
  cfg: params.cfg,
371
374
  accountId: params.accountId,
372
375
  label: "matrix dm allowlist",
373
376
  list: params.allowFrom,
374
- runtime: params.runtime,
375
- resolveTargets
377
+ runtime: params.runtime
376
378
  }),
377
379
  resolveMatrixMonitorUserAllowlist({
378
380
  cfg: params.cfg,
@@ -380,16 +382,9 @@ async function resolveMatrixMonitorConfig(params) {
380
382
  label: "matrix group allowlist",
381
383
  list: params.groupAllowFrom,
382
384
  failClosedOnUnresolved: true,
383
- runtime: params.runtime,
384
- resolveTargets
385
+ runtime: params.runtime
385
386
  }),
386
- resolveMatrixMonitorRoomsConfig({
387
- cfg: params.cfg,
388
- accountId: params.accountId,
389
- roomsConfig: params.roomsConfig,
390
- runtime: params.runtime,
391
- resolveTargets
392
- })
387
+ resolveMatrixMonitorRoomsConfig()
393
388
  ]);
394
389
  return {
395
390
  allowFrom: allowFrom.entries,
@@ -408,20 +403,10 @@ function createDirectRoomTracker(client, opts = {}) {
408
403
  const log = opts.log ?? (() => {});
409
404
  let lastDmUpdateMs = 0;
410
405
  let hasSeededDmCache = false;
411
- let cachedSelfUserId = null;
412
406
  const joinedMembersCache = /* @__PURE__ */ new Map();
413
407
  const directMemberFlagCache = /* @__PURE__ */ new Map();
414
408
  const recentInviteCandidates = /* @__PURE__ */ new Map();
415
409
  const locallyPromotedDirectRooms = /* @__PURE__ */ new Map();
416
- const ensureSelfUserId = async () => {
417
- if (cachedSelfUserId) return cachedSelfUserId;
418
- try {
419
- cachedSelfUserId = await client.getUserId();
420
- } catch {
421
- cachedSelfUserId = null;
422
- }
423
- return cachedSelfUserId;
424
- };
425
410
  const refreshDmCache = async () => {
426
411
  const now = Date.now();
427
412
  if (now - lastDmUpdateMs < DM_CACHE_TTL_MS) return;
@@ -528,12 +513,11 @@ function createDirectRoomTracker(client, opts = {}) {
528
513
  log(`matrix: remembered invite candidate room=${roomId} sender=${normalizedRemoteUserId}`);
529
514
  },
530
515
  isDirectMessage: async (params) => {
531
- const { roomId, senderId } = params;
516
+ const { roomId, senderId, selfUserId } = params;
532
517
  if (await checkRoomPolicy("isExplicitlyConfiguredRoom", roomId)) {
533
518
  log(`matrix: dm rejected via explicit room config room=${roomId}`);
534
519
  return false;
535
520
  }
536
- const selfUserId = params.selfUserId ?? await ensureSelfUserId();
537
521
  const joinedMembers = params.joinedMembers ?? await resolveJoinedMembers(roomId);
538
522
  const strictDirectMembership = isStrictDirectMembership({
539
523
  selfUserId,
@@ -577,12 +561,12 @@ function createDirectRoomTracker(client, opts = {}) {
577
561
  const promoteDirectRoom = async (source) => {
578
562
  const promotion = await promoteMatrixDirectRoomCandidate({
579
563
  client,
580
- remoteUserId: senderId ?? "",
564
+ remoteUserId: senderId,
581
565
  roomId,
582
566
  selfUserId
583
567
  });
584
568
  if (promotion.classifyAsDirect) {
585
- rememberLocallyPromotedDirectRoom(roomId, senderId ?? "");
569
+ rememberLocallyPromotedDirectRoom(roomId, senderId);
586
570
  log(`matrix: dm detected via ${source} room=${roomId} reason=${promotion.reason} repaired=${String(promotion.repaired)}`);
587
571
  }
588
572
  return promotion.classifyAsDirect;
@@ -600,6 +584,7 @@ const EventType = {
600
584
  RoomMessage: "m.room.message",
601
585
  RoomMessageEncrypted: "m.room.encrypted",
602
586
  RoomMember: "m.room.member",
587
+ RoomName: "m.room.name",
603
588
  Location: "m.location",
604
589
  Reaction: MATRIX_REACTION_EVENT_TYPE
605
590
  };
@@ -612,7 +597,7 @@ const matrixIngressIdentity = defineStableChannelIngressIdentity({
612
597
  normalize: normalizeMatrixEntry,
613
598
  matchEntry({ subject, entry }) {
614
599
  const senderId = subject.identifiers[0]?.value;
615
- return entry.value === "*" || resolveMatrixAllowListMatch({
600
+ return resolveMatrixAllowListMatch({
616
601
  allowList: [entry.value],
617
602
  userId: senderId ?? ""
618
603
  }).allowed;
@@ -701,7 +686,7 @@ async function resolveMatrixMonitorCommandAccess(state, params) {
701
686
  allowFrom: commandAllowFrom,
702
687
  groupAllowFrom: commandGroupAllowFrom,
703
688
  command: {
704
- useAccessGroups: params.useAccessGroups,
689
+ useAccessGroups: true,
705
690
  allowTextCommands: params.allowTextCommands,
706
691
  hasControlCommand: params.hasControlCommand,
707
692
  groupOwnerAllowFrom: "none",
@@ -741,7 +726,7 @@ const matrixVerificationConstants = {
741
726
  const MAX_TRACKED_VERIFICATION_EVENTS = 1024;
742
727
  const SAS_NOTICE_RETRY_DELAY_MS = 750;
743
728
  const VERIFICATION_EVENT_STARTUP_GRACE_MS = 3e4;
744
- const loadMatrixDirectRoomDeps = createLazyRuntimeModule(() => Promise.all([import("./direct-management-DDaWVbQI.mjs").then((n) => n.t), import("./direct-management-DDaWVbQI.mjs").then((n) => n.o)]).then(([directManagementModule, directRoomModule]) => ({
729
+ const loadMatrixDirectRoomDeps = createLazyRuntimeModule(() => Promise.all([import("./direct-management-D59C1WO-.mjs").then((n) => n.t), import("./direct-management-D59C1WO-.mjs").then((n) => n.o)]).then(([directManagementModule, directRoomModule]) => ({
745
730
  inspectMatrixDirectRooms: directManagementModule.inspectMatrixDirectRooms,
746
731
  isStrictDirectRoom: directRoomModule.isStrictDirectRoom
747
732
  })));
@@ -803,8 +788,8 @@ function formatVerificationStageNotice(params) {
803
788
  function formatVerificationSasNotice(summary) {
804
789
  const sas = summary.sas;
805
790
  if (!sas) return null;
806
- const emojiLine = Array.isArray(sas.emoji) && sas.emoji.length > 0 ? `SAS emoji: ${sas.emoji.map(([emoji, name]) => `${normalizeNullableString(emoji) ?? "?"} ${normalizeNullableString(name) ?? "?"}`).join(" | ")}` : null;
807
- const decimalLine = Array.isArray(sas.decimal) && sas.decimal.length === 3 ? `SAS decimal: ${sas.decimal.join(" ")}` : null;
791
+ const emojiLine = sas.emoji?.length ? `SAS emoji: ${sas.emoji.map(([emoji, name]) => `${normalizeNullableString(emoji) ?? "?"} ${normalizeNullableString(name) ?? "?"}`).join(" | ")}` : null;
792
+ const decimalLine = sas.decimal ? `SAS decimal: ${sas.decimal.join(" ")}` : null;
808
793
  if (!emojiLine && !decimalLine) return null;
809
794
  const lines = [`Matrix verification SAS with ${summary.otherUserId}:`];
810
795
  if (emojiLine) lines.push(emojiLine);
@@ -822,65 +807,18 @@ function resolveVerificationFlowCandidates(params) {
822
807
  content["m.relates_to"]?.event_id
823
808
  ]);
824
809
  }
825
- function resolveSummaryRecency(summary) {
826
- const ts = Date.parse(summary.updatedAt ?? "");
827
- return Number.isFinite(ts) ? ts : 0;
828
- }
829
810
  function isActiveVerificationSummary(summary) {
830
811
  if (summary.completed) return false;
831
812
  if (summary.phaseName === "cancelled" || summary.phaseName === "done") return false;
832
- if (typeof summary.phase === "number" && summary.phase >= 4) return false;
813
+ if (summary.phase >= 4) return false;
833
814
  return true;
834
815
  }
835
- async function resolveVerificationSummaryForSignal(client, params) {
836
- if (!client.crypto) return null;
837
- await client.crypto.ensureVerificationDmTracked({
838
- roomId: params.roomId,
839
- userId: params.senderId
840
- }).catch(() => null);
841
- const list = await client.crypto.listVerifications();
842
- if (list.length === 0) return null;
843
- const candidates = resolveVerificationFlowCandidates({
844
- event: params.event,
845
- flowId: params.flowId
846
- });
847
- const byTransactionId = list.find((entry) => candidates.some((candidate) => entry.transactionId === candidate));
848
- if (byTransactionId) return byTransactionId;
849
- const { inspectMatrixDirectRooms, isStrictDirectRoom } = await loadMatrixDirectRoomDeps();
850
- const inspection = await inspectMatrixDirectRooms({
851
- client,
852
- remoteUserId: params.senderId
853
- }).catch(() => null);
854
- const activeRoomId = normalizeNullableString(inspection?.activeRoomId);
855
- if (activeRoomId) {
856
- if (activeRoomId !== params.roomId) return null;
857
- } else if (!await isStrictDirectRoom({
858
- client,
859
- roomId: params.roomId,
860
- remoteUserId: params.senderId
861
- })) return null;
862
- const activeByUser = list.filter((entry) => entry.otherUserId === params.senderId && isActiveVerificationSummary(entry)).toSorted((a, b) => resolveSummaryRecency(b) - resolveSummaryRecency(a));
863
- return activeByUser.find((entry) => normalizeNullableString(entry.roomId) === params.roomId) ?? activeByUser[0] ?? null;
864
- }
865
- async function resolveVerificationSasNoticeForSignal(client, params) {
866
- for (let attempt = 0;; attempt += 1) {
867
- const summary = await resolveVerificationSummaryForSignal(client, params);
868
- const sasNotice = summary && isActiveVerificationSummary(summary) ? formatVerificationSasNotice(summary) : null;
869
- if (sasNotice || attempt > 0 || params.stage !== "ready" && params.stage !== "start") return {
870
- summary,
871
- sasNotice
872
- };
873
- await new Promise((resolve) => {
874
- setTimeout(resolve, params.sasNoticeRetryDelayMs ?? SAS_NOTICE_RETRY_DELAY_MS);
875
- });
876
- }
877
- }
878
816
  function trackBounded(set, value) {
879
817
  if (!value || set.has(value)) return false;
880
818
  set.add(value);
881
819
  if (set.size > MAX_TRACKED_VERIFICATION_EVENTS) {
882
820
  const oldest = set.values().next().value;
883
- if (typeof oldest === "string") set.delete(oldest);
821
+ if (oldest !== void 0) set.delete(oldest);
884
822
  }
885
823
  return true;
886
824
  }
@@ -1006,14 +944,51 @@ function createMatrixVerificationEventRouter(params) {
1006
944
  senderId,
1007
945
  event
1008
946
  });
1009
- const { summary, sasNotice } = await resolveVerificationSasNoticeForSignal(params.client, {
1010
- roomId,
1011
- event,
1012
- senderId,
1013
- flowId,
1014
- stage: signal.stage,
1015
- sasNoticeRetryDelayMs: params.sasNoticeRetryDelayMs
1016
- }).catch(() => ({
947
+ const { client, sasNoticeRetryDelayMs } = params;
948
+ const resolveSummary = async () => {
949
+ if (!client.crypto) return null;
950
+ await client.crypto.ensureVerificationDmTracked({
951
+ roomId,
952
+ userId: senderId
953
+ }).catch(() => null);
954
+ const list = await client.crypto.listVerifications();
955
+ if (list.length === 0) return null;
956
+ const candidates = resolveVerificationFlowCandidates({
957
+ event,
958
+ flowId
959
+ });
960
+ const byTransactionId = list.find((entry) => candidates.some((candidate) => entry.transactionId === candidate));
961
+ if (byTransactionId) return byTransactionId;
962
+ const { inspectMatrixDirectRooms, isStrictDirectRoom } = await loadMatrixDirectRoomDeps();
963
+ const inspection = await inspectMatrixDirectRooms({
964
+ client,
965
+ remoteUserId: senderId
966
+ }).catch(() => null);
967
+ const activeRoomId = normalizeNullableString(inspection?.activeRoomId);
968
+ if (activeRoomId) {
969
+ if (activeRoomId !== roomId) return null;
970
+ } else if (!await isStrictDirectRoom({
971
+ client,
972
+ roomId,
973
+ remoteUserId: senderId
974
+ })) return null;
975
+ const activeByUser = list.filter((entry) => entry.otherUserId === senderId && isActiveVerificationSummary(entry));
976
+ return activeByUser.find((entry) => normalizeNullableString(entry.roomId) === roomId) ?? activeByUser[0] ?? null;
977
+ };
978
+ const resolveSasNotice = async () => {
979
+ for (let attempt = 0;; attempt += 1) {
980
+ const summary = await resolveSummary();
981
+ const sasNotice = summary && isActiveVerificationSummary(summary) ? formatVerificationSasNotice(summary) : null;
982
+ if (sasNotice || attempt > 0 || signal.stage !== "ready" && signal.stage !== "start") return {
983
+ summary,
984
+ sasNotice
985
+ };
986
+ await new Promise((resolve) => {
987
+ setTimeout(resolve, sasNoticeRetryDelayMs ?? SAS_NOTICE_RETRY_DELAY_MS);
988
+ });
989
+ }
990
+ };
991
+ const { summary, sasNotice } = await resolveSasNotice().catch(() => ({
1017
992
  summary: null,
1018
993
  sasNotice: null
1019
994
  }));
@@ -1028,10 +1003,7 @@ function createMatrixVerificationEventRouter(params) {
1028
1003
  }
1029
1004
  for (const body of notices) await sendVerificationNotice(roomId, body);
1030
1005
  };
1031
- if (params.runDetachedTask) params.runDetachedTask(`verification event handler room=${roomId} id=${event.event_id ?? "unknown"}`, routeTask);
1032
- else routeTask().catch((err) => {
1033
- params.logVerboseMessage(`matrix: failed routing verification event: ${String(err)}`);
1034
- });
1006
+ params.runDetachedTask(`verification event handler room=${roomId} id=${event.event_id ?? "unknown"}`, routeTask);
1035
1007
  return true;
1036
1008
  }
1037
1009
  return {
@@ -1046,15 +1018,6 @@ const MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT = 3;
1046
1018
  function formatMatrixPostHealthySyncDecryptionHint(accountId) {
1047
1019
  return `matrix: repeated fresh encrypted messages are still failing to decrypt after Matrix resumed healthy sync. This device may still be missing new room keys. Check 'openclaw matrix verify status --verbose --account ${accountId}' and 'openclaw matrix devices list --account ${accountId}'.`;
1048
1020
  }
1049
- function isFreshPostHealthySyncDecryptFailure(params) {
1050
- const { event, healthySyncSinceMs, nowMs } = params;
1051
- if (typeof healthySyncSinceMs !== "number" || !Number.isFinite(healthySyncSinceMs)) return false;
1052
- const eventTs = event.origin_server_ts;
1053
- if (!Number.isFinite(eventTs) || eventTs <= 0) return false;
1054
- if (eventTs < healthySyncSinceMs) return false;
1055
- if (eventTs > nowMs + 6e4) return false;
1056
- return true;
1057
- }
1058
1021
  function createMatrixPostHealthySyncDecryptFailureTracker(params) {
1059
1022
  let observations = [];
1060
1023
  let warningEmitted = false;
@@ -1074,11 +1037,12 @@ function createMatrixPostHealthySyncDecryptFailureTracker(params) {
1074
1037
  trackedHealthySyncSinceMs = healthySyncSinceMs;
1075
1038
  resetObservations();
1076
1039
  }
1077
- if (!isFreshPostHealthySyncDecryptFailure({
1078
- event,
1079
- healthySyncSinceMs,
1080
- nowMs
1081
- })) return {
1040
+ if (typeof healthySyncSinceMs !== "number" || !Number.isFinite(healthySyncSinceMs)) return {
1041
+ freshAfterHealthySync: false,
1042
+ failureCount: 0
1043
+ };
1044
+ const eventTs = event.origin_server_ts;
1045
+ if (!Number.isFinite(eventTs) || eventTs <= 0 || eventTs < healthySyncSinceMs || eventTs > nowMs + 6e4) return {
1082
1046
  freshAfterHealthySync: false,
1083
1047
  failureCount: 0
1084
1048
  };
@@ -1121,7 +1085,6 @@ function formatMatrixSelfDecryptionHint(accountId) {
1121
1085
  return `matrix: failed to decrypt a message from this same Matrix user. This usually means another Matrix device did not share the room key, or another OpenClaw runtime is using the same account. Check 'openclaw matrix verify status --verbose --account ${accountId}' and 'openclaw matrix devices list --account ${accountId}'.`;
1122
1086
  }
1123
1087
  async function resolveMatrixSelfUserId(client, logVerboseMessage) {
1124
- if (typeof client.getUserId !== "function") return null;
1125
1088
  try {
1126
1089
  return await client.getUserId() ?? null;
1127
1090
  } catch (err) {
@@ -1130,7 +1093,7 @@ async function resolveMatrixSelfUserId(client, logVerboseMessage) {
1130
1093
  }
1131
1094
  }
1132
1095
  function registerMatrixMonitorEvents(params) {
1133
- const { cfg, client, auth, allowFrom, dmEnabled, dmPolicy, readStoreAllowFrom, directTracker, invalidateMemberDisplayName, logVerboseMessage, warnedEncryptedRooms, warnedCryptoMissingRooms, logger, getHealthySyncSinceMs, formatNativeDependencyHint, onRoomMessage, runDetachedTask, sasNoticeRetryDelayMs } = params;
1096
+ const { cfg, client, auth, allowFrom, dmEnabled, dmPolicy, readStoreAllowFrom, directTracker, invalidateMemberDisplayName, invalidateRoomName, logVerboseMessage, warnedEncryptedRooms, warnedCryptoMissingRooms, logger, getHealthySyncSinceMs, formatNativeDependencyHint, runDetachedTask, sasNoticeRetryDelayMs } = params;
1134
1097
  const postHealthySyncDecryptFailureTracker = createMatrixPostHealthySyncDecryptFailureTracker({ getHealthySyncSinceMs });
1135
1098
  const { routeVerificationEvent, routeVerificationSummary } = createMatrixVerificationEventRouter({
1136
1099
  client,
@@ -1142,20 +1105,8 @@ function registerMatrixMonitorEvents(params) {
1142
1105
  runDetachedTask,
1143
1106
  sasNoticeRetryDelayMs
1144
1107
  });
1145
- const runMonitorTask = (label, task) => {
1146
- if (runDetachedTask) return runDetachedTask(label, task);
1147
- return Promise.resolve().then(task).catch((error) => {
1148
- logVerboseMessage(`matrix: ${label} failed (${String(error)})`);
1149
- });
1150
- };
1151
- const dispatchRoomMessage = (label, roomId, event) => {
1152
- runMonitorTask(`${label} room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1153
- await onRoomMessage(roomId, event);
1154
- });
1155
- };
1156
1108
  const onRoomMessageEvent = (roomId, event) => {
1157
- if (routeVerificationEvent(roomId, event)) return;
1158
- dispatchRoomMessage("room message handler", roomId, event);
1109
+ routeVerificationEvent(roomId, event);
1159
1110
  };
1160
1111
  const onEncryptedEvent = (roomId, event) => {
1161
1112
  const eventId = event?.event_id ?? "unknown";
@@ -1166,12 +1117,10 @@ function registerMatrixMonitorEvents(params) {
1166
1117
  const eventId = event?.event_id ?? "unknown";
1167
1118
  const eventType = event?.type ?? "unknown";
1168
1119
  logVerboseMessage(`matrix: decrypted event room=${roomId} type=${eventType} id=${eventId}`);
1169
- if (routeVerificationEvent(roomId, event)) return;
1170
- if (eventType !== EventType.RoomMessage) return;
1171
- dispatchRoomMessage("decrypted room message handler", roomId, event);
1120
+ routeVerificationEvent(roomId, event);
1172
1121
  };
1173
1122
  const onFailedDecryption = (roomId, event, error) => {
1174
- runMonitorTask(`failed decryption handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1123
+ runDetachedTask(`failed decryption handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1175
1124
  const failureState = postHealthySyncDecryptFailureTracker.recordFailure(roomId, event, error);
1176
1125
  const selfUserId = await resolveMatrixSelfUserId(client, logVerboseMessage);
1177
1126
  const sender = typeof event.sender === "string" ? event.sender : null;
@@ -1206,7 +1155,7 @@ function registerMatrixMonitorEvents(params) {
1206
1155
  });
1207
1156
  };
1208
1157
  const onVerificationSummary = (summary) => {
1209
- runMonitorTask("verification summary handler", async () => {
1158
+ runDetachedTask("verification summary handler", async () => {
1210
1159
  await routeVerificationSummary(summary);
1211
1160
  });
1212
1161
  };
@@ -1215,9 +1164,9 @@ function registerMatrixMonitorEvents(params) {
1215
1164
  const eventId = event?.event_id ?? "unknown";
1216
1165
  const sender = event?.sender ?? "unknown";
1217
1166
  const invitee = normalizeOptionalString(event?.state_key) ?? "";
1218
- const senderIsInvitee = Boolean(invitee) && (normalizeOptionalString(event?.sender) ?? "") === invitee;
1219
- const isDirect = (event?.content)?.is_direct === true;
1220
1167
  const rememberedSender = normalizeOptionalString(event?.sender);
1168
+ const senderIsInvitee = Boolean(invitee) && rememberedSender === invitee;
1169
+ const isDirect = (event?.content)?.is_direct === true;
1221
1170
  if (rememberedSender && !senderIsInvitee) directTracker?.rememberInvite?.(roomId, rememberedSender);
1222
1171
  logVerboseMessage(`matrix: invite room=${roomId} sender=${sender} direct=${String(isDirect)} id=${eventId}`);
1223
1172
  };
@@ -1226,7 +1175,7 @@ function registerMatrixMonitorEvents(params) {
1226
1175
  const eventId = event?.event_id ?? "unknown";
1227
1176
  logVerboseMessage(`matrix: join room=${roomId} id=${eventId}`);
1228
1177
  if (event.membershipProvenance !== "transition" || event.state_key !== auth.userId) return;
1229
- runMonitorTask(`join introduction room=${roomId}`, async () => {
1178
+ runDetachedTask(`join introduction room=${roomId}`, async () => {
1230
1179
  const members = await readJoinedMatrixMembers(client, roomId);
1231
1180
  const remoteUserId = members?.find((member) => member !== auth.userId);
1232
1181
  if (!members?.includes(auth.userId) || !remoteUserId || await directTracker.isDirectMessage({
@@ -1314,10 +1263,7 @@ function registerMatrixMonitorEvents(params) {
1314
1263
  if (stateKey) invalidateMemberDisplayName?.(roomId, stateKey);
1315
1264
  logVerboseMessage(`matrix: member event room=${roomId} stateKey=${stateKey} membership=${membership ?? "unknown"}`);
1316
1265
  }
1317
- if (eventType === EventType.Reaction) {
1318
- dispatchRoomMessage("reaction handler", roomId, event);
1319
- return;
1320
- }
1266
+ if (eventType === EventType.RoomName) invalidateRoomName?.(roomId);
1321
1267
  routeVerificationEvent(roomId, event);
1322
1268
  };
1323
1269
  client.on("room.message", onRoomMessageEvent);
@@ -1339,12 +1285,7 @@ function registerMatrixMonitorEvents(params) {
1339
1285
  client.off("room.event", onRoomEvent);
1340
1286
  };
1341
1287
  }
1342
- // extensions/matrix/src/matrix/monitor/context-summary.ts
1343
- const MAX_CONTEXT_BODY_LENGTH = 500;
1344
- function truncateMatrixContextBody(value) {
1345
- if (value.length <= MAX_CONTEXT_BODY_LENGTH) return value;
1346
- return `${sliceUtf16Safe(value, 0, 497)}...`;
1347
- }
1288
+ // extensions/matrix/src/matrix/monitor/event-context.ts
1348
1289
  function summarizeMatrixMessageContextEvent(event) {
1349
1290
  if (isPollStartType(event.type)) {
1350
1291
  const pollSummary = parsePollStart(event.content);
@@ -1357,7 +1298,7 @@ function summarizeMatrixMessageContextEvent(event) {
1357
1298
  msgtype: normalizeOptionalString(content.msgtype)
1358
1299
  });
1359
1300
  }
1360
- // extensions/matrix/src/matrix/monitor/event-context.ts
1301
+ const MAX_CONTEXT_BODY_LENGTH = 500;
1361
1302
  function createMatrixEventContextResolver(params) {
1362
1303
  const cache = /* @__PURE__ */ new Map();
1363
1304
  const isThread = params.kind === "thread";
@@ -1379,7 +1320,11 @@ function createMatrixEventContextResolver(params) {
1379
1320
  const context = {};
1380
1321
  if (isThread || !event.unsigned?.redacted_because) {
1381
1322
  const body = summarizeMatrixMessageContextEvent(event);
1382
- let summary = body ? truncateMatrixContextBody(body) : void 0;
1323
+ let summary = body ? truncateWithMarker(body, MAX_CONTEXT_BODY_LENGTH, {
1324
+ marker: "...",
1325
+ reserve: 3,
1326
+ trimEnd: false
1327
+ }) : void 0;
1383
1328
  if (isThread && !summary) {
1384
1329
  const msgtype = normalizeOptionalString(event.content.msgtype);
1385
1330
  const eventType = normalizeOptionalString(event.type);
@@ -1429,28 +1374,6 @@ const matrixPreflightAudio = createChannelPreflightAudio({
1429
1374
  channel: "matrix",
1430
1375
  isAudio: isMatrixAudioContent
1431
1376
  });
1432
- async function resolveMatrixPreflightAudioTranscript(params) {
1433
- return await matrixPreflightAudio.resolve({
1434
- request: {
1435
- ctx: {
1436
- media: [{
1437
- path: params.mediaPath,
1438
- contentType: params.mediaContentType
1439
- }],
1440
- Provider: "matrix",
1441
- Surface: "matrix",
1442
- OriginatingChannel: "matrix",
1443
- OriginatingTo: params.originatingTo,
1444
- AccountId: params.accountId,
1445
- MessageThreadId: params.messageThreadId,
1446
- ChatType: params.chatType,
1447
- SessionKey: params.sessionKey
1448
- },
1449
- cfg: params.cfg
1450
- },
1451
- abortSignal: params.abortSignal
1452
- });
1453
- }
1454
1377
  // extensions/matrix/src/matrix/monitor/handler-helpers.ts
1455
1378
  const MATRIX_TOOL_PROGRESS_MAX_CHARS = 300;
1456
1379
  const MAX_TRACKED_SHARED_DM_CONTEXT_NOTICES = 512;
@@ -1468,27 +1391,6 @@ function hasBundledMatrixReplacementRelation(event) {
1468
1391
  if (!relations || typeof relations !== "object") return false;
1469
1392
  return relations[RelationType.Replace] !== void 0;
1470
1393
  }
1471
- function resolveMatrixInboundBodyText(params) {
1472
- if (params.mediaPlaceholder) {
1473
- if (params.filename?.trim()) {
1474
- const attachment = resolveMatrixMessageAttachment({
1475
- body: params.rawBody,
1476
- filename: params.filename,
1477
- msgtype: params.msgtype
1478
- });
1479
- if (attachment && !attachment.caption) return params.mediaPlaceholder;
1480
- }
1481
- return params.rawBody || params.mediaPlaceholder;
1482
- }
1483
- if (!params.mediaDownloadFailed || !params.hadMediaUrl) return params.rawBody;
1484
- return formatMatrixMessageText({
1485
- body: params.rawBody,
1486
- filename: params.filename,
1487
- msgtype: params.msgtype,
1488
- tooLarge: params.mediaSizeLimitExceeded,
1489
- unavailable: true
1490
- }) ?? "";
1491
- }
1492
1394
  function markTrackedRoomIfFirst(set, roomId) {
1493
1395
  if (set.has(roomId)) return false;
1494
1396
  set.add(roomId);
@@ -1561,11 +1463,11 @@ function formatMatrixToolProgressMarkdownCode(text) {
1561
1463
  return `\`${(text.length <= MATRIX_TOOL_PROGRESS_MAX_CHARS ? text : `${truncateUtf16Safe(text, 299).trimEnd()}...`).replaceAll("`", "'")}\``;
1562
1464
  }
1563
1465
  // extensions/matrix/src/matrix/monitor/handler-runtime.ts
1564
- const loadMatrixSendModule = createLazyRuntimeModule(() => import("./send-C1qeMQAy.mjs").then((n) => n.s));
1466
+ const loadMatrixSendModule = createLazyRuntimeModule(() => import("./send-CWjH-l-T.mjs").then((n) => n.s));
1565
1467
  const loadAcpBindingRuntime = createLazyRuntimeModule(() => import("openclaw/plugin-sdk/acp-binding-runtime"));
1566
1468
  const loadSessionBindingRuntime = createLazyRuntimeModule(() => import("openclaw/plugin-sdk/session-binding-runtime"));
1567
- const loadMatrixReactionEvents = createLazyRuntimeModule(() => import("./reaction-events-ClY9h_FC.mjs"));
1568
- const loadMatrixDraftStream = createLazyRuntimeModule(() => import("./draft-stream-dmhBHufd.mjs"));
1469
+ const loadMatrixReactionEvents = createLazyRuntimeModule(() => import("./reaction-events-BMsatzs4.mjs"));
1470
+ const loadMatrixDraftStream = createLazyRuntimeModule(() => import("./draft-stream-C09OtoJZ.mjs"));
1569
1471
  async function matrixTextWouldActivateMentions(client, text) {
1570
1472
  const { resolveMatrixMentionsForBody } = await loadMatrixSendModule();
1571
1473
  const mentions = await resolveMatrixMentionsForBody({
@@ -1577,7 +1479,7 @@ async function matrixTextWouldActivateMentions(client, text) {
1577
1479
  // extensions/matrix/src/matrix/monitor/handler-context.ts
1578
1480
  async function resolveMatrixInboundContext(config) {
1579
1481
  const { handler, ingress, roomId, event, eventTs, resolveThreadContext, resolveReplyContext, senderId, sharedDmContextNoticeRooms } = config;
1580
- const { client, core, accountId, runtime, logVerboseMessage, groupPolicy, getRoomInfo, historyLimit, dmSessionScope, resolveStorePath: resolveStorePathImpl, createChannelInboundEnvelopeBuilderAsync: createChannelInboundEnvelopeBuilderImpl, finalizeInboundContext } = handler;
1482
+ const { client, core, accountId, runtime, logVerboseMessage, groupPolicy, getRoomInfo, historyLimit, dmSessionScope } = handler;
1581
1483
  const { cfg, resolveMessageIngress, route: _route, isDirectMessage, isRoom, effectiveRoomUsers, effectiveGroupAllowFrom, threadRootId, thread, senderName, bodyText, commandBodyText, roomConfig, messageId, inboundHistory, wasMentioned, effectiveWasMentioned, shouldBypassMention, canDetectMention, shouldRequireMention, commandAuthorized, isControlCommand, locationPayload, media, preflightAudioTranscript, hasExplicitSessionBinding } = ingress;
1582
1484
  const contextVisibilityMode = resolveChannelContextVisibilityMode({
1583
1485
  cfg,
@@ -1598,16 +1500,16 @@ async function resolveMatrixInboundContext(config) {
1598
1500
  }).allowed;
1599
1501
  return true;
1600
1502
  };
1601
- const shouldIncludeRoomContextSender = (kind, contextSenderId) => evaluateSupplementalContextVisibility({
1503
+ const shouldIncludeRoomContextSender = (contextSenderId) => evaluateSupplementalContextVisibility({
1602
1504
  mode: contextVisibilityMode,
1603
- kind,
1505
+ kind: "thread",
1604
1506
  senderAllowed: isRoomContextSenderAllowed(contextSenderId)
1605
1507
  }).include;
1606
1508
  let threadContext = ingress.threadContext ?? (threadRootId ? await resolveThreadContext({
1607
1509
  roomId,
1608
1510
  eventId: threadRootId
1609
1511
  }) : void 0);
1610
- if (threadContext?.senderId && !shouldIncludeRoomContextSender("thread", threadContext.senderId)) {
1512
+ if (threadContext?.senderId && !shouldIncludeRoomContextSender(threadContext.senderId)) {
1611
1513
  logVerboseMessage(`matrix: drop thread root context (mode=${contextVisibilityMode})`);
1612
1514
  threadContext = void 0;
1613
1515
  }
@@ -1622,11 +1524,11 @@ async function resolveMatrixInboundContext(config) {
1622
1524
  eventId: replyToEventId
1623
1525
  }) : void 0;
1624
1526
  const replySenderAllowed = !replyContext?.senderId || isRoomContextSenderAllowed(replyContext.senderId);
1625
- const roomName = (isRoom ? await getRoomInfo(roomId) : void 0)?.name;
1527
+ const roomName = (isRoom ? await getRoomInfo(roomId, { currentName: true }) : void 0)?.name;
1626
1528
  const envelopeFrom = isDirectMessage ? senderName : roomName ?? roomId;
1627
1529
  const textWithId = `${bodyText}\n[matrix event id: ${messageId} room: ${roomId}]`;
1628
- const storePath = resolveStorePathImpl(cfg.session?.store, { agentId: _route.agentId });
1629
- const buildEnvelope = await createChannelInboundEnvelopeBuilderImpl({
1530
+ const storePath = resolveStorePath(cfg.session?.store, { agentId: _route.agentId });
1531
+ const buildEnvelope = await createChannelInboundEnvelopeBuilderAsync({
1630
1532
  cfg,
1631
1533
  route: _route
1632
1534
  });
@@ -1667,7 +1569,6 @@ async function resolveMatrixInboundContext(config) {
1667
1569
  channelIngress,
1668
1570
  channel: "matrix",
1669
1571
  contextVisibility: contextVisibilityMode,
1670
- finalize: finalizeInboundContext,
1671
1572
  supplemental: {
1672
1573
  quote: replyContext ? {
1673
1574
  id: threadTarget ? void 0 : replyToEventId ?? void 0,
@@ -1740,7 +1641,7 @@ async function resolveMatrixInboundContext(config) {
1740
1641
  }
1741
1642
  });
1742
1643
  if (quoteHidden) logVerboseMessage(`matrix: drop reply context (mode=${contextVisibilityMode})`);
1743
- logVerboseMessage(`matrix inbound: room=${roomId} from=${senderId} preview="${truncateUtf16Safe(bodyText, 200).replace(/\n/g, "\\n")}"`);
1644
+ logVerboseMessage(`matrix inbound: room=${roomId} from=${senderId} chars=${bodyText.length}`);
1744
1645
  const replyTarget = ctxPayload.To;
1745
1646
  if (!replyTarget) {
1746
1647
  runtime.error?.("matrix: missing reply target");
@@ -1796,7 +1697,6 @@ async function createMatrixDraftController(params) {
1796
1697
  let currentDraftMessageGeneration = 0;
1797
1698
  let currentDraftBlockOffset = 0;
1798
1699
  let latestDraftFullText = "";
1799
- const pendingDraftBoundaries = [];
1800
1700
  let currentDraftReplyToId = draftReplyToId;
1801
1701
  const progressConfigEntry = accountConfig ?? cfg.channels?.matrix;
1802
1702
  const progressSeed = `${accountId}:${roomId}`;
@@ -1848,26 +1748,17 @@ async function createMatrixDraftController(params) {
1848
1748
  };
1849
1749
  };
1850
1750
  const updateDraftFromLatestFullText = () => {
1851
- const nextDraftBoundaryOffset = pendingDraftBoundaries.find((boundary) => boundary.messageGeneration === currentDraftMessageGeneration)?.endOffset;
1852
- const blockText = latestDraftFullText.slice(currentDraftBlockOffset, nextDraftBoundaryOffset);
1751
+ const blockText = latestDraftFullText.slice(currentDraftBlockOffset);
1853
1752
  if (blockText) draftStream?.update(blockText);
1854
1753
  };
1855
- const queueDraftBlockBoundary = (payload, context) => {
1856
- const payloadTextLength = payload.text?.length ?? 0;
1857
- const messageGeneration = context?.assistantMessageIndex ?? currentDraftMessageGeneration;
1858
- const nextDraftBoundaryOffset = (pendingDraftBoundaries.findLast((entry) => entry.messageGeneration === messageGeneration)?.endOffset ?? 0) + payloadTextLength;
1859
- pendingDraftBoundaries.push({
1860
- messageGeneration,
1861
- endOffset: nextDraftBoundaryOffset
1862
- });
1863
- };
1864
- const advanceDraftBlockBoundary = (options) => {
1865
- const completedBoundary = pendingDraftBoundaries.shift();
1866
- if (completedBoundary) {
1867
- if (completedBoundary.messageGeneration === currentDraftMessageGeneration) currentDraftBlockOffset = completedBoundary.endOffset;
1868
- return;
1869
- }
1870
- if (options?.fallbackToLatestEnd) currentDraftBlockOffset = latestDraftFullText.length;
1754
+ const captureDraftBlockBoundary = (text, info) => ({
1755
+ messageGeneration: info.assistantMessageIndex ?? currentDraftMessageGeneration,
1756
+ previewMessageGeneration: currentDraftMessageGeneration,
1757
+ previewEndOffset: latestDraftFullText.length,
1758
+ endOffset: info.blockSourceRange?.[1] ?? currentDraftBlockOffset + (text?.length ?? 0)
1759
+ });
1760
+ const advanceDraftBlockBoundary = (boundary) => {
1761
+ if (boundary.messageGeneration === currentDraftMessageGeneration) currentDraftBlockOffset = Math.max(currentDraftBlockOffset, boundary.endOffset);
1871
1762
  };
1872
1763
  const resetDraftBlockOffsets = () => {
1873
1764
  currentDraftMessageGeneration += 1;
@@ -1881,7 +1772,6 @@ async function createMatrixDraftController(params) {
1881
1772
  currentDraftMessageGeneration = 0;
1882
1773
  currentDraftBlockOffset = 0;
1883
1774
  latestDraftFullText = "";
1884
- pendingDraftBoundaries.length = 0;
1885
1775
  currentDraftReplyToId = draftReplyToId;
1886
1776
  progressDraft.beginNewTurn({ force: true });
1887
1777
  };
@@ -1890,7 +1780,7 @@ async function createMatrixDraftController(params) {
1890
1780
  previewLifecycle,
1891
1781
  cancelProgressDraft: () => progressDraft.cancel(),
1892
1782
  buildPreviewToolProgressReplyOptions,
1893
- queueDraftBlockBoundary,
1783
+ captureDraftBlockBoundary,
1894
1784
  advanceDraftBlockBoundary,
1895
1785
  resetDraftBlockOffsets,
1896
1786
  beginAssistantMessage: () => progressDraft.beginAssistantMessage(),
@@ -2005,7 +1895,7 @@ function createRoomHistoryTracker(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoom
2005
1895
  }
2006
1896
  function rememberWatermark(key, snapshotIdx) {
2007
1897
  const nextSnapshotIdx = Math.max(agentWatermarks.get(key) ?? 0, snapshotIdx);
2008
- if (agentWatermarks.has(key)) agentWatermarks.delete(key);
1898
+ agentWatermarks.delete(key);
2009
1899
  setBoundedMap(agentWatermarks, key, nextSnapshotIdx, maxWatermarkEntries);
2010
1900
  }
2011
1901
  function markConsumedAfterReservedGap(queue, key, firstReservedRel, snapshotIdx) {
@@ -2018,19 +1908,10 @@ function createRoomHistoryTracker(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoom
2018
1908
  }
2019
1909
  }
2020
1910
  function rememberPreparedTrigger(queue, retryKey, prepared) {
2021
- if (queue.preparedTriggers.has(retryKey)) queue.preparedTriggers.delete(retryKey);
1911
+ queue.preparedTriggers.delete(retryKey);
2022
1912
  setBoundedMap(queue.preparedTriggers, retryKey, prepared, maxPreparedTriggerEntries);
2023
1913
  return prepared;
2024
1914
  }
2025
- function computePendingHistory(queue, agentId, roomId, limit, endAbsExclusive = queue.baseIndex + queue.entries.length, startAbsOverride, threadRootId) {
2026
- if (limit <= 0 || queue.entries.length === 0) return [];
2027
- const key = wmKey(agentId, roomId, threadRootId);
2028
- const wm = startAbsOverride ?? agentWatermarks.get(key) ?? 0;
2029
- const startRel = Math.max(wm, queue.baseIndex) - queue.baseIndex;
2030
- const endRel = Math.max(startRel, Math.min(endAbsExclusive - queue.baseIndex, queue.entries.length));
2031
- const available = queue.entries.slice(startRel, endRel).filter((entry) => !entry.discarded && !entry.reserved && !entry.consumedBy?.has(key));
2032
- return available.length > limit ? available.slice(-limit) : available;
2033
- }
2034
1915
  function prepareTrigger(agentId, roomId, limit, entry, threadRootId, reservedSlot) {
2035
1916
  let slot = reservedSlot;
2036
1917
  const queue = getScopedQueue(roomId, threadRootId);
@@ -2047,8 +1928,20 @@ function createRoomHistoryTracker(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoom
2047
1928
  }
2048
1929
  }
2049
1930
  if (slot) queue.entries[slot.slotIdx - queue.baseIndex] = entry;
1931
+ const requestedEndAbsExclusive = slot?.slotIdx;
1932
+ const startAbsOverride = slot?.watermarkIdx;
1933
+ const endAbsExclusive = requestedEndAbsExclusive ?? queue.baseIndex + queue.entries.length;
1934
+ let history = [];
1935
+ if (!(limit <= 0 || queue.entries.length === 0)) {
1936
+ const key = wmKey(agentId, roomId, threadRootId);
1937
+ const wm = startAbsOverride ?? agentWatermarks.get(key) ?? 0;
1938
+ const startRel = Math.max(wm, queue.baseIndex) - queue.baseIndex;
1939
+ const endRel = Math.max(startRel, Math.min(endAbsExclusive - queue.baseIndex, queue.entries.length));
1940
+ const available = queue.entries.slice(startRel, endRel).filter((queued) => !queued.discarded && !queued.reserved && !queued.consumedBy?.has(key));
1941
+ history = available.length > limit ? available.slice(-limit) : available;
1942
+ }
2050
1943
  const prepared = {
2051
- history: computePendingHistory(queue, agentId, roomId, limit, slot?.slotIdx, slot?.watermarkIdx, threadRootId),
1944
+ history,
2052
1945
  ...slot ? { snapshotIdx: slot.slotIdx + 1 } : appendToQueue(queue, entry)
2053
1946
  };
2054
1947
  if (retryKey) return rememberPreparedTrigger(queue, retryKey, prepared);
@@ -2104,7 +1997,7 @@ function createRoomHistoryTracker(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoom
2104
1997
  }
2105
1998
  // extensions/matrix/src/matrix/monitor/handler-ingress-access.ts
2106
1999
  async function resolveMatrixIngressAccess(config) {
2107
- const { handler, params: paramsLocal, roomId, event, eventTs, senderId, isReactionEvent, readStoreAllowFrom, shouldSendPairingReply, resolveLiveAccountAllowlists, roomHistoryTracker, commitInboundEventIfClaimed } = config;
2000
+ const { handler, params: paramsLocal, roomId, event, eventTs, senderId, isReactionEvent, readStoreAllowFrom, shouldSendPairingReply, resolveLiveAccountAllowlists, roomHistoryTracker } = config;
2108
2001
  const { core, cfg, accountId, accountConfig, client, logVerboseMessage, groupPolicy, dmEnabled, dmPolicy, dmThreadReplies, threadReplies, roomsConfig, accountAllowBots, configuredBotUserIds, needsRoomAliasesForConfig, getRoomInfo, getMemberDisplayName } = handler;
2109
2002
  const content = paramsLocal.content;
2110
2003
  const isDirectMessage = paramsLocal.isDirectMessage;
@@ -2130,12 +2023,8 @@ async function resolveMatrixIngressAccess(config) {
2130
2023
  const markReservedHistorySlotConsumed = () => {
2131
2024
  reservedHistorySlotConsumed = true;
2132
2025
  };
2133
- const commitInboundEventIfClaimedAndDiscardReserved = async () => {
2134
- discardReservedHistorySlot();
2135
- await commitInboundEventIfClaimed();
2136
- };
2137
2026
  if (isRoom && groupPolicy === "disabled") {
2138
- await commitInboundEventIfClaimedAndDiscardReserved();
2027
+ discardReservedHistorySlot();
2139
2028
  return;
2140
2029
  }
2141
2030
  const roomInfoForConfig = isRoom && needsRoomAliasesForConfig ? await getRoomInfo(roomId, { includeAliases: true }) : void 0;
@@ -2151,7 +2040,7 @@ async function resolveMatrixIngressAccess(config) {
2151
2040
  const roomMatchMeta = roomConfigInfo ? `matchKey=${roomConfigInfo.matchKey ?? "none"} matchSource=${roomConfigInfo.matchSource ?? "none"}` : "matchKey=none matchSource=none";
2152
2041
  if (isConfiguredBotSender && allowBotsMode === "off") {
2153
2042
  logVerboseMessage(`matrix: drop configured bot sender=${senderId} (allowBots=false${isDirectMessage ? "" : `, ${roomMatchMeta}`})`);
2154
- await commitInboundEventIfClaimedAndDiscardReserved();
2043
+ discardReservedHistorySlot();
2155
2044
  return;
2156
2045
  }
2157
2046
  const botLoopProtection = isConfiguredBotSender && senderId !== selfUserId ? {
@@ -2166,18 +2055,18 @@ async function resolveMatrixIngressAccess(config) {
2166
2055
  } : void 0;
2167
2056
  if (isRoom && roomConfig && !roomConfigInfo?.allowed) {
2168
2057
  logVerboseMessage(`matrix: room disabled room=${roomId} (${roomMatchMeta})`);
2169
- await commitInboundEventIfClaimedAndDiscardReserved();
2058
+ discardReservedHistorySlot();
2170
2059
  return;
2171
2060
  }
2172
2061
  if (isRoom && groupPolicy === "allowlist") {
2173
2062
  if (!roomConfigInfo?.allowlistConfigured) {
2174
2063
  logVerboseMessage(`matrix: drop room message (no allowlist, ${roomMatchMeta})`);
2175
- await commitInboundEventIfClaimedAndDiscardReserved();
2064
+ discardReservedHistorySlot();
2176
2065
  return;
2177
2066
  }
2178
2067
  if (!roomConfig) {
2179
2068
  logVerboseMessage(`matrix: drop room message (not in allowlist, ${roomMatchMeta})`);
2180
- await commitInboundEventIfClaimedAndDiscardReserved();
2069
+ discardReservedHistorySlot();
2181
2070
  return;
2182
2071
  }
2183
2072
  }
@@ -2206,7 +2095,7 @@ async function resolveMatrixIngressAccess(config) {
2206
2095
  const ingressDecision = messageIngress.ingress;
2207
2096
  if (isDirectMessage) {
2208
2097
  if (!dmEnabled || dmPolicy === "disabled") {
2209
- await commitInboundEventIfClaimedAndDiscardReserved();
2098
+ discardReservedHistorySlot();
2210
2099
  return;
2211
2100
  }
2212
2101
  const senderReason = messageIngress.senderAccess.reasonCode;
@@ -2221,7 +2110,7 @@ async function resolveMatrixIngressAccess(config) {
2221
2110
  });
2222
2111
  if (!code) {
2223
2112
  logVerboseMessage(`matrix pairing request ignored sender=${senderId} (pending limit reached)`);
2224
- await commitInboundEventIfClaimedAndDiscardReserved();
2113
+ discardReservedHistorySlot();
2225
2114
  return;
2226
2115
  }
2227
2116
  if (shouldSendPairingReply(senderId, created)) {
@@ -2238,27 +2127,26 @@ async function resolveMatrixIngressAccess(config) {
2238
2127
  cfg,
2239
2128
  accountId
2240
2129
  });
2241
- await commitInboundEventIfClaimed();
2242
2130
  } catch (err) {
2243
2131
  logVerboseMessage(`matrix pairing reply failed for ${senderId}: ${String(err)}`);
2244
2132
  discardReservedHistorySlot();
2245
- return;
2133
+ throw err;
2246
2134
  }
2247
2135
  } else {
2248
2136
  logVerboseMessage(`matrix pairing reminder suppressed sender=${senderId} (cooldown)`);
2249
- await commitInboundEventIfClaimedAndDiscardReserved();
2137
+ discardReservedHistorySlot();
2250
2138
  }
2251
2139
  }
2252
2140
  if (isReactionEvent || dmPolicy !== "pairing") {
2253
2141
  logVerboseMessage(`matrix: blocked ${isReactionEvent ? "reaction" : "dm"} sender ${senderId} (dmPolicy=${dmPolicy}, reason=${senderReason})`);
2254
- await commitInboundEventIfClaimedAndDiscardReserved();
2142
+ discardReservedHistorySlot();
2255
2143
  }
2256
2144
  return;
2257
2145
  }
2258
2146
  }
2259
2147
  if (isRoom && ingressDecision.decision !== "allow") {
2260
2148
  logVerboseMessage(`matrix: blocked sender ${senderId} (ingress=${ingressDecision.reasonCode}, ${roomMatchMeta})`);
2261
- await commitInboundEventIfClaimedAndDiscardReserved();
2149
+ discardReservedHistorySlot();
2262
2150
  return;
2263
2151
  }
2264
2152
  if (isRoom) logVerboseMessage(`matrix: allow room ${roomId} (${roomMatchMeta})`);
@@ -2278,7 +2166,7 @@ async function resolveMatrixIngressAccess(config) {
2278
2166
  isDirectMessage,
2279
2167
  logVerboseMessage
2280
2168
  });
2281
- await commitInboundEventIfClaimedAndDiscardReserved();
2169
+ discardReservedHistorySlot();
2282
2170
  return;
2283
2171
  }
2284
2172
  return {
@@ -2296,7 +2184,6 @@ async function resolveMatrixIngressAccess(config) {
2296
2184
  historyThreadId,
2297
2185
  discardReservedHistorySlot,
2298
2186
  markReservedHistorySlotConsumed,
2299
- commitInboundEventIfClaimedAndDiscardReserved,
2300
2187
  roomConfig,
2301
2188
  allowBotsMode,
2302
2189
  isConfiguredBotSender,
@@ -2369,7 +2256,13 @@ function hasVisibleNativeMatrixUserMention(text, userId) {
2369
2256
  if (!text || !localpart) return false;
2370
2257
  return new RegExp(String.raw`(?:^|\p{White_Space})(?:${escapeRegExp(userId)}(?=$|\p{White_Space}|:\p{White_Space}|[,!?;](?=$|\p{White_Space}))|${escapeRegExp(`@${localpart}`)}(?=$|\p{White_Space}|:\p{White_Space}))`, "u").test(text);
2371
2258
  }
2372
- function resolveMatrixMentionPrefixCandidates(params) {
2259
+ function stripMatchedMatrixMentionPrefix(text, source, flags) {
2260
+ const match = text.match(new RegExp(`^\\s*${source}(?:\\s*[:,])?(?:\\s+|$)`, flags));
2261
+ return match ? text.slice(match[0].length).trimStart() : null;
2262
+ }
2263
+ function stripMatrixMentionPrefix(params) {
2264
+ const text = params.text;
2265
+ if (!text) return text;
2373
2266
  const candidates = [];
2374
2267
  const seen = /* @__PURE__ */ new Set();
2375
2268
  const localpart = params.userId ? resolveMatrixUserLocalpart(params.userId) : null;
@@ -2387,16 +2280,7 @@ function resolveMatrixMentionPrefixCandidates(params) {
2387
2280
  seen.add(normalized);
2388
2281
  candidates.push(trimmed);
2389
2282
  }
2390
- return candidates;
2391
- }
2392
- function stripMatchedMatrixMentionPrefix(text, source, flags) {
2393
- const match = text.match(new RegExp(`^\\s*${source}(?:\\s*[:,])?(?:\\s+|$)`, flags));
2394
- return match ? text.slice(match[0].length).trimStart() : null;
2395
- }
2396
- function stripMatrixMentionPrefix(params) {
2397
- const text = params.text;
2398
- if (!text) return text;
2399
- for (const candidate of resolveMatrixMentionPrefixCandidates(params)) {
2283
+ for (const candidate of candidates) {
2400
2284
  const stripped = stripMatchedMatrixMentionPrefix(text, escapeRegExp(candidate), "i");
2401
2285
  if (stripped !== null) return stripped;
2402
2286
  }
@@ -2406,63 +2290,52 @@ function stripMatrixMentionPrefix(params) {
2406
2290
  }
2407
2291
  return text;
2408
2292
  }
2409
- function isVisibleMentionLabel(params) {
2410
- const cleaned = extractVisibleMentionText(params.text);
2411
- if (!cleaned) return false;
2412
- if (params.mentionRegexes.some((pattern) => pattern.test(cleaned))) return true;
2413
- const localpart = resolveMatrixUserLocalpart(params.userId);
2414
- return [
2415
- extractVisibleMentionText(params.userId),
2416
- localpart ? extractVisibleMentionText(localpart) : null,
2417
- localpart ? extractVisibleMentionText(`@${localpart}`) : null,
2418
- params.displayName ? extractVisibleMentionText(params.displayName) : null,
2419
- params.displayName ? extractVisibleMentionText(`@${params.displayName}`) : null,
2420
- params.displayName ? extractVisibleMentionText(`@[${params.displayName}]`) : null
2421
- ].filter((value) => Boolean(value)).includes(cleaned);
2422
- }
2423
2293
  function hasVisibleRoomMention(value) {
2424
2294
  const cleaned = extractVisibleMentionText(value);
2425
2295
  return /(^|[^a-z0-9_])@room\b/i.test(cleaned);
2426
2296
  }
2427
- /**
2428
- * Check if formatted_body contains a matrix.to link whose visible label still
2429
- * looks like a real mention for the given user. Do not trust href alone, since
2430
- * senders can hide arbitrary matrix.to links behind unrelated link text.
2431
- * Many Matrix clients (including Element) use HTML links in formatted_body instead of
2432
- * or in addition to the m.mentions field.
2433
- */
2434
- function checkFormattedBodyMention(params) {
2435
- if (!params.formattedBody || !params.userId) return false;
2436
- for (const match of params.formattedBody.matchAll(/<a\b[^>]*href=(["'])(https:\/\/matrix\.to\/#[^"']+)\1[^>]*>(.*?)<\/a>/gis)) {
2437
- const href = match[2];
2438
- const visibleLabel = match[3] ?? "";
2439
- if (!href) continue;
2440
- try {
2441
- const parsed = new URL(href);
2442
- if (decodeURIComponent(parsed.hash.replace(/^#\/?/, "").trim()) !== params.userId.trim()) continue;
2443
- if (isVisibleMentionLabel({
2444
- text: visibleLabel,
2445
- userId: params.userId,
2446
- mentionRegexes: params.mentionRegexes,
2447
- displayName: params.displayName
2448
- })) return true;
2449
- } catch {
2450
- continue;
2451
- }
2452
- }
2453
- return false;
2454
- }
2455
2297
  function resolveMentions(params) {
2456
2298
  const mentions = params.content["m.mentions"];
2457
2299
  const mentionedUsers = Array.isArray(mentions?.user_ids) ? new Set(mentions.user_ids) : /* @__PURE__ */ new Set();
2458
2300
  const textMentioned = getMatrixRuntime().channel.mentions.matchesMentionPatterns(params.text ?? "", params.mentionRegexes);
2459
2301
  const visibleRoomMention = hasVisibleRoomMention(params.text) || hasVisibleRoomMention(params.content.formatted_body);
2460
- const mentionedInFormattedBody = params.userId ? checkFormattedBodyMention({
2461
- formattedBody: params.content.formatted_body,
2462
- userId: params.userId,
2463
- displayName: params.displayName,
2464
- mentionRegexes: params.mentionRegexes
2465
- }) : false;
2302
+ /**
2303
+ * Check if formatted_body contains a matrix.to link whose visible label still
2304
+ * looks like a real mention for the given user. Do not trust href alone, since
2305
+ * senders can hide arbitrary matrix.to links behind unrelated link text.
2306
+ * Many Matrix clients (including Element) use HTML links in formatted_body instead of
2307
+ * or in addition to the m.mentions field.
2308
+ */
2309
+ function checkFormattedBodyMention(userId) {
2310
+ const formattedBody = params.content.formatted_body;
2311
+ const { displayName, mentionRegexes } = params;
2312
+ if (!formattedBody || !userId) return false;
2313
+ for (const match of formattedBody.matchAll(/<a\b[^>]*href=(["'])(https:\/\/matrix\.to\/#[^"']+)\1[^>]*>(.*?)<\/a>/gis)) {
2314
+ const href = match[2];
2315
+ const visibleLabel = match[3] ?? "";
2316
+ if (!href) continue;
2317
+ try {
2318
+ const parsed = new URL(href);
2319
+ if (decodeURIComponent(parsed.hash.replace(/^#\/?/, "").trim()) !== userId.trim()) continue;
2320
+ const cleaned = extractVisibleMentionText(visibleLabel);
2321
+ if (!cleaned) continue;
2322
+ if (mentionRegexes.some((pattern) => pattern.test(cleaned))) return true;
2323
+ const localpart = resolveMatrixUserLocalpart(userId);
2324
+ if ([
2325
+ extractVisibleMentionText(userId),
2326
+ localpart ? extractVisibleMentionText(localpart) : null,
2327
+ localpart ? extractVisibleMentionText(`@${localpart}`) : null,
2328
+ displayName ? extractVisibleMentionText(displayName) : null,
2329
+ displayName ? extractVisibleMentionText(`@${displayName}`) : null,
2330
+ displayName ? extractVisibleMentionText(`@[${displayName}]`) : null
2331
+ ].filter((value) => Boolean(value)).includes(cleaned)) return true;
2332
+ } catch {
2333
+ continue;
2334
+ }
2335
+ }
2336
+ return false;
2337
+ }
2338
+ const mentionedInFormattedBody = params.userId ? checkFormattedBodyMention(params.userId) : false;
2466
2339
  const metadataBackedUserMention = Boolean(params.userId && mentionedUsers.has(params.userId) && (mentionedInFormattedBody || textMentioned || hasVisibleNativeMatrixUserMention(params.text, params.userId)));
2467
2340
  const metadataBackedRoomMention = Boolean(mentions?.room) && visibleRoomMention;
2468
2341
  const explicitMention = mentionedInFormattedBody || metadataBackedUserMention || metadataBackedRoomMention;
@@ -2473,9 +2346,9 @@ function resolveMentions(params) {
2473
2346
  }
2474
2347
  // extensions/matrix/src/matrix/monitor/handler-ingress-content.ts
2475
2348
  async function resolveMatrixIngressContent(config) {
2476
- const { handler, params: paramsLocal, access, roomId, event, eventType, isPollEvent, eventTs, senderId, roomHistoryTracker, resolveThreadContext, commitInboundEventIfClaimed } = config;
2349
+ const { handler, params: paramsLocal, access, roomId, event, eventType, isPollEvent, eventTs, senderId, roomHistoryTracker, resolveThreadContext } = config;
2477
2350
  const { client, core, accountId, accountConfig, logger, logVerboseMessage, historyLimit, mediaMaxBytes, dmSessionScope, getMemberDisplayName } = handler;
2478
- const { cfg, content: accessContent, messageId, audioPreflightMode, isDirectMessage, isRoom, locationPayload, reservedHistorySlot, threadRootId, thread, historyThreadId, discardReservedHistorySlot, markReservedHistorySlotConsumed, commitInboundEventIfClaimedAndDiscardReserved, roomConfig, allowBotsMode, isConfiguredBotSender, selfUserId, roomMatchMeta, getSenderName, accessState } = access;
2351
+ const { cfg, content: accessContent, messageId, audioPreflightMode, isDirectMessage, isRoom, locationPayload, reservedHistorySlot, threadRootId, thread, historyThreadId, discardReservedHistorySlot, markReservedHistorySlotConsumed, roomConfig, allowBotsMode, isConfiguredBotSender, selfUserId, roomMatchMeta, getSenderName, accessState } = access;
2479
2352
  const { resolveMessageIngress } = accessState;
2480
2353
  let content = accessContent;
2481
2354
  let pollSnapshotPromise = null;
@@ -2501,7 +2374,7 @@ async function resolveMatrixIngressContent(config) {
2501
2374
  });
2502
2375
  const pendingHistoryPollText = !pendingHistoryText && isPollEvent && historyLimit > 0 ? (await getPollSnapshot())?.text : "";
2503
2376
  if (!mentionPrecheckText && !mediaUrl && !isPollEvent) {
2504
- await commitInboundEventIfClaimedAndDiscardReserved();
2377
+ discardReservedHistorySlot();
2505
2378
  return;
2506
2379
  }
2507
2380
  let preflightMedia = null;
@@ -2565,16 +2438,23 @@ async function resolveMatrixIngressContent(config) {
2565
2438
  }
2566
2439
  if (shouldRunMatrixAudioPreflight) {
2567
2440
  preflightMedia = await downloadMedia(preflightAudioMediaUrl);
2568
- if (preflightMedia) preflightAudioTranscript = await resolveMatrixPreflightAudioTranscript({
2569
- mediaPath: preflightMedia.path,
2570
- mediaContentType: preflightMedia.contentType,
2571
- cfg,
2572
- accountId,
2573
- chatType: isDirectMessage ? "direct" : "channel",
2574
- originatingTo: `room:${roomId}`,
2575
- messageThreadId: thread.threadId,
2576
- sessionKey: _route.sessionKey
2577
- });
2441
+ if (preflightMedia) preflightAudioTranscript = await matrixPreflightAudio.resolve({ request: {
2442
+ ctx: {
2443
+ media: [{
2444
+ path: preflightMedia.path,
2445
+ contentType: preflightMedia.contentType
2446
+ }],
2447
+ Provider: "matrix",
2448
+ Surface: "matrix",
2449
+ OriginatingChannel: "matrix",
2450
+ OriginatingTo: `room:${roomId}`,
2451
+ AccountId: accountId,
2452
+ MessageThreadId: thread.threadId,
2453
+ ChatType: isDirectMessage ? "direct" : "channel",
2454
+ SessionKey: _route.sessionKey
2455
+ },
2456
+ cfg
2457
+ } });
2578
2458
  }
2579
2459
  const agentMentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, _route.agentId, {
2580
2460
  provider: "matrix",
@@ -2592,7 +2472,7 @@ async function resolveMatrixIngressContent(config) {
2592
2472
  });
2593
2473
  if (isConfiguredBotSender && allowBotsMode === "mentions" && !isDirectMessage && !wasMentioned) {
2594
2474
  logVerboseMessage(`matrix: drop configured bot sender=${senderId} (allowBots=mentions, missing mention, ${roomMatchMeta})`);
2595
- await commitInboundEventIfClaimedAndDiscardReserved();
2475
+ discardReservedHistorySlot();
2596
2476
  return;
2597
2477
  }
2598
2478
  const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
@@ -2607,7 +2487,6 @@ async function resolveMatrixIngressContent(config) {
2607
2487
  });
2608
2488
  const hasControlCommandInMessage = core.channel.text.hasControlCommand(commandCheckText, cfg);
2609
2489
  const commandAccess = await resolveMatrixMonitorCommandAccess(accessState, {
2610
- useAccessGroups: true,
2611
2490
  allowTextCommands,
2612
2491
  hasControlCommand: hasControlCommandInMessage
2613
2492
  });
@@ -2619,7 +2498,7 @@ async function resolveMatrixIngressContent(config) {
2619
2498
  reason: "control command (unauthorized)",
2620
2499
  target: senderId
2621
2500
  });
2622
- await commitInboundEventIfClaimedAndDiscardReserved();
2501
+ discardReservedHistorySlot();
2623
2502
  return;
2624
2503
  }
2625
2504
  const configuredRequireMention = isRoom ? roomConfig?.autoReply === true ? false : roomConfig?.autoReply === false ? true : typeof roomConfig?.requireMention === "boolean" ? roomConfig?.requireMention : true : false;
@@ -2667,7 +2546,6 @@ async function resolveMatrixIngressContent(config) {
2667
2546
  roomId,
2668
2547
  reason: "no-mention"
2669
2548
  });
2670
- await commitInboundEventIfClaimed();
2671
2549
  return;
2672
2550
  }
2673
2551
  if (preflightAudioTranscript) await matrixPreflightAudio.send({
@@ -2692,40 +2570,47 @@ async function resolveMatrixIngressContent(config) {
2692
2570
  let media = preflightMedia;
2693
2571
  const finalMediaUrl = mediaContent.url;
2694
2572
  if (!media && !mediaDownloadFailed && finalMediaUrl?.startsWith("mxc://")) media = await downloadMedia(finalMediaUrl);
2695
- let bodyText = resolveMatrixInboundBodyText({
2696
- rawBody: locationPayload?.text ?? mediaContent.body,
2697
- filename: typeof content.filename === "string" ? content.filename : void 0,
2698
- mediaPlaceholder: media?.placeholder,
2573
+ const rawBody = locationPayload?.text ?? mediaContent.body;
2574
+ const filename = typeof content.filename === "string" ? content.filename : void 0;
2575
+ const mediaPlaceholder = media?.placeholder;
2576
+ let bodyText = rawBody;
2577
+ if (mediaPlaceholder) {
2578
+ bodyText = rawBody || mediaPlaceholder;
2579
+ if (filename?.trim()) {
2580
+ const attachment = resolveMatrixMessageAttachment({
2581
+ body: rawBody,
2582
+ filename,
2583
+ msgtype: content.msgtype
2584
+ });
2585
+ if (attachment && !attachment.caption) bodyText = mediaPlaceholder;
2586
+ }
2587
+ } else if (mediaDownloadFailed && Boolean(finalMediaUrl)) bodyText = formatMatrixMessageText({
2588
+ body: rawBody,
2589
+ filename,
2699
2590
  msgtype: content.msgtype,
2700
- hadMediaUrl: Boolean(finalMediaUrl),
2701
- mediaDownloadFailed,
2702
- mediaSizeLimitExceeded
2703
- });
2591
+ tooLarge: mediaSizeLimitExceeded,
2592
+ unavailable: true
2593
+ }) ?? "";
2704
2594
  if (preflightMedia && bodyText && bodyText !== preflightMedia.placeholder && isLikelyBareFilename(bodyText)) bodyText = preflightMedia.placeholder;
2705
2595
  if (preflightAudioTranscript) {
2706
2596
  const transcriptBody = formatAudioTranscriptForAgent(preflightAudioTranscript);
2707
2597
  bodyText = !bodyText || bodyText === media?.placeholder ? transcriptBody : `${bodyText}\n${transcriptBody}`;
2708
2598
  }
2709
2599
  if (!bodyText) {
2710
- await commitInboundEventIfClaimedAndDiscardReserved();
2600
+ discardReservedHistorySlot();
2711
2601
  return;
2712
2602
  }
2713
2603
  const commandBodyText = hasControlCommandInMessage ? commandCheckText : bodyText;
2714
2604
  const senderName = await getSenderName();
2715
2605
  if (_configuredBinding) {
2716
2606
  const { ensureConfiguredAcpBindingReady } = await loadAcpBindingRuntime();
2717
- if (!(await ensureConfiguredAcpBindingReady({
2607
+ const ensured = await ensureConfiguredAcpBindingReady({
2718
2608
  cfg,
2719
2609
  configuredBinding: _configuredBinding
2720
- })).ok) {
2721
- logInboundDrop({
2722
- log: logVerboseMessage,
2723
- channel: "matrix",
2724
- reason: "configured ACP binding unavailable",
2725
- target: _configuredBinding.spec.conversationId
2726
- });
2610
+ });
2611
+ if (!ensured.ok) {
2727
2612
  discardReservedHistorySlot();
2728
- return;
2613
+ throw new Error(`Matrix configured ACP binding is unavailable: ${ensured.error}`);
2729
2614
  }
2730
2615
  }
2731
2616
  if (_runtimeBindingId) {
@@ -2768,113 +2653,7 @@ async function resolveMatrixIngressContent(config) {
2768
2653
  threadContext
2769
2654
  };
2770
2655
  }
2771
- // extensions/matrix/src/matrix/monitor/location.ts
2772
- function decodeGeoUriParamValue(value) {
2773
- try {
2774
- return decodeURIComponent(value);
2775
- } catch {
2776
- return value;
2777
- }
2778
- }
2779
- function parseGeoUri(value) {
2780
- if (!value.toLowerCase().startsWith("geo:")) return null;
2781
- const [coordsPart, ...paramParts] = value.slice(4).split(";");
2782
- if (!coordsPart) return null;
2783
- const coords = coordsPart.split(",");
2784
- if (coords.length < 2) return null;
2785
- const latitude = parseStrictFiniteNumber(coords[0] ?? "");
2786
- const longitude = parseStrictFiniteNumber(coords[1] ?? "");
2787
- if (latitude === void 0 || longitude === void 0) return null;
2788
- const params = /* @__PURE__ */ new Map();
2789
- for (const part of paramParts) {
2790
- const segment = part.trim();
2791
- if (!segment) continue;
2792
- const eqIndex = segment.indexOf("=");
2793
- const rawKey = eqIndex === -1 ? segment : segment.slice(0, eqIndex);
2794
- const rawValue = eqIndex === -1 ? "" : segment.slice(eqIndex + 1);
2795
- const key = normalizeLowercaseStringOrEmpty(rawKey);
2796
- if (!key) continue;
2797
- const valuePart = rawValue.trim();
2798
- params.set(key, valuePart ? decodeGeoUriParamValue(valuePart) : "");
2799
- }
2800
- const accuracyRaw = params.get("u");
2801
- return {
2802
- latitude,
2803
- longitude,
2804
- accuracy: accuracyRaw ? parseStrictFiniteNumber(accuracyRaw) : void 0
2805
- };
2806
- }
2807
- function resolveMatrixLocation(params) {
2808
- const { eventType, content } = params;
2809
- if (!(eventType === EventType.Location || eventType === EventType.RoomMessage && content.msgtype === EventType.Location)) return null;
2810
- const geoUri = normalizeOptionalString(content.geo_uri) ?? "";
2811
- if (!geoUri) return null;
2812
- const parsed = parseGeoUri(geoUri);
2813
- if (!parsed) return null;
2814
- const caption = normalizeOptionalString(content.body) ?? "";
2815
- const location = {
2816
- latitude: parsed.latitude,
2817
- longitude: parsed.longitude,
2818
- accuracy: parsed.accuracy,
2819
- caption: caption || void 0,
2820
- source: "pin",
2821
- isLive: false
2822
- };
2823
- return {
2824
- text: formatLocationText(location),
2825
- context: toLocationContext(location)
2826
- };
2827
- }
2828
- // extensions/matrix/src/matrix/monitor/handler-ingress-prefix.ts
2829
- async function readMatrixIngressPrefix(config) {
2830
- const { client, senderId, dropPreStartupMessages, eventTs, eventAge, startupMs, event, eventType, eventId, inboundDeduper, roomId, logVerboseMessage, directTracker, claimInboundReplay } = config;
2831
- const selfUserId = await client.getUserId();
2832
- if (senderId === selfUserId) return;
2833
- if (dropPreStartupMessages) {
2834
- if (typeof eventTs === "number" && eventTs < startupMs) return;
2835
- if (typeof eventTs !== "number" && typeof eventAge === "number" && eventAge > 0) return;
2836
- }
2837
- const content = event.content;
2838
- if (eventType === EventType.RoomMessage && isMatrixVerificationRoomMessage({
2839
- msgtype: content.msgtype,
2840
- body: content.body
2841
- })) {
2842
- logVerboseMessage(`matrix: skip verification/system room message room=${roomId}`);
2843
- return;
2844
- }
2845
- const locationPayload = resolveMatrixLocation({
2846
- eventType,
2847
- content
2848
- });
2849
- const relates = content["m.relates_to"];
2850
- if (relates && "rel_type" in relates && relates.rel_type === RelationType.Replace) return;
2851
- if (hasBundledMatrixReplacementRelation(event)) return;
2852
- if (eventId && inboundDeduper) {
2853
- const claim = await inboundDeduper.claim({
2854
- roomId,
2855
- eventId
2856
- });
2857
- if (claim.kind === "claimed") claimInboundReplay(claim.handle);
2858
- else if (claim.kind !== "invalid") {
2859
- logVerboseMessage(`matrix: skip duplicate inbound event room=${roomId} id=${eventId}`);
2860
- return;
2861
- }
2862
- }
2863
- return {
2864
- content,
2865
- isDirectMessage: await directTracker.isDirectMessage({
2866
- roomId,
2867
- senderId,
2868
- selfUserId
2869
- }),
2870
- locationPayload,
2871
- selfUserId
2872
- };
2873
- }
2874
- // extensions/matrix/src/matrix/monitor/replies.ts
2875
- function joinMatrixVisibleContent(contents) {
2876
- return contents.filter((content) => Boolean(content)).join("\n");
2877
- }
2656
+ // extensions/matrix/src/matrix/monitor/handler-reply-dispatcher.ts
2878
2657
  function mergeMatrixReplyDeliveryResults(results) {
2879
2658
  const single = results.length === 1 ? results[0] : void 0;
2880
2659
  if (single?.visibleReplySent) return single;
@@ -2883,7 +2662,7 @@ function mergeMatrixReplyDeliveryResults(results) {
2883
2662
  visibleReplySent: false,
2884
2663
  suppression: { reason: "no_visible_result" }
2885
2664
  };
2886
- const content = joinMatrixVisibleContent(visibleResults.map((result) => result.content));
2665
+ const content = visibleResults.map((result) => result.content).filter(Boolean).join("\n");
2887
2666
  if (visibleResults.some((result) => result.receipt || result.messageIds?.length)) return createAcceptedChannelDeliveryResult({
2888
2667
  deliveryResults: visibleResults,
2889
2668
  content
@@ -2912,83 +2691,63 @@ function resolveVisibleMatrixReplyText(text) {
2912
2691
  });
2913
2692
  return visibleText.trim() ? visibleText : void 0;
2914
2693
  }
2915
- async function deliverMatrixReplies(params) {
2916
- const core = getMatrixRuntime();
2917
- const logVerbose = (message) => {
2918
- if (core.logging.shouldLogVerbose()) params.runtime.log?.(message);
2919
- };
2920
- const hasRepliedRef = params.hasRepliedRef ?? { value: false };
2921
- const accepted = createChannelDeliveryAccumulator();
2922
- try {
2923
- for (const reply of params.replies) {
2924
- const visibleText = resolveVisibleMatrixReplyText(reply.text);
2925
- const { hasMedia, hasText, mediaUrls } = resolveSendableOutboundReplyParts(reply);
2926
- if (reply.isReasoning === true || !hasMedia && reply.text && visibleText === void 0) {
2927
- logVerbose("matrix reply suppressed as reasoning-only");
2928
- continue;
2929
- }
2930
- if (!hasText && !hasMedia) {
2931
- if (reply?.audioAsVoice) {
2932
- logVerbose("matrix reply has audioAsVoice without media/text; skipping");
2933
- continue;
2934
- }
2935
- params.runtime.error?.("matrix reply missing text/media");
2936
- continue;
2937
- }
2938
- const explicitReplyToId = reply.replyToTag || reply.replyToCurrent ? reply.replyToId?.trim() : void 0;
2939
- const rawText = visibleText ?? "";
2940
- const replyToIdForReply = explicitReplyToId || (!params.threadId && params.replyToMode !== "off" && (params.replyToMode === "all" || !hasRepliedRef.value) ? (reply.replyToId ?? params.replyToId)?.trim() : void 0);
2941
- const fallbackReplyToId = params.threadId ? (reply.replyToId ?? params.replyToId)?.trim() : void 0;
2942
- const onDeliveryResult = (result) => {
2943
- accepted.add({ receipt: result.receipt }, result.content);
2944
- if (replyToIdForReply) hasRepliedRef.value = true;
2945
- };
2946
- const extraContent = resolveMatrixExtraContent(reply);
2947
- const targets = mediaUrls.length > 0 ? mediaUrls : [void 0];
2948
- for (const [index, mediaUrl] of targets.entries()) await sendMessageMatrix(params.roomId, index === 0 ? rawText : "", {
2949
- client: params.client,
2950
- cfg: params.cfg,
2694
+ function createMatrixReplyDispatcher(config) {
2695
+ const { cfg, prefixOptions, humanDelay, typingCallbacks, streaming, draftStream, draftController, client, roomId, runtime, replyToMode, threadTarget, replyToEventId, accountId, mediaLocalRoots, logVerboseMessage } = config;
2696
+ const quietDraftStreaming = streaming === "quiet" || streaming === "progress";
2697
+ let hasReplied = false;
2698
+ const deliverPayload = async (reply) => {
2699
+ const core = getMatrixRuntime();
2700
+ const logVerbose = (message) => {
2701
+ if (core.logging.shouldLogVerbose()) runtime.log?.(message);
2702
+ };
2703
+ const accepted = createChannelDeliveryAccumulator();
2704
+ const visibleText = resolveVisibleMatrixReplyText(reply.text);
2705
+ const { hasMedia, hasText, mediaUrls } = resolveSendableOutboundReplyParts(reply);
2706
+ if (reply.isReasoning === true || !hasMedia && reply.text && visibleText === void 0) {
2707
+ logVerbose("matrix reply suppressed as reasoning-only");
2708
+ return accepted.result();
2709
+ }
2710
+ if (!hasText && !hasMedia) {
2711
+ if (reply.audioAsVoice) logVerbose("matrix reply has audioAsVoice without media/text; skipping");
2712
+ else runtime.error?.("matrix reply missing text/media");
2713
+ return accepted.result();
2714
+ }
2715
+ const explicitReplyToId = reply.replyToTag || reply.replyToCurrent ? reply.replyToId?.trim() : void 0;
2716
+ const ambientReplyToId = threadTarget ?? replyToEventId;
2717
+ const replyToIdForReply = explicitReplyToId || (!threadTarget && replyToMode !== "off" && (replyToMode === "all" || !hasReplied) ? (reply.replyToId ?? ambientReplyToId)?.trim() : void 0);
2718
+ const fallbackReplyToId = threadTarget ? (reply.replyToId ?? ambientReplyToId)?.trim() : void 0;
2719
+ const onDeliveryResult = (result) => {
2720
+ accepted.add({ receipt: result.receipt }, result.content);
2721
+ if (replyToIdForReply) hasReplied = true;
2722
+ };
2723
+ const extraContent = resolveMatrixExtraContent(reply);
2724
+ const targets = mediaUrls.length > 0 ? mediaUrls : [void 0];
2725
+ try {
2726
+ for (const [index, mediaUrl] of targets.entries()) await sendMessageMatrix(roomId, index === 0 ? visibleText ?? "" : "", {
2727
+ client,
2728
+ cfg,
2951
2729
  ...mediaUrl !== void 0 ? {
2952
2730
  mediaUrl,
2953
- mediaLocalRoots: params.mediaLocalRoots,
2731
+ mediaLocalRoots,
2954
2732
  audioAsVoice: reply.audioAsVoice
2955
2733
  } : {},
2956
2734
  replyToId: replyToIdForReply,
2957
2735
  fallbackReplyToId,
2958
- threadId: params.threadId,
2959
- accountId: params.accountId,
2736
+ threadId: threadTarget,
2737
+ accountId,
2960
2738
  extraContent: index === 0 ? extraContent : void 0,
2961
2739
  onDeliveryResult
2962
2740
  });
2741
+ } catch (error) {
2742
+ throw toMatrixPartialDeliveryError(error, [accepted.result()]);
2963
2743
  }
2964
- } catch (error) {
2965
- throw toMatrixPartialDeliveryError(error, [accepted.result()]);
2966
- }
2967
- return accepted.result();
2968
- }
2969
- // extensions/matrix/src/matrix/monitor/handler-reply-dispatcher.ts
2970
- function createMatrixReplyDispatcher(config) {
2971
- const { cfg, prefixOptions, humanDelay, typingCallbacks, streaming, draftStream, draftController, client, roomId, runtime, replyToMode, threadTarget, replyToEventId, accountId, mediaLocalRoots, logVerboseMessage } = config;
2972
- const quietDraftStreaming = streaming === "quiet" || streaming === "progress";
2973
- const hasRepliedRef = { value: false };
2974
- const deliverPayload = (reply) => deliverMatrixReplies({
2975
- cfg,
2976
- replies: [reply],
2977
- roomId,
2978
- client,
2979
- runtime,
2980
- replyToMode,
2981
- hasRepliedRef,
2982
- threadId: threadTarget,
2983
- replyToId: threadTarget ?? replyToEventId ?? void 0,
2984
- accountId,
2985
- mediaLocalRoots
2986
- });
2744
+ return accepted.result();
2745
+ };
2987
2746
  const { previewLifecycle } = draftController;
2988
2747
  let nonFinalReplyDeliveryFailed = false;
2989
- const beginNextBlockDraft = () => {
2748
+ const beginNextBlockDraft = (boundary) => {
2990
2749
  draftController.beginDraftGeneration();
2991
- draftController.advanceDraftBlockBoundary({ fallbackToLatestEnd: true });
2750
+ draftController.advanceDraftBlockBoundary(boundary);
2992
2751
  draftStream?.reset();
2993
2752
  draftController.resetReplyToIdForNextBlock();
2994
2753
  draftController.updateDraftFromLatestFullText();
@@ -3023,6 +2782,7 @@ function createMatrixReplyDispatcher(config) {
3023
2782
  } : payload;
3024
2783
  const { hasMedia } = resolveSendableOutboundReplyParts(payload);
3025
2784
  const payloadText = payload.text ?? ttsSupplement?.spokenText;
2785
+ const blockBoundary = info.kind === "block" && !payload.isCompactionNotice ? draftController.captureDraftBlockBoundary(payloadText, info) : void 0;
3026
2786
  const payloadReplyMismatch = (!threadTarget && replyToMode !== "off" || payload.replyToTag || payload.replyToCurrent) && normalizeOptionalString(payload.replyToId) !== draftController.currentReplyToId();
3027
2787
  let retainedDraftDelivery;
3028
2788
  let deliveryResult;
@@ -3052,8 +2812,7 @@ function createMatrixReplyDispatcher(config) {
3052
2812
  });
3053
2813
  return createDraftDeliveryResult(draftEventId, prepareMatrixSingleText(edit.text, {
3054
2814
  cfg,
3055
- accountId,
3056
- preserveWhitespace: true
2815
+ accountId
3057
2816
  }).convertedText);
3058
2817
  },
3059
2818
  createPreviewReceipt: createDraftReceipt,
@@ -3077,12 +2836,17 @@ function createMatrixReplyDispatcher(config) {
3077
2836
  })).deliveryResult;
3078
2837
  } catch (error) {
3079
2838
  if (retainedDraftDelivery) previewLifecycle.retainPreview();
2839
+ if (blockBoundary) beginNextBlockDraft(retainedDraftDelivery ? {
2840
+ ...blockBoundary,
2841
+ messageGeneration: blockBoundary.previewMessageGeneration,
2842
+ endOffset: blockBoundary.messageGeneration === blockBoundary.previewMessageGeneration ? Math.max(blockBoundary.endOffset, blockBoundary.previewEndOffset) : blockBoundary.previewEndOffset
2843
+ } : blockBoundary);
3080
2844
  throw toMatrixPartialDeliveryError(error, retainedDraftDelivery ? [retainedDraftDelivery] : []);
3081
2845
  }
3082
2846
  if (retainedDraftDelivery && !deliveryResult?.visibleReplySent) previewLifecycle.retainPreview();
3083
2847
  const mergedDelivery = mergeMatrixReplyDeliveryResults([retainedDraftDelivery?.messageIds?.includes(draftStream?.eventId() ?? "") ? retainedDraftDelivery : void 0, deliveryResult].filter((result) => result !== void 0));
3084
- if (info.kind === "block") {
3085
- beginNextBlockDraft();
2848
+ if (blockBoundary) {
2849
+ beginNextBlockDraft(blockBoundary);
3086
2850
  await typingCallbacks.onReplyStart();
3087
2851
  }
3088
2852
  return mergedDelivery;
@@ -3090,7 +2854,6 @@ function createMatrixReplyDispatcher(config) {
3090
2854
  onReplyError: (err, info) => {
3091
2855
  if (info.kind === "final") previewLifecycle.observeFailure();
3092
2856
  else nonFinalReplyDeliveryFailed = true;
3093
- if (info.kind === "block") beginNextBlockDraft();
3094
2857
  runtime.error?.(`matrix ${info.kind} reply failed: ${String(err)}`);
3095
2858
  },
3096
2859
  nonFinalReplyDeliveryFailed: () => nonFinalReplyDeliveryFailed
@@ -3101,7 +2864,7 @@ const ALLOW_FROM_STORE_CACHE_TTL_MS = 3e4;
3101
2864
  const PAIRING_REPLY_COOLDOWN_MS = 3e5;
3102
2865
  const MAX_TRACKED_PAIRING_REPLY_SENDERS = 512;
3103
2866
  function createMatrixHandlerState(config) {
3104
- const { core, accountId, runtime, allowFromResolvedEntries, groupAllowFromResolvedEntries, resolveLiveUserAllowlist } = config;
2867
+ const { core, accountId, runtime, allowFromResolvedEntries, groupAllowFromResolvedEntries } = config;
3105
2868
  let cachedStoreAllowFrom = null;
3106
2869
  const liveAllowlistCache = /* @__PURE__ */ new Map();
3107
2870
  const resolveCachedLiveAllowlist = async (paramsValue) => {
@@ -3116,7 +2879,7 @@ function createMatrixHandlerState(config) {
3116
2879
  });
3117
2880
  const cached = liveAllowlistCache.get(paramsValue.scope);
3118
2881
  if (cached?.signature === signature) return cached.entries;
3119
- const entries = await resolveLiveUserAllowlist({
2882
+ const entries = await resolveMatrixMonitorLiveUserAllowlist({
3120
2883
  cfg: paramsValue.cfg,
3121
2884
  accountId,
3122
2885
  entries: paramsValue.entries,
@@ -3156,24 +2919,23 @@ function createMatrixHandlerState(config) {
3156
2919
  };
3157
2920
  const readStoreAllowFrom = async () => {
3158
2921
  const now = Date.now();
3159
- if (cachedStoreAllowFrom && isFutureDateTimestampMs(cachedStoreAllowFrom.expiresAtMs, { nowMs: now })) return cachedStoreAllowFrom.value;
2922
+ if (cachedStoreAllowFrom && cachedStoreAllowFrom.expiresAtMs > now) return cachedStoreAllowFrom.value;
3160
2923
  cachedStoreAllowFrom = null;
3161
2924
  const value = await core.channel.pairing.readAllowFromStore({
3162
2925
  channel: "matrix",
3163
2926
  env: process.env,
3164
2927
  accountId
3165
2928
  }).catch(() => []);
3166
- const expiresAtMs = resolveExpiresAtMsFromDurationMs(ALLOW_FROM_STORE_CACHE_TTL_MS, { nowMs: now });
3167
- cachedStoreAllowFrom = expiresAtMs === void 0 ? null : {
2929
+ cachedStoreAllowFrom = {
3168
2930
  value,
3169
- expiresAtMs
2931
+ expiresAtMs: now + ALLOW_FROM_STORE_CACHE_TTL_MS
3170
2932
  };
3171
2933
  return value;
3172
2934
  };
3173
2935
  const shouldSendPairingReply = (senderId, created) => {
3174
2936
  const now = Date.now();
3175
2937
  const lastSentAtMs = pairingReplySentAtMsBySender.get(senderId);
3176
- if (!created && typeof lastSentAtMs === "number" && now - lastSentAtMs < PAIRING_REPLY_COOLDOWN_MS) return false;
2938
+ if (!created && lastSentAtMs !== void 0 && now - lastSentAtMs < PAIRING_REPLY_COOLDOWN_MS) return false;
3177
2939
  setBoundedMap(pairingReplySentAtMsBySender, senderId, now, MAX_TRACKED_PAIRING_REPLY_SENDERS);
3178
2940
  return true;
3179
2941
  };
@@ -3183,28 +2945,70 @@ function createMatrixHandlerState(config) {
3183
2945
  shouldSendPairingReply
3184
2946
  };
3185
2947
  }
2948
+ // extensions/matrix/src/matrix/monitor/location.ts
2949
+ function decodeGeoUriParamValue(value) {
2950
+ try {
2951
+ return decodeURIComponent(value);
2952
+ } catch {
2953
+ return value;
2954
+ }
2955
+ }
2956
+ function resolveMatrixLocation(params) {
2957
+ const { eventType, content } = params;
2958
+ if (!(eventType === EventType.Location || eventType === EventType.RoomMessage && content.msgtype === EventType.Location)) return null;
2959
+ const geoUri = normalizeOptionalString(content.geo_uri) ?? "";
2960
+ if (!geoUri) return null;
2961
+ if (!geoUri.toLowerCase().startsWith("geo:")) return null;
2962
+ const [coordsPart, ...paramParts] = geoUri.slice(4).split(";");
2963
+ if (!coordsPart) return null;
2964
+ const coords = coordsPart.split(",");
2965
+ if (coords.length < 2) return null;
2966
+ const latitude = parseStrictFiniteNumber(coords[0] ?? "");
2967
+ const longitude = parseStrictFiniteNumber(coords[1] ?? "");
2968
+ if (latitude === void 0 || longitude === void 0) return null;
2969
+ const geoParams = /* @__PURE__ */ new Map();
2970
+ for (const part of paramParts) {
2971
+ const segment = part.trim();
2972
+ if (!segment) continue;
2973
+ const eqIndex = segment.indexOf("=");
2974
+ const rawKey = eqIndex === -1 ? segment : segment.slice(0, eqIndex);
2975
+ const rawValue = eqIndex === -1 ? "" : segment.slice(eqIndex + 1);
2976
+ const key = normalizeLowercaseStringOrEmpty(rawKey);
2977
+ if (!key) continue;
2978
+ const valuePart = rawValue.trim();
2979
+ geoParams.set(key, valuePart ? decodeGeoUriParamValue(valuePart) : "");
2980
+ }
2981
+ const accuracyRaw = geoParams.get("u");
2982
+ const location = {
2983
+ latitude,
2984
+ longitude,
2985
+ accuracy: accuracyRaw ? parseStrictFiniteNumber(accuracyRaw) : void 0,
2986
+ caption: (normalizeOptionalString(content.body) ?? "") || void 0,
2987
+ source: "pin",
2988
+ isLive: false
2989
+ };
2990
+ return {
2991
+ text: formatLocationText(location),
2992
+ context: toLocationContext(location)
2993
+ };
2994
+ }
3186
2995
  // extensions/matrix/src/matrix/monitor/handler.ts
3187
2996
  const SESSION_RESTART_RECOVERY_TOMBSTONE_ERROR_CODE = "SESSION_RESTART_RECOVERY_TOMBSTONE";
3188
2997
  const RESTART_RECOVERY_TOMBSTONE_NOTICE = "This session ended during gateway restart recovery and cannot accept more messages. Send /new or /reset to start a replacement session.";
3189
2998
  function createMatrixRoomMessageHandler(params) {
3190
- const { client, core, cfg: startupConfig, accountId, runtime, logger, logVerboseMessage, allowFromResolvedEntries = [], groupAllowFromResolvedEntries = [], configuredBotUserIds = /* @__PURE__ */ new Set(), replyToMode, streaming, previewToolProgressEnabled, blockStreamingEnabled, historyLimit, startupMs, dropPreStartupMessages, inboundDeduper, directTracker, getMemberDisplayName, resolveLiveUserAllowlist = resolveMatrixMonitorLiveUserAllowlist, resolveStorePath: resolveStorePathImpl = resolveStorePath, createChannelInboundEnvelopeBuilderAsync: createChannelInboundEnvelopeBuilderImpl = createChannelInboundEnvelopeBuilderAsync, resolveHumanDelayConfig: resolveHumanDelayConfigImpl = resolveHumanDelayConfig } = params;
2999
+ const { client, core, cfg: startupConfig, accountId, runtime, logger, logVerboseMessage, allowFromResolvedEntries = [], groupAllowFromResolvedEntries = [], configuredBotUserIds = /* @__PURE__ */ new Set(), replyToMode, streaming, previewToolProgressEnabled, blockStreamingEnabled, historyLimit, directTracker, getMemberDisplayName } = params;
3191
3000
  const handlerConfig = {
3192
3001
  ...params,
3193
3002
  allowFromResolvedEntries,
3194
3003
  groupAllowFromResolvedEntries,
3195
- configuredBotUserIds,
3196
- resolveLiveUserAllowlist,
3197
- resolveStorePath: resolveStorePathImpl,
3198
- createChannelInboundEnvelopeBuilderAsync: createChannelInboundEnvelopeBuilderImpl,
3199
- resolveHumanDelayConfig: resolveHumanDelayConfigImpl
3004
+ configuredBotUserIds
3200
3005
  };
3201
3006
  const handlerState = createMatrixHandlerState({
3202
3007
  core,
3203
3008
  accountId,
3204
3009
  runtime,
3205
3010
  allowFromResolvedEntries,
3206
- groupAllowFromResolvedEntries,
3207
- resolveLiveUserAllowlist
3011
+ groupAllowFromResolvedEntries
3208
3012
  });
3209
3013
  const resolveThreadContext = createMatrixEventContextResolver({
3210
3014
  kind: "thread",
@@ -3221,9 +3025,8 @@ function createMatrixRoomMessageHandler(params) {
3221
3025
  const roomHistoryTracker = createRoomHistoryTracker();
3222
3026
  const roomIngressQueue = new KeyedAsyncQueue();
3223
3027
  const sharedDmContextNoticeRooms = /* @__PURE__ */ new Set();
3224
- return async (roomId, event) => {
3028
+ return async (roomId, event, lifecycle) => {
3225
3029
  const eventId = typeof event.event_id === "string" ? event.event_id.trim() : "";
3226
- let inboundReplayClaim;
3227
3030
  let draftControllerRef;
3228
3031
  try {
3229
3032
  const eventType = event.type;
@@ -3238,39 +3041,42 @@ function createMatrixRoomMessageHandler(params) {
3238
3041
  const senderId = event.sender;
3239
3042
  if (!senderId) return;
3240
3043
  const eventTs = event.origin_server_ts;
3241
- const eventAge = event.unsigned?.age;
3242
- const commitInboundEventIfClaimed = async () => {
3243
- const claim = inboundReplayClaim;
3244
- if (!claim) return;
3245
- await claim.commit();
3246
- if (inboundReplayClaim === claim) inboundReplayClaim = void 0;
3247
- };
3248
- const readIngressPrefix = () => readMatrixIngressPrefix({
3249
- client,
3250
- senderId,
3251
- dropPreStartupMessages,
3252
- eventTs: eventTs ?? void 0,
3253
- eventAge: eventAge ?? void 0,
3254
- startupMs,
3255
- event,
3256
- eventType,
3257
- eventId,
3258
- inboundDeduper,
3259
- roomId,
3260
- logVerboseMessage,
3261
- directTracker,
3262
- claimInboundReplay: (handle) => {
3263
- inboundReplayClaim = handle;
3044
+ const readIngressPrefix = async () => {
3045
+ const selfUserId = await client.getUserId();
3046
+ if (senderId === selfUserId) return;
3047
+ const content = locationContent;
3048
+ if (eventType === EventType.RoomMessage && isMatrixVerificationRoomMessage({
3049
+ msgtype: content.msgtype,
3050
+ body: content.body
3051
+ })) {
3052
+ logVerboseMessage(`matrix: skip verification/system room message room=${roomId}`);
3053
+ return;
3264
3054
  }
3265
- });
3055
+ const locationPayload = resolveMatrixLocation({
3056
+ eventType,
3057
+ content
3058
+ });
3059
+ const relates = content["m.relates_to"];
3060
+ if (relates && "rel_type" in relates && relates.rel_type === RelationType.Replace) return;
3061
+ if (hasBundledMatrixReplacementRelation(event)) return;
3062
+ return {
3063
+ content,
3064
+ isDirectMessage: await directTracker.isDirectMessage({
3065
+ roomId,
3066
+ senderId,
3067
+ selfUserId
3068
+ }),
3069
+ locationPayload,
3070
+ selfUserId
3071
+ };
3072
+ };
3266
3073
  const ingressContext = {
3267
3074
  handler: handlerConfig,
3268
3075
  roomId,
3269
3076
  event,
3270
3077
  eventTs: eventTs ?? void 0,
3271
3078
  senderId,
3272
- roomHistoryTracker,
3273
- commitInboundEventIfClaimed
3079
+ roomHistoryTracker
3274
3080
  };
3275
3081
  const continueIngress = async (paramsLocal) => {
3276
3082
  const access = await resolveMatrixIngressAccess({
@@ -3367,7 +3173,7 @@ function createMatrixRoomMessageHandler(params) {
3367
3173
  const replyDispatcher = createMatrixReplyDispatcher({
3368
3174
  cfg,
3369
3175
  prefixOptions,
3370
- humanDelay: resolveHumanDelayConfigImpl(cfg, _route.agentId),
3176
+ humanDelay: resolveHumanDelayConfig(cfg, _route.agentId),
3371
3177
  typingCallbacks,
3372
3178
  streaming,
3373
3179
  draftStream,
@@ -3392,27 +3198,11 @@ function createMatrixRoomMessageHandler(params) {
3392
3198
  route: _route,
3393
3199
  sessionKey: _route.sessionKey
3394
3200
  });
3395
- const replayClaimAtDispatch = inboundReplayClaim;
3396
- const turnAdoptionLifecycle = replayClaimAtDispatch ? {
3397
- admission: "exclusive",
3398
- onDeferred: () => {
3399
- if (inboundReplayClaim !== replayClaimAtDispatch) return false;
3400
- inboundReplayClaim = void 0;
3401
- },
3402
- onAdopted: async () => {
3403
- if (inboundReplayClaim === replayClaimAtDispatch) inboundReplayClaim = void 0;
3404
- await replayClaimAtDispatch.commit();
3405
- },
3406
- onAbandoned: () => {
3407
- if (inboundReplayClaim === replayClaimAtDispatch) inboundReplayClaim = void 0;
3408
- replayClaimAtDispatch.release();
3409
- }
3410
- } : void 0;
3411
3201
  const turnResultPromise = core.channel.inbound.run({
3412
3202
  channel: "matrix",
3413
3203
  accountId: _route.accountId,
3414
3204
  raw: event,
3415
- ...turnAdoptionLifecycle ? { turnAdoptionLifecycle } : {},
3205
+ turnAdoptionLifecycle: lifecycle,
3416
3206
  adapter: {
3417
3207
  ingest: () => ({
3418
3208
  id: messageId,
@@ -3477,11 +3267,6 @@ function createMatrixRoomMessageHandler(params) {
3477
3267
  skillFilter: roomConfig?.skills,
3478
3268
  disableBlockStreaming: !blockStreamingEnabled,
3479
3269
  onPartialReply: draftStream ? (payload) => draftController.onPartialReply(payload.text ?? "") : void 0,
3480
- onBlockReplyQueued: draftStream ? (payload, context) => {
3481
- if (payload.isCompactionNotice === true) return false;
3482
- draftController.queueDraftBlockBoundary(payload, context);
3483
- return false;
3484
- } : void 0,
3485
3270
  onAssistantMessageStart: draftStream ? () => {
3486
3271
  draftController.resetDraftBlockOffsets();
3487
3272
  draftController.beginAssistantMessage();
@@ -3514,36 +3299,29 @@ function createMatrixRoomMessageHandler(params) {
3514
3299
  deliveryPartCount: 1,
3515
3300
  extraContent: { msgtype: "m.notice" }
3516
3301
  });
3517
- await commitInboundEventIfClaimed();
3518
3302
  } catch (noticeError) {
3519
3303
  runtime.error?.(`matrix: failed completing restart-recovery tombstone notice room=${roomId} id=${eventId || "unknown"}: ${String(noticeError)}`);
3304
+ throw noticeError;
3520
3305
  }
3521
3306
  return;
3522
3307
  }
3523
- if (!turnResult.dispatched) {
3524
- if (turnResult.admission.kind === "drop" && turnResult.admission.reason === "bot-loop-protection") await commitInboundEventIfClaimed();
3525
- return;
3526
- }
3308
+ if (!turnResult.dispatched) return;
3527
3309
  const { dispatchResult } = turnResult;
3528
3310
  const { queuedFinal } = dispatchResult;
3529
3311
  const failedDeliveryKind = draftController.previewLifecycle.finalFailed ? "final" : !queuedFinal && replyDispatcher.nonFinalReplyDeliveryFailed() ? "non-final" : void 0;
3530
3312
  if (failedDeliveryKind) {
3531
- logVerboseMessage(`matrix: ${failedDeliveryKind} reply delivery failed room=${roomId} id=${messageId}; keeping replay committed`);
3532
- await commitInboundEventIfClaimed();
3313
+ logVerboseMessage(`matrix: ${failedDeliveryKind} reply delivery failed room=${roomId} id=${messageId}; turn already adopted`);
3533
3314
  return;
3534
3315
  }
3535
3316
  if (isRoom && triggerSnapshot) roomHistoryTracker.consumeHistory(_route.agentId, roomId, triggerSnapshot, messageId, threadRootId ? thread.threadId : void 0);
3536
- if (!hasFinalInboundReplyDispatch(dispatchResult)) {
3537
- await commitInboundEventIfClaimed();
3538
- return;
3539
- }
3317
+ if (!hasFinalInboundReplyDispatch(dispatchResult)) return;
3540
3318
  const finalCount = resolveInboundReplyDispatchCounts(dispatchResult).final;
3541
3319
  logVerboseMessage(`matrix: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${replyTarget}`);
3542
- await commitInboundEventIfClaimed();
3543
3320
  } catch (err) {
3544
3321
  const draftController = draftControllerRef;
3545
3322
  if (draftController?.draftStream?.eventId()) draftController.previewLifecycle.retainPreview();
3546
3323
  runtime.error?.(`matrix handler failed: ${String(err)}`);
3324
+ throw err;
3547
3325
  } finally {
3548
3326
  const draftStream = draftControllerRef?.draftStream;
3549
3327
  if (draftStream) {
@@ -3551,10 +3329,102 @@ function createMatrixRoomMessageHandler(params) {
3551
3329
  await draftControllerRef?.previewLifecycle.cleanup();
3552
3330
  await draftStream.cleanupPending();
3553
3331
  }
3554
- inboundReplayClaim?.release();
3555
3332
  }
3556
3333
  };
3557
3334
  }
3335
+ // extensions/matrix/src/matrix/monitor/ingress.ts
3336
+ const MatrixIngressPayloadError = createChannelIngressError("MatrixIngressPayloadError");
3337
+ function inspectMatrixIngressEvent(raw) {
3338
+ if (!raw || typeof raw.roomId !== "string" || !raw.roomId.trim() || !raw.event || typeof raw.event.event_id !== "string" || !raw.event.event_id.trim()) throw new MatrixIngressPayloadError("Matrix ingress event is missing its room or event ID");
3339
+ return {
3340
+ eventId: raw.event.event_id,
3341
+ laneKey: `room:${raw.roomId}`
3342
+ };
3343
+ }
3344
+ function createMatrixIngressMonitor(params) {
3345
+ let queue = params.queue;
3346
+ const getQueue = () => queue ??= getMatrixRuntime().state.openChannelIngressQueue({ accountId: params.accountId });
3347
+ let lastReceivedAt = 0;
3348
+ let initializeOrder;
3349
+ const monitor = createChannelIngressMonitor({
3350
+ queue: getQueue,
3351
+ inspect: inspectMatrixIngressEvent,
3352
+ payload: {
3353
+ version: 1,
3354
+ serialize: (raw) => raw,
3355
+ deserialize: (body) => body,
3356
+ encode: ({ body }) => ({
3357
+ version: 1,
3358
+ ...body
3359
+ }),
3360
+ decode: (payload) => {
3361
+ inspectMatrixIngressEvent(payload);
3362
+ return {
3363
+ version: payload.version,
3364
+ body: payload
3365
+ };
3366
+ },
3367
+ createClaimError: (kind) => new MatrixIngressPayloadError(kind === "invalid-version" ? "Matrix ingress payload version is unsupported" : "Matrix event identity changed after durable admission")
3368
+ },
3369
+ deliver: async ({ roomId, event, historical }, lifecycle) => {
3370
+ if (historical) return;
3371
+ if (event.type === EventType.RoomMessageEncrypted && !params.client.crypto) return;
3372
+ const [hydrated] = await params.client.hydrateEvents(roomId, [event]);
3373
+ if (!hydrated || hydrated.type === EventType.RoomMessageEncrypted || getMatrixEventProjection(hydrated)?.decryptionFailure) throw new Error("Matrix ingress event is waiting for decryption");
3374
+ return await params.dispatch(roomId, hydrated, lifecycle);
3375
+ },
3376
+ pollIntervalMs: 1e3,
3377
+ retention: "standard",
3378
+ waitForDeliveryIdleOnStop: false,
3379
+ drain: {
3380
+ deferredLaneOccupancy: "release",
3381
+ onLog: params.onError,
3382
+ resolveNonRetryableFailure: (error) => error instanceof MatrixIngressPayloadError ? {
3383
+ reason: "invalid-event",
3384
+ message: error.message
3385
+ } : null
3386
+ },
3387
+ onError: params.onError
3388
+ });
3389
+ const admitSync = async (sync, { hasSavedSync }) => {
3390
+ const events = [];
3391
+ const rooms = [...Object.entries(sync.rooms?.join ?? {}), ...Object.entries(sync.rooms?.leave ?? {})];
3392
+ for (const [roomId, room] of rooms) for (const event of room.timeline?.events ?? []) {
3393
+ if (!(event.type === EventType.RoomMessage || event.type === EventType.RoomMessageEncrypted || event.type === EventType.Location || event.type === EventType.Reaction || isPollEventType(event.type))) continue;
3394
+ const historical = !hasSavedSync && (typeof event.origin_server_ts === "number" && event.origin_server_ts < params.startupMs || typeof event.origin_server_ts !== "number" && typeof event.unsigned?.age === "number" && event.unsigned.age > 0);
3395
+ events.push({
3396
+ roomId,
3397
+ event: {
3398
+ ...event,
3399
+ room_id: roomId
3400
+ },
3401
+ ...historical ? { historical: true } : {}
3402
+ });
3403
+ }
3404
+ if (events.length === 0) return;
3405
+ await (initializeOrder ??= (async () => {
3406
+ const ingressQueue = getQueue();
3407
+ const { pending, claims } = ingressQueue.listUnsettled ? await ingressQueue.listUnsettled() : {
3408
+ pending: await ingressQueue.listPending({ limit: "all" }),
3409
+ claims: await ingressQueue.listClaims()
3410
+ };
3411
+ for (const row of [...pending, ...claims]) lastReceivedAt = Math.max(lastReceivedAt, row.receivedAt);
3412
+ })());
3413
+ for (const event of events) {
3414
+ const result = await monitor.admit(event, { receivedAt: Math.max(Date.now(), lastReceivedAt + 1) });
3415
+ if (result.kind === "durable") {
3416
+ const admitted = result.queueResult;
3417
+ if (admitted.kind === "accepted" || admitted.kind === "pending" || admitted.kind === "claimed") lastReceivedAt = Math.max(lastReceivedAt, admitted.record.receivedAt);
3418
+ }
3419
+ }
3420
+ };
3421
+ return {
3422
+ admitSync,
3423
+ start: monitor.start,
3424
+ stop: monitor.stop,
3425
+ waitForIdle: monitor.waitForIdle
3426
+ };
3427
+ }
3558
3428
  // extensions/matrix/src/matrix/monitor/recent-invite.ts
3559
3429
  function shouldPromoteRecentInviteRoom(params) {
3560
3430
  if (!params.roomInfo.nameResolved || !params.roomInfo.aliasesResolved) return false;
@@ -3568,18 +3438,18 @@ function shouldPromoteRecentInviteRoom(params) {
3568
3438
  }
3569
3439
  // extensions/matrix/src/matrix/monitor/startup.ts
3570
3440
  const loadMatrixStartupMaintenanceDeps = createLazyRuntimeModule(() => Promise.all([
3571
- import("./setup-core-D2r4BivQ.mjs").then((n) => n.f),
3572
- import("./device-health-DnKAXW1v.mjs").then((n) => n.t),
3573
- import("./setup-core-D2r4BivQ.mjs").then((n) => n.u),
3574
- import("./startup-verification-B3LEbW33.mjs")
3441
+ import("./setup-core-BaKffgBi.mjs").then((n) => n.f),
3442
+ import("./device-health-D7n-lPeb.mjs").then((n) => n.t),
3443
+ import("./setup-core-BaKffgBi.mjs").then((n) => n.u),
3444
+ import("./startup-verification-C-lhD0gk.mjs")
3575
3445
  ]).then(([configUpdateModule, deviceHealthModule, profileModule, startupVerificationModule]) => ({
3576
3446
  updateMatrixAccountConfig: configUpdateModule.updateMatrixAccountConfig,
3577
- summarizeMatrixDeviceHealth: deviceHealthModule.summarizeMatrixDeviceHealth,
3447
+ listStaleOpenClawMatrixDevices: deviceHealthModule.listStaleOpenClawMatrixDevices,
3578
3448
  syncMatrixOwnProfile: profileModule.syncMatrixOwnProfile,
3579
3449
  ensureMatrixStartupVerification: startupVerificationModule.ensureMatrixStartupVerification
3580
3450
  })));
3581
- async function runMatrixStartupMaintenance(params, deps) {
3582
- const runtimeDeps = deps ?? await loadMatrixStartupMaintenanceDeps();
3451
+ async function runMatrixStartupMaintenance(params) {
3452
+ const runtimeDeps = await loadMatrixStartupMaintenanceDeps();
3583
3453
  throwIfMatrixStartupAborted(params.abortSignal);
3584
3454
  try {
3585
3455
  const profileSync = await runtimeDeps.syncMatrixOwnProfile({
@@ -3606,8 +3476,8 @@ async function runMatrixStartupMaintenance(params, deps) {
3606
3476
  if (!(params.auth.encryption && params.client.crypto)) return;
3607
3477
  try {
3608
3478
  throwIfMatrixStartupAborted(params.abortSignal);
3609
- const deviceHealth = runtimeDeps.summarizeMatrixDeviceHealth(await params.client.listOwnDevices());
3610
- if (deviceHealth.staleOpenClawDevices.length > 0) params.logger.warn(`matrix: stale OpenClaw devices detected for ${params.auth.userId}: ${deviceHealth.staleOpenClawDevices.map((device) => device.deviceId).join(", ")}. Run 'openclaw matrix devices prune-stale --account ${params.effectiveAccountId}' to keep encrypted-room trust healthy.`);
3479
+ const staleOpenClawDevices = runtimeDeps.listStaleOpenClawMatrixDevices(await params.client.listOwnDevices());
3480
+ if (staleOpenClawDevices.length > 0) params.logger.warn(`matrix: stale OpenClaw devices detected for ${params.auth.userId}: ${staleOpenClawDevices.map((device) => device.deviceId).join(", ")}. Run 'openclaw matrix devices prune-stale --account ${params.effectiveAccountId}' to keep encrypted-room trust healthy.`);
3611
3481
  } catch (err) {
3612
3482
  if (isMatrixStartupAbortError(err)) throw err;
3613
3483
  params.logger.debug?.("Failed to inspect matrix device hygiene (non-fatal)", { error: String(err) });
@@ -3634,10 +3504,6 @@ async function runMatrixStartupMaintenance(params, deps) {
3634
3504
  }
3635
3505
  }
3636
3506
  // extensions/matrix/src/matrix/monitor/status.ts
3637
- function cloneLastDisconnect(value) {
3638
- if (!value || typeof value === "string") return value ?? null;
3639
- return { ...value };
3640
- }
3641
3507
  function formatSyncError(error) {
3642
3508
  if (!error) return null;
3643
3509
  if (error instanceof Error) return error.message || error.name || "unknown";
@@ -3655,22 +3521,9 @@ function createMatrixMonitorStatusController(params) {
3655
3521
  lifecycle: "starting"
3656
3522
  };
3657
3523
  const emit = () => {
3658
- params.statusSink?.({
3659
- ...status,
3660
- lastDisconnect: cloneLastDisconnect(status.lastDisconnect)
3661
- });
3524
+ params.statusSink?.({ ...status });
3662
3525
  };
3663
- let startupComplete = params.deferReadyUntilStartupComplete !== true;
3664
- let pendingReadyAt = null;
3665
- let pendingTransportActivity = false;
3666
3526
  const noteConnected = (at = Date.now(), options) => {
3667
- if (!startupComplete) {
3668
- pendingReadyAt = at;
3669
- pendingTransportActivity ||= options?.transportActivity === true;
3670
- status.lastEventAt = at;
3671
- emit();
3672
- return;
3673
- }
3674
3527
  const lastConnectedAt = status.connected === true ? status.lastConnectedAt ?? at : at;
3675
3528
  Object.assign(status, channelReadyPatch({
3676
3529
  lastConnectedAt,
@@ -3683,8 +3536,6 @@ function createMatrixMonitorStatusController(params) {
3683
3536
  };
3684
3537
  const noteDisconnected = (paramsLocal) => {
3685
3538
  const at = paramsLocal.at ?? Date.now();
3686
- pendingReadyAt = null;
3687
- pendingTransportActivity = false;
3688
3539
  const tokenInvalidated = isMatrixAccessTokenInvalidatedError(paramsLocal.error);
3689
3540
  if (status.lifecycle === "blocked" && status.terminalDisconnect === true && !tokenInvalidated) {
3690
3541
  status.connected = false;
@@ -3710,16 +3561,6 @@ function createMatrixMonitorStatusController(params) {
3710
3561
  };
3711
3562
  emit();
3712
3563
  return {
3713
- markStartupComplete(at = Date.now()) {
3714
- startupComplete = true;
3715
- if (pendingReadyAt !== null) {
3716
- const readyAt = Math.max(pendingReadyAt, at);
3717
- const transportActivity = pendingTransportActivity;
3718
- pendingReadyAt = null;
3719
- pendingTransportActivity = false;
3720
- noteConnected(readyAt, { transportActivity });
3721
- }
3722
- },
3723
3564
  noteSyncState(state, error, at = Date.now()) {
3724
3565
  if (isMatrixReadySyncState(state)) {
3725
3566
  noteConnected(at, { transportActivity: state === "SYNCING" });
@@ -3757,59 +3598,6 @@ function createMatrixMonitorStatusController(params) {
3757
3598
  }
3758
3599
  };
3759
3600
  }
3760
- // extensions/matrix/src/matrix/monitor/sync-lifecycle.ts
3761
- function formatSyncLifecycleError(state, error) {
3762
- if (error instanceof Error) return error;
3763
- const message = typeof error === "string" && error.trim() ? error.trim() : void 0;
3764
- if (state === "STOPPED") return new Error(message ?? "Matrix sync stopped unexpectedly");
3765
- return new Error(message ?? `Matrix sync entered ${state} unexpectedly`);
3766
- }
3767
- function createMatrixMonitorSyncLifecycle(params) {
3768
- let fatalError = null;
3769
- let resolveFatalWait = null;
3770
- let rejectFatalWait = null;
3771
- const settleFatal = (error) => {
3772
- if (fatalError) return;
3773
- fatalError = error;
3774
- rejectFatalWait?.(error);
3775
- resolveFatalWait = null;
3776
- rejectFatalWait = null;
3777
- };
3778
- const onSyncState = (state, _prevState, error) => {
3779
- if (isMatrixTerminalSyncState(state) && !params.isStopping?.()) {
3780
- const fatalErrorLocal = formatSyncLifecycleError(state, error);
3781
- params.statusController.noteUnexpectedError(fatalErrorLocal);
3782
- settleFatal(fatalErrorLocal);
3783
- return;
3784
- }
3785
- if (fatalError) return;
3786
- if (params.isStopping?.() && !isMatrixTerminalSyncState(state)) return;
3787
- params.statusController.noteSyncState(state, error);
3788
- };
3789
- const onUnexpectedError = (error) => {
3790
- if (params.isStopping?.()) return;
3791
- params.statusController.noteUnexpectedError(error);
3792
- settleFatal(error);
3793
- };
3794
- params.client.on("sync.state", onSyncState);
3795
- params.client.on("sync.unexpected_error", onUnexpectedError);
3796
- return {
3797
- async waitForFatalStop() {
3798
- if (fatalError) throw fatalError;
3799
- await new Promise((resolve, reject) => {
3800
- resolveFatalWait = resolve;
3801
- rejectFatalWait = (error) => reject(error);
3802
- });
3803
- },
3804
- dispose() {
3805
- resolveFatalWait?.();
3806
- resolveFatalWait = null;
3807
- rejectFatalWait = null;
3808
- params.client.off("sync.state", onSyncState);
3809
- params.client.off("sync.unexpected_error", onUnexpectedError);
3810
- }
3811
- };
3812
- }
3813
3601
  // extensions/matrix/src/matrix/monitor/index.ts
3814
3602
  function resolveMatrixStreamingMode(streaming) {
3815
3603
  const mode = streaming?.mode;
@@ -3822,6 +3610,12 @@ function resolveMatrixPreviewToolProgressEnabled(streaming) {
3822
3610
  if (mode === "progress") return streaming?.progress?.toolProgress ?? streaming?.preview?.toolProgress ?? false;
3823
3611
  return streaming?.preview?.toolProgress ?? true;
3824
3612
  }
3613
+ function formatSyncLifecycleError(state, error) {
3614
+ if (error instanceof Error) return error;
3615
+ const message = typeof error === "string" && error.trim() ? error.trim() : void 0;
3616
+ if (state === "STOPPED") return new Error(message ?? "Matrix sync stopped unexpectedly");
3617
+ return new Error(message ?? `Matrix sync entered ${state} unexpectedly`);
3618
+ }
3825
3619
  const DEFAULT_MEDIA_MAX_MB = 20;
3826
3620
  async function monitorMatrixProvider(opts = {}) {
3827
3621
  if (opts.abortSignal?.aborted) return;
@@ -3902,8 +3696,7 @@ async function monitorMatrixProvider(opts = {}) {
3902
3696
  const statusController = createMatrixMonitorStatusController({
3903
3697
  accountId: auth.accountId,
3904
3698
  baseUrl: auth.homeserver,
3905
- statusSink: opts.setStatus,
3906
- deferReadyUntilStartupComplete: true
3699
+ statusSink: opts.setStatus
3907
3700
  });
3908
3701
  let cleanedUp = false;
3909
3702
  let cleanupPromise = null;
@@ -3917,7 +3710,12 @@ async function monitorMatrixProvider(opts = {}) {
3917
3710
  });
3918
3711
  let disposeAutoJoin = () => {};
3919
3712
  let disposeMonitorEvents = () => {};
3920
- let syncLifecycle = null;
3713
+ let disposeSyncIngress = () => {};
3714
+ let ingress;
3715
+ let fatalError = null;
3716
+ let resolveFatalWait = null;
3717
+ let rejectFatalWait = null;
3718
+ const isStopping = () => cleanedUp || monitorLifecycleSignal?.aborted === true;
3921
3719
  let monitorSetupClosed = false;
3922
3720
  const cleanup = (mode = "persist") => {
3923
3721
  if (cleanupPromise) return cleanupPromise;
@@ -3981,6 +3779,29 @@ async function monitorMatrixProvider(opts = {}) {
3981
3779
  }
3982
3780
  if (isMatrixDisconnectedSyncState(state)) healthySyncSinceMs = void 0;
3983
3781
  };
3782
+ const settleFatal = (error) => {
3783
+ if (fatalError) return;
3784
+ fatalError = error;
3785
+ rejectFatalWait?.(error);
3786
+ resolveFatalWait = null;
3787
+ rejectFatalWait = null;
3788
+ };
3789
+ const onSyncLifecycleState = (state, _prevState, error) => {
3790
+ if (isMatrixTerminalSyncState(state) && !isStopping()) {
3791
+ const fatalErrorLocal = formatSyncLifecycleError(state, error);
3792
+ statusController.noteUnexpectedError(fatalErrorLocal);
3793
+ settleFatal(fatalErrorLocal);
3794
+ return;
3795
+ }
3796
+ if (fatalError) return;
3797
+ if (isStopping() && !isMatrixTerminalSyncState(state)) return;
3798
+ statusController.noteSyncState(state, error);
3799
+ };
3800
+ const onUnexpectedSyncError = (error) => {
3801
+ if (isStopping()) return;
3802
+ statusController.noteUnexpectedError(error);
3803
+ settleFatal(error);
3804
+ };
3984
3805
  const monitorRetirement = {
3985
3806
  closeTaskAdmission: () => {
3986
3807
  monitorSetupClosed = true;
@@ -3989,17 +3810,24 @@ async function monitorMatrixProvider(opts = {}) {
3989
3810
  detachListeners: () => {
3990
3811
  disposeAutoJoin();
3991
3812
  disposeMonitorEvents();
3813
+ disposeSyncIngress();
3992
3814
  client?.off("sync.state", onSyncState);
3993
- syncLifecycle?.dispose();
3815
+ resolveFatalWait?.();
3816
+ resolveFatalWait = null;
3817
+ rejectFatalWait = null;
3818
+ client?.off("sync.state", onSyncLifecycleState);
3819
+ client?.off("sync.unexpected_error", onUnexpectedSyncError);
3820
+ },
3821
+ waitForTasks: async () => {
3822
+ await ingress?.stop();
3823
+ await monitorTaskRunner.waitForIdle();
3994
3824
  },
3995
- waitForTasks: monitorTaskRunner.waitForIdle,
3996
3825
  cleanup: () => threadBindingManager?.stop()
3997
3826
  };
3998
3827
  try {
3999
3828
  clientLease = await acquireSharedMatrixClient({
4000
3829
  cfg,
4001
3830
  auth: authWithLimit,
4002
- startClient: false,
4003
3831
  accountId: auth.accountId,
4004
3832
  abortSignal: opts.abortSignal,
4005
3833
  role: "monitor"
@@ -4007,18 +3835,10 @@ async function monitorMatrixProvider(opts = {}) {
4007
3835
  client = clientLease.client;
4008
3836
  monitorLifecycleSignal = opts.abortSignal ? AbortSignal.any([opts.abortSignal, clientLease.abortSignal]) : clientLease.abortSignal;
4009
3837
  clientLease.registerMonitorRetirement(monitorRetirement);
4010
- const inboundDeduper = createMatrixInboundEventDeduper({
4011
- auth,
4012
- env: process.env
4013
- });
4014
- syncLifecycle = createMatrixMonitorSyncLifecycle({
4015
- client,
4016
- statusController,
4017
- isStopping: () => cleanedUp || monitorLifecycleSignal?.aborted === true
4018
- });
3838
+ client.on("sync.state", onSyncLifecycleState);
3839
+ client.on("sync.unexpected_error", onUnexpectedSyncError);
4019
3840
  client.on("sync.state", onSyncState);
4020
- const dropPreStartupMessages = !client.hasPersistedSyncState();
4021
- const { getRoomInfo, getMemberDisplayName, invalidateMemberDisplayName } = createMatrixRoomInfoResolver(client);
3841
+ const { getRoomInfo, getMemberDisplayName, invalidateMemberDisplayName, invalidateRoomName } = createMatrixRoomInfoResolver(client);
4022
3842
  const isExplicitlyConfiguredRoom = async (roomId) => {
4023
3843
  const roomInfoForConfig = needsRoomAliasesForConfig ? await getRoomInfo(roomId, { includeAliases: true }) : void 0;
4024
3844
  const aliases = roomInfoForConfig ? [roomInfoForConfig.canonicalAlias ?? "", ...roomInfoForConfig.altAliases].filter(Boolean) : [];
@@ -4087,9 +3907,6 @@ async function monitorMatrixProvider(opts = {}) {
4087
3907
  dmPolicy,
4088
3908
  mediaMaxBytes,
4089
3909
  historyLimit,
4090
- startupMs,
4091
- dropPreStartupMessages,
4092
- inboundDeduper,
4093
3910
  directTracker,
4094
3911
  getRoomInfo,
4095
3912
  getMemberDisplayName,
@@ -4130,21 +3947,30 @@ async function monitorMatrixProvider(opts = {}) {
4130
3947
  needsRoomAliasesForConfig,
4131
3948
  getRoomInfo,
4132
3949
  invalidateMemberDisplayName,
3950
+ invalidateRoomName,
4133
3951
  logVerboseMessage,
4134
3952
  warnedEncryptedRooms,
4135
3953
  warnedCryptoMissingRooms,
4136
3954
  logger,
4137
3955
  getHealthySyncSinceMs: () => healthySyncSinceMs,
4138
3956
  formatNativeDependencyHint: core.system.formatNativeDependencyHint,
4139
- onRoomMessage: handleRoomMessage,
4140
3957
  runDetachedTask: monitorTaskRunner.runDetachedTask
4141
3958
  });
3959
+ ingress = createMatrixIngressMonitor({
3960
+ accountId: effectiveAccountId,
3961
+ client,
3962
+ startupMs,
3963
+ dispatch: (roomId, event, lifecycle) => monitorTaskRunner.runTask(() => handleRoomMessage(roomId, event, lifecycle)),
3964
+ onError: (error) => logger.warn("matrix ingress failed", { error: String(error) })
3965
+ });
3966
+ disposeSyncIngress = await client.bindSyncIngress(ingress.admitSync);
4142
3967
  logVerboseMessage("matrix: starting client");
4143
3968
  await clientLease.start(monitorLifecycleSignal);
4144
3969
  if (monitorSetupClosed) {
4145
3970
  await cleanup("stop");
4146
3971
  return;
4147
3972
  }
3973
+ ingress.start();
4148
3974
  logVerboseMessage("matrix: client started");
4149
3975
  logger.info(`matrix: logged in as ${auth.userId}`);
4150
3976
  monitorTaskRunner.runDetachedTask("deviceId backfill", async () => {
@@ -4186,7 +4012,6 @@ async function monitorMatrixProvider(opts = {}) {
4186
4012
  await cleanup("stop");
4187
4013
  return;
4188
4014
  }
4189
- statusController.markStartupComplete();
4190
4015
  await Promise.race([waitUntilAbort(monitorLifecycleSignal, async () => {
4191
4016
  try {
4192
4017
  logVerboseMessage("matrix: stopping client");
@@ -4194,7 +4019,13 @@ async function monitorMatrixProvider(opts = {}) {
4194
4019
  } catch (err) {
4195
4020
  logger.warn("matrix: failed during monitor shutdown cleanup", { error: String(err) });
4196
4021
  }
4197
- }), syncLifecycle.waitForFatalStop()]);
4022
+ }), new Promise((resolve, reject) => {
4023
+ if (fatalError) reject(fatalError);
4024
+ else {
4025
+ resolveFatalWait = resolve;
4026
+ rejectFatalWait = reject;
4027
+ }
4028
+ })]);
4198
4029
  await cleanup();
4199
4030
  } catch (err) {
4200
4031
  if (monitorSetupClosed || monitorLifecycleSignal?.aborted && isMatrixStartupAbortError(err)) {