@kodelyth/matrix 2026.5.39 → 2026.5.42

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 (321) hide show
  1. package/CHANGELOG.md +321 -0
  2. package/SPEC-SUPPORT.md +116 -0
  3. package/api.ts +38 -0
  4. package/auth-presence.ts +56 -0
  5. package/channel-plugin-api.ts +3 -0
  6. package/cli-metadata.ts +11 -0
  7. package/contract-api.ts +17 -0
  8. package/dist/account-selection-Y50DNJ2l.js +158 -0
  9. package/dist/active-client-CmFdvPdO.js +20 -0
  10. package/dist/api.js +12 -0
  11. package/dist/approval-handler.runtime-BIi4fL0R.js +377 -0
  12. package/dist/approval-ids-BGHK7PnZ.js +7 -0
  13. package/dist/approval-reaction-auth-CL0-nCNV.js +27 -0
  14. package/dist/approval-reactions-nDm2x-K5.js +162 -0
  15. package/dist/async-lock-SsmtFXtt.js +19 -0
  16. package/dist/auth-presence.js +26 -0
  17. package/dist/backup-health-3BHbHxyd.js +60 -0
  18. package/dist/channel-C0kCyTNB.js +1380 -0
  19. package/dist/channel-plugin-api.js +2 -0
  20. package/dist/channel.runtime-CdrdEN-0.js +250 -0
  21. package/dist/cli-FtY6Nuzw.js +1338 -0
  22. package/dist/cli-metadata-Dkwua7CB.js +22 -0
  23. package/dist/cli-metadata.js +2 -0
  24. package/dist/client-BnohYygh.js +25 -0
  25. package/dist/client-PhrTwuC4.js +30 -0
  26. package/dist/client-bootstrap-Mcj8ChJ5.js +114 -0
  27. package/dist/config-paths-DVvt6vM3.js +114 -0
  28. package/dist/config-schema-BMGOlhdI.js +308 -0
  29. package/dist/config-secret-input.runtime-Dv_4Br_f.js +2 -0
  30. package/dist/contract-api.js +8 -0
  31. package/dist/create-client-J0htTaRj.js +64 -0
  32. package/dist/credentials-B7GsBbgQ.js +56 -0
  33. package/dist/credentials-read-8fE4qoWs.js +112 -0
  34. package/dist/credentials-write.runtime-BibplB4Y.js +17 -0
  35. package/dist/crypto-node.runtime-D9qxgRPa.js +12 -0
  36. package/dist/crypto-runtime-1pKW4O2F.js +1214 -0
  37. package/dist/deps-DVpDS81G.js +208 -0
  38. package/dist/device-health-Ct2wDSPG.js +16 -0
  39. package/dist/directory-live-i3T8uORc.js +150 -0
  40. package/dist/doctor-contract-BLzYHl_9.js +246 -0
  41. package/dist/doctor-contract-api.js +2 -0
  42. package/dist/doctor-diR5gE7D.js +153 -0
  43. package/dist/draft-stream-HpPJ_VJt.js +143 -0
  44. package/dist/encryption-guidance-BNEgckrZ.js +15 -0
  45. package/dist/env-auth-UFiTGkDM.js +63 -0
  46. package/dist/env-vars-EQKQv-FE.js +63 -0
  47. package/dist/errors-BETj3zr9.js +17 -0
  48. package/dist/exec-approval-resolver-BxPorU_t.js +15 -0
  49. package/dist/helper-api.js +4 -0
  50. package/dist/http-client-DoQgbQsU.js +331 -0
  51. package/dist/index.js +46 -0
  52. package/dist/legacy-crypto-inspector-zK0hDCbt.js +41 -0
  53. package/dist/legacy-crypto-restore-DSFIXuDo.js +85 -0
  54. package/dist/logging-Df7aPD1z.js +99 -0
  55. package/dist/matrix-migration.runtime-BNoT1Prt.js +525 -0
  56. package/dist/media-text-ZhGA8Pcs.js +146 -0
  57. package/dist/messages-CRA9WGg0.js +140 -0
  58. package/dist/migration-snapshot-backup-BR-xD7Ew.js +69 -0
  59. package/dist/migration-snapshot.runtime-BLcy_Nvw.js +2 -0
  60. package/dist/monitor-DQm7_13y.js +4331 -0
  61. package/dist/plugin-entry.handlers.runtime.js +51 -0
  62. package/dist/probe.runtime-CjJS53Kz.js +3 -0
  63. package/dist/profile-update-DqkPgZ1P.js +68 -0
  64. package/dist/reaction-common-CmVLzP-u.js +71 -0
  65. package/dist/reaction-events-D0nUJuZV.js +121 -0
  66. package/dist/record-shared-DGvSFn5M.js +2 -0
  67. package/dist/resolve-targets-ChECUzD2.js +140 -0
  68. package/dist/resolver.runtime-hdY3n0GO.js +5 -0
  69. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  70. package/dist/route-xRKj_ESW.js +161 -0
  71. package/dist/runtime-B-Fyrmxo.js +8 -0
  72. package/dist/runtime-api-BYXXkxq2.js +24 -0
  73. package/dist/runtime-api.js +25 -0
  74. package/dist/runtime-heavy-api.js +3 -0
  75. package/dist/runtime-lwTSy9Yt.js +6 -0
  76. package/dist/runtime-setter-api.js +2 -0
  77. package/dist/sdk-Jhq7mLtD.js +1704 -0
  78. package/dist/secret-contract-DEMcDsjl.js +120 -0
  79. package/dist/secret-contract-api.js +2 -0
  80. package/dist/send-CJunc6QM.js +1517 -0
  81. package/dist/setup-bootstrap-rJ0qZWPe.js +62 -0
  82. package/dist/setup-core-BEYoXF3J.js +677 -0
  83. package/dist/setup-entry.js +19 -0
  84. package/dist/setup-plugin-api.js +43 -0
  85. package/dist/setup-surface-c28ON6jq.js +537 -0
  86. package/dist/shared-D6MFMnpG.js +642 -0
  87. package/dist/startup-abort-B2J3MU_h.js +109 -0
  88. package/dist/startup-verification-CkD4Cwce.js +132 -0
  89. package/dist/storage-nyO0DOFE.js +281 -0
  90. package/dist/storage-paths-BTAketfg.js +52 -0
  91. package/dist/subagent-hooks-api-Dr_xnMRG.js +170 -0
  92. package/dist/subagent-hooks-api.js +2 -0
  93. package/dist/sync-state-Bx0gPaGA.js +12 -0
  94. package/dist/target-ids-Bsazo8si.js +77 -0
  95. package/dist/test-api.js +4 -0
  96. package/dist/thread-binding-api-IGU0-L70.js +17 -0
  97. package/dist/thread-binding-api.js +2 -0
  98. package/dist/thread-bindings-FjAZmDUP.js +352 -0
  99. package/dist/thread-bindings-runtime.js +2 -0
  100. package/dist/thread-bindings-shared-fvfP7jVs.js +97 -0
  101. package/dist/timeout-abort-signal-DpSHDHhR.js +2 -0
  102. package/dist/tool-actions.runtime-Cbo7YcYZ.js +532 -0
  103. package/dist/url-validation-DlrXNjAE.js +36 -0
  104. package/dist/verification-7tDPRpJU.js +345 -0
  105. package/doctor-contract-api.ts +1 -0
  106. package/helper-api.ts +3 -0
  107. package/index.ts +55 -0
  108. package/klaw.plugin.json +3 -891
  109. package/package.json +4 -4
  110. package/plugin-entry.handlers.runtime.ts +1 -0
  111. package/runtime-api.ts +72 -0
  112. package/runtime-heavy-api.ts +1 -0
  113. package/runtime-setter-api.ts +3 -0
  114. package/secret-contract-api.ts +5 -0
  115. package/setup-entry.ts +17 -0
  116. package/setup-plugin-api.ts +3 -0
  117. package/src/account-selection.ts +223 -0
  118. package/src/actions.ts +346 -0
  119. package/src/approval-auth.ts +25 -0
  120. package/src/approval-handler.runtime.ts +592 -0
  121. package/src/approval-ids.ts +6 -0
  122. package/src/approval-native.ts +345 -0
  123. package/src/approval-reaction-auth.ts +45 -0
  124. package/src/approval-reactions.ts +313 -0
  125. package/src/auth-precedence.ts +61 -0
  126. package/src/channel-account-paths.ts +97 -0
  127. package/src/channel.runtime.ts +17 -0
  128. package/src/channel.setup.ts +48 -0
  129. package/src/channel.ts +667 -0
  130. package/src/cli-metadata.ts +19 -0
  131. package/src/cli.ts +2298 -0
  132. package/src/config-adapter.ts +41 -0
  133. package/src/config-schema.ts +159 -0
  134. package/src/config-ui-hints.ts +56 -0
  135. package/src/directory-live.ts +238 -0
  136. package/src/doctor-contract.ts +287 -0
  137. package/src/doctor.ts +262 -0
  138. package/src/env-vars.ts +92 -0
  139. package/src/exec-approval-resolver.ts +23 -0
  140. package/src/exec-approvals.ts +287 -0
  141. package/src/group-mentions.ts +41 -0
  142. package/src/legacy-crypto-inspector-availability.ts +60 -0
  143. package/src/legacy-crypto.ts +531 -0
  144. package/src/legacy-state.ts +156 -0
  145. package/src/matrix/account-config.ts +175 -0
  146. package/src/matrix/accounts.ts +194 -0
  147. package/src/matrix/actions/client.ts +31 -0
  148. package/src/matrix/actions/devices.ts +34 -0
  149. package/src/matrix/actions/limits.ts +6 -0
  150. package/src/matrix/actions/messages.ts +129 -0
  151. package/src/matrix/actions/pins.ts +63 -0
  152. package/src/matrix/actions/polls.ts +109 -0
  153. package/src/matrix/actions/profile.ts +37 -0
  154. package/src/matrix/actions/reactions.ts +59 -0
  155. package/src/matrix/actions/room.ts +71 -0
  156. package/src/matrix/actions/summary.ts +88 -0
  157. package/src/matrix/actions/types.ts +63 -0
  158. package/src/matrix/actions/verification.ts +589 -0
  159. package/src/matrix/actions.ts +37 -0
  160. package/src/matrix/active-client.ts +26 -0
  161. package/src/matrix/async-lock.ts +18 -0
  162. package/src/matrix/backup-health.ts +124 -0
  163. package/src/matrix/client/config-runtime-api.ts +9 -0
  164. package/src/matrix/client/config-secret-input.runtime.ts +1 -0
  165. package/src/matrix/client/config.ts +853 -0
  166. package/src/matrix/client/create-client.ts +105 -0
  167. package/src/matrix/client/env-auth.ts +95 -0
  168. package/src/matrix/client/file-sync-store.ts +289 -0
  169. package/src/matrix/client/logging.ts +140 -0
  170. package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
  171. package/src/matrix/client/private-network-host.ts +1 -0
  172. package/src/matrix/client/runtime.ts +4 -0
  173. package/src/matrix/client/shared.ts +316 -0
  174. package/src/matrix/client/storage.ts +543 -0
  175. package/src/matrix/client/types.ts +50 -0
  176. package/src/matrix/client/url-validation.ts +73 -0
  177. package/src/matrix/client-bootstrap.ts +173 -0
  178. package/src/matrix/client.ts +23 -0
  179. package/src/matrix/config-paths.ts +31 -0
  180. package/src/matrix/config-update.ts +292 -0
  181. package/src/matrix/credentials-read.ts +208 -0
  182. package/src/matrix/credentials-write.runtime.ts +35 -0
  183. package/src/matrix/credentials.ts +95 -0
  184. package/src/matrix/deps.ts +309 -0
  185. package/src/matrix/device-health.ts +29 -0
  186. package/src/matrix/direct-management.ts +349 -0
  187. package/src/matrix/direct-room.ts +128 -0
  188. package/src/matrix/draft-stream.ts +225 -0
  189. package/src/matrix/encryption-guidance.ts +24 -0
  190. package/src/matrix/errors.ts +21 -0
  191. package/src/matrix/format.ts +426 -0
  192. package/src/matrix/legacy-crypto-inspector.ts +95 -0
  193. package/src/matrix/media-errors.ts +20 -0
  194. package/src/matrix/media-text.ts +162 -0
  195. package/src/matrix/monitor/access-state.ts +145 -0
  196. package/src/matrix/monitor/ack-config.ts +27 -0
  197. package/src/matrix/monitor/allowlist.ts +89 -0
  198. package/src/matrix/monitor/auto-join.ts +86 -0
  199. package/src/matrix/monitor/config.ts +569 -0
  200. package/src/matrix/monitor/context-summary.ts +43 -0
  201. package/src/matrix/monitor/direct.ts +296 -0
  202. package/src/matrix/monitor/events.ts +397 -0
  203. package/src/matrix/monitor/handler.ts +2266 -0
  204. package/src/matrix/monitor/inbound-dedupe.ts +267 -0
  205. package/src/matrix/monitor/index.ts +540 -0
  206. package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
  207. package/src/matrix/monitor/location.ts +108 -0
  208. package/src/matrix/monitor/media.ts +119 -0
  209. package/src/matrix/monitor/mentions.ts +256 -0
  210. package/src/matrix/monitor/reaction-events.ts +197 -0
  211. package/src/matrix/monitor/recent-invite.ts +30 -0
  212. package/src/matrix/monitor/replies.ts +136 -0
  213. package/src/matrix/monitor/reply-context.ts +92 -0
  214. package/src/matrix/monitor/room-history.ts +301 -0
  215. package/src/matrix/monitor/room-info.ts +126 -0
  216. package/src/matrix/monitor/rooms.ts +52 -0
  217. package/src/matrix/monitor/route.ts +179 -0
  218. package/src/matrix/monitor/runtime-api.ts +28 -0
  219. package/src/matrix/monitor/startup-verification.ts +237 -0
  220. package/src/matrix/monitor/startup.ts +218 -0
  221. package/src/matrix/monitor/status.ts +120 -0
  222. package/src/matrix/monitor/sync-lifecycle.ts +91 -0
  223. package/src/matrix/monitor/task-runner.ts +38 -0
  224. package/src/matrix/monitor/test-events.ts +21 -0
  225. package/src/matrix/monitor/thread-context.ts +108 -0
  226. package/src/matrix/monitor/threads.ts +85 -0
  227. package/src/matrix/monitor/types.ts +30 -0
  228. package/src/matrix/monitor/verification-events.ts +643 -0
  229. package/src/matrix/monitor/verification-utils.ts +46 -0
  230. package/src/matrix/outbound-media-runtime.ts +1 -0
  231. package/src/matrix/poll-summary.ts +110 -0
  232. package/src/matrix/poll-types.ts +429 -0
  233. package/src/matrix/probe.runtime.ts +4 -0
  234. package/src/matrix/probe.ts +97 -0
  235. package/src/matrix/profile.ts +184 -0
  236. package/src/matrix/reaction-common.ts +147 -0
  237. package/src/matrix/sdk/crypto-bootstrap.ts +438 -0
  238. package/src/matrix/sdk/crypto-facade.ts +242 -0
  239. package/src/matrix/sdk/crypto-node.runtime.ts +17 -0
  240. package/src/matrix/sdk/crypto-runtime.ts +14 -0
  241. package/src/matrix/sdk/decrypt-bridge.ts +410 -0
  242. package/src/matrix/sdk/event-helpers.ts +83 -0
  243. package/src/matrix/sdk/http-client.ts +87 -0
  244. package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
  245. package/src/matrix/sdk/idb-persistence.ts +288 -0
  246. package/src/matrix/sdk/logger.ts +108 -0
  247. package/src/matrix/sdk/read-response-with-limit.ts +19 -0
  248. package/src/matrix/sdk/recovery-key-store.ts +453 -0
  249. package/src/matrix/sdk/timeout-abort-signal.ts +1 -0
  250. package/src/matrix/sdk/transport-runtime-api.ts +18 -0
  251. package/src/matrix/sdk/transport.ts +352 -0
  252. package/src/matrix/sdk/types.ts +245 -0
  253. package/src/matrix/sdk/verification-manager.ts +795 -0
  254. package/src/matrix/sdk/verification-status.ts +23 -0
  255. package/src/matrix/sdk.ts +2152 -0
  256. package/src/matrix/send/client.ts +93 -0
  257. package/src/matrix/send/formatting.ts +189 -0
  258. package/src/matrix/send/media.ts +244 -0
  259. package/src/matrix/send/targets.ts +104 -0
  260. package/src/matrix/send/types.ts +131 -0
  261. package/src/matrix/send.ts +660 -0
  262. package/src/matrix/session-store-metadata.ts +108 -0
  263. package/src/matrix/startup-abort.ts +44 -0
  264. package/src/matrix/subagent-hooks.ts +308 -0
  265. package/src/matrix/sync-state.ts +27 -0
  266. package/src/matrix/target-ids.ts +79 -0
  267. package/src/matrix/thread-bindings-shared.ts +206 -0
  268. package/src/matrix/thread-bindings.ts +580 -0
  269. package/src/matrix-migration.runtime.ts +9 -0
  270. package/src/migration-config.ts +243 -0
  271. package/src/migration-snapshot-backup.ts +116 -0
  272. package/src/migration-snapshot.ts +53 -0
  273. package/src/onboarding.ts +775 -0
  274. package/src/outbound.ts +248 -0
  275. package/src/plugin-entry.runtime.js +115 -0
  276. package/src/plugin-entry.runtime.ts +70 -0
  277. package/src/profile-update.ts +71 -0
  278. package/src/record-shared.ts +3 -0
  279. package/src/resolve-targets.ts +175 -0
  280. package/src/resolver.runtime.ts +5 -0
  281. package/src/resolver.ts +21 -0
  282. package/src/runtime-api.ts +106 -0
  283. package/src/runtime.ts +13 -0
  284. package/src/secret-contract.ts +174 -0
  285. package/src/session-route.ts +126 -0
  286. package/src/setup-bootstrap.ts +102 -0
  287. package/src/setup-config.ts +222 -0
  288. package/src/setup-contract.ts +90 -0
  289. package/src/setup-core.ts +146 -0
  290. package/src/setup-dm-policy.ts +15 -0
  291. package/src/setup-surface.ts +4 -0
  292. package/src/startup-maintenance.ts +114 -0
  293. package/src/storage-paths.ts +92 -0
  294. package/src/thread-binding-api.ts +23 -0
  295. package/src/tool-actions.runtime.ts +1 -0
  296. package/src/tool-actions.ts +498 -0
  297. package/src/types.ts +257 -0
  298. package/subagent-hooks-api.ts +31 -0
  299. package/test-api.ts +21 -0
  300. package/thread-binding-api.ts +4 -0
  301. package/thread-bindings-runtime.ts +4 -0
  302. package/tsconfig.json +16 -0
  303. package/api.js +0 -7
  304. package/auth-presence.js +0 -7
  305. package/channel-plugin-api.js +0 -7
  306. package/cli-metadata.js +0 -7
  307. package/contract-api.js +0 -7
  308. package/doctor-contract-api.js +0 -7
  309. package/helper-api.js +0 -7
  310. package/index.js +0 -7
  311. package/plugin-entry.handlers.runtime.js +0 -7
  312. package/runtime-api.js +0 -7
  313. package/runtime-heavy-api.js +0 -7
  314. package/runtime-setter-api.js +0 -7
  315. package/secret-contract-api.js +0 -7
  316. package/setup-entry.js +0 -7
  317. package/setup-plugin-api.js +0 -7
  318. package/subagent-hooks-api.js +0 -7
  319. package/test-api.js +0 -7
  320. package/thread-binding-api.js +0 -7
  321. package/thread-bindings-runtime.js +0 -7
@@ -0,0 +1,4331 @@
1
+ import { t as isMatrixQualifiedUserId } from "./target-ids-Bsazo8si.js";
2
+ import { c as resolveMatrixAccountConfig, s as resolveMatrixAccountAllowlistConfig } from "./config-paths-DVvt6vM3.js";
3
+ import { t as getMatrixRuntime } from "./runtime-B-Fyrmxo.js";
4
+ import { m as resolveConfiguredMatrixBotUserIds } from "./setup-core-BEYoXF3J.js";
5
+ import { a as buildAllowlistResolutionSummary, c as createTypingCallbacks, d as logInboundDrop, f as logTypingFailure, h as toLocationContext, i as addAllowlistUserEntriesFromConfigEntry, l as formatLocationText, m as summarizeMapping, n as resolveMatrixStoredSessionMeta, o as canonicalizeAllowlistWithResolvedIds, p as patchAllowlistUsersInConfigEntries, r as resolveMatrixRoomConfig, s as createReplyPrefixOptions, u as getAgentScopedMediaLocalRoots } from "./channel-C0kCyTNB.js";
6
+ import { a as normalizeMatrixUserId, i as normalizeMatrixAllowList, o as resolveMatrixAllowListMatch } from "./config-schema-BMGOlhdI.js";
7
+ import { r as isMatrixNotFoundError, t as formatMatrixErrorMessage } from "./errors-BETj3zr9.js";
8
+ import { i as resolveMatrixStateFilePath } from "./storage-nyO0DOFE.js";
9
+ import { D as parsePollStartContent, S as formatPollAsText, T as isPollStartType, _ as readJoinedMatrixMembers, a as sendMessageMatrix, f as promoteMatrixDirectRoomCandidate, g as isStrictDirectMembership, h as hasDirectMatrixMemberFlag, t as chunkMatrixText, v as MATRIX_KLAW_FINALIZED_PREVIEW_KEY, w as isPollEventType } from "./send-CJunc6QM.js";
10
+ import { t as createMatrixThreadBindingManager } from "./thread-bindings-FjAZmDUP.js";
11
+ import { t as createAsyncLock } from "./async-lock-SsmtFXtt.js";
12
+ import { i as throwIfMatrixStartupAborted, o as LogService, r as isMatrixStartupAbortError } from "./startup-abort-B2J3MU_h.js";
13
+ import { i as isMatrixMediaSizeLimitError, r as MatrixMediaSizeLimitError } from "./http-client-DoQgbQsU.js";
14
+ import { n as isMatrixReadySyncState, r as isMatrixTerminalSyncState, t as isMatrixDisconnectedSyncState } from "./sync-state-Bx0gPaGA.js";
15
+ import { a as resolveMatrixMessageBody, i as resolveMatrixMessageAttachment, n as formatMatrixMediaUnavailableText, r as formatMatrixMessageText, s as fetchMatrixPollSnapshot, t as formatMatrixMediaTooLargeText } from "./media-text-ZhGA8Pcs.js";
16
+ import { n as setActiveMatrixClient } from "./active-client-CmFdvPdO.js";
17
+ import { t as isBunRuntime } from "./runtime-lwTSy9Yt.js";
18
+ import { c as backfillMatrixAuthDeviceIdAfterStartup, i as resolveSharedMatrixClient, l as resolveMatrixAuth, n as releaseSharedClientInstance, u as resolveMatrixAuthContext } from "./shared-D6MFMnpG.js";
19
+ import "./client-PhrTwuC4.js";
20
+ import { d as resolveDefaultGroupPolicy, h as warnMissingProviderGroupPolicyFallbackOnce, m as resolveThreadBindingMaxAgeMsForChannel, p as resolveThreadBindingIdleTimeoutMsForChannel, t as GROUP_POLICY_BLOCKED_LABEL, u as resolveAllowlistProviderRuntimeGroupPolicy } from "./runtime-api-BYXXkxq2.js";
21
+ import { t as resolveMatrixTargets } from "./resolve-targets-ChECUzD2.js";
22
+ import { t as formatMatrixEncryptedEventDisabledWarning } from "./encryption-guidance-BNEgckrZ.js";
23
+ import { a as EventType, i as resolveMatrixThreadRouting, n as resolveMatrixReplyToEventId, o as RelationType, r as resolveMatrixThreadRootId, t as resolveMatrixInboundRoute } from "./route-xRKj_ESW.js";
24
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringifiedOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
25
+ import { createPreviewMessageReceipt, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter } from "klaw/plugin-sdk/channel-message";
26
+ import { CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "klaw/plugin-sdk/approval-handler-adapter-runtime";
27
+ import { resolveInboundLastRouteSessionKey } from "klaw/plugin-sdk/routing";
28
+ import { loadSessionStore, resolveSessionStoreEntry } from "klaw/plugin-sdk/session-store-runtime";
29
+ import { readJsonFileWithFallback, writeJsonFileAtomically } from "klaw/plugin-sdk/json-store";
30
+ import { format } from "node:util";
31
+ import { buildTtsSupplementMediaPayload, getReplyPayloadTtsSupplement } from "klaw/plugin-sdk/reply-payload";
32
+ import { resolveAckReaction } from "klaw/plugin-sdk/channel-feedback";
33
+ import { hasFinalInboundReplyDispatch } from "klaw/plugin-sdk/inbound-reply-dispatch";
34
+ import { waitUntilAbort } from "klaw/plugin-sdk/channel-lifecycle";
35
+ import { registerChannelRuntimeContext } from "klaw/plugin-sdk/channel-runtime-context";
36
+ import { isDangerousNameMatchingEnabled } from "klaw/plugin-sdk/dangerous-name-runtime";
37
+ import { createChannelIngressResolver, defineStableChannelIngressIdentity } from "klaw/plugin-sdk/channel-ingress-runtime";
38
+ import { buildChannelProgressDraftLineForEntry, createChannelProgressDraftGate, formatChannelProgressDraftLine, formatChannelProgressDraftLineForEntry, formatChannelProgressDraftText, isChannelProgressDraftWorkToolName, mergeChannelProgressDraftLine, normalizeChannelProgressDraftLineIdentity, resolveChannelProgressDraftMaxLines } from "klaw/plugin-sdk/channel-streaming";
39
+ import { evaluateSupplementalContextVisibility, resolveChannelContextVisibilityMode } from "klaw/plugin-sdk/context-visibility-runtime";
40
+ import { mergePairLoopGuardConfig } from "klaw/plugin-sdk/pair-loop-guard-runtime";
41
+ import { buildInboundHistoryFromEntries } from "klaw/plugin-sdk/reply-history";
42
+ import { resolvePinnedMainDmOwnerFromAllowlist } from "klaw/plugin-sdk/security-runtime";
43
+ import { escapeRegExp } from "klaw/plugin-sdk/text-utility-runtime";
44
+ import { createConnectedChannelStatusPatch, createTransportActivityStatusPatch } from "klaw/plugin-sdk/gateway-runtime";
45
+ //#region extensions/matrix/src/matrix/monitor/auto-join.ts
46
+ function registerMatrixAutoJoin(params) {
47
+ const { client, accountConfig, runtime } = params;
48
+ const core = getMatrixRuntime();
49
+ const logVerbose = (message) => {
50
+ if (!core.logging.shouldLogVerbose()) return;
51
+ runtime.log?.(message);
52
+ };
53
+ const autoJoin = accountConfig.autoJoin ?? "off";
54
+ const rawAllowlist = (accountConfig.autoJoinAllowlist ?? []).map((entry) => normalizeStringifiedOptionalString(entry)).filter((entry) => Boolean(entry));
55
+ const autoJoinAllowlist = new Set(rawAllowlist);
56
+ const allowedRoomIds = new Set(rawAllowlist.filter((entry) => entry.startsWith("!")));
57
+ const allowedAliases = rawAllowlist.filter((entry) => entry.startsWith("#"));
58
+ const resolvedAliasRoomIds = /* @__PURE__ */ new Map();
59
+ if (autoJoin === "off") return;
60
+ if (autoJoin === "always") logVerbose("matrix: auto-join enabled for all invites");
61
+ else logVerbose("matrix: auto-join enabled for allowlist invites");
62
+ const resolveAllowedAliasRoomId = async (alias) => {
63
+ if (resolvedAliasRoomIds.has(alias)) return resolvedAliasRoomIds.get(alias) ?? null;
64
+ const resolved = await params.client.resolveRoom(alias);
65
+ if (resolved) resolvedAliasRoomIds.set(alias, resolved);
66
+ return resolved;
67
+ };
68
+ const resolveAllowedAliasRoomIds = async () => {
69
+ return (await Promise.all(allowedAliases.map(async (alias) => {
70
+ try {
71
+ return await resolveAllowedAliasRoomId(alias);
72
+ } catch (err) {
73
+ runtime.error?.(`matrix: failed resolving allowlisted alias ${alias}: ${String(err)}`);
74
+ return null;
75
+ }
76
+ }))).filter((roomId) => Boolean(roomId));
77
+ };
78
+ client.on("room.invite", async (roomId, _inviteEvent) => {
79
+ if (autoJoin === "allowlist") {
80
+ const allowedAliasRoomIds = await resolveAllowedAliasRoomIds();
81
+ if (!(autoJoinAllowlist.has("*") || allowedRoomIds.has(roomId) || allowedAliasRoomIds.some((resolvedRoomId) => resolvedRoomId === roomId))) {
82
+ logVerbose(`matrix: invite ignored (not in allowlist) room=${roomId}`);
83
+ return;
84
+ }
85
+ }
86
+ try {
87
+ await client.joinRoom(roomId);
88
+ logVerbose(`matrix: joined room ${roomId}`);
89
+ } catch (err) {
90
+ runtime.error?.(`matrix: failed to join room ${roomId}: ${String(err)}`);
91
+ }
92
+ });
93
+ }
94
+ //#endregion
95
+ //#region extensions/matrix/src/matrix/monitor/config.ts
96
+ function normalizeMatrixUserLookupEntry(raw) {
97
+ return raw.replace(/^matrix:/i, "").replace(/^user:/i, "").trim();
98
+ }
99
+ function normalizeMatrixRoomLookupEntry(raw) {
100
+ return raw.replace(/^matrix:/i, "").replace(/^(room|channel):/i, "").trim();
101
+ }
102
+ function filterResolvedMatrixAllowlistEntries(entries) {
103
+ return entries.filter((entry) => {
104
+ const trimmed = entry.trim();
105
+ if (!trimmed) return false;
106
+ if (trimmed === "*") return true;
107
+ return isMatrixQualifiedUserId(normalizeMatrixUserLookupEntry(trimmed));
108
+ });
109
+ }
110
+ function filterFailClosedMatrixAllowlistEntries(entries) {
111
+ return entries.filter((entry) => entry.trim().length > 0);
112
+ }
113
+ function listResolvedMatrixAllowlistEntries(params) {
114
+ const resolvedEntries = [];
115
+ const seen = /* @__PURE__ */ new Set();
116
+ for (const entry of params.entries) {
117
+ const input = String(entry).trim();
118
+ if (!input || seen.has(input)) continue;
119
+ seen.add(input);
120
+ const resolved = params.resolvedMap.get(input);
121
+ if (!resolved?.resolved || !resolved.id) continue;
122
+ const id = normalizeMatrixUserId(resolved.id);
123
+ if (isMatrixQualifiedUserId(id)) resolvedEntries.push({
124
+ input,
125
+ id
126
+ });
127
+ }
128
+ return resolvedEntries;
129
+ }
130
+ function normalizeConfiguredMatrixAllowlistEntries(entries) {
131
+ const normalized = [];
132
+ for (const entry of entries ?? []) {
133
+ const trimmed = String(entry).trim();
134
+ if (trimmed) normalized.push(trimmed);
135
+ }
136
+ return normalized;
137
+ }
138
+ function isMatrixDangerousNameMatchingEnabled(params) {
139
+ return isDangerousNameMatchingEnabled(resolveMatrixAccountConfig({
140
+ cfg: params.cfg,
141
+ accountId: params.accountId
142
+ }));
143
+ }
144
+ function addUniqueMatrixAllowlistEntry(params) {
145
+ const trimmed = params.entry.trim();
146
+ if (!trimmed) return;
147
+ const key = trimmed.toLowerCase();
148
+ if (params.seen.has(key)) return;
149
+ params.seen.add(key);
150
+ params.entries.push(trimmed);
151
+ }
152
+ function resolveStableMatrixMonitorUserEntries(entries) {
153
+ const directMatches = [];
154
+ for (const entry of entries) {
155
+ const input = String(entry).trim();
156
+ if (!input) continue;
157
+ const query = normalizeMatrixUserLookupEntry(input);
158
+ if (!query || query === "*") continue;
159
+ directMatches.push(isMatrixQualifiedUserId(query) ? {
160
+ input,
161
+ resolved: true,
162
+ id: normalizeMatrixUserId(query)
163
+ } : {
164
+ input,
165
+ resolved: false
166
+ });
167
+ }
168
+ return buildAllowlistResolutionSummary(directMatches);
169
+ }
170
+ function logStableMatrixAllowlistUnresolved(params) {
171
+ if (params.unresolved.length === 0) return;
172
+ summarizeMapping(params.label, [], params.unresolved, params.runtime);
173
+ params.runtime.log?.(`${params.label} entries must be full Matrix IDs (example: @user:server). Unresolved entries will not match any sender. To match Matrix display names, set channels.matrix.dangerouslyAllowNameMatching=true.`);
174
+ }
175
+ function resolveStableMatrixMonitorUserAllowlist(params) {
176
+ const allowList = params.allowList;
177
+ const resolution = resolveStableMatrixMonitorUserEntries(allowList);
178
+ const canonicalized = canonicalizeAllowlistWithResolvedIds({
179
+ existing: allowList,
180
+ resolvedMap: resolution.resolvedMap
181
+ });
182
+ logStableMatrixAllowlistUnresolved({
183
+ label: params.label,
184
+ unresolved: resolution.unresolved,
185
+ runtime: params.runtime
186
+ });
187
+ return {
188
+ entries: params.failClosedOnUnresolved ? filterFailClosedMatrixAllowlistEntries(canonicalized) : filterResolvedMatrixAllowlistEntries(canonicalized),
189
+ resolvedEntries: listResolvedMatrixAllowlistEntries({
190
+ entries: allowList,
191
+ resolvedMap: resolution.resolvedMap
192
+ })
193
+ };
194
+ }
195
+ async function resolveMatrixMonitorUserEntries(params) {
196
+ const directMatches = [];
197
+ const pending = [];
198
+ for (const entry of params.entries) {
199
+ const input = String(entry).trim();
200
+ if (!input) continue;
201
+ const query = normalizeMatrixUserLookupEntry(input);
202
+ if (!query || query === "*") continue;
203
+ if (isMatrixQualifiedUserId(query)) {
204
+ directMatches.push({
205
+ input,
206
+ resolved: true,
207
+ id: normalizeMatrixUserId(query)
208
+ });
209
+ continue;
210
+ }
211
+ pending.push({
212
+ input,
213
+ query
214
+ });
215
+ }
216
+ (pending.length === 0 ? [] : await params.resolveTargets({
217
+ cfg: params.cfg,
218
+ accountId: params.accountId,
219
+ inputs: pending.map((entry) => entry.query),
220
+ kind: "user",
221
+ runtime: params.runtime
222
+ })).forEach((entry, index) => {
223
+ const source = pending[index];
224
+ if (!source) return;
225
+ directMatches.push({
226
+ input: source.input,
227
+ resolved: entry.resolved,
228
+ id: entry.id ? normalizeMatrixUserId(entry.id) : void 0
229
+ });
230
+ });
231
+ return buildAllowlistResolutionSummary(directMatches);
232
+ }
233
+ async function resolveMatrixMonitorUserAllowlist(params) {
234
+ const allowList = (params.list ?? []).map(String);
235
+ if (allowList.length === 0) return {
236
+ entries: allowList,
237
+ resolvedEntries: []
238
+ };
239
+ if (!isMatrixDangerousNameMatchingEnabled({
240
+ cfg: params.cfg,
241
+ accountId: params.accountId
242
+ })) return resolveStableMatrixMonitorUserAllowlist({
243
+ allowList,
244
+ failClosedOnUnresolved: params.failClosedOnUnresolved,
245
+ label: params.label,
246
+ runtime: params.runtime
247
+ });
248
+ const resolution = await resolveMatrixMonitorUserEntries({
249
+ cfg: params.cfg,
250
+ accountId: params.accountId,
251
+ entries: allowList,
252
+ runtime: params.runtime,
253
+ resolveTargets: params.resolveTargets
254
+ });
255
+ const canonicalized = canonicalizeAllowlistWithResolvedIds({
256
+ existing: allowList,
257
+ resolvedMap: resolution.resolvedMap
258
+ });
259
+ summarizeMapping(params.label, resolution.mapping, resolution.unresolved, params.runtime);
260
+ if (resolution.unresolved.length > 0) params.runtime.log?.(`${params.label} entries must be full Matrix IDs (example: @user:server). Unresolved entries will not match any sender.`);
261
+ return {
262
+ entries: params.failClosedOnUnresolved ? filterFailClosedMatrixAllowlistEntries(canonicalized) : filterResolvedMatrixAllowlistEntries(canonicalized),
263
+ resolvedEntries: listResolvedMatrixAllowlistEntries({
264
+ entries: allowList,
265
+ resolvedMap: resolution.resolvedMap
266
+ })
267
+ };
268
+ }
269
+ async function resolveMatrixMonitorLiveUserAllowlist(params) {
270
+ const liveEntries = normalizeConfiguredMatrixAllowlistEntries(params.entries);
271
+ if (liveEntries.length === 0) return [];
272
+ const allowNameMatching = isMatrixDangerousNameMatchingEnabled({
273
+ cfg: params.cfg,
274
+ accountId: params.accountId
275
+ });
276
+ const effective = [];
277
+ const seen = /* @__PURE__ */ new Set();
278
+ const startupByInput = new Map((params.startupResolvedEntries ?? []).map((entry) => [entry.input, entry.id]));
279
+ const pending = [];
280
+ for (const entry of liveEntries) {
281
+ const query = normalizeMatrixUserLookupEntry(entry);
282
+ if (entry === "*") {
283
+ addUniqueMatrixAllowlistEntry({
284
+ entries: effective,
285
+ seen,
286
+ entry
287
+ });
288
+ continue;
289
+ }
290
+ if (isMatrixQualifiedUserId(query)) {
291
+ addUniqueMatrixAllowlistEntry({
292
+ entries: effective,
293
+ seen,
294
+ entry: normalizeMatrixUserId(query)
295
+ });
296
+ continue;
297
+ }
298
+ const startupId = startupByInput.get(entry);
299
+ if (allowNameMatching && startupId) {
300
+ addUniqueMatrixAllowlistEntry({
301
+ entries: effective,
302
+ seen,
303
+ entry: startupId
304
+ });
305
+ continue;
306
+ }
307
+ if (allowNameMatching) {
308
+ pending.push(entry);
309
+ continue;
310
+ }
311
+ if (params.failClosedOnUnresolved) addUniqueMatrixAllowlistEntry({
312
+ entries: effective,
313
+ seen,
314
+ entry
315
+ });
316
+ }
317
+ if (pending.length === 0) return effective;
318
+ const canonicalized = canonicalizeAllowlistWithResolvedIds({
319
+ existing: pending,
320
+ resolvedMap: (await resolveMatrixMonitorUserEntries({
321
+ cfg: params.cfg,
322
+ accountId: params.accountId,
323
+ entries: pending,
324
+ runtime: params.runtime,
325
+ resolveTargets: params.resolveTargets ?? resolveMatrixTargets
326
+ })).resolvedMap
327
+ });
328
+ const resolvedEntries = params.failClosedOnUnresolved ? filterFailClosedMatrixAllowlistEntries(canonicalized) : filterResolvedMatrixAllowlistEntries(canonicalized);
329
+ for (const entry of resolvedEntries) addUniqueMatrixAllowlistEntry({
330
+ entries: effective,
331
+ seen,
332
+ entry
333
+ });
334
+ return effective;
335
+ }
336
+ async function resolveMatrixMonitorRoomsConfig(params) {
337
+ const roomsConfig = params.roomsConfig;
338
+ if (!roomsConfig || Object.keys(roomsConfig).length === 0) return roomsConfig;
339
+ const mapping = [];
340
+ const unresolved = [];
341
+ const nextRooms = {};
342
+ const allowNameMatching = isMatrixDangerousNameMatchingEnabled({
343
+ cfg: params.cfg,
344
+ accountId: params.accountId
345
+ });
346
+ if (roomsConfig["*"]) nextRooms["*"] = roomsConfig["*"];
347
+ const pending = [];
348
+ for (const [entry, roomConfig] of Object.entries(roomsConfig)) {
349
+ if (entry === "*") continue;
350
+ const input = entry.trim();
351
+ if (!input) continue;
352
+ const cleaned = normalizeMatrixRoomLookupEntry(input);
353
+ if (!cleaned) {
354
+ unresolved.push(entry);
355
+ continue;
356
+ }
357
+ if (cleaned.startsWith("!") && cleaned.includes(":")) {
358
+ if (!nextRooms[cleaned]) nextRooms[cleaned] = roomConfig;
359
+ if (cleaned !== input) mapping.push(`${input}→${cleaned}`);
360
+ continue;
361
+ }
362
+ if (!cleaned.startsWith("#") && !allowNameMatching) {
363
+ unresolved.push(input);
364
+ continue;
365
+ }
366
+ pending.push({
367
+ input,
368
+ query: cleaned,
369
+ config: roomConfig
370
+ });
371
+ }
372
+ if (pending.length > 0) (await params.resolveTargets({
373
+ cfg: params.cfg,
374
+ accountId: params.accountId,
375
+ inputs: pending.map((entry) => entry.query),
376
+ kind: "group",
377
+ runtime: params.runtime
378
+ })).forEach((entry, index) => {
379
+ const source = pending[index];
380
+ if (!source) return;
381
+ if (entry.resolved && entry.id) {
382
+ const roomKey = normalizeMatrixRoomLookupEntry(entry.id);
383
+ if (!nextRooms[roomKey]) nextRooms[roomKey] = source.config;
384
+ mapping.push(`${source.input}→${roomKey}`);
385
+ } else unresolved.push(source.input);
386
+ });
387
+ summarizeMapping("matrix rooms", mapping, unresolved, params.runtime);
388
+ if (unresolved.length > 0) params.runtime.log?.("matrix rooms must be room IDs or aliases (example: !room:server or #alias:server). Unresolved entries are ignored.");
389
+ const roomUsers = /* @__PURE__ */ new Set();
390
+ for (const roomConfig of Object.values(nextRooms)) addAllowlistUserEntriesFromConfigEntry(roomUsers, roomConfig);
391
+ if (roomUsers.size === 0) return nextRooms;
392
+ if (!allowNameMatching) {
393
+ const resolution = resolveStableMatrixMonitorUserEntries(Array.from(roomUsers));
394
+ logStableMatrixAllowlistUnresolved({
395
+ label: "matrix room users",
396
+ unresolved: resolution.unresolved,
397
+ runtime: params.runtime
398
+ });
399
+ return patchAllowlistUsersInConfigEntries({
400
+ entries: nextRooms,
401
+ resolvedMap: resolution.resolvedMap,
402
+ strategy: "canonicalize"
403
+ });
404
+ }
405
+ const resolution = await resolveMatrixMonitorUserEntries({
406
+ cfg: params.cfg,
407
+ accountId: params.accountId,
408
+ entries: Array.from(roomUsers),
409
+ runtime: params.runtime,
410
+ resolveTargets: params.resolveTargets
411
+ });
412
+ summarizeMapping("matrix room users", resolution.mapping, resolution.unresolved, params.runtime);
413
+ if (resolution.unresolved.length > 0) params.runtime.log?.("matrix room users entries must be full Matrix IDs (example: @user:server). Unresolved entries will not match any sender.");
414
+ return patchAllowlistUsersInConfigEntries({
415
+ entries: nextRooms,
416
+ resolvedMap: resolution.resolvedMap,
417
+ strategy: "canonicalize"
418
+ });
419
+ }
420
+ async function resolveMatrixMonitorConfig(params) {
421
+ const resolveTargets = params.resolveTargets ?? resolveMatrixTargets;
422
+ const [allowFrom, groupAllowFrom, roomsConfig] = await Promise.all([
423
+ resolveMatrixMonitorUserAllowlist({
424
+ cfg: params.cfg,
425
+ accountId: params.accountId,
426
+ label: "matrix dm allowlist",
427
+ list: params.allowFrom,
428
+ runtime: params.runtime,
429
+ resolveTargets
430
+ }),
431
+ resolveMatrixMonitorUserAllowlist({
432
+ cfg: params.cfg,
433
+ accountId: params.accountId,
434
+ label: "matrix group allowlist",
435
+ list: params.groupAllowFrom,
436
+ failClosedOnUnresolved: true,
437
+ runtime: params.runtime,
438
+ resolveTargets
439
+ }),
440
+ resolveMatrixMonitorRoomsConfig({
441
+ cfg: params.cfg,
442
+ accountId: params.accountId,
443
+ roomsConfig: params.roomsConfig,
444
+ runtime: params.runtime,
445
+ resolveTargets
446
+ })
447
+ ]);
448
+ return {
449
+ allowFrom: allowFrom.entries,
450
+ allowFromResolvedEntries: allowFrom.resolvedEntries,
451
+ groupAllowFrom: groupAllowFrom.entries,
452
+ groupAllowFromResolvedEntries: groupAllowFrom.resolvedEntries,
453
+ roomsConfig
454
+ };
455
+ }
456
+ //#endregion
457
+ //#region extensions/matrix/src/matrix/monitor/direct.ts
458
+ const DM_CACHE_TTL_MS = 3e4;
459
+ const RECENT_INVITE_TTL_MS = 3e4;
460
+ const MAX_TRACKED_DM_ROOMS = 1024;
461
+ const MAX_TRACKED_DM_MEMBER_FLAGS = 2048;
462
+ function rememberBounded$1(map, key, value, maxSize = MAX_TRACKED_DM_ROOMS) {
463
+ map.set(key, value);
464
+ if (map.size > maxSize) {
465
+ const oldest = map.keys().next().value;
466
+ if (typeof oldest === "string") map.delete(oldest);
467
+ }
468
+ }
469
+ function createDirectRoomTracker(client, opts = {}) {
470
+ const log = opts.log ?? (() => {});
471
+ let lastDmUpdateMs = 0;
472
+ let hasSeededDmCache = false;
473
+ let cachedSelfUserId = null;
474
+ const joinedMembersCache = /* @__PURE__ */ new Map();
475
+ const directMemberFlagCache = /* @__PURE__ */ new Map();
476
+ const recentInviteCandidates = /* @__PURE__ */ new Map();
477
+ const locallyPromotedDirectRooms = /* @__PURE__ */ new Map();
478
+ const ensureSelfUserId = async () => {
479
+ if (cachedSelfUserId) return cachedSelfUserId;
480
+ try {
481
+ cachedSelfUserId = await client.getUserId();
482
+ } catch {
483
+ cachedSelfUserId = null;
484
+ }
485
+ return cachedSelfUserId;
486
+ };
487
+ const refreshDmCache = async () => {
488
+ const now = Date.now();
489
+ if (now - lastDmUpdateMs < DM_CACHE_TTL_MS) return;
490
+ lastDmUpdateMs = now;
491
+ hasSeededDmCache = await client.dms.update() || hasSeededDmCache;
492
+ };
493
+ const resolveJoinedMembers = async (roomId) => {
494
+ const cached = joinedMembersCache.get(roomId);
495
+ const now = Date.now();
496
+ if (cached && now - cached.ts < DM_CACHE_TTL_MS) return cached.members;
497
+ try {
498
+ const normalized = await readJoinedMatrixMembers(client, roomId);
499
+ if (!normalized) throw new Error("membership unavailable");
500
+ rememberBounded$1(joinedMembersCache, roomId, {
501
+ members: normalized,
502
+ ts: now
503
+ });
504
+ return normalized;
505
+ } catch (err) {
506
+ log(`matrix: dm member lookup failed room=${roomId} (${String(err)})`);
507
+ return null;
508
+ }
509
+ };
510
+ const resolveDirectMemberFlag = async (roomId, userId) => {
511
+ const normalizedUserId = userId?.trim();
512
+ if (!normalizedUserId) return null;
513
+ const cacheKey = `${roomId}\n${normalizedUserId}`;
514
+ const cached = directMemberFlagCache.get(cacheKey);
515
+ const now = Date.now();
516
+ if (cached && now - cached.ts < DM_CACHE_TTL_MS) return cached.isDirect;
517
+ const isDirect = await hasDirectMatrixMemberFlag(client, roomId, normalizedUserId);
518
+ rememberBounded$1(directMemberFlagCache, cacheKey, {
519
+ isDirect,
520
+ ts: now
521
+ }, MAX_TRACKED_DM_MEMBER_FLAGS);
522
+ return isDirect;
523
+ };
524
+ const hasRecentInviteCandidate = (roomId, remoteUserId) => {
525
+ const normalizedRemoteUserId = remoteUserId?.trim();
526
+ if (!normalizedRemoteUserId) return false;
527
+ const cached = recentInviteCandidates.get(roomId);
528
+ if (!cached) return false;
529
+ if (Date.now() - cached.ts >= RECENT_INVITE_TTL_MS) {
530
+ recentInviteCandidates.delete(roomId);
531
+ return false;
532
+ }
533
+ return cached.remoteUserId === normalizedRemoteUserId;
534
+ };
535
+ const canPromoteRecentInvite = async (roomId) => {
536
+ try {
537
+ return await opts.canPromoteRecentInvite?.(roomId) ?? true;
538
+ } catch (err) {
539
+ log(`matrix: recent invite promotion veto failed room=${roomId} (${String(err)})`);
540
+ return false;
541
+ }
542
+ };
543
+ const canPromoteUnmappedStrictRoom = async (roomId) => {
544
+ try {
545
+ return await opts.canPromoteUnmappedStrictRoom?.(roomId) ?? false;
546
+ } catch (err) {
547
+ log(`matrix: unmapped strict room promotion veto failed room=${roomId} (${String(err)})`);
548
+ return false;
549
+ }
550
+ };
551
+ const shouldKeepLocallyPromotedDirectRoom = async (roomId) => {
552
+ try {
553
+ return await opts.shouldKeepLocallyPromotedDirectRoom?.(roomId);
554
+ } catch (err) {
555
+ log(`matrix: local promotion keep-check failed room=${roomId} (${String(err)})`);
556
+ return;
557
+ }
558
+ };
559
+ const hasLocallyPromotedDirectRoom = (roomId, remoteUserId) => {
560
+ const normalizedRemoteUserId = remoteUserId?.trim();
561
+ if (!normalizedRemoteUserId) return false;
562
+ return locallyPromotedDirectRooms.get(roomId)?.remoteUserId === normalizedRemoteUserId;
563
+ };
564
+ const rememberLocallyPromotedDirectRoom = (roomId, remoteUserId) => {
565
+ const normalizedRemoteUserId = remoteUserId.trim();
566
+ if (!normalizedRemoteUserId) return;
567
+ rememberBounded$1(locallyPromotedDirectRooms, roomId, { remoteUserId: normalizedRemoteUserId });
568
+ };
569
+ return {
570
+ invalidateRoom: (roomId) => {
571
+ joinedMembersCache.delete(roomId);
572
+ for (const key of directMemberFlagCache.keys()) if (key.startsWith(`${roomId}\n`)) directMemberFlagCache.delete(key);
573
+ lastDmUpdateMs = 0;
574
+ log(`matrix: invalidated dm cache room=${roomId}`);
575
+ },
576
+ rememberInvite: (roomId, remoteUserId) => {
577
+ const normalizedRemoteUserId = remoteUserId.trim();
578
+ if (!normalizedRemoteUserId) return;
579
+ rememberBounded$1(recentInviteCandidates, roomId, {
580
+ remoteUserId: normalizedRemoteUserId,
581
+ ts: Date.now()
582
+ });
583
+ log(`matrix: remembered invite candidate room=${roomId} sender=${normalizedRemoteUserId}`);
584
+ },
585
+ isDirectMessage: async (params) => {
586
+ const { roomId, senderId } = params;
587
+ const selfUserId = params.selfUserId ?? await ensureSelfUserId();
588
+ const joinedMembers = await resolveJoinedMembers(roomId);
589
+ const strictDirectMembership = isStrictDirectMembership({
590
+ selfUserId,
591
+ remoteUserId: senderId,
592
+ joinedMembers
593
+ });
594
+ try {
595
+ await refreshDmCache();
596
+ } catch (err) {
597
+ log(`matrix: dm cache refresh failed (${String(err)})`);
598
+ }
599
+ if (client.dms.isDm(roomId)) {
600
+ if (strictDirectMembership) {
601
+ log(`matrix: dm detected via m.direct room=${roomId}`);
602
+ return true;
603
+ }
604
+ log(`matrix: ignoring stale m.direct classification room=${roomId}`);
605
+ }
606
+ if (strictDirectMembership) {
607
+ const directViaSelf = await resolveDirectMemberFlag(roomId, selfUserId);
608
+ if (directViaSelf === true) {
609
+ log(`matrix: dm detected via member state room=${roomId}`);
610
+ return true;
611
+ }
612
+ if (directViaSelf === false) {
613
+ log(`matrix: dm rejected via member state room=${roomId}`);
614
+ return false;
615
+ }
616
+ if (!hasSeededDmCache) {
617
+ log(`matrix: dm detected via exact 2-member fallback before dm cache seed room=${roomId}`);
618
+ return true;
619
+ }
620
+ if (hasLocallyPromotedDirectRoom(roomId, senderId)) {
621
+ if (await shouldKeepLocallyPromotedDirectRoom(roomId) !== false) {
622
+ log(`matrix: dm detected via local promotion room=${roomId}`);
623
+ return true;
624
+ }
625
+ locallyPromotedDirectRooms.delete(roomId);
626
+ log(`matrix: local promotion cleared room=${roomId}`);
627
+ }
628
+ if (hasRecentInviteCandidate(roomId, senderId) && await canPromoteRecentInvite(roomId)) {
629
+ const promotion = await promoteMatrixDirectRoomCandidate({
630
+ client,
631
+ remoteUserId: senderId ?? "",
632
+ roomId,
633
+ selfUserId
634
+ });
635
+ if (promotion.classifyAsDirect) {
636
+ rememberLocallyPromotedDirectRoom(roomId, senderId ?? "");
637
+ log(`matrix: dm detected via recent invite room=${roomId} reason=${promotion.reason} repaired=${String(promotion.repaired)}`);
638
+ return true;
639
+ }
640
+ }
641
+ if (await canPromoteUnmappedStrictRoom(roomId)) {
642
+ const promotion = await promoteMatrixDirectRoomCandidate({
643
+ client,
644
+ remoteUserId: senderId ?? "",
645
+ roomId,
646
+ selfUserId
647
+ });
648
+ if (promotion.classifyAsDirect) {
649
+ rememberLocallyPromotedDirectRoom(roomId, senderId ?? "");
650
+ log(`matrix: dm detected via per-room strict fallback room=${roomId} reason=${promotion.reason} repaired=${String(promotion.repaired)}`);
651
+ return true;
652
+ }
653
+ }
654
+ }
655
+ log(`matrix: dm check room=${roomId} result=group members=${joinedMembers?.length ?? "unknown"}`);
656
+ return false;
657
+ }
658
+ };
659
+ }
660
+ //#endregion
661
+ //#region extensions/matrix/src/matrix/monitor/access-state.ts
662
+ function normalizeMatrixEntry(raw) {
663
+ return normalizeMatrixAllowList([raw ?? ""])[0] ?? null;
664
+ }
665
+ const matrixIngressIdentity = defineStableChannelIngressIdentity({
666
+ key: "sender-id",
667
+ normalize: normalizeMatrixEntry,
668
+ matchEntry({ subject, entry }) {
669
+ const senderId = subject.identifiers[0]?.value;
670
+ return entry.value === "*" || resolveMatrixAllowListMatch({
671
+ allowList: [entry.value],
672
+ userId: senderId ?? ""
673
+ }).allowed;
674
+ }
675
+ });
676
+ function resolveMatrixGroupIngress(params) {
677
+ if (params.groupPolicy === "disabled") return {
678
+ groupPolicy: "disabled",
679
+ groupAllowFrom: []
680
+ };
681
+ if (params.effectiveRoomUsers.length > 0) return {
682
+ groupPolicy: "allowlist",
683
+ groupAllowFrom: params.effectiveRoomUsers
684
+ };
685
+ if (params.groupPolicy === "allowlist" && params.effectiveGroupAllowFrom.length > 0) return {
686
+ groupPolicy: "allowlist",
687
+ groupAllowFrom: params.effectiveGroupAllowFrom
688
+ };
689
+ return {
690
+ groupPolicy: "open",
691
+ groupAllowFrom: []
692
+ };
693
+ }
694
+ async function resolveMatrixMonitorAccessState(params) {
695
+ const dmPolicy = params.dmPolicy ?? "pairing";
696
+ const groupPolicy = params.groupPolicy ?? "open";
697
+ const effectiveGroupAllowFrom = normalizeMatrixAllowList(params.groupAllowFrom);
698
+ const effectiveRoomUsers = normalizeMatrixAllowList(params.roomUsers);
699
+ const groupIngress = resolveMatrixGroupIngress({
700
+ groupPolicy,
701
+ effectiveGroupAllowFrom,
702
+ effectiveRoomUsers
703
+ });
704
+ const accountId = params.accountId ?? "default";
705
+ const eventKind = params.eventKind ?? "message";
706
+ return {
707
+ effectiveGroupAllowFrom,
708
+ effectiveRoomUsers,
709
+ messageIngress: await createChannelIngressResolver({
710
+ channelId: "matrix",
711
+ accountId,
712
+ identity: matrixIngressIdentity,
713
+ readStoreAllowFrom: async () => params.storeAllowFrom
714
+ }).message({
715
+ subject: { stableId: params.senderId },
716
+ conversation: {
717
+ kind: params.isRoom ? "group" : "direct",
718
+ id: params.isRoom ? "matrix-room" : "matrix-dm"
719
+ },
720
+ event: {
721
+ kind: eventKind,
722
+ authMode: "inbound",
723
+ mayPair: params.isRoom ? false : eventKind === "message"
724
+ },
725
+ dmPolicy,
726
+ groupPolicy: params.isRoom ? groupIngress.groupPolicy : "disabled",
727
+ policy: { groupAllowFromFallbackToAllowFrom: false },
728
+ allowFrom: params.allowFrom,
729
+ ...params.isRoom ? { groupAllowFrom: groupIngress.groupAllowFrom } : {}
730
+ }),
731
+ accountId,
732
+ senderId: params.senderId,
733
+ isRoom: params.isRoom
734
+ };
735
+ }
736
+ async function resolveMatrixMonitorCommandAccess(state, params) {
737
+ const commandAllowFrom = state.isRoom ? [] : state.messageIngress.senderAccess.effectiveAllowFrom;
738
+ const commandGroupAllowFrom = state.effectiveRoomUsers.length > 0 ? state.effectiveRoomUsers : state.effectiveGroupAllowFrom;
739
+ return (await createChannelIngressResolver({
740
+ channelId: "matrix",
741
+ accountId: state.accountId,
742
+ identity: matrixIngressIdentity
743
+ }).command({
744
+ subject: { stableId: state.senderId },
745
+ conversation: {
746
+ kind: state.isRoom ? "group" : "direct",
747
+ id: state.isRoom ? "matrix-room" : "matrix-dm"
748
+ },
749
+ dmPolicy: "allowlist",
750
+ groupPolicy: "allowlist",
751
+ policy: { groupAllowFromFallbackToAllowFrom: false },
752
+ allowFrom: commandAllowFrom,
753
+ groupAllowFrom: commandGroupAllowFrom,
754
+ command: {
755
+ useAccessGroups: params.useAccessGroups,
756
+ allowTextCommands: params.allowTextCommands,
757
+ hasControlCommand: params.hasControlCommand,
758
+ groupOwnerAllowFrom: "none",
759
+ commandGroupAllowFromFallbackToAllowFrom: false
760
+ }
761
+ })).commandAccess;
762
+ }
763
+ //#endregion
764
+ //#region extensions/matrix/src/matrix/monitor/verification-utils.ts
765
+ const VERIFICATION_EVENT_PREFIX = "m.key.verification.";
766
+ const VERIFICATION_REQUEST_MSGTYPE = "m.key.verification.request";
767
+ const VERIFICATION_NOTICE_PREFIXES = [
768
+ "Matrix verification request received from ",
769
+ "Matrix verification is ready with ",
770
+ "Matrix verification started with ",
771
+ "Matrix verification completed with ",
772
+ "Matrix verification cancelled by ",
773
+ "Matrix verification SAS with "
774
+ ];
775
+ function trimMaybeString$1(input) {
776
+ return normalizeOptionalString(input) ?? "";
777
+ }
778
+ function isMatrixVerificationEventType(type) {
779
+ return trimMaybeString$1(type).startsWith(VERIFICATION_EVENT_PREFIX);
780
+ }
781
+ function isMatrixVerificationRequestMsgType(msgtype) {
782
+ return trimMaybeString$1(msgtype) === VERIFICATION_REQUEST_MSGTYPE;
783
+ }
784
+ function isMatrixVerificationNoticeBody(body) {
785
+ const text = trimMaybeString$1(body);
786
+ return VERIFICATION_NOTICE_PREFIXES.some((prefix) => text.startsWith(prefix));
787
+ }
788
+ function isMatrixVerificationRoomMessage(content) {
789
+ return isMatrixVerificationRequestMsgType(content.msgtype) || trimMaybeString$1(content.msgtype) === "m.notice" && isMatrixVerificationNoticeBody(content.body);
790
+ }
791
+ const matrixVerificationConstants = {
792
+ eventPrefix: VERIFICATION_EVENT_PREFIX,
793
+ requestMsgtype: VERIFICATION_REQUEST_MSGTYPE
794
+ };
795
+ //#endregion
796
+ //#region extensions/matrix/src/matrix/monitor/verification-events.ts
797
+ const MAX_TRACKED_VERIFICATION_EVENTS = 1024;
798
+ const SAS_NOTICE_RETRY_DELAY_MS = 750;
799
+ const VERIFICATION_EVENT_STARTUP_GRACE_MS = 3e4;
800
+ let matrixDirectRoomDepsPromise;
801
+ async function loadMatrixDirectRoomDeps() {
802
+ matrixDirectRoomDepsPromise ??= Promise.all([import("./send-CJunc6QM.js").then((n) => n.d), import("./send-CJunc6QM.js").then((n) => n.m)]).then(([directManagementModule, directRoomModule]) => ({
803
+ inspectMatrixDirectRooms: directManagementModule.inspectMatrixDirectRooms,
804
+ isStrictDirectRoom: directRoomModule.isStrictDirectRoom
805
+ }));
806
+ return await matrixDirectRoomDepsPromise;
807
+ }
808
+ function trimMaybeString(input) {
809
+ if (typeof input !== "string") return null;
810
+ const trimmed = input.trim();
811
+ return trimmed.length > 0 ? trimmed : null;
812
+ }
813
+ function readVerificationSignal(event) {
814
+ const type = trimMaybeString(event?.type) ?? "";
815
+ const content = event?.content ?? {};
816
+ const msgtype = trimMaybeString(content.msgtype) ?? "";
817
+ const relatedEventId = trimMaybeString(content["m.relates_to"]?.event_id);
818
+ const transactionId = trimMaybeString(content.transaction_id);
819
+ if (type === EventType.RoomMessage && isMatrixVerificationRequestMsgType(msgtype)) return {
820
+ stage: "request",
821
+ flowId: trimMaybeString(event.event_id) ?? transactionId ?? relatedEventId
822
+ };
823
+ if (!isMatrixVerificationEventType(type)) return null;
824
+ const flowId = transactionId ?? relatedEventId ?? trimMaybeString(event.event_id);
825
+ if (type === `${matrixVerificationConstants.eventPrefix}request`) return {
826
+ stage: "request",
827
+ flowId
828
+ };
829
+ if (type === `${matrixVerificationConstants.eventPrefix}ready`) return {
830
+ stage: "ready",
831
+ flowId
832
+ };
833
+ if (type === "m.key.verification.start") return {
834
+ stage: "start",
835
+ flowId
836
+ };
837
+ if (type === "m.key.verification.cancel") return {
838
+ stage: "cancel",
839
+ flowId
840
+ };
841
+ if (type === "m.key.verification.done") return {
842
+ stage: "done",
843
+ flowId
844
+ };
845
+ return {
846
+ stage: "other",
847
+ flowId
848
+ };
849
+ }
850
+ function formatVerificationStageNotice(params) {
851
+ const { stage, senderId, event } = params;
852
+ const content = event.content;
853
+ switch (stage) {
854
+ case "request": return `Matrix verification request received from ${senderId}. Open "Verify by emoji" in your Matrix client to continue.`;
855
+ case "ready": return `Matrix verification is ready with ${senderId}. Choose "Verify by emoji" to reveal the emoji sequence.`;
856
+ case "start": return `Matrix verification started with ${senderId}.`;
857
+ case "done": return `Matrix verification completed with ${senderId}.`;
858
+ case "cancel": {
859
+ const code = trimMaybeString(content.code);
860
+ const reason = trimMaybeString(content.reason);
861
+ if (code && reason) return `Matrix verification cancelled by ${senderId} (${code}: ${reason}).`;
862
+ if (reason) return `Matrix verification cancelled by ${senderId} (${reason}).`;
863
+ return `Matrix verification cancelled by ${senderId}.`;
864
+ }
865
+ default: return null;
866
+ }
867
+ }
868
+ function formatVerificationSasNotice(summary) {
869
+ const sas = summary.sas;
870
+ if (!sas) return null;
871
+ const emojiLine = Array.isArray(sas.emoji) && sas.emoji.length > 0 ? `SAS emoji: ${sas.emoji.map(([emoji, name]) => `${trimMaybeString(emoji) ?? "?"} ${trimMaybeString(name) ?? "?"}`).join(" | ")}` : null;
872
+ const decimalLine = Array.isArray(sas.decimal) && sas.decimal.length === 3 ? `SAS decimal: ${sas.decimal.join(" ")}` : null;
873
+ if (!emojiLine && !decimalLine) return null;
874
+ const lines = [`Matrix verification SAS with ${summary.otherUserId}:`];
875
+ if (emojiLine) lines.push(emojiLine);
876
+ if (decimalLine) lines.push(decimalLine);
877
+ lines.push("If both sides match, choose 'They match' in your Matrix app.");
878
+ return lines.join("\n");
879
+ }
880
+ function resolveVerificationFlowCandidates(params) {
881
+ const { event, flowId } = params;
882
+ const content = event.content;
883
+ const candidates = /* @__PURE__ */ new Set();
884
+ const add = (value) => {
885
+ const normalized = trimMaybeString(value);
886
+ if (normalized) candidates.add(normalized);
887
+ };
888
+ add(flowId);
889
+ add(event.event_id);
890
+ add(content.transaction_id);
891
+ add(content["m.relates_to"]?.event_id);
892
+ return Array.from(candidates);
893
+ }
894
+ function resolveSummaryRecency(summary) {
895
+ const ts = Date.parse(summary.updatedAt ?? "");
896
+ return Number.isFinite(ts) ? ts : 0;
897
+ }
898
+ function isActiveVerificationSummary(summary) {
899
+ if (summary.completed === true) return false;
900
+ if (summary.phaseName === "cancelled" || summary.phaseName === "done") return false;
901
+ if (typeof summary.phase === "number" && summary.phase >= 4) return false;
902
+ return true;
903
+ }
904
+ async function resolveVerificationSummaryForSignal(client, params) {
905
+ if (!client.crypto) return null;
906
+ await client.crypto.ensureVerificationDmTracked({
907
+ roomId: params.roomId,
908
+ userId: params.senderId
909
+ }).catch(() => null);
910
+ const list = await client.crypto.listVerifications();
911
+ if (list.length === 0) return null;
912
+ const candidates = resolveVerificationFlowCandidates({
913
+ event: params.event,
914
+ flowId: params.flowId
915
+ });
916
+ const byTransactionId = list.find((entry) => candidates.some((candidate) => entry.transactionId === candidate));
917
+ if (byTransactionId) return byTransactionId;
918
+ const { inspectMatrixDirectRooms, isStrictDirectRoom } = await loadMatrixDirectRoomDeps();
919
+ const activeRoomId = trimMaybeString((await inspectMatrixDirectRooms({
920
+ client,
921
+ remoteUserId: params.senderId
922
+ }).catch(() => null))?.activeRoomId);
923
+ if (activeRoomId) {
924
+ if (activeRoomId !== params.roomId) return null;
925
+ } else if (!await isStrictDirectRoom({
926
+ client,
927
+ roomId: params.roomId,
928
+ remoteUserId: params.senderId
929
+ })) return null;
930
+ const activeByUser = list.filter((entry) => entry.otherUserId === params.senderId && isActiveVerificationSummary(entry)).toSorted((a, b) => resolveSummaryRecency(b) - resolveSummaryRecency(a));
931
+ const activeInRoom = activeByUser.filter((entry) => {
932
+ return trimMaybeString(entry.roomId) === params.roomId;
933
+ });
934
+ if (activeInRoom.length > 0) return activeInRoom[0] ?? null;
935
+ return activeByUser[0] ?? null;
936
+ }
937
+ async function resolveVerificationSasNoticeForSignal(client, params) {
938
+ const summary = await resolveVerificationSummaryForSignal(client, params);
939
+ const immediateNotice = summary && isActiveVerificationSummary(summary) ? formatVerificationSasNotice(summary) : null;
940
+ if (immediateNotice || params.stage !== "ready" && params.stage !== "start") return {
941
+ summary,
942
+ sasNotice: immediateNotice
943
+ };
944
+ await new Promise((resolve) => setTimeout(resolve, params.sasNoticeRetryDelayMs ?? SAS_NOTICE_RETRY_DELAY_MS));
945
+ const retriedSummary = await resolveVerificationSummaryForSignal(client, params);
946
+ return {
947
+ summary: retriedSummary,
948
+ sasNotice: retriedSummary && isActiveVerificationSummary(retriedSummary) ? formatVerificationSasNotice(retriedSummary) : null
949
+ };
950
+ }
951
+ function trackBounded(set, value) {
952
+ if (!value || set.has(value)) return false;
953
+ set.add(value);
954
+ if (set.size > MAX_TRACKED_VERIFICATION_EVENTS) {
955
+ const oldest = set.values().next().value;
956
+ if (typeof oldest === "string") set.delete(oldest);
957
+ }
958
+ return true;
959
+ }
960
+ async function sendVerificationNotice(params) {
961
+ const roomId = trimMaybeString(params.roomId);
962
+ if (!roomId) return;
963
+ try {
964
+ await params.client.sendMessage(roomId, {
965
+ msgtype: "m.notice",
966
+ body: params.body
967
+ });
968
+ } catch (err) {
969
+ params.logVerboseMessage(`matrix: failed sending verification notice room=${roomId}: ${String(err)}`);
970
+ }
971
+ }
972
+ async function isVerificationNoticeAuthorized(params) {
973
+ if (!params.dmEnabled || params.dmPolicy === "disabled") {
974
+ params.logVerboseMessage(`matrix: blocked verification sender ${params.senderId} (dmPolicy=${params.dmPolicy}, dmEnabled=${String(params.dmEnabled)})`);
975
+ return false;
976
+ }
977
+ const storeAllowFrom = params.dmPolicy !== "allowlist" && params.dmPolicy !== "open" ? await params.readStoreAllowFrom() : [];
978
+ if ((await resolveMatrixMonitorAccessState({
979
+ allowFrom: params.allowFrom,
980
+ storeAllowFrom,
981
+ dmPolicy: params.dmPolicy,
982
+ groupPolicy: "open",
983
+ groupAllowFrom: [],
984
+ roomUsers: [],
985
+ senderId: params.senderId,
986
+ isRoom: false
987
+ })).messageIngress.senderAccess.decision === "allow") return true;
988
+ params.logVerboseMessage(`matrix: blocked verification sender ${params.senderId} (dmPolicy=${params.dmPolicy})`);
989
+ return false;
990
+ }
991
+ function createMatrixVerificationEventRouter(params) {
992
+ const routerStartedAtMs = Date.now();
993
+ const routedVerificationEvents = /* @__PURE__ */ new Set();
994
+ const routedVerificationSasFingerprints = /* @__PURE__ */ new Set();
995
+ const routedVerificationStageNotices = /* @__PURE__ */ new Set();
996
+ const verificationFlowRooms = /* @__PURE__ */ new Map();
997
+ const verificationUserRooms = /* @__PURE__ */ new Map();
998
+ async function resolveActiveDirectRoomId(remoteUserId) {
999
+ const { inspectMatrixDirectRooms } = await loadMatrixDirectRoomDeps();
1000
+ return trimMaybeString((await inspectMatrixDirectRooms({
1001
+ client: params.client,
1002
+ remoteUserId
1003
+ }).catch(() => null))?.activeRoomId);
1004
+ }
1005
+ function shouldEmitVerificationEventNotice(event) {
1006
+ const eventTs = typeof event.origin_server_ts === "number" && Number.isFinite(event.origin_server_ts) ? event.origin_server_ts : null;
1007
+ if (eventTs === null) return true;
1008
+ return eventTs >= routerStartedAtMs - VERIFICATION_EVENT_STARTUP_GRACE_MS;
1009
+ }
1010
+ function rememberVerificationRoom(roomId, event, flowId) {
1011
+ for (const candidate of resolveVerificationFlowCandidates({
1012
+ event,
1013
+ flowId
1014
+ })) {
1015
+ verificationFlowRooms.set(candidate, roomId);
1016
+ if (verificationFlowRooms.size > MAX_TRACKED_VERIFICATION_EVENTS) {
1017
+ const oldest = verificationFlowRooms.keys().next().value;
1018
+ if (typeof oldest === "string") verificationFlowRooms.delete(oldest);
1019
+ }
1020
+ }
1021
+ }
1022
+ function rememberVerificationUserRoom(remoteUserId, roomId) {
1023
+ const normalizedUserId = trimMaybeString(remoteUserId);
1024
+ const normalizedRoomId = trimMaybeString(roomId);
1025
+ if (!normalizedUserId || !normalizedRoomId) return;
1026
+ verificationUserRooms.delete(normalizedUserId);
1027
+ verificationUserRooms.set(normalizedUserId, normalizedRoomId);
1028
+ if (verificationUserRooms.size > MAX_TRACKED_VERIFICATION_EVENTS) {
1029
+ const oldest = verificationUserRooms.keys().next().value;
1030
+ if (typeof oldest === "string") verificationUserRooms.delete(oldest);
1031
+ }
1032
+ }
1033
+ async function resolveSummaryRoomId(summary) {
1034
+ const mappedRoomId = trimMaybeString(summary.roomId) ?? trimMaybeString(summary.transactionId ? verificationFlowRooms.get(summary.transactionId) : null) ?? trimMaybeString(verificationFlowRooms.get(summary.id));
1035
+ if (mappedRoomId) return mappedRoomId;
1036
+ const remoteUserId = trimMaybeString(summary.otherUserId);
1037
+ if (!remoteUserId) return null;
1038
+ const recentRoomId = trimMaybeString(verificationUserRooms.get(remoteUserId));
1039
+ const activeRoomId = await resolveActiveDirectRoomId(remoteUserId);
1040
+ if (recentRoomId && activeRoomId && recentRoomId === activeRoomId) return recentRoomId;
1041
+ if (activeRoomId) return activeRoomId;
1042
+ if (recentRoomId && await (await loadMatrixDirectRoomDeps()).isStrictDirectRoom({
1043
+ client: params.client,
1044
+ roomId: recentRoomId,
1045
+ remoteUserId
1046
+ })) return recentRoomId;
1047
+ return null;
1048
+ }
1049
+ async function routeVerificationSummary(summary) {
1050
+ const roomId = await resolveSummaryRoomId(summary);
1051
+ if (!roomId || !isActiveVerificationSummary(summary)) return;
1052
+ if (!await (await loadMatrixDirectRoomDeps()).isStrictDirectRoom({
1053
+ client: params.client,
1054
+ roomId,
1055
+ remoteUserId: summary.otherUserId
1056
+ })) {
1057
+ params.logVerboseMessage(`matrix: ignoring verification summary outside strict DM room=${roomId} sender=${summary.otherUserId}`);
1058
+ return;
1059
+ }
1060
+ if (!await isVerificationNoticeAuthorized({
1061
+ senderId: summary.otherUserId,
1062
+ allowFrom: params.allowFrom,
1063
+ dmEnabled: params.dmEnabled,
1064
+ dmPolicy: params.dmPolicy,
1065
+ readStoreAllowFrom: params.readStoreAllowFrom,
1066
+ logVerboseMessage: params.logVerboseMessage
1067
+ })) return;
1068
+ const sasNotice = formatVerificationSasNotice(summary);
1069
+ if (!sasNotice) return;
1070
+ if (!trackBounded(routedVerificationSasFingerprints, `${summary.id}:${JSON.stringify(summary.sas)}`)) return;
1071
+ await sendVerificationNotice({
1072
+ client: params.client,
1073
+ roomId,
1074
+ body: sasNotice,
1075
+ logVerboseMessage: params.logVerboseMessage
1076
+ });
1077
+ }
1078
+ function routeVerificationEvent(roomId, event) {
1079
+ const senderId = trimMaybeString(event?.sender);
1080
+ if (!senderId) return false;
1081
+ const signal = readVerificationSignal(event);
1082
+ if (!signal) return false;
1083
+ rememberVerificationRoom(roomId, event, signal.flowId);
1084
+ const routeTask = async () => {
1085
+ if (!shouldEmitVerificationEventNotice(event)) {
1086
+ params.logVerboseMessage(`matrix: ignoring historical verification event room=${roomId} id=${event.event_id ?? "unknown"} type=${event.type ?? "unknown"}`);
1087
+ return;
1088
+ }
1089
+ const flowId = signal.flowId;
1090
+ const sourceFingerprint = trimMaybeString(event?.event_id) ?? `${senderId}:${event.type}:${flowId ?? "none"}`;
1091
+ if (!await (await loadMatrixDirectRoomDeps()).isStrictDirectRoom({
1092
+ client: params.client,
1093
+ roomId,
1094
+ remoteUserId: senderId
1095
+ })) {
1096
+ params.logVerboseMessage(`matrix: ignoring verification event outside strict DM room=${roomId} sender=${senderId}`);
1097
+ return;
1098
+ }
1099
+ if (!await isVerificationNoticeAuthorized({
1100
+ senderId,
1101
+ allowFrom: params.allowFrom,
1102
+ dmEnabled: params.dmEnabled,
1103
+ dmPolicy: params.dmPolicy,
1104
+ readStoreAllowFrom: params.readStoreAllowFrom,
1105
+ logVerboseMessage: params.logVerboseMessage
1106
+ })) return;
1107
+ rememberVerificationUserRoom(senderId, roomId);
1108
+ if (!trackBounded(routedVerificationEvents, sourceFingerprint)) return;
1109
+ const stageNotice = formatVerificationStageNotice({
1110
+ stage: signal.stage,
1111
+ senderId,
1112
+ event
1113
+ });
1114
+ const { summary, sasNotice } = await resolveVerificationSasNoticeForSignal(params.client, {
1115
+ roomId,
1116
+ event,
1117
+ senderId,
1118
+ flowId,
1119
+ stage: signal.stage,
1120
+ sasNoticeRetryDelayMs: params.sasNoticeRetryDelayMs
1121
+ }).catch(() => ({
1122
+ summary: null,
1123
+ sasNotice: null
1124
+ }));
1125
+ const notices = [];
1126
+ if (stageNotice) {
1127
+ if (trackBounded(routedVerificationStageNotices, `${roomId}:${senderId}:${flowId ?? sourceFingerprint}:${signal.stage}`)) notices.push(stageNotice);
1128
+ }
1129
+ if (summary && sasNotice) {
1130
+ if (trackBounded(routedVerificationSasFingerprints, `${summary.id}:${JSON.stringify(summary.sas)}`)) notices.push(sasNotice);
1131
+ }
1132
+ if (notices.length === 0) return;
1133
+ for (const body of notices) await sendVerificationNotice({
1134
+ client: params.client,
1135
+ roomId,
1136
+ body,
1137
+ logVerboseMessage: params.logVerboseMessage
1138
+ });
1139
+ };
1140
+ if (params.runDetachedTask) params.runDetachedTask(`verification event handler room=${roomId} id=${event.event_id ?? "unknown"}`, routeTask);
1141
+ else routeTask().catch((err) => {
1142
+ params.logVerboseMessage(`matrix: failed routing verification event: ${String(err)}`);
1143
+ });
1144
+ return true;
1145
+ }
1146
+ return {
1147
+ routeVerificationEvent,
1148
+ routeVerificationSummary
1149
+ };
1150
+ }
1151
+ //#endregion
1152
+ //#region extensions/matrix/src/matrix/monitor/events.ts
1153
+ const MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_WINDOW_MS = 2 * 6e4;
1154
+ const MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_THRESHOLD = 3;
1155
+ const MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT = 3;
1156
+ function formatMatrixPostHealthySyncDecryptionHint(accountId) {
1157
+ 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 'klaw matrix verify status --verbose --account ${accountId}' and 'klaw matrix devices list --account ${accountId}'.`;
1158
+ }
1159
+ function isFreshPostHealthySyncDecryptFailure(params) {
1160
+ const { event, healthySyncSinceMs, graceMs = 0, nowMs } = params;
1161
+ if (typeof healthySyncSinceMs !== "number" || !Number.isFinite(healthySyncSinceMs)) return false;
1162
+ const eventTs = event.origin_server_ts;
1163
+ if (!Number.isFinite(eventTs) || eventTs <= 0) return false;
1164
+ if (eventTs < healthySyncSinceMs + graceMs) return false;
1165
+ if (eventTs > nowMs + 6e4) return false;
1166
+ return true;
1167
+ }
1168
+ function createMatrixPostHealthySyncDecryptFailureTracker(params) {
1169
+ let observations = [];
1170
+ let warningEmitted = false;
1171
+ let trackedHealthySyncSinceMs;
1172
+ const resetObservations = () => {
1173
+ observations = [];
1174
+ warningEmitted = false;
1175
+ };
1176
+ const pruneObservations = (nowMs) => {
1177
+ observations = observations.filter((entry) => nowMs - entry.eventTs <= MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_WINDOW_MS);
1178
+ if (observations.length === 0) warningEmitted = false;
1179
+ };
1180
+ return { recordFailure(roomId, event, error) {
1181
+ const nowMs = Date.now();
1182
+ const healthySyncSinceMs = params.getHealthySyncSinceMs?.();
1183
+ if (healthySyncSinceMs !== trackedHealthySyncSinceMs) {
1184
+ trackedHealthySyncSinceMs = healthySyncSinceMs;
1185
+ resetObservations();
1186
+ }
1187
+ if (!isFreshPostHealthySyncDecryptFailure({
1188
+ event,
1189
+ healthySyncSinceMs,
1190
+ graceMs: params.startupGraceMs,
1191
+ nowMs
1192
+ })) return {
1193
+ freshAfterHealthySync: false,
1194
+ failureCount: 0
1195
+ };
1196
+ pruneObservations(nowMs);
1197
+ const key = `${roomId}|${event.event_id}`;
1198
+ if (!observations.some((entry) => entry.key === key)) observations.push({
1199
+ key,
1200
+ roomId,
1201
+ eventId: event.event_id,
1202
+ sender: typeof event.sender === "string" ? event.sender : null,
1203
+ eventTs: event.origin_server_ts,
1204
+ error: error.message
1205
+ });
1206
+ const failureCount = observations.length;
1207
+ if (warningEmitted || failureCount < MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_THRESHOLD) return {
1208
+ freshAfterHealthySync: true,
1209
+ failureCount
1210
+ };
1211
+ warningEmitted = true;
1212
+ const rooms = [...new Set(observations.map((entry) => entry.roomId))].slice(0, MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT);
1213
+ const senders = [...new Set(observations.map((entry) => entry.sender).filter(Boolean))].slice(0, MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT);
1214
+ const eventIds = observations.slice(-MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT).map((entry) => entry.eventId);
1215
+ const latestError = observations.at(-1)?.error ?? error.message;
1216
+ return {
1217
+ freshAfterHealthySync: true,
1218
+ failureCount,
1219
+ warning: {
1220
+ rooms,
1221
+ roomCount: new Set(observations.map((entry) => entry.roomId)).size,
1222
+ senders,
1223
+ senderCount: new Set(observations.map((entry) => entry.sender).filter(Boolean)).size,
1224
+ eventIds,
1225
+ latestError,
1226
+ windowMs: MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_WINDOW_MS
1227
+ }
1228
+ };
1229
+ } };
1230
+ }
1231
+ function formatMatrixSelfDecryptionHint(accountId) {
1232
+ 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 Klaw runtime is using the same account. Check 'klaw matrix verify status --verbose --account ${accountId}' and 'klaw matrix devices list --account ${accountId}'.`;
1233
+ }
1234
+ async function resolveMatrixSelfUserId(client, logVerboseMessage) {
1235
+ if (typeof client.getUserId !== "function") return null;
1236
+ try {
1237
+ return await client.getUserId() ?? null;
1238
+ } catch (err) {
1239
+ logVerboseMessage(`matrix: failed resolving self user id for decrypt warning: ${String(err)}`);
1240
+ return null;
1241
+ }
1242
+ }
1243
+ function registerMatrixMonitorEvents(params) {
1244
+ const { cfg, client, auth, allowFrom, dmEnabled, dmPolicy, readStoreAllowFrom, directTracker, logVerboseMessage, warnedEncryptedRooms, warnedCryptoMissingRooms, logger, startupGraceMs, getHealthySyncSinceMs, formatNativeDependencyHint, onRoomMessage, runDetachedTask, sasNoticeRetryDelayMs } = params;
1245
+ const postHealthySyncDecryptFailureTracker = createMatrixPostHealthySyncDecryptFailureTracker({
1246
+ getHealthySyncSinceMs,
1247
+ startupGraceMs
1248
+ });
1249
+ const { routeVerificationEvent, routeVerificationSummary } = createMatrixVerificationEventRouter({
1250
+ client,
1251
+ allowFrom,
1252
+ dmEnabled,
1253
+ dmPolicy,
1254
+ readStoreAllowFrom,
1255
+ logVerboseMessage,
1256
+ runDetachedTask,
1257
+ sasNoticeRetryDelayMs
1258
+ });
1259
+ const runMonitorTask = (label, task) => {
1260
+ if (runDetachedTask) return runDetachedTask(label, task);
1261
+ return Promise.resolve().then(task).catch((error) => {
1262
+ logVerboseMessage(`matrix: ${label} failed (${String(error)})`);
1263
+ });
1264
+ };
1265
+ client.on("room.message", (roomId, event) => {
1266
+ if (routeVerificationEvent(roomId, event)) return;
1267
+ runMonitorTask(`room message handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1268
+ await onRoomMessage(roomId, event);
1269
+ });
1270
+ });
1271
+ client.on("room.encrypted_event", (roomId, event) => {
1272
+ const eventId = event?.event_id ?? "unknown";
1273
+ logVerboseMessage(`matrix: encrypted event room=${roomId} type=${event?.type ?? "unknown"} id=${eventId}`);
1274
+ });
1275
+ client.on("room.decrypted_event", (roomId, event) => {
1276
+ const eventId = event?.event_id ?? "unknown";
1277
+ const eventType = event?.type ?? "unknown";
1278
+ logVerboseMessage(`matrix: decrypted event room=${roomId} type=${eventType} id=${eventId}`);
1279
+ if (routeVerificationEvent(roomId, event)) return;
1280
+ if (eventType !== EventType.RoomMessage) return;
1281
+ runMonitorTask(`decrypted room message handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1282
+ await onRoomMessage(roomId, event);
1283
+ });
1284
+ });
1285
+ client.on("room.failed_decryption", async (roomId, event, error) => {
1286
+ const failureState = postHealthySyncDecryptFailureTracker.recordFailure(roomId, event, error);
1287
+ const selfUserId = await resolveMatrixSelfUserId(client, logVerboseMessage);
1288
+ const sender = typeof event.sender === "string" ? event.sender : null;
1289
+ const senderMatchesOwnUser = Boolean(selfUserId && sender && selfUserId === sender);
1290
+ logger.warn(failureState.freshAfterHealthySync ? "Failed to decrypt fresh post-healthy-sync message" : "Failed to decrypt message", {
1291
+ roomId,
1292
+ eventId: event.event_id,
1293
+ sender,
1294
+ senderMatchesOwnUser,
1295
+ error: error.message,
1296
+ freshAfterHealthySync: failureState.freshAfterHealthySync,
1297
+ ...failureState.freshAfterHealthySync ? { postHealthySyncFailureCount: failureState.failureCount } : {}
1298
+ });
1299
+ if (failureState.warning) logger.warn(formatMatrixPostHealthySyncDecryptionHint(auth.accountId), {
1300
+ roomId,
1301
+ eventId: event.event_id,
1302
+ failureCount: failureState.failureCount,
1303
+ roomCount: failureState.warning.roomCount,
1304
+ rooms: failureState.warning.rooms,
1305
+ senderCount: failureState.warning.senderCount,
1306
+ senders: failureState.warning.senders,
1307
+ sampleEventIds: failureState.warning.eventIds,
1308
+ latestError: failureState.warning.latestError,
1309
+ windowMs: failureState.warning.windowMs
1310
+ });
1311
+ if (senderMatchesOwnUser) logger.warn(formatMatrixSelfDecryptionHint(auth.accountId), {
1312
+ roomId,
1313
+ eventId: event.event_id,
1314
+ sender
1315
+ });
1316
+ logVerboseMessage(`matrix: failed decrypt room=${roomId} id=${event.event_id ?? "unknown"} freshAfterHealthySync=${String(failureState.freshAfterHealthySync)} error=${error.message}`);
1317
+ });
1318
+ client.on("verification.summary", (summary) => {
1319
+ runMonitorTask("verification summary handler", async () => {
1320
+ await routeVerificationSummary(summary);
1321
+ });
1322
+ });
1323
+ client.on("room.invite", (roomId, event) => {
1324
+ directTracker?.invalidateRoom(roomId);
1325
+ const eventId = event?.event_id ?? "unknown";
1326
+ const sender = event?.sender ?? "unknown";
1327
+ const invitee = normalizeOptionalString(event?.state_key) ?? "";
1328
+ const senderIsInvitee = Boolean(invitee) && (normalizeOptionalString(event?.sender) ?? "") === invitee;
1329
+ const isDirect = (event?.content)?.is_direct === true;
1330
+ const rememberedSender = normalizeOptionalString(event?.sender);
1331
+ if (rememberedSender && !senderIsInvitee) directTracker?.rememberInvite?.(roomId, rememberedSender);
1332
+ logVerboseMessage(`matrix: invite room=${roomId} sender=${sender} direct=${String(isDirect)} id=${eventId}`);
1333
+ });
1334
+ client.on("room.join", (roomId, event) => {
1335
+ directTracker?.invalidateRoom(roomId);
1336
+ logVerboseMessage(`matrix: join room=${roomId} id=${event?.event_id ?? "unknown"}`);
1337
+ });
1338
+ client.on("room.event", (roomId, event) => {
1339
+ const eventType = event?.type ?? "unknown";
1340
+ if (eventType === EventType.RoomMessageEncrypted) {
1341
+ logVerboseMessage(`matrix: encrypted raw event room=${roomId} id=${event?.event_id ?? "unknown"}`);
1342
+ if (auth.encryption !== true && !warnedEncryptedRooms.has(roomId)) {
1343
+ warnedEncryptedRooms.add(roomId);
1344
+ const warning = formatMatrixEncryptedEventDisabledWarning(cfg, auth.accountId);
1345
+ logger.warn(warning, { roomId });
1346
+ }
1347
+ if (auth.encryption === true && !client.crypto && !warnedCryptoMissingRooms.has(roomId)) {
1348
+ warnedCryptoMissingRooms.add(roomId);
1349
+ const warning = `matrix: encryption enabled but crypto is unavailable; ${formatNativeDependencyHint({
1350
+ packageName: "@matrix-org/matrix-sdk-crypto-nodejs",
1351
+ manager: "pnpm",
1352
+ downloadCommand: "node node_modules/@matrix-org/matrix-sdk-crypto-nodejs/download-lib.js"
1353
+ })}`;
1354
+ logger.warn(warning, { roomId });
1355
+ }
1356
+ return;
1357
+ }
1358
+ if (eventType === EventType.RoomMember) {
1359
+ directTracker?.invalidateRoom(roomId);
1360
+ const membership = (event?.content)?.membership;
1361
+ logVerboseMessage(`matrix: member event room=${roomId} stateKey=${event.state_key ?? ""} membership=${membership ?? "unknown"}`);
1362
+ }
1363
+ if (eventType === EventType.Reaction) {
1364
+ runMonitorTask(`reaction handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1365
+ await onRoomMessage(roomId, event);
1366
+ });
1367
+ return;
1368
+ }
1369
+ routeVerificationEvent(roomId, event);
1370
+ });
1371
+ }
1372
+ //#endregion
1373
+ //#region extensions/matrix/src/matrix/monitor/ack-config.ts
1374
+ function resolveMatrixAckReactionConfig(params) {
1375
+ const matrixConfig = params.cfg.channels?.matrix;
1376
+ const accountConfig = resolveMatrixAccountConfig({
1377
+ cfg: params.cfg,
1378
+ accountId: params.accountId
1379
+ });
1380
+ return {
1381
+ ackReaction: resolveAckReaction(params.cfg, params.agentId, {
1382
+ channel: "matrix",
1383
+ accountId: params.accountId ?? void 0
1384
+ }).trim(),
1385
+ ackReactionScope: accountConfig.ackReactionScope ?? matrixConfig?.ackReactionScope ?? params.cfg.messages?.ackReactionScope ?? "group-mentions"
1386
+ };
1387
+ }
1388
+ //#endregion
1389
+ //#region extensions/matrix/src/matrix/monitor/location.ts
1390
+ function decodeGeoUriParamValue(value) {
1391
+ try {
1392
+ return decodeURIComponent(value);
1393
+ } catch {
1394
+ return value;
1395
+ }
1396
+ }
1397
+ function parseGeoUri(value) {
1398
+ const trimmed = value.trim();
1399
+ if (!trimmed) return null;
1400
+ if (!normalizeLowercaseStringOrEmpty(trimmed).startsWith("geo:")) return null;
1401
+ const [coordsPart, ...paramParts] = trimmed.slice(4).split(";");
1402
+ const coords = coordsPart.split(",");
1403
+ if (coords.length < 2) return null;
1404
+ const latitude = Number.parseFloat(coords[0] ?? "");
1405
+ const longitude = Number.parseFloat(coords[1] ?? "");
1406
+ if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
1407
+ const params = /* @__PURE__ */ new Map();
1408
+ for (const part of paramParts) {
1409
+ const segment = part.trim();
1410
+ if (!segment) continue;
1411
+ const eqIndex = segment.indexOf("=");
1412
+ const rawKey = eqIndex === -1 ? segment : segment.slice(0, eqIndex);
1413
+ const rawValue = eqIndex === -1 ? "" : segment.slice(eqIndex + 1);
1414
+ const key = normalizeLowercaseStringOrEmpty(rawKey);
1415
+ if (!key) continue;
1416
+ const valuePart = rawValue.trim();
1417
+ params.set(key, valuePart ? decodeGeoUriParamValue(valuePart) : "");
1418
+ }
1419
+ const accuracyRaw = params.get("u");
1420
+ const accuracy = accuracyRaw ? Number.parseFloat(accuracyRaw) : void 0;
1421
+ return {
1422
+ latitude,
1423
+ longitude,
1424
+ accuracy: Number.isFinite(accuracy) ? accuracy : void 0
1425
+ };
1426
+ }
1427
+ function resolveMatrixLocation(params) {
1428
+ const { eventType, content } = params;
1429
+ if (!(eventType === EventType.Location || eventType === EventType.RoomMessage && content.msgtype === EventType.Location)) return null;
1430
+ const geoUri = normalizeOptionalString(content.geo_uri) ?? "";
1431
+ if (!geoUri) return null;
1432
+ const parsed = parseGeoUri(geoUri);
1433
+ if (!parsed) return null;
1434
+ const caption = normalizeOptionalString(content.body) ?? "";
1435
+ const location = {
1436
+ latitude: parsed.latitude,
1437
+ longitude: parsed.longitude,
1438
+ accuracy: parsed.accuracy,
1439
+ caption: caption || void 0,
1440
+ source: "pin",
1441
+ isLive: false
1442
+ };
1443
+ return {
1444
+ text: formatLocationText(location),
1445
+ context: toLocationContext(location)
1446
+ };
1447
+ }
1448
+ //#endregion
1449
+ //#region extensions/matrix/src/matrix/monitor/media.ts
1450
+ const MATRIX_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS = 3e4;
1451
+ async function fetchMatrixMediaBuffer(params) {
1452
+ try {
1453
+ return { buffer: await params.client.downloadContent(params.mxcUrl, {
1454
+ maxBytes: params.maxBytes,
1455
+ readIdleTimeoutMs: MATRIX_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS
1456
+ }) };
1457
+ } catch (err) {
1458
+ if (isMatrixMediaSizeLimitError(err)) throw err;
1459
+ throw new Error(`Matrix media download failed: ${String(err)}`, { cause: err });
1460
+ }
1461
+ }
1462
+ /**
1463
+ * Download and decrypt encrypted media from a Matrix room.
1464
+ * Uses the Matrix crypto adapter's decryptMedia helper.
1465
+ */
1466
+ async function fetchEncryptedMediaBuffer(params) {
1467
+ if (!params.client.crypto) throw new Error("Cannot decrypt media: crypto not enabled");
1468
+ const decrypted = await params.client.crypto.decryptMedia(params.file, {
1469
+ maxBytes: params.maxBytes,
1470
+ readIdleTimeoutMs: MATRIX_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS
1471
+ });
1472
+ if (decrypted.byteLength > params.maxBytes) throw new MatrixMediaSizeLimitError();
1473
+ return { buffer: decrypted };
1474
+ }
1475
+ async function downloadMatrixMedia(params) {
1476
+ let fetched;
1477
+ if (typeof params.sizeBytes === "number" && params.sizeBytes > params.maxBytes) throw new MatrixMediaSizeLimitError();
1478
+ if (params.file) fetched = await fetchEncryptedMediaBuffer({
1479
+ client: params.client,
1480
+ file: params.file,
1481
+ maxBytes: params.maxBytes
1482
+ });
1483
+ else fetched = await fetchMatrixMediaBuffer({
1484
+ client: params.client,
1485
+ mxcUrl: params.mxcUrl,
1486
+ maxBytes: params.maxBytes
1487
+ });
1488
+ if (!fetched) return null;
1489
+ const headerType = params.contentType ?? void 0;
1490
+ const saved = await getMatrixRuntime().channel.media.saveMediaBuffer(fetched.buffer, headerType, "inbound", params.maxBytes, params.originalFilename);
1491
+ return {
1492
+ path: saved.path,
1493
+ contentType: saved.contentType,
1494
+ placeholder: "[matrix media]"
1495
+ };
1496
+ }
1497
+ //#endregion
1498
+ //#region extensions/matrix/src/matrix/monitor/mentions.ts
1499
+ const HTML_ENTITY_REPLACEMENTS = {
1500
+ amp: "&",
1501
+ apos: "'",
1502
+ gt: ">",
1503
+ lt: "<",
1504
+ nbsp: " ",
1505
+ quot: "\""
1506
+ };
1507
+ const MAX_UNICODE_SCALAR_VALUE = 1114111;
1508
+ function decodeNumericHtmlEntity(match, rawValue, radix) {
1509
+ const codePoint = Number.parseInt(rawValue, radix);
1510
+ if (!Number.isSafeInteger(codePoint) || codePoint < 0 || codePoint > MAX_UNICODE_SCALAR_VALUE || codePoint >= 55296 && codePoint <= 57343) return match;
1511
+ return String.fromCodePoint(codePoint);
1512
+ }
1513
+ function decodeHtmlEntities(value) {
1514
+ return value.replace(/&(#x?[0-9a-f]+|\w+);/gi, (match, entity) => {
1515
+ const normalized = normalizeLowercaseStringOrEmpty(entity);
1516
+ if (normalized.startsWith("#x")) return decodeNumericHtmlEntity(match, normalized.slice(2), 16);
1517
+ if (normalized.startsWith("#")) return decodeNumericHtmlEntity(match, normalized.slice(1), 10);
1518
+ return HTML_ENTITY_REPLACEMENTS[normalized] ?? match;
1519
+ });
1520
+ }
1521
+ function normalizeVisibleMentionText(value) {
1522
+ return normalizeLowercaseStringOrEmpty(decodeHtmlEntities(value.replace(/<[^>]+>/g, " ").replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u206f]/g, "")).replace(/\s+/g, " "));
1523
+ }
1524
+ function extractVisibleMentionText(value) {
1525
+ return normalizeVisibleMentionText(value ?? "");
1526
+ }
1527
+ function resolveMatrixUserLocalpart(userId) {
1528
+ const trimmed = userId.trim();
1529
+ if (!trimmed.startsWith("@")) return null;
1530
+ const colonIndex = trimmed.indexOf(":");
1531
+ if (colonIndex <= 1) return null;
1532
+ return trimmed.slice(1, colonIndex).trim() || null;
1533
+ }
1534
+ function resolveMatrixMentionPrefixCandidates(params) {
1535
+ const candidates = [];
1536
+ const seen = /* @__PURE__ */ new Set();
1537
+ const append = (candidate) => {
1538
+ const trimmed = candidate?.trim();
1539
+ if (!trimmed) return;
1540
+ const normalized = normalizeLowercaseStringOrEmpty(trimmed);
1541
+ if (seen.has(normalized)) return;
1542
+ seen.add(normalized);
1543
+ candidates.push(trimmed);
1544
+ };
1545
+ append(params.userId);
1546
+ const localpart = params.userId ? resolveMatrixUserLocalpart(params.userId) : null;
1547
+ append(localpart ? `@${localpart}` : null);
1548
+ append(params.displayName);
1549
+ append(params.displayName ? `@${params.displayName}` : null);
1550
+ return candidates;
1551
+ }
1552
+ function stripMatchedMatrixMentionPrefix(text, pattern) {
1553
+ const match = text.match(pattern);
1554
+ if (!match) return null;
1555
+ return text.slice(match[0].length).trimStart();
1556
+ }
1557
+ function stripNativeMatrixMentionPrefix(text, candidate) {
1558
+ return stripMatchedMatrixMentionPrefix(text, new RegExp(`^\\s*${escapeRegExp(candidate)}(?:\\s*[:,])?(?:\\s+|$)`, "i"));
1559
+ }
1560
+ function stripRegexMatrixMentionPrefix(text, pattern) {
1561
+ const flags = pattern.flags.replace(/[gy]/g, "");
1562
+ return stripMatchedMatrixMentionPrefix(text, new RegExp(`^\\s*(?:${pattern.source})(?:\\s*[:,])?(?:\\s+|$)`, flags));
1563
+ }
1564
+ function stripMatrixMentionPrefix(params) {
1565
+ const text = params.text;
1566
+ if (!text) return text;
1567
+ for (const candidate of resolveMatrixMentionPrefixCandidates(params)) {
1568
+ const stripped = stripNativeMatrixMentionPrefix(text, candidate);
1569
+ if (stripped !== null) return stripped;
1570
+ }
1571
+ for (const pattern of params.mentionRegexes ?? []) {
1572
+ const stripped = stripRegexMatrixMentionPrefix(text, pattern);
1573
+ if (stripped !== null) return stripped;
1574
+ }
1575
+ return text;
1576
+ }
1577
+ function isVisibleMentionLabel(params) {
1578
+ const cleaned = extractVisibleMentionText(params.text);
1579
+ if (!cleaned) return false;
1580
+ if (params.mentionRegexes.some((pattern) => pattern.test(cleaned))) return true;
1581
+ const localpart = resolveMatrixUserLocalpart(params.userId);
1582
+ return [
1583
+ extractVisibleMentionText(params.userId),
1584
+ localpart ? extractVisibleMentionText(localpart) : null,
1585
+ localpart ? extractVisibleMentionText(`@${localpart}`) : null,
1586
+ params.displayName ? extractVisibleMentionText(params.displayName) : null,
1587
+ params.displayName ? extractVisibleMentionText(`@${params.displayName}`) : null
1588
+ ].filter((value) => Boolean(value)).includes(cleaned);
1589
+ }
1590
+ function hasVisibleRoomMention(value) {
1591
+ const cleaned = extractVisibleMentionText(value);
1592
+ return /(^|[^a-z0-9_])@room\b/i.test(cleaned);
1593
+ }
1594
+ /**
1595
+ * Check if formatted_body contains a matrix.to link whose visible label still
1596
+ * looks like a real mention for the given user. Do not trust href alone, since
1597
+ * senders can hide arbitrary matrix.to links behind unrelated link text.
1598
+ * Many Matrix clients (including Element) use HTML links in formatted_body instead of
1599
+ * or in addition to the m.mentions field.
1600
+ */
1601
+ function checkFormattedBodyMention(params) {
1602
+ if (!params.formattedBody || !params.userId) return false;
1603
+ for (const match of params.formattedBody.matchAll(/<a\b[^>]*href=(["'])(https:\/\/matrix\.to\/#[^"']+)\1[^>]*>(.*?)<\/a>/gis)) {
1604
+ const href = match[2];
1605
+ const visibleLabel = match[3] ?? "";
1606
+ if (!href) continue;
1607
+ try {
1608
+ const parsed = new URL(href);
1609
+ if (decodeURIComponent(parsed.hash.replace(/^#\/?/, "").trim()) !== params.userId.trim()) continue;
1610
+ if (isVisibleMentionLabel({
1611
+ text: visibleLabel,
1612
+ userId: params.userId,
1613
+ mentionRegexes: params.mentionRegexes,
1614
+ displayName: params.displayName
1615
+ })) return true;
1616
+ } catch {
1617
+ continue;
1618
+ }
1619
+ }
1620
+ return false;
1621
+ }
1622
+ function resolveMentions(params) {
1623
+ const mentions = params.content["m.mentions"];
1624
+ const mentionedUsers = Array.isArray(mentions?.user_ids) ? new Set(mentions.user_ids) : /* @__PURE__ */ new Set();
1625
+ const textMentioned = getMatrixRuntime().channel.mentions.matchesMentionPatterns(params.text ?? "", params.mentionRegexes);
1626
+ const visibleRoomMention = hasVisibleRoomMention(params.text) || hasVisibleRoomMention(params.content.formatted_body);
1627
+ const mentionedInFormattedBody = params.userId ? checkFormattedBodyMention({
1628
+ formattedBody: params.content.formatted_body,
1629
+ userId: params.userId,
1630
+ displayName: params.displayName,
1631
+ mentionRegexes: params.mentionRegexes
1632
+ }) : false;
1633
+ const metadataBackedUserMention = Boolean(params.userId && mentionedUsers.has(params.userId) && (mentionedInFormattedBody || textMentioned));
1634
+ const metadataBackedRoomMention = Boolean(mentions?.room) && visibleRoomMention;
1635
+ const explicitMention = mentionedInFormattedBody || metadataBackedUserMention || metadataBackedRoomMention;
1636
+ return {
1637
+ wasMentioned: explicitMention || textMentioned || visibleRoomMention,
1638
+ hasExplicitMention: explicitMention
1639
+ };
1640
+ }
1641
+ //#endregion
1642
+ //#region extensions/matrix/src/matrix/monitor/replies.ts
1643
+ const THINKING_TAG_RE = /<\s*\/?\s*(?:think(?:ing)?|thought|antthinking)\b[^<>]*>/gi;
1644
+ const THINKING_BLOCK_RE = /<\s*(?:think(?:ing)?|thought|antthinking)\b[^<>]*>[\s\S]*?<\s*\/\s*(?:think(?:ing)?|thought|antthinking)\s*>/gi;
1645
+ function shouldSuppressReasoningReplyText(text) {
1646
+ if (typeof text !== "string") return false;
1647
+ const trimmedStart = text.trimStart();
1648
+ if (!trimmedStart) return false;
1649
+ if (normalizeLowercaseStringOrEmpty(trimmedStart).startsWith("reasoning:")) return true;
1650
+ THINKING_TAG_RE.lastIndex = 0;
1651
+ if (!THINKING_TAG_RE.test(text)) return false;
1652
+ THINKING_BLOCK_RE.lastIndex = 0;
1653
+ const withoutThinkingBlocks = text.replace(THINKING_BLOCK_RE, "");
1654
+ THINKING_TAG_RE.lastIndex = 0;
1655
+ return !withoutThinkingBlocks.replace(THINKING_TAG_RE, "").trim();
1656
+ }
1657
+ async function deliverMatrixReplies(params) {
1658
+ const core = getMatrixRuntime();
1659
+ const tableMode = params.tableMode ?? core.channel.text.resolveMarkdownTableMode({
1660
+ cfg: params.cfg,
1661
+ channel: "matrix",
1662
+ accountId: params.accountId
1663
+ });
1664
+ const logVerbose = (message) => {
1665
+ if (core.logging.shouldLogVerbose()) params.runtime.log?.(message);
1666
+ };
1667
+ let hasReplied = false;
1668
+ let deliveredAny = false;
1669
+ for (const reply of params.replies) {
1670
+ if (reply.isReasoning === true || shouldSuppressReasoningReplyText(reply.text)) {
1671
+ logVerbose("matrix reply suppressed as reasoning-only");
1672
+ continue;
1673
+ }
1674
+ const hasMedia = Boolean(reply?.mediaUrl) || (reply?.mediaUrls?.length ?? 0) > 0;
1675
+ if (!reply?.text && !hasMedia) {
1676
+ if (reply?.audioAsVoice) {
1677
+ logVerbose("matrix reply has audioAsVoice without media/text; skipping");
1678
+ continue;
1679
+ }
1680
+ params.runtime.error?.("matrix reply missing text/media");
1681
+ continue;
1682
+ }
1683
+ const replyToIdRaw = reply.replyToId?.trim();
1684
+ const replyToId = params.threadId || params.replyToMode === "off" ? void 0 : replyToIdRaw;
1685
+ const rawText = reply.text ?? "";
1686
+ const mediaList = reply.mediaUrls?.length ? reply.mediaUrls : reply.mediaUrl ? [reply.mediaUrl] : [];
1687
+ const shouldIncludeReply = (id) => Boolean(id) && (params.replyToMode === "all" || !hasReplied);
1688
+ const replyToIdForReply = shouldIncludeReply(replyToId) ? replyToId : void 0;
1689
+ if (mediaList.length === 0) {
1690
+ let sentTextChunk = false;
1691
+ const { chunks } = chunkMatrixText(rawText, {
1692
+ cfg: params.cfg,
1693
+ accountId: params.accountId,
1694
+ tableMode
1695
+ });
1696
+ for (const chunk of chunks) {
1697
+ const trimmed = chunk.trim();
1698
+ if (!trimmed) continue;
1699
+ await sendMessageMatrix(params.roomId, trimmed, {
1700
+ client: params.client,
1701
+ cfg: params.cfg,
1702
+ replyToId: replyToIdForReply,
1703
+ threadId: params.threadId,
1704
+ accountId: params.accountId
1705
+ });
1706
+ deliveredAny = true;
1707
+ sentTextChunk = true;
1708
+ }
1709
+ if (replyToIdForReply && !hasReplied && sentTextChunk) hasReplied = true;
1710
+ continue;
1711
+ }
1712
+ let first = true;
1713
+ for (const mediaUrl of mediaList) {
1714
+ const caption = first ? rawText : "";
1715
+ await sendMessageMatrix(params.roomId, caption, {
1716
+ client: params.client,
1717
+ cfg: params.cfg,
1718
+ mediaUrl,
1719
+ mediaLocalRoots: params.mediaLocalRoots,
1720
+ replyToId: replyToIdForReply,
1721
+ threadId: params.threadId,
1722
+ audioAsVoice: reply.audioAsVoice,
1723
+ accountId: params.accountId
1724
+ });
1725
+ deliveredAny = true;
1726
+ first = false;
1727
+ }
1728
+ if (replyToIdForReply && !hasReplied) hasReplied = true;
1729
+ }
1730
+ return deliveredAny;
1731
+ }
1732
+ //#endregion
1733
+ //#region extensions/matrix/src/matrix/monitor/context-summary.ts
1734
+ function trimMatrixMaybeString(value) {
1735
+ if (typeof value !== "string") return;
1736
+ return value.trim() || void 0;
1737
+ }
1738
+ function summarizeMatrixMessageContextEvent(event) {
1739
+ if (isPollStartType(event.type)) {
1740
+ const pollSummary = parsePollStartContent(event.content);
1741
+ if (pollSummary) return formatPollAsText(pollSummary);
1742
+ }
1743
+ const content = event.content;
1744
+ return formatMatrixMessageText({
1745
+ body: resolveMatrixMessageBody({
1746
+ body: trimMatrixMaybeString(content.body),
1747
+ filename: trimMatrixMaybeString(content.filename),
1748
+ msgtype: trimMatrixMaybeString(content.msgtype)
1749
+ }),
1750
+ attachment: resolveMatrixMessageAttachment({
1751
+ body: trimMatrixMaybeString(content.body),
1752
+ filename: trimMatrixMaybeString(content.filename),
1753
+ msgtype: trimMatrixMaybeString(content.msgtype)
1754
+ })
1755
+ });
1756
+ }
1757
+ //#endregion
1758
+ //#region extensions/matrix/src/matrix/monitor/reply-context.ts
1759
+ const MAX_CACHED_REPLY_CONTEXTS = 256;
1760
+ const MAX_REPLY_BODY_LENGTH = 500;
1761
+ function truncateReplyBody(value) {
1762
+ if (value.length <= MAX_REPLY_BODY_LENGTH) return value;
1763
+ return `${value.slice(0, MAX_REPLY_BODY_LENGTH - 3)}...`;
1764
+ }
1765
+ function summarizeMatrixReplyEvent(event) {
1766
+ const body = summarizeMatrixMessageContextEvent(event);
1767
+ return body ? truncateReplyBody(body) : void 0;
1768
+ }
1769
+ /**
1770
+ * Creates a cached resolver that fetches the body and sender of a replied-to
1771
+ * Matrix event. This allows the agent to see the content of the message being
1772
+ * replied to, not just its event ID.
1773
+ */
1774
+ function createMatrixReplyContextResolver(params) {
1775
+ const cache = /* @__PURE__ */ new Map();
1776
+ const remember = (key, value) => {
1777
+ cache.set(key, value);
1778
+ if (cache.size > MAX_CACHED_REPLY_CONTEXTS) {
1779
+ const oldest = cache.keys().next().value;
1780
+ if (typeof oldest === "string") cache.delete(oldest);
1781
+ }
1782
+ return value;
1783
+ };
1784
+ return async (input) => {
1785
+ const cacheKey = `${input.roomId}:${input.eventId}`;
1786
+ const cached = cache.get(cacheKey);
1787
+ if (cached) {
1788
+ cache.delete(cacheKey);
1789
+ cache.set(cacheKey, cached);
1790
+ return cached;
1791
+ }
1792
+ const event = await params.client.getEvent(input.roomId, input.eventId).catch((err) => {
1793
+ params.logVerboseMessage(`matrix: failed resolving reply context room=${input.roomId} id=${input.eventId}: ${String(err)}`);
1794
+ return null;
1795
+ });
1796
+ if (!event) return {};
1797
+ const rawEvent = event;
1798
+ if (rawEvent.unsigned?.redacted_because) return remember(cacheKey, {});
1799
+ const replyToBody = summarizeMatrixReplyEvent(rawEvent);
1800
+ if (!replyToBody) return remember(cacheKey, {});
1801
+ const senderId = trimMatrixMaybeString(rawEvent.sender);
1802
+ return remember(cacheKey, {
1803
+ replyToBody,
1804
+ replyToSender: (senderId && await params.getMemberDisplayName(input.roomId, senderId).catch(() => void 0)) ?? senderId,
1805
+ replyToSenderId: senderId
1806
+ });
1807
+ };
1808
+ }
1809
+ //#endregion
1810
+ //#region extensions/matrix/src/matrix/monitor/room-history.ts
1811
+ /** Maximum entries retained per room (hard cap to bound memory). */
1812
+ const DEFAULT_MAX_QUEUE_SIZE = 200;
1813
+ /** Maximum number of rooms to retain queues for (FIFO eviction beyond this). */
1814
+ const DEFAULT_MAX_ROOM_QUEUES = 1e3;
1815
+ /** Maximum number of (agentId, roomId) watermark entries to retain. */
1816
+ const MAX_WATERMARK_ENTRIES = 5e3;
1817
+ /** Maximum prepared trigger snapshots retained per room for retry reuse. */
1818
+ const MAX_PREPARED_TRIGGER_ENTRIES = 500;
1819
+ function createRoomHistoryTrackerInternal(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoomQueues = DEFAULT_MAX_ROOM_QUEUES, maxWatermarkEntries = MAX_WATERMARK_ENTRIES, maxPreparedTriggerEntries = MAX_PREPARED_TRIGGER_ENTRIES) {
1820
+ const roomQueues = /* @__PURE__ */ new Map();
1821
+ /** Maps `${agentId}:${roomId}` → absolute consumed-up-to index */
1822
+ const agentWatermarks = /* @__PURE__ */ new Map();
1823
+ let nextQueueGeneration = 1;
1824
+ function clearRoomWatermarks(roomId) {
1825
+ const roomSuffix = `:${roomId}`;
1826
+ for (const key of agentWatermarks.keys()) if (key.endsWith(roomSuffix)) agentWatermarks.delete(key);
1827
+ }
1828
+ function getOrCreateQueue(roomId) {
1829
+ let queue = roomQueues.get(roomId);
1830
+ if (!queue) {
1831
+ queue = {
1832
+ entries: [],
1833
+ baseIndex: 0,
1834
+ generation: nextQueueGeneration++,
1835
+ preparedTriggers: /* @__PURE__ */ new Map()
1836
+ };
1837
+ roomQueues.set(roomId, queue);
1838
+ if (roomQueues.size > maxRoomQueues) {
1839
+ const oldest = roomQueues.keys().next().value;
1840
+ if (oldest !== void 0) {
1841
+ roomQueues.delete(oldest);
1842
+ clearRoomWatermarks(oldest);
1843
+ }
1844
+ }
1845
+ }
1846
+ return queue;
1847
+ }
1848
+ function appendToQueue(queue, entry) {
1849
+ queue.entries.push(entry);
1850
+ if (queue.entries.length > maxQueueSize) {
1851
+ const overflow = queue.entries.length - maxQueueSize;
1852
+ queue.entries.splice(0, overflow);
1853
+ queue.baseIndex += overflow;
1854
+ }
1855
+ return {
1856
+ snapshotIdx: queue.baseIndex + queue.entries.length,
1857
+ queueGeneration: queue.generation
1858
+ };
1859
+ }
1860
+ function wmKey(agentId, roomId) {
1861
+ return `${agentId}:${roomId}`;
1862
+ }
1863
+ function preparedTriggerKey(agentId, messageId) {
1864
+ if (!messageId?.trim()) return null;
1865
+ return `${agentId}:${messageId.trim()}`;
1866
+ }
1867
+ function rememberWatermark(key, snapshotIdx) {
1868
+ const nextSnapshotIdx = Math.max(agentWatermarks.get(key) ?? 0, snapshotIdx);
1869
+ if (agentWatermarks.has(key)) agentWatermarks.delete(key);
1870
+ agentWatermarks.set(key, nextSnapshotIdx);
1871
+ if (agentWatermarks.size > maxWatermarkEntries) {
1872
+ const oldest = agentWatermarks.keys().next().value;
1873
+ if (oldest !== void 0) agentWatermarks.delete(oldest);
1874
+ }
1875
+ }
1876
+ function rememberPreparedTrigger(queue, retryKey, prepared) {
1877
+ if (queue.preparedTriggers.has(retryKey)) queue.preparedTriggers.delete(retryKey);
1878
+ queue.preparedTriggers.set(retryKey, prepared);
1879
+ if (queue.preparedTriggers.size > maxPreparedTriggerEntries) {
1880
+ const oldest = queue.preparedTriggers.keys().next().value;
1881
+ if (oldest !== void 0) queue.preparedTriggers.delete(oldest);
1882
+ }
1883
+ return prepared;
1884
+ }
1885
+ function computePendingHistory(queue, agentId, roomId, limit) {
1886
+ if (limit <= 0 || queue.entries.length === 0) return [];
1887
+ const wm = agentWatermarks.get(wmKey(agentId, roomId)) ?? 0;
1888
+ const startRel = Math.max(wm, queue.baseIndex) - queue.baseIndex;
1889
+ const available = queue.entries.slice(startRel);
1890
+ return available.length > limit ? available.slice(-limit) : available;
1891
+ }
1892
+ return {
1893
+ recordPending(roomId, entry) {
1894
+ appendToQueue(getOrCreateQueue(roomId), entry);
1895
+ },
1896
+ getPendingHistory(agentId, roomId, limit) {
1897
+ const queue = roomQueues.get(roomId);
1898
+ if (!queue) return [];
1899
+ return computePendingHistory(queue, agentId, roomId, limit);
1900
+ },
1901
+ recordTrigger(roomId, entry) {
1902
+ return appendToQueue(getOrCreateQueue(roomId), entry);
1903
+ },
1904
+ prepareTrigger(agentId, roomId, limit, entry) {
1905
+ const queue = getOrCreateQueue(roomId);
1906
+ const retryKey = preparedTriggerKey(agentId, entry.messageId);
1907
+ if (retryKey) {
1908
+ const prepared = queue.preparedTriggers.get(retryKey);
1909
+ if (prepared) return rememberPreparedTrigger(queue, retryKey, prepared);
1910
+ }
1911
+ const prepared = {
1912
+ history: computePendingHistory(queue, agentId, roomId, limit),
1913
+ ...appendToQueue(queue, entry)
1914
+ };
1915
+ if (retryKey) return rememberPreparedTrigger(queue, retryKey, prepared);
1916
+ return prepared;
1917
+ },
1918
+ consumeHistory(agentId, roomId, snapshot, messageId) {
1919
+ const key = wmKey(agentId, roomId);
1920
+ const queue = roomQueues.get(roomId);
1921
+ if (!queue) {
1922
+ agentWatermarks.delete(key);
1923
+ return;
1924
+ }
1925
+ if (queue.generation !== snapshot.queueGeneration) return;
1926
+ rememberWatermark(key, snapshot.snapshotIdx);
1927
+ const retryKey = preparedTriggerKey(agentId, messageId);
1928
+ if (queue && retryKey) queue.preparedTriggers.delete(retryKey);
1929
+ }
1930
+ };
1931
+ }
1932
+ function createRoomHistoryTracker(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoomQueues = DEFAULT_MAX_ROOM_QUEUES, maxWatermarkEntries = MAX_WATERMARK_ENTRIES, maxPreparedTriggerEntries = MAX_PREPARED_TRIGGER_ENTRIES) {
1933
+ const tracker = createRoomHistoryTrackerInternal(maxQueueSize, maxRoomQueues, maxWatermarkEntries, maxPreparedTriggerEntries);
1934
+ return {
1935
+ recordPending: tracker.recordPending,
1936
+ prepareTrigger: tracker.prepareTrigger,
1937
+ consumeHistory: tracker.consumeHistory
1938
+ };
1939
+ }
1940
+ //#endregion
1941
+ //#region extensions/matrix/src/matrix/monitor/thread-context.ts
1942
+ const MAX_TRACKED_THREAD_STARTERS = 256;
1943
+ const MAX_THREAD_STARTER_BODY_LENGTH = 500;
1944
+ function truncateThreadStarterBody(value) {
1945
+ if (value.length <= MAX_THREAD_STARTER_BODY_LENGTH) return value;
1946
+ return `${value.slice(0, MAX_THREAD_STARTER_BODY_LENGTH - 3)}...`;
1947
+ }
1948
+ function summarizeMatrixThreadStarterEvent(event) {
1949
+ const body = summarizeMatrixMessageContextEvent(event);
1950
+ if (body) return truncateThreadStarterBody(body);
1951
+ const content = event.content;
1952
+ const msgtype = trimMatrixMaybeString(content.msgtype);
1953
+ if (msgtype) return `Matrix ${msgtype} message`;
1954
+ const eventType = trimMatrixMaybeString(event.type);
1955
+ return eventType ? `Matrix ${eventType} event` : void 0;
1956
+ }
1957
+ function formatMatrixThreadStarterBody(params) {
1958
+ const senderLabel = params.senderName ?? params.senderId ?? "unknown sender";
1959
+ const lines = [`Matrix thread root ${params.threadRootId} from ${senderLabel}:`];
1960
+ if (params.summary) lines.push(params.summary);
1961
+ return lines.join("\n");
1962
+ }
1963
+ function createMatrixThreadContextResolver(params) {
1964
+ const cache = /* @__PURE__ */ new Map();
1965
+ const remember = (key, value) => {
1966
+ cache.set(key, value);
1967
+ if (cache.size > MAX_TRACKED_THREAD_STARTERS) {
1968
+ const oldest = cache.keys().next().value;
1969
+ if (typeof oldest === "string") cache.delete(oldest);
1970
+ }
1971
+ return value;
1972
+ };
1973
+ return async (input) => {
1974
+ const cacheKey = `${input.roomId}:${input.threadRootId}`;
1975
+ const cached = cache.get(cacheKey);
1976
+ if (cached) return cached;
1977
+ const rootEvent = await params.client.getEvent(input.roomId, input.threadRootId).catch((err) => {
1978
+ params.logVerboseMessage(`matrix: failed resolving thread root room=${input.roomId} id=${input.threadRootId}: ${String(err)}`);
1979
+ return null;
1980
+ });
1981
+ if (!rootEvent) return { threadStarterBody: `Matrix thread root ${input.threadRootId}` };
1982
+ const rawEvent = rootEvent;
1983
+ const senderId = trimMatrixMaybeString(rawEvent.sender);
1984
+ const senderName = senderId && await params.getMemberDisplayName(input.roomId, senderId).catch(() => void 0);
1985
+ const senderLabel = senderName ?? senderId;
1986
+ const summary = summarizeMatrixThreadStarterEvent(rawEvent);
1987
+ return remember(cacheKey, {
1988
+ threadStarterBody: formatMatrixThreadStarterBody({
1989
+ threadRootId: input.threadRootId,
1990
+ senderId,
1991
+ senderName,
1992
+ summary
1993
+ }),
1994
+ senderId,
1995
+ senderLabel,
1996
+ summary
1997
+ });
1998
+ };
1999
+ }
2000
+ //#endregion
2001
+ //#region extensions/matrix/src/matrix/monitor/handler.ts
2002
+ const ALLOW_FROM_STORE_CACHE_TTL_MS = 3e4;
2003
+ const PAIRING_REPLY_COOLDOWN_MS = 5 * 6e4;
2004
+ const MATRIX_TOOL_PROGRESS_MAX_CHARS = 300;
2005
+ let matrixSendModulePromise;
2006
+ let acpBindingRuntimePromise;
2007
+ let sessionBindingRuntimePromise;
2008
+ let matrixReactionEventsPromise;
2009
+ let matrixDraftStreamPromise;
2010
+ function loadMatrixSendModule() {
2011
+ matrixSendModulePromise ??= import("./send-CJunc6QM.js").then((n) => n.l);
2012
+ return matrixSendModulePromise;
2013
+ }
2014
+ function loadAcpBindingRuntime() {
2015
+ acpBindingRuntimePromise ??= import("klaw/plugin-sdk/acp-binding-runtime");
2016
+ return acpBindingRuntimePromise;
2017
+ }
2018
+ function loadSessionBindingRuntime() {
2019
+ sessionBindingRuntimePromise ??= import("klaw/plugin-sdk/session-binding-runtime");
2020
+ return sessionBindingRuntimePromise;
2021
+ }
2022
+ function loadMatrixReactionEvents() {
2023
+ matrixReactionEventsPromise ??= import("./reaction-events-D0nUJuZV.js");
2024
+ return matrixReactionEventsPromise;
2025
+ }
2026
+ function loadMatrixDraftStream() {
2027
+ matrixDraftStreamPromise ??= import("./draft-stream-HpPJ_VJt.js");
2028
+ return matrixDraftStreamPromise;
2029
+ }
2030
+ const MAX_TRACKED_PAIRING_REPLY_SENDERS = 512;
2031
+ const MAX_TRACKED_SHARED_DM_CONTEXT_NOTICES = 512;
2032
+ var MatrixRetryableInboundError = class extends Error {
2033
+ constructor(message, options) {
2034
+ super(message, options);
2035
+ this.name = "MatrixRetryableInboundError";
2036
+ }
2037
+ };
2038
+ async function redactMatrixDraftEvent(client, roomId, draftEventId) {
2039
+ await client.redactEvent(roomId, draftEventId).catch(() => {});
2040
+ }
2041
+ function buildMatrixFinalizedPreviewContent() {
2042
+ return { [MATRIX_KLAW_FINALIZED_PREVIEW_KEY]: true };
2043
+ }
2044
+ function resolveMatrixMentionPrecheckText(params) {
2045
+ if (params.locationText?.trim()) return params.locationText.trim();
2046
+ if (typeof params.content.body === "string" && params.content.body.trim()) return params.content.body.trim();
2047
+ if (isPollStartType(params.eventType)) {
2048
+ const parsed = parsePollStartContent(params.content);
2049
+ if (parsed) return formatPollAsText(parsed);
2050
+ }
2051
+ return "";
2052
+ }
2053
+ function hasBundledMatrixReplacementRelation(event) {
2054
+ const relations = event.unsigned?.["m.relations"];
2055
+ if (!relations || typeof relations !== "object") return false;
2056
+ return relations[RelationType.Replace] !== void 0;
2057
+ }
2058
+ function resolveMatrixInboundBodyText(params) {
2059
+ if (params.mediaPlaceholder) return params.rawBody || params.mediaPlaceholder;
2060
+ if (!params.mediaDownloadFailed || !params.hadMediaUrl) return params.rawBody;
2061
+ if (params.mediaSizeLimitExceeded) return formatMatrixMediaTooLargeText({
2062
+ body: params.rawBody,
2063
+ filename: params.filename,
2064
+ msgtype: params.msgtype
2065
+ });
2066
+ return formatMatrixMediaUnavailableText({
2067
+ body: params.rawBody,
2068
+ filename: params.filename,
2069
+ msgtype: params.msgtype
2070
+ });
2071
+ }
2072
+ function markTrackedRoomIfFirst(set, roomId) {
2073
+ if (set.has(roomId)) return false;
2074
+ set.add(roomId);
2075
+ if (set.size > MAX_TRACKED_SHARED_DM_CONTEXT_NOTICES) {
2076
+ const oldest = set.keys().next().value;
2077
+ if (typeof oldest === "string") set.delete(oldest);
2078
+ }
2079
+ return true;
2080
+ }
2081
+ function resolveMatrixSharedDmContextNotice(params) {
2082
+ if ((params.dmSessionScope ?? "per-user") === "per-room") return null;
2083
+ if (params.sentRooms.has(params.roomId)) return null;
2084
+ try {
2085
+ const currentSession = resolveMatrixStoredSessionMeta(resolveSessionStoreEntry({
2086
+ store: loadSessionStore(params.storePath),
2087
+ sessionKey: params.sessionKey
2088
+ }).existing);
2089
+ if (!currentSession) return null;
2090
+ if (currentSession.channel && currentSession.channel !== "matrix") return null;
2091
+ if (currentSession.accountId && currentSession.accountId !== params.accountId) return null;
2092
+ if (!currentSession.directUserId) return null;
2093
+ if (!currentSession.roomId || currentSession.roomId === params.roomId) return null;
2094
+ return [
2095
+ "This Matrix DM is sharing a session with another Matrix DM room.",
2096
+ "Use /focus here for a one-off isolated thread session when thread bindings are enabled, or set",
2097
+ "channels.matrix.dm.sessionScope to per-room to isolate each Matrix DM room."
2098
+ ].join(" ");
2099
+ } catch (err) {
2100
+ params.logVerboseMessage(`matrix: failed checking shared DM session notice room=${params.roomId} (${String(err)})`);
2101
+ return null;
2102
+ }
2103
+ }
2104
+ function resolveMatrixPendingHistoryText(params) {
2105
+ if (params.mentionPrecheckText) return params.mentionPrecheckText;
2106
+ if (!params.mediaUrl) return "";
2107
+ const body = typeof params.content.body === "string" ? params.content.body.trim() : void 0;
2108
+ const filename = typeof params.content.filename === "string" ? params.content.filename.trim() : void 0;
2109
+ const msgtype = typeof params.content.msgtype === "string" ? params.content.msgtype : void 0;
2110
+ return formatMatrixMessageText({
2111
+ body: resolveMatrixMessageBody({
2112
+ body,
2113
+ filename,
2114
+ msgtype
2115
+ }),
2116
+ attachment: resolveMatrixMessageAttachment({
2117
+ body,
2118
+ filename,
2119
+ msgtype
2120
+ })
2121
+ }) ?? "";
2122
+ }
2123
+ function resolveMatrixAllowBotsMode(value) {
2124
+ if (value === true) return "all";
2125
+ if (value === "mentions") return "mentions";
2126
+ return "off";
2127
+ }
2128
+ function formatMatrixToolProgressMarkdownCode(text) {
2129
+ return `\`${(text.length <= MATRIX_TOOL_PROGRESS_MAX_CHARS ? text : `${text.slice(0, MATRIX_TOOL_PROGRESS_MAX_CHARS - 1).trimEnd()}...`).replaceAll("`", "'")}\``;
2130
+ }
2131
+ function createMatrixRoomMessageHandler(params) {
2132
+ const { client, core, cfg, accountId, accountConfig, runtime, logger, logVerboseMessage, allowFromResolvedEntries = [], groupAllowFromResolvedEntries = [], roomsConfig, accountAllowBots, configuredBotUserIds = /* @__PURE__ */ new Set(), groupPolicy, replyToMode, threadReplies, dmThreadReplies, dmSessionScope, streaming, previewToolProgressEnabled, blockStreamingEnabled, dmEnabled, dmPolicy, textLimit, mediaMaxBytes, historyLimit, startupMs, startupGraceMs, dropPreStartupMessages, inboundDeduper, directTracker, getRoomInfo, getMemberDisplayName, needsRoomAliasesForConfig, resolveLiveUserAllowlist = resolveMatrixMonitorLiveUserAllowlist } = params;
2133
+ const contextVisibilityMode = resolveChannelContextVisibilityMode({
2134
+ cfg,
2135
+ channel: "matrix",
2136
+ accountId
2137
+ });
2138
+ let cachedStoreAllowFrom = null;
2139
+ let liveDmAllowlistCache = null;
2140
+ let liveGroupAllowlistCache = null;
2141
+ const resolveCachedLiveAllowlist = async (params) => {
2142
+ const accountConfig = resolveMatrixAccountConfig({
2143
+ cfg: params.cfg,
2144
+ accountId
2145
+ });
2146
+ const signature = JSON.stringify({
2147
+ entries: (params.entries ?? []).map((entry) => String(entry).trim()),
2148
+ failClosedOnUnresolved: params.failClosedOnUnresolved === true,
2149
+ dangerouslyAllowNameMatching: isDangerousNameMatchingEnabled(accountConfig)
2150
+ });
2151
+ if (params.cache?.signature === signature) return params.cache.entries;
2152
+ const entries = await resolveLiveUserAllowlist({
2153
+ cfg: params.cfg,
2154
+ accountId,
2155
+ entries: params.entries,
2156
+ failClosedOnUnresolved: params.failClosedOnUnresolved,
2157
+ startupResolvedEntries: params.startupResolvedEntries,
2158
+ runtime
2159
+ });
2160
+ const next = {
2161
+ signature,
2162
+ entries
2163
+ };
2164
+ params.updateCache(next);
2165
+ return entries;
2166
+ };
2167
+ const pairingReplySentAtMsBySender = /* @__PURE__ */ new Map();
2168
+ const resolveThreadContext = createMatrixThreadContextResolver({
2169
+ client,
2170
+ getMemberDisplayName,
2171
+ logVerboseMessage
2172
+ });
2173
+ const resolveReplyContext = createMatrixReplyContextResolver({
2174
+ client,
2175
+ getMemberDisplayName,
2176
+ logVerboseMessage
2177
+ });
2178
+ const roomHistoryTracker = createRoomHistoryTracker();
2179
+ const roomIngressTails = /* @__PURE__ */ new Map();
2180
+ const sharedDmContextNoticeRooms = /* @__PURE__ */ new Set();
2181
+ const readStoreAllowFrom = async () => {
2182
+ const now = Date.now();
2183
+ if (cachedStoreAllowFrom && now < cachedStoreAllowFrom.expiresAtMs) return cachedStoreAllowFrom.value;
2184
+ const value = await core.channel.pairing.readAllowFromStore({
2185
+ channel: "matrix",
2186
+ env: process.env,
2187
+ accountId
2188
+ }).catch(() => []);
2189
+ cachedStoreAllowFrom = {
2190
+ value,
2191
+ expiresAtMs: now + ALLOW_FROM_STORE_CACHE_TTL_MS
2192
+ };
2193
+ return value;
2194
+ };
2195
+ const shouldSendPairingReply = (senderId, created) => {
2196
+ const now = Date.now();
2197
+ if (created) {
2198
+ pairingReplySentAtMsBySender.set(senderId, now);
2199
+ return true;
2200
+ }
2201
+ const lastSentAtMs = pairingReplySentAtMsBySender.get(senderId);
2202
+ if (typeof lastSentAtMs === "number" && now - lastSentAtMs < PAIRING_REPLY_COOLDOWN_MS) return false;
2203
+ pairingReplySentAtMsBySender.set(senderId, now);
2204
+ if (pairingReplySentAtMsBySender.size > MAX_TRACKED_PAIRING_REPLY_SENDERS) {
2205
+ const oldestSender = pairingReplySentAtMsBySender.keys().next().value;
2206
+ if (typeof oldestSender === "string") pairingReplySentAtMsBySender.delete(oldestSender);
2207
+ }
2208
+ return true;
2209
+ };
2210
+ const runRoomIngress = async (roomId, task) => {
2211
+ const previous = roomIngressTails.get(roomId) ?? Promise.resolve();
2212
+ let releaseCurrent;
2213
+ const current = new Promise((resolve) => {
2214
+ releaseCurrent = resolve;
2215
+ });
2216
+ const chain = previous.catch(() => {}).then(() => current);
2217
+ roomIngressTails.set(roomId, chain);
2218
+ await previous.catch(() => {});
2219
+ try {
2220
+ return await task();
2221
+ } finally {
2222
+ releaseCurrent();
2223
+ if (roomIngressTails.get(roomId) === chain) roomIngressTails.delete(roomId);
2224
+ }
2225
+ };
2226
+ return async (roomId, event) => {
2227
+ const eventId = typeof event.event_id === "string" ? event.event_id.trim() : "";
2228
+ let claimedInboundEvent = false;
2229
+ let draftStreamRef;
2230
+ let draftConsumed = false;
2231
+ try {
2232
+ const eventType = event.type;
2233
+ if (eventType === EventType.RoomMessageEncrypted) return;
2234
+ const isPollEvent = isPollEventType(eventType);
2235
+ const isReactionEvent = eventType === EventType.Reaction;
2236
+ const locationContent = event.content;
2237
+ const isLocationEvent = eventType === EventType.Location || eventType === EventType.RoomMessage && locationContent.msgtype === EventType.Location;
2238
+ if (eventType !== EventType.RoomMessage && !isPollEvent && !isLocationEvent && !isReactionEvent) return;
2239
+ logVerboseMessage(`matrix: inbound event room=${roomId} type=${eventType} id=${event.event_id ?? "unknown"}`);
2240
+ if (event.unsigned?.redacted_because) return;
2241
+ const senderId = event.sender;
2242
+ if (!senderId) return;
2243
+ const eventTs = event.origin_server_ts;
2244
+ const eventAge = event.unsigned?.age;
2245
+ const commitInboundEventIfClaimed = async () => {
2246
+ if (!claimedInboundEvent || !inboundDeduper || !eventId) return;
2247
+ await inboundDeduper.commitEvent({
2248
+ roomId,
2249
+ eventId
2250
+ });
2251
+ claimedInboundEvent = false;
2252
+ };
2253
+ const readIngressPrefix = async () => {
2254
+ const selfUserId = await client.getUserId();
2255
+ if (senderId === selfUserId) return;
2256
+ if (dropPreStartupMessages) {
2257
+ if (typeof eventTs === "number" && eventTs < startupMs - startupGraceMs) return;
2258
+ if (typeof eventTs !== "number" && typeof eventAge === "number" && eventAge > startupGraceMs) return;
2259
+ }
2260
+ let content = event.content;
2261
+ if (eventType === EventType.RoomMessage && isMatrixVerificationRoomMessage({
2262
+ msgtype: content.msgtype,
2263
+ body: content.body
2264
+ })) {
2265
+ logVerboseMessage(`matrix: skip verification/system room message room=${roomId}`);
2266
+ return;
2267
+ }
2268
+ const locationPayload = resolveMatrixLocation({
2269
+ eventType,
2270
+ content
2271
+ });
2272
+ const relates = content["m.relates_to"];
2273
+ if (relates && "rel_type" in relates && relates.rel_type === RelationType.Replace) return;
2274
+ if (hasBundledMatrixReplacementRelation(event)) return;
2275
+ if (eventId && inboundDeduper) {
2276
+ claimedInboundEvent = inboundDeduper.claimEvent({
2277
+ roomId,
2278
+ eventId
2279
+ });
2280
+ if (!claimedInboundEvent) {
2281
+ logVerboseMessage(`matrix: skip duplicate inbound event room=${roomId} id=${eventId}`);
2282
+ return;
2283
+ }
2284
+ }
2285
+ return {
2286
+ content,
2287
+ isDirectMessage: await directTracker.isDirectMessage({
2288
+ roomId,
2289
+ senderId,
2290
+ selfUserId
2291
+ }),
2292
+ locationPayload,
2293
+ selfUserId
2294
+ };
2295
+ };
2296
+ const continueIngress = async (params) => {
2297
+ let content = params.content;
2298
+ const isDirectMessage = params.isDirectMessage;
2299
+ const isRoom = !isDirectMessage;
2300
+ const { locationPayload, selfUserId } = params;
2301
+ if (isRoom && groupPolicy === "disabled") {
2302
+ await commitInboundEventIfClaimed();
2303
+ return;
2304
+ }
2305
+ const roomInfoForConfig = isRoom && needsRoomAliasesForConfig ? await getRoomInfo(roomId, { includeAliases: true }) : void 0;
2306
+ const roomAliasesForConfig = roomInfoForConfig ? [roomInfoForConfig.canonicalAlias ?? "", ...roomInfoForConfig.altAliases].filter(Boolean) : [];
2307
+ const roomConfigInfo = isRoom ? resolveMatrixRoomConfig({
2308
+ rooms: roomsConfig,
2309
+ roomId,
2310
+ aliases: roomAliasesForConfig
2311
+ }) : void 0;
2312
+ const roomConfig = roomConfigInfo?.config;
2313
+ const allowBotsMode = resolveMatrixAllowBotsMode(roomConfig?.allowBots ?? accountAllowBots);
2314
+ const isConfiguredBotSender = configuredBotUserIds.has(senderId);
2315
+ const roomMatchMeta = roomConfigInfo ? `matchKey=${roomConfigInfo.matchKey ?? "none"} matchSource=${roomConfigInfo.matchSource ?? "none"}` : "matchKey=none matchSource=none";
2316
+ if (isConfiguredBotSender && allowBotsMode === "off") {
2317
+ logVerboseMessage(`matrix: drop configured bot sender=${senderId} (allowBots=false${isDirectMessage ? "" : `, ${roomMatchMeta}`})`);
2318
+ await commitInboundEventIfClaimed();
2319
+ return;
2320
+ }
2321
+ const botLoopProtection = isConfiguredBotSender && senderId !== selfUserId ? {
2322
+ scopeId: accountId,
2323
+ conversationId: roomId,
2324
+ senderId,
2325
+ receiverId: selfUserId,
2326
+ config: mergePairLoopGuardConfig(accountConfig?.botLoopProtection, roomConfig?.botLoopProtection),
2327
+ defaultsConfig: cfg.channels?.defaults?.botLoopProtection,
2328
+ defaultEnabled: true,
2329
+ nowMs: eventTs ?? void 0
2330
+ } : void 0;
2331
+ if (isRoom && roomConfig && !roomConfigInfo?.allowed) {
2332
+ logVerboseMessage(`matrix: room disabled room=${roomId} (${roomMatchMeta})`);
2333
+ await commitInboundEventIfClaimed();
2334
+ return;
2335
+ }
2336
+ if (isRoom && groupPolicy === "allowlist") {
2337
+ if (!roomConfigInfo?.allowlistConfigured) {
2338
+ logVerboseMessage(`matrix: drop room message (no allowlist, ${roomMatchMeta})`);
2339
+ await commitInboundEventIfClaimed();
2340
+ return;
2341
+ }
2342
+ if (!roomConfig) {
2343
+ logVerboseMessage(`matrix: drop room message (not in allowlist, ${roomMatchMeta})`);
2344
+ await commitInboundEventIfClaimed();
2345
+ return;
2346
+ }
2347
+ }
2348
+ let senderNamePromise = null;
2349
+ const getSenderName = async () => {
2350
+ senderNamePromise ??= getMemberDisplayName(roomId, senderId).catch(() => senderId);
2351
+ return await senderNamePromise;
2352
+ };
2353
+ const storeAllowFrom = isDirectMessage && dmPolicy !== "allowlist" && dmPolicy !== "open" ? await readStoreAllowFrom() : [];
2354
+ const roomUsers = roomConfig?.users ?? [];
2355
+ const liveCfg = core.config.current();
2356
+ const liveAccountAllowlists = resolveMatrixAccountAllowlistConfig({
2357
+ cfg: liveCfg,
2358
+ accountId
2359
+ });
2360
+ const accessState = await resolveMatrixMonitorAccessState({
2361
+ allowFrom: await resolveCachedLiveAllowlist({
2362
+ cfg: liveCfg,
2363
+ entries: liveAccountAllowlists.dmAllowFrom,
2364
+ startupResolvedEntries: allowFromResolvedEntries,
2365
+ cache: liveDmAllowlistCache,
2366
+ updateCache: (next) => {
2367
+ liveDmAllowlistCache = next;
2368
+ }
2369
+ }),
2370
+ storeAllowFrom,
2371
+ dmPolicy,
2372
+ groupPolicy,
2373
+ groupAllowFrom: await resolveCachedLiveAllowlist({
2374
+ cfg: liveCfg,
2375
+ entries: liveAccountAllowlists.groupAllowFrom,
2376
+ failClosedOnUnresolved: true,
2377
+ startupResolvedEntries: groupAllowFromResolvedEntries,
2378
+ cache: liveGroupAllowlistCache,
2379
+ updateCache: (next) => {
2380
+ liveGroupAllowlistCache = next;
2381
+ }
2382
+ }),
2383
+ roomUsers,
2384
+ senderId,
2385
+ isRoom,
2386
+ accountId,
2387
+ eventKind: isReactionEvent ? "reaction" : "message"
2388
+ });
2389
+ const { effectiveGroupAllowFrom, effectiveRoomUsers, messageIngress } = accessState;
2390
+ const ingressDecision = messageIngress.ingress;
2391
+ if (isDirectMessage) {
2392
+ if (!dmEnabled || dmPolicy === "disabled") {
2393
+ await commitInboundEventIfClaimed();
2394
+ return;
2395
+ }
2396
+ const senderReason = messageIngress.senderAccess.reasonCode;
2397
+ if (ingressDecision.decision !== "allow") {
2398
+ if (ingressDecision.admission === "pairing-required") {
2399
+ const senderName = await getSenderName();
2400
+ const { code, created } = await core.channel.pairing.upsertPairingRequest({
2401
+ channel: "matrix",
2402
+ id: senderId,
2403
+ accountId,
2404
+ meta: { name: senderName }
2405
+ });
2406
+ if (shouldSendPairingReply(senderId, created)) {
2407
+ const pairingReply = core.channel.pairing.buildPairingReply({
2408
+ channel: "matrix",
2409
+ idLine: `Your Matrix user id: ${senderId}`,
2410
+ code
2411
+ });
2412
+ logVerboseMessage(created ? `matrix pairing request sender=${senderId} name=${senderName ?? "unknown"} (reason=${senderReason})` : `matrix pairing reminder sender=${senderId} name=${senderName ?? "unknown"} (reason=${senderReason})`);
2413
+ try {
2414
+ const { sendMessageMatrix } = await loadMatrixSendModule();
2415
+ await sendMessageMatrix(`room:${roomId}`, created ? pairingReply : `${pairingReply}\n\nPairing request is still pending approval. Reusing existing code.`, {
2416
+ client,
2417
+ cfg,
2418
+ accountId
2419
+ });
2420
+ await commitInboundEventIfClaimed();
2421
+ } catch (err) {
2422
+ logVerboseMessage(`matrix pairing reply failed for ${senderId}: ${String(err)}`);
2423
+ return;
2424
+ }
2425
+ } else {
2426
+ logVerboseMessage(`matrix pairing reminder suppressed sender=${senderId} (cooldown)`);
2427
+ await commitInboundEventIfClaimed();
2428
+ }
2429
+ }
2430
+ if (isReactionEvent || dmPolicy !== "pairing") {
2431
+ logVerboseMessage(`matrix: blocked ${isReactionEvent ? "reaction" : "dm"} sender ${senderId} (dmPolicy=${dmPolicy}, reason=${senderReason})`);
2432
+ await commitInboundEventIfClaimed();
2433
+ }
2434
+ return;
2435
+ }
2436
+ }
2437
+ if (isRoom && ingressDecision.decision !== "allow") {
2438
+ logVerboseMessage(`matrix: blocked sender ${senderId} (ingress=${ingressDecision.reasonCode}, ${roomMatchMeta})`);
2439
+ await commitInboundEventIfClaimed();
2440
+ return;
2441
+ }
2442
+ if (isRoom) logVerboseMessage(`matrix: allow room ${roomId} (${roomMatchMeta})`);
2443
+ if (isReactionEvent) {
2444
+ const senderName = await getSenderName();
2445
+ const { handleInboundMatrixReaction } = await loadMatrixReactionEvents();
2446
+ await handleInboundMatrixReaction({
2447
+ client,
2448
+ core,
2449
+ cfg,
2450
+ accountId,
2451
+ roomId,
2452
+ event,
2453
+ senderId,
2454
+ senderLabel: senderName,
2455
+ selfUserId,
2456
+ isDirectMessage,
2457
+ logVerboseMessage
2458
+ });
2459
+ await commitInboundEventIfClaimed();
2460
+ return;
2461
+ }
2462
+ let pollSnapshotPromise = null;
2463
+ const getPollSnapshot = async () => {
2464
+ if (!isPollEvent) return null;
2465
+ pollSnapshotPromise ??= fetchMatrixPollSnapshot(client, roomId, event).catch((err) => {
2466
+ logVerboseMessage(`matrix: failed resolving poll snapshot room=${roomId} id=${event.event_id ?? "unknown"}: ${String(err)}`);
2467
+ return null;
2468
+ });
2469
+ return await pollSnapshotPromise;
2470
+ };
2471
+ const mentionPrecheckText = resolveMatrixMentionPrecheckText({
2472
+ eventType,
2473
+ content,
2474
+ locationText: locationPayload?.text
2475
+ });
2476
+ const contentUrl = "url" in content && typeof content.url === "string" ? content.url : void 0;
2477
+ const contentFile = "file" in content && content.file && typeof content.file === "object" ? content.file : void 0;
2478
+ const mediaUrl = contentUrl ?? contentFile?.url;
2479
+ const pendingHistoryText = resolveMatrixPendingHistoryText({
2480
+ mentionPrecheckText,
2481
+ content,
2482
+ mediaUrl
2483
+ });
2484
+ const pendingHistoryPollText = !pendingHistoryText && isPollEvent && historyLimit > 0 ? (await getPollSnapshot())?.text : "";
2485
+ if (!mentionPrecheckText && !mediaUrl && !isPollEvent) {
2486
+ await commitInboundEventIfClaimed();
2487
+ return;
2488
+ }
2489
+ const messageId = event.event_id ?? "";
2490
+ const threadRootId = resolveMatrixThreadRootId({
2491
+ event,
2492
+ content
2493
+ });
2494
+ const thread = resolveMatrixThreadRouting({
2495
+ isDirectMessage,
2496
+ threadReplies,
2497
+ dmThreadReplies,
2498
+ messageId,
2499
+ threadRootId
2500
+ });
2501
+ const { route: _route, configuredBinding: _configuredBinding, runtimeBindingId: _runtimeBindingId } = resolveMatrixInboundRoute({
2502
+ cfg,
2503
+ accountId,
2504
+ roomId,
2505
+ senderId,
2506
+ isDirectMessage,
2507
+ dmSessionScope,
2508
+ threadId: thread.threadId,
2509
+ eventTs: eventTs ?? void 0,
2510
+ resolveAgentRoute: core.channel.routing.resolveAgentRoute
2511
+ });
2512
+ const hasExplicitSessionBinding = _configuredBinding !== null || _runtimeBindingId !== null;
2513
+ const agentMentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, _route.agentId);
2514
+ const selfDisplayName = content.formatted_body ? await getMemberDisplayName(roomId, selfUserId).catch(() => void 0) : void 0;
2515
+ const { wasMentioned, hasExplicitMention } = resolveMentions({
2516
+ content,
2517
+ userId: selfUserId,
2518
+ displayName: selfDisplayName,
2519
+ text: mentionPrecheckText,
2520
+ mentionRegexes: agentMentionRegexes
2521
+ });
2522
+ if (isConfiguredBotSender && allowBotsMode === "mentions" && !isDirectMessage && !wasMentioned) {
2523
+ logVerboseMessage(`matrix: drop configured bot sender=${senderId} (allowBots=mentions, missing mention, ${roomMatchMeta})`);
2524
+ await commitInboundEventIfClaimed();
2525
+ return;
2526
+ }
2527
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
2528
+ cfg,
2529
+ surface: "matrix"
2530
+ });
2531
+ const useAccessGroups = cfg.commands?.useAccessGroups !== false;
2532
+ const commandCheckText = stripMatrixMentionPrefix({
2533
+ text: mentionPrecheckText,
2534
+ userId: selfUserId,
2535
+ displayName: selfDisplayName,
2536
+ mentionRegexes: agentMentionRegexes
2537
+ });
2538
+ const hasControlCommandInMessage = core.channel.text.hasControlCommand(commandCheckText, cfg);
2539
+ const commandAccess = await resolveMatrixMonitorCommandAccess(accessState, {
2540
+ useAccessGroups,
2541
+ allowTextCommands,
2542
+ hasControlCommand: hasControlCommandInMessage
2543
+ });
2544
+ const commandAuthorized = commandAccess.authorized;
2545
+ if (isRoom && commandAccess.shouldBlockControlCommand) {
2546
+ logInboundDrop({
2547
+ log: logVerboseMessage,
2548
+ channel: "matrix",
2549
+ reason: "control command (unauthorized)",
2550
+ target: senderId
2551
+ });
2552
+ await commitInboundEventIfClaimed();
2553
+ return;
2554
+ }
2555
+ const shouldRequireMention = isRoom ? roomConfig?.autoReply === true ? false : roomConfig?.autoReply === false ? true : typeof roomConfig?.requireMention === "boolean" ? roomConfig?.requireMention : true : false;
2556
+ const shouldBypassMention = allowTextCommands && isRoom && shouldRequireMention && !wasMentioned && !hasExplicitMention && commandAuthorized && hasControlCommandInMessage;
2557
+ const canDetectMention = agentMentionRegexes.length > 0 || hasExplicitMention;
2558
+ if (isRoom && shouldRequireMention && !wasMentioned && !shouldBypassMention) {
2559
+ const pendingHistoryBody = pendingHistoryText || pendingHistoryPollText;
2560
+ if (historyLimit > 0 && pendingHistoryBody) {
2561
+ const pendingEntry = {
2562
+ sender: senderId,
2563
+ body: pendingHistoryBody,
2564
+ timestamp: eventTs ?? void 0,
2565
+ messageId
2566
+ };
2567
+ roomHistoryTracker.recordPending(roomId, pendingEntry);
2568
+ }
2569
+ logger.info("skipping room message", {
2570
+ roomId,
2571
+ reason: "no-mention"
2572
+ });
2573
+ await commitInboundEventIfClaimed();
2574
+ return;
2575
+ }
2576
+ if (isPollEvent) {
2577
+ const pollSnapshot = await getPollSnapshot();
2578
+ if (!pollSnapshot) return;
2579
+ content = {
2580
+ msgtype: "m.text",
2581
+ body: pollSnapshot.text
2582
+ };
2583
+ }
2584
+ let media = null;
2585
+ let mediaDownloadFailed = false;
2586
+ let mediaSizeLimitExceeded = false;
2587
+ const finalContentUrl = "url" in content && typeof content.url === "string" ? content.url : void 0;
2588
+ const finalContentFile = "file" in content && content.file && typeof content.file === "object" ? content.file : void 0;
2589
+ const finalMediaUrl = finalContentUrl ?? finalContentFile?.url;
2590
+ const contentBody = typeof content.body === "string" ? content.body.trim() : "";
2591
+ const originalFilename = (typeof content.filename === "string" ? content.filename.trim() : "") || contentBody || void 0;
2592
+ const contentInfo = "info" in content && content.info && typeof content.info === "object" ? content.info : void 0;
2593
+ const contentType = contentInfo?.mimetype;
2594
+ const contentSize = typeof contentInfo?.size === "number" ? contentInfo.size : void 0;
2595
+ if (finalMediaUrl?.startsWith("mxc://")) try {
2596
+ media = await downloadMatrixMedia({
2597
+ client,
2598
+ mxcUrl: finalMediaUrl,
2599
+ contentType,
2600
+ sizeBytes: contentSize,
2601
+ maxBytes: mediaMaxBytes,
2602
+ file: finalContentFile,
2603
+ originalFilename
2604
+ });
2605
+ } catch (err) {
2606
+ mediaDownloadFailed = true;
2607
+ if (isMatrixMediaSizeLimitError(err)) mediaSizeLimitExceeded = true;
2608
+ const errorText = formatMatrixErrorMessage(err);
2609
+ logVerboseMessage(`matrix: media download failed room=${roomId} id=${event.event_id ?? "unknown"} type=${content.msgtype} error=${errorText}`);
2610
+ logger.warn("matrix media download failed", {
2611
+ roomId,
2612
+ eventId: event.event_id,
2613
+ msgtype: content.msgtype,
2614
+ encrypted: Boolean(finalContentFile),
2615
+ error: errorText
2616
+ });
2617
+ }
2618
+ const bodyText = resolveMatrixInboundBodyText({
2619
+ rawBody: locationPayload?.text ?? contentBody,
2620
+ filename: typeof content.filename === "string" ? content.filename : void 0,
2621
+ mediaPlaceholder: media?.placeholder,
2622
+ msgtype: content.msgtype,
2623
+ hadMediaUrl: Boolean(finalMediaUrl),
2624
+ mediaDownloadFailed,
2625
+ mediaSizeLimitExceeded
2626
+ });
2627
+ if (!bodyText) {
2628
+ await commitInboundEventIfClaimed();
2629
+ return;
2630
+ }
2631
+ const commandBodyText = hasControlCommandInMessage ? commandCheckText : bodyText;
2632
+ const senderName = await getSenderName();
2633
+ if (_configuredBinding) {
2634
+ const { ensureConfiguredAcpBindingReady } = await loadAcpBindingRuntime();
2635
+ if (!(await ensureConfiguredAcpBindingReady({
2636
+ cfg,
2637
+ configuredBinding: _configuredBinding
2638
+ })).ok) {
2639
+ logInboundDrop({
2640
+ log: logVerboseMessage,
2641
+ channel: "matrix",
2642
+ reason: "configured ACP binding unavailable",
2643
+ target: _configuredBinding.spec.conversationId
2644
+ });
2645
+ return;
2646
+ }
2647
+ }
2648
+ if (_runtimeBindingId) {
2649
+ const { getSessionBindingService } = await loadSessionBindingRuntime();
2650
+ getSessionBindingService().touch(_runtimeBindingId, eventTs ?? void 0);
2651
+ }
2652
+ const preparedTrigger = isRoom && historyLimit > 0 ? roomHistoryTracker.prepareTrigger(_route.agentId, roomId, historyLimit, {
2653
+ sender: senderName,
2654
+ body: bodyText,
2655
+ timestamp: eventTs ?? void 0,
2656
+ messageId
2657
+ }) : void 0;
2658
+ return {
2659
+ route: _route,
2660
+ hasExplicitSessionBinding,
2661
+ roomConfig,
2662
+ isDirectMessage,
2663
+ isRoom,
2664
+ shouldRequireMention,
2665
+ wasMentioned,
2666
+ shouldBypassMention,
2667
+ canDetectMention,
2668
+ commandAuthorized,
2669
+ inboundHistory: preparedTrigger ? buildInboundHistoryFromEntries({
2670
+ entries: preparedTrigger.history,
2671
+ limit: historyLimit
2672
+ }) : void 0,
2673
+ senderName,
2674
+ bodyText,
2675
+ commandBodyText,
2676
+ media,
2677
+ locationPayload,
2678
+ messageId,
2679
+ triggerSnapshot: preparedTrigger,
2680
+ threadRootId,
2681
+ thread,
2682
+ botLoopProtection,
2683
+ effectiveGroupAllowFrom,
2684
+ effectiveRoomUsers
2685
+ };
2686
+ };
2687
+ const ingressResult = historyLimit > 0 ? await runRoomIngress(roomId, async () => {
2688
+ const prefix = await readIngressPrefix();
2689
+ if (!prefix) return;
2690
+ if (prefix.isDirectMessage) return { deferredPrefix: prefix };
2691
+ return { ingressResult: await continueIngress(prefix) };
2692
+ }) : void 0;
2693
+ const resolvedIngressResult = historyLimit > 0 ? ingressResult?.deferredPrefix ? await continueIngress(ingressResult.deferredPrefix) : ingressResult?.ingressResult : await (async () => {
2694
+ const prefix = await readIngressPrefix();
2695
+ if (!prefix) return;
2696
+ return await continueIngress(prefix);
2697
+ })();
2698
+ if (!resolvedIngressResult) return;
2699
+ const { route: _route, hasExplicitSessionBinding, roomConfig, isDirectMessage, isRoom, shouldRequireMention, wasMentioned, shouldBypassMention, canDetectMention, commandAuthorized, inboundHistory, senderName, bodyText, commandBodyText, media, locationPayload, messageId, triggerSnapshot, threadRootId, thread, botLoopProtection, effectiveGroupAllowFrom, effectiveRoomUsers } = resolvedIngressResult;
2700
+ const replyToEventId = resolveMatrixReplyToEventId(event.content);
2701
+ const threadTarget = thread.threadId;
2702
+ const isRoomContextSenderAllowed = (contextSenderId) => {
2703
+ if (!isRoom || !contextSenderId) return true;
2704
+ if (effectiveRoomUsers.length > 0) return resolveMatrixAllowListMatch({
2705
+ allowList: effectiveRoomUsers,
2706
+ userId: contextSenderId
2707
+ }).allowed;
2708
+ if (groupPolicy === "allowlist" && effectiveGroupAllowFrom.length > 0) return resolveMatrixAllowListMatch({
2709
+ allowList: effectiveGroupAllowFrom,
2710
+ userId: contextSenderId
2711
+ }).allowed;
2712
+ return true;
2713
+ };
2714
+ const shouldIncludeRoomContextSender = (kind, contextSenderId) => evaluateSupplementalContextVisibility({
2715
+ mode: contextVisibilityMode,
2716
+ kind,
2717
+ senderAllowed: isRoomContextSenderAllowed(contextSenderId)
2718
+ }).include;
2719
+ let threadContext = threadRootId ? await resolveThreadContext({
2720
+ roomId,
2721
+ threadRootId
2722
+ }) : void 0;
2723
+ let threadContextBlockedByPolicy = false;
2724
+ if (threadContext?.senderId && !shouldIncludeRoomContextSender("thread", threadContext.senderId)) {
2725
+ logVerboseMessage(`matrix: drop thread root context (mode=${contextVisibilityMode})`);
2726
+ threadContextBlockedByPolicy = true;
2727
+ threadContext = void 0;
2728
+ }
2729
+ let replyContext;
2730
+ if (replyToEventId && replyToEventId === threadRootId && threadContext?.summary) replyContext = {
2731
+ replyToBody: threadContext.summary,
2732
+ replyToSender: threadContext.senderLabel,
2733
+ replyToSenderId: threadContext.senderId
2734
+ };
2735
+ else if (replyToEventId && replyToEventId === threadRootId && threadContextBlockedByPolicy) replyContext = await resolveReplyContext({
2736
+ roomId,
2737
+ eventId: replyToEventId
2738
+ });
2739
+ else replyContext = replyToEventId ? await resolveReplyContext({
2740
+ roomId,
2741
+ eventId: replyToEventId
2742
+ }) : void 0;
2743
+ if (replyContext?.replyToSenderId && !shouldIncludeRoomContextSender("quote", replyContext.replyToSenderId)) {
2744
+ logVerboseMessage(`matrix: drop reply context (mode=${contextVisibilityMode})`);
2745
+ replyContext = void 0;
2746
+ }
2747
+ const roomName = (isRoom ? await getRoomInfo(roomId) : void 0)?.name;
2748
+ const envelopeFrom = isDirectMessage ? senderName : roomName ?? roomId;
2749
+ const textWithId = `${bodyText}\n[matrix event id: ${messageId} room: ${roomId}]`;
2750
+ const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: _route.agentId });
2751
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
2752
+ const previousTimestamp = core.channel.session.readSessionUpdatedAt({
2753
+ storePath,
2754
+ sessionKey: _route.sessionKey
2755
+ });
2756
+ const sharedDmNoticeSessionKey = threadTarget ? _route.mainSessionKey || _route.sessionKey : _route.sessionKey;
2757
+ const sharedDmContextNotice = isDirectMessage ? hasExplicitSessionBinding ? null : resolveMatrixSharedDmContextNotice({
2758
+ storePath,
2759
+ sessionKey: sharedDmNoticeSessionKey,
2760
+ roomId,
2761
+ accountId: _route.accountId,
2762
+ dmSessionScope,
2763
+ sentRooms: sharedDmContextNoticeRooms,
2764
+ logVerboseMessage
2765
+ }) : null;
2766
+ const body = core.channel.reply.formatAgentEnvelope({
2767
+ channel: "Matrix",
2768
+ from: envelopeFrom,
2769
+ timestamp: eventTs ?? void 0,
2770
+ previousTimestamp,
2771
+ envelope: envelopeOptions,
2772
+ body: textWithId
2773
+ });
2774
+ const groupSystemPrompt = normalizeOptionalString(roomConfig?.systemPrompt);
2775
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
2776
+ Body: body,
2777
+ RawBody: bodyText,
2778
+ CommandBody: commandBodyText,
2779
+ BodyForAgent: bodyText,
2780
+ BodyForCommands: commandBodyText,
2781
+ InboundHistory: inboundHistory && inboundHistory.length > 0 ? inboundHistory : void 0,
2782
+ From: isDirectMessage ? `matrix:${senderId}` : `matrix:channel:${roomId}`,
2783
+ To: `room:${roomId}`,
2784
+ SessionKey: _route.sessionKey,
2785
+ AccountId: _route.accountId,
2786
+ ChatType: isDirectMessage ? "direct" : "channel",
2787
+ ConversationLabel: envelopeFrom,
2788
+ SenderName: senderName,
2789
+ SenderId: senderId,
2790
+ SenderUsername: senderId.split(":")[0]?.replace(/^@/, ""),
2791
+ GroupSubject: isRoom ? roomName ?? roomId : void 0,
2792
+ GroupId: isRoom ? roomId : void 0,
2793
+ GroupChannel: isRoom ? roomId : void 0,
2794
+ GroupSystemPrompt: isRoom ? groupSystemPrompt : void 0,
2795
+ Provider: "matrix",
2796
+ Surface: "matrix",
2797
+ WasMentioned: isRoom ? wasMentioned : void 0,
2798
+ MessageSid: messageId,
2799
+ ReplyToId: threadTarget ? void 0 : replyToEventId ?? void 0,
2800
+ ReplyToBody: replyContext?.replyToBody,
2801
+ ReplyToSender: replyContext?.replyToSender,
2802
+ MessageThreadId: threadTarget,
2803
+ ThreadStarterBody: threadContext?.threadStarterBody,
2804
+ Timestamp: eventTs ?? void 0,
2805
+ MediaPath: media?.path,
2806
+ MediaType: media?.contentType,
2807
+ MediaUrl: media?.path,
2808
+ ...locationPayload?.context,
2809
+ CommandAuthorized: commandAuthorized,
2810
+ CommandSource: "text",
2811
+ NativeChannelId: roomId,
2812
+ NativeDirectUserId: isDirectMessage ? senderId : void 0,
2813
+ OriginatingChannel: "matrix",
2814
+ OriginatingTo: `room:${roomId}`
2815
+ });
2816
+ logVerboseMessage(`matrix inbound: room=${roomId} from=${senderId} preview="${bodyText.slice(0, 200).replace(/\n/g, "\\n")}"`);
2817
+ const replyTarget = ctxPayload.To;
2818
+ if (!replyTarget) {
2819
+ runtime.error?.("matrix: missing reply target");
2820
+ return;
2821
+ }
2822
+ const { ackReaction, ackReactionScope: ackScope } = resolveMatrixAckReactionConfig({
2823
+ cfg,
2824
+ agentId: _route.agentId,
2825
+ accountId
2826
+ });
2827
+ const shouldAckReaction = () => Boolean(ackReaction && core.channel.reactions.shouldAckReaction({
2828
+ scope: ackScope,
2829
+ isDirect: isDirectMessage,
2830
+ isGroup: isRoom,
2831
+ isMentionableGroup: isRoom,
2832
+ requireMention: shouldRequireMention,
2833
+ canDetectMention,
2834
+ effectiveWasMentioned: wasMentioned || shouldBypassMention,
2835
+ shouldBypassMention
2836
+ }));
2837
+ if (shouldAckReaction() && messageId) loadMatrixSendModule().then(({ reactMatrixMessage }) => reactMatrixMessage(roomId, messageId, ackReaction, client)).catch((err) => {
2838
+ logVerboseMessage(`matrix react failed for room ${roomId}: ${String(err)}`);
2839
+ });
2840
+ if (messageId) loadMatrixSendModule().then(({ sendReadReceiptMatrix }) => sendReadReceiptMatrix(roomId, messageId, client)).catch((err) => {
2841
+ logVerboseMessage(`matrix: read receipt failed room=${roomId} id=${messageId}: ${String(err)}`);
2842
+ });
2843
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2844
+ cfg,
2845
+ channel: "matrix",
2846
+ accountId: _route.accountId
2847
+ });
2848
+ const mediaLocalRoots = getAgentScopedMediaLocalRoots(cfg, _route.agentId);
2849
+ let finalReplyDeliveryFailed = false;
2850
+ let nonFinalReplyDeliveryFailed = false;
2851
+ let retryableReplyDeliveryFailed = false;
2852
+ const { onModelSelected, ...prefixOptions } = createReplyPrefixOptions({
2853
+ cfg,
2854
+ agentId: _route.agentId,
2855
+ channel: "matrix",
2856
+ accountId: _route.accountId
2857
+ });
2858
+ const typingCallbacks = createTypingCallbacks({
2859
+ start: async () => {
2860
+ const { sendTypingMatrix } = await loadMatrixSendModule();
2861
+ await sendTypingMatrix(roomId, true, void 0, client);
2862
+ },
2863
+ stop: async () => {
2864
+ const { sendTypingMatrix } = await loadMatrixSendModule();
2865
+ await sendTypingMatrix(roomId, false, void 0, client);
2866
+ },
2867
+ onStartError: (err) => {
2868
+ logTypingFailure({
2869
+ log: logVerboseMessage,
2870
+ channel: "matrix",
2871
+ action: "start",
2872
+ target: roomId,
2873
+ error: err
2874
+ });
2875
+ },
2876
+ onStopError: (err) => {
2877
+ logTypingFailure({
2878
+ log: logVerboseMessage,
2879
+ channel: "matrix",
2880
+ action: "stop",
2881
+ target: roomId,
2882
+ error: err
2883
+ });
2884
+ }
2885
+ });
2886
+ const draftStreamingEnabled = streaming !== "off";
2887
+ const quietDraftStreaming = streaming === "quiet" || streaming === "progress";
2888
+ const progressDraftStreaming = streaming === "progress";
2889
+ const draftReplyToId = replyToMode !== "off" && !threadTarget ? messageId : void 0;
2890
+ const draftStream = draftStreamingEnabled ? await loadMatrixDraftStream().then(({ createMatrixDraftStream }) => createMatrixDraftStream({
2891
+ roomId,
2892
+ client,
2893
+ cfg,
2894
+ mode: quietDraftStreaming ? "quiet" : "partial",
2895
+ threadId: threadTarget,
2896
+ replyToId: draftReplyToId,
2897
+ preserveReplyId: replyToMode === "all",
2898
+ accountId: _route.accountId,
2899
+ log: logVerboseMessage
2900
+ })) : void 0;
2901
+ draftStreamRef = draftStream;
2902
+ const shouldStreamPreviewToolProgress = Boolean(draftStream) && previewToolProgressEnabled;
2903
+ const shouldSuppressDefaultToolProgressMessages = Boolean(draftStream) && (shouldStreamPreviewToolProgress || params.streaming === "progress");
2904
+ let currentDraftMessageGeneration = 0;
2905
+ let currentDraftBlockOffset = 0;
2906
+ let latestDraftFullText = "";
2907
+ const pendingDraftBoundaries = [];
2908
+ const latestQueuedDraftBoundaryOffsets = /* @__PURE__ */ new Map();
2909
+ let currentDraftReplyToId = draftReplyToId;
2910
+ let previewToolProgressSuppressed = false;
2911
+ let previewToolProgressLines = [];
2912
+ const progressConfigEntry = params.accountConfig ?? cfg.channels?.matrix;
2913
+ const progressSeed = `${_route.accountId}:${roomId}`;
2914
+ const renderProgressDraft = () => {
2915
+ if (!draftStream || !progressDraftStreaming) return;
2916
+ const previewText = formatChannelProgressDraftText({
2917
+ entry: progressConfigEntry,
2918
+ lines: previewToolProgressLines,
2919
+ seed: progressSeed,
2920
+ formatLine: formatMatrixToolProgressMarkdownCode,
2921
+ bullet: "-"
2922
+ });
2923
+ if (!previewText) return;
2924
+ draftStream.update(previewText);
2925
+ };
2926
+ const progressDraftGate = createChannelProgressDraftGate({ onStart: renderProgressDraft });
2927
+ const pushPreviewToolProgress = async (line, options) => {
2928
+ if (!draftStream) return;
2929
+ if (options?.toolName !== void 0 && !isChannelProgressDraftWorkToolName(options.toolName)) return;
2930
+ const normalized = normalizeChannelProgressDraftLineIdentity(line);
2931
+ const progressLine = typeof line === "object" && line !== void 0 ? line : normalized;
2932
+ if (!progressDraftStreaming) {
2933
+ if (!shouldStreamPreviewToolProgress || previewToolProgressSuppressed || !normalized) return;
2934
+ const nextLines = mergeChannelProgressDraftLine(previewToolProgressLines, progressLine, { maxLines: resolveChannelProgressDraftMaxLines(progressConfigEntry) });
2935
+ if (nextLines === previewToolProgressLines) return;
2936
+ previewToolProgressLines = nextLines;
2937
+ draftStream.update(formatChannelProgressDraftText({
2938
+ entry: progressConfigEntry,
2939
+ lines: previewToolProgressLines,
2940
+ seed: progressSeed,
2941
+ formatLine: formatMatrixToolProgressMarkdownCode,
2942
+ bullet: "-"
2943
+ }));
2944
+ return;
2945
+ }
2946
+ if (shouldStreamPreviewToolProgress && !previewToolProgressSuppressed && normalized) previewToolProgressLines = mergeChannelProgressDraftLine(previewToolProgressLines, progressLine, { maxLines: resolveChannelProgressDraftMaxLines(progressConfigEntry) });
2947
+ const alreadyStarted = progressDraftGate.hasStarted;
2948
+ await progressDraftGate.noteWork();
2949
+ if (alreadyStarted && progressDraftGate.hasStarted) renderProgressDraft();
2950
+ };
2951
+ const suppressPreviewToolProgressForAnswerText = (text) => {
2952
+ if (!text?.trim()) return;
2953
+ previewToolProgressSuppressed = true;
2954
+ previewToolProgressLines = [];
2955
+ };
2956
+ const resetPreviewToolProgress = () => {
2957
+ previewToolProgressSuppressed = false;
2958
+ previewToolProgressLines = [];
2959
+ };
2960
+ const buildPreviewToolProgressReplyOptions = () => {
2961
+ if (!shouldSuppressDefaultToolProgressMessages) return {};
2962
+ const options = { suppressDefaultToolProgressMessages: true };
2963
+ if (!shouldStreamPreviewToolProgress) return options;
2964
+ return {
2965
+ ...options,
2966
+ onToolStart: async (payload) => {
2967
+ const toolName = payload.name?.trim();
2968
+ await pushPreviewToolProgress(formatChannelProgressDraftLineForEntry(progressConfigEntry, {
2969
+ event: "tool",
2970
+ name: toolName,
2971
+ phase: payload.phase,
2972
+ args: payload.args
2973
+ }, payload.detailMode ? { detailMode: payload.detailMode } : void 0), { toolName });
2974
+ },
2975
+ onItemEvent: async (payload) => {
2976
+ await pushPreviewToolProgress(buildChannelProgressDraftLineForEntry(progressConfigEntry, {
2977
+ event: "item",
2978
+ itemId: payload.itemId,
2979
+ itemKind: payload.kind,
2980
+ title: payload.title,
2981
+ name: payload.name,
2982
+ phase: payload.phase,
2983
+ status: payload.status,
2984
+ summary: payload.summary,
2985
+ progressText: payload.progressText,
2986
+ meta: payload.meta
2987
+ }));
2988
+ },
2989
+ onPlanUpdate: async (payload) => {
2990
+ if (payload.phase !== "update") return;
2991
+ await pushPreviewToolProgress(formatChannelProgressDraftLine({
2992
+ event: "plan",
2993
+ phase: payload.phase,
2994
+ title: payload.title,
2995
+ explanation: payload.explanation,
2996
+ steps: payload.steps
2997
+ }));
2998
+ },
2999
+ onApprovalEvent: async (payload) => {
3000
+ if (payload.phase !== "requested") return;
3001
+ await pushPreviewToolProgress(formatChannelProgressDraftLine({
3002
+ event: "approval",
3003
+ phase: payload.phase,
3004
+ title: payload.title,
3005
+ command: payload.command,
3006
+ reason: payload.reason,
3007
+ message: payload.message
3008
+ }));
3009
+ },
3010
+ onCommandOutput: async (payload) => {
3011
+ if (payload.phase !== "end") return;
3012
+ await pushPreviewToolProgress(formatChannelProgressDraftLine({
3013
+ event: "command-output",
3014
+ phase: payload.phase,
3015
+ title: payload.title,
3016
+ name: payload.name,
3017
+ status: payload.status,
3018
+ exitCode: payload.exitCode
3019
+ }));
3020
+ },
3021
+ onPatchSummary: async (payload) => {
3022
+ if (payload.phase !== "end") return;
3023
+ await pushPreviewToolProgress(formatChannelProgressDraftLine({
3024
+ event: "patch",
3025
+ phase: payload.phase,
3026
+ title: payload.title,
3027
+ name: payload.name,
3028
+ added: payload.added,
3029
+ modified: payload.modified,
3030
+ deleted: payload.deleted,
3031
+ summary: payload.summary
3032
+ }));
3033
+ }
3034
+ };
3035
+ };
3036
+ const getDisplayableDraftText = () => {
3037
+ const nextDraftBoundaryOffset = pendingDraftBoundaries.find((boundary) => boundary.messageGeneration === currentDraftMessageGeneration)?.endOffset;
3038
+ if (nextDraftBoundaryOffset === void 0) return latestDraftFullText.slice(currentDraftBlockOffset);
3039
+ return latestDraftFullText.slice(currentDraftBlockOffset, nextDraftBoundaryOffset);
3040
+ };
3041
+ const updateDraftFromLatestFullText = () => {
3042
+ const blockText = getDisplayableDraftText();
3043
+ if (blockText) draftStream?.update(blockText);
3044
+ };
3045
+ const queueDraftBlockBoundary = (payload, context) => {
3046
+ const payloadTextLength = payload.text?.length ?? 0;
3047
+ const messageGeneration = context?.assistantMessageIndex ?? currentDraftMessageGeneration;
3048
+ const nextDraftBoundaryOffset = (latestQueuedDraftBoundaryOffsets.get(messageGeneration) ?? 0) + payloadTextLength;
3049
+ latestQueuedDraftBoundaryOffsets.set(messageGeneration, nextDraftBoundaryOffset);
3050
+ pendingDraftBoundaries.push({
3051
+ messageGeneration,
3052
+ endOffset: nextDraftBoundaryOffset
3053
+ });
3054
+ };
3055
+ const advanceDraftBlockBoundary = (options) => {
3056
+ const completedBoundary = pendingDraftBoundaries.shift();
3057
+ if (completedBoundary) {
3058
+ if (!pendingDraftBoundaries.some((entry) => entry.messageGeneration === completedBoundary.messageGeneration)) latestQueuedDraftBoundaryOffsets.delete(completedBoundary.messageGeneration);
3059
+ if (completedBoundary.messageGeneration === currentDraftMessageGeneration) currentDraftBlockOffset = completedBoundary.endOffset;
3060
+ return;
3061
+ }
3062
+ if (options?.fallbackToLatestEnd) currentDraftBlockOffset = latestDraftFullText.length;
3063
+ };
3064
+ const resetDraftBlockOffsets = () => {
3065
+ currentDraftMessageGeneration += 1;
3066
+ currentDraftBlockOffset = 0;
3067
+ latestDraftFullText = "";
3068
+ };
3069
+ const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } = core.channel.reply.createReplyDispatcherWithTyping({
3070
+ ...prefixOptions,
3071
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, _route.agentId),
3072
+ deliver: async (payload, info) => {
3073
+ if (draftStream && info.kind !== "tool" && !payload.isCompactionNotice) {
3074
+ const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
3075
+ const ttsSupplement = getReplyPayloadTtsSupplement(payload);
3076
+ const fallbackPayload = ttsSupplement && ttsSupplement.visibleTextAlreadyDelivered !== true && !payload.text?.trim() ? {
3077
+ ...payload,
3078
+ text: ttsSupplement.spokenText
3079
+ } : payload;
3080
+ if (draftConsumed) {
3081
+ await draftStream.discardPending();
3082
+ await deliverMatrixReplies({
3083
+ cfg,
3084
+ replies: [fallbackPayload],
3085
+ roomId,
3086
+ client,
3087
+ runtime,
3088
+ textLimit,
3089
+ replyToMode,
3090
+ threadId: threadTarget,
3091
+ accountId: _route.accountId,
3092
+ mediaLocalRoots,
3093
+ tableMode
3094
+ });
3095
+ return;
3096
+ }
3097
+ const payloadReplyToId = normalizeOptionalString(payload.replyToId);
3098
+ const payloadReplyMismatch = replyToMode !== "off" && !threadTarget && payloadReplyToId !== currentDraftReplyToId;
3099
+ let mustDeliverFinalNormally = draftStream.mustDeliverFinalNormally();
3100
+ if (Boolean(payload.text?.trim()) && !payload.isError && !payloadReplyMismatch && !mustDeliverFinalNormally) {
3101
+ await draftStream.stop();
3102
+ mustDeliverFinalNormally = draftStream.mustDeliverFinalNormally();
3103
+ } else await draftStream.discardPending();
3104
+ const draftEventId = draftStream.eventId();
3105
+ if (draftEventId && payload.text && !payload.isError && !hasMedia && !payloadReplyMismatch && !mustDeliverFinalNormally) {
3106
+ const finalPreviewText = payload.text;
3107
+ await deliverWithFinalizableLivePreviewAdapter({
3108
+ kind: "final",
3109
+ payload,
3110
+ adapter: defineFinalizableLivePreviewAdapter({
3111
+ draft: {
3112
+ flush: async () => {},
3113
+ clear: async () => {},
3114
+ discardPending: async () => {},
3115
+ id: () => draftEventId
3116
+ },
3117
+ buildFinalEdit: () => ({
3118
+ text: finalPreviewText,
3119
+ finalizeLive: !(quietDraftStreaming || !draftStream.matchesPreparedText(finalPreviewText)),
3120
+ ...quietDraftStreaming ? { extraContent: buildMatrixFinalizedPreviewContent() } : {}
3121
+ }),
3122
+ editFinal: async (_draftEventId, edit) => {
3123
+ if (edit.finalizeLive) {
3124
+ if (!await draftStream.finalizeLive()) throw new Error("Matrix draft live finalize failed");
3125
+ return;
3126
+ }
3127
+ const { editMessageMatrix } = await loadMatrixSendModule();
3128
+ await editMessageMatrix(roomId, _draftEventId, edit.text, {
3129
+ client,
3130
+ cfg,
3131
+ threadId: threadTarget,
3132
+ accountId: _route.accountId,
3133
+ extraContent: edit.extraContent
3134
+ });
3135
+ },
3136
+ createPreviewReceipt: (id) => createPreviewMessageReceipt({
3137
+ id,
3138
+ ...threadTarget ? { threadId: threadTarget } : {},
3139
+ ...currentDraftReplyToId ? { replyToId: currentDraftReplyToId } : {}
3140
+ }),
3141
+ logPreviewEditFailure: (err) => {
3142
+ logVerboseMessage(`matrix: preview final edit failed: ${String(err)}`);
3143
+ }
3144
+ }),
3145
+ deliverNormally: async () => {
3146
+ await redactMatrixDraftEvent(client, roomId, draftEventId);
3147
+ await deliverMatrixReplies({
3148
+ cfg,
3149
+ replies: [fallbackPayload],
3150
+ roomId,
3151
+ client,
3152
+ runtime,
3153
+ textLimit,
3154
+ replyToMode,
3155
+ threadId: threadTarget,
3156
+ accountId: _route.accountId,
3157
+ mediaLocalRoots,
3158
+ tableMode
3159
+ });
3160
+ }
3161
+ });
3162
+ draftConsumed = true;
3163
+ } else if (draftEventId && hasMedia && !payloadReplyMismatch) {
3164
+ let textEditOk = !mustDeliverFinalNormally;
3165
+ const payloadText = payload.text ?? ttsSupplement?.spokenText;
3166
+ const payloadTextMatchesDraft = typeof payloadText === "string" && draftStream.matchesPreparedText(payloadText);
3167
+ const reusesDraftTextUnchanged = typeof payloadText === "string" && Boolean(payloadText.trim()) && payloadTextMatchesDraft;
3168
+ if (textEditOk && payloadText && (quietDraftStreaming || typeof payloadText === "string" && !payloadTextMatchesDraft)) {
3169
+ const { editMessageMatrix } = await loadMatrixSendModule();
3170
+ textEditOk = await editMessageMatrix(roomId, draftEventId, payloadText, {
3171
+ client,
3172
+ cfg,
3173
+ threadId: threadTarget,
3174
+ accountId: _route.accountId,
3175
+ extraContent: quietDraftStreaming ? buildMatrixFinalizedPreviewContent() : void 0
3176
+ }).then(() => true, () => false);
3177
+ } else if (textEditOk && reusesDraftTextUnchanged) textEditOk = await draftStream.finalizeLive();
3178
+ const reusesDraftAsFinalText = Boolean(payloadText?.trim()) && textEditOk;
3179
+ if (!reusesDraftAsFinalText) await redactMatrixDraftEvent(client, roomId, draftEventId);
3180
+ await deliverMatrixReplies({
3181
+ cfg,
3182
+ replies: [ttsSupplement && reusesDraftAsFinalText ? buildTtsSupplementMediaPayload(payload) : {
3183
+ ...payload,
3184
+ text: reusesDraftAsFinalText ? void 0 : payload.text ?? (ttsSupplement?.visibleTextAlreadyDelivered === true ? void 0 : ttsSupplement?.spokenText)
3185
+ }],
3186
+ roomId,
3187
+ client,
3188
+ runtime,
3189
+ textLimit,
3190
+ replyToMode,
3191
+ threadId: threadTarget,
3192
+ accountId: _route.accountId,
3193
+ mediaLocalRoots,
3194
+ tableMode
3195
+ });
3196
+ draftConsumed = true;
3197
+ } else {
3198
+ const draftRedacted = Boolean(draftEventId) && (payload.isError || payloadReplyMismatch || mustDeliverFinalNormally);
3199
+ if (draftRedacted && draftEventId) await redactMatrixDraftEvent(client, roomId, draftEventId);
3200
+ const deliveredFallback = await deliverMatrixReplies({
3201
+ cfg,
3202
+ replies: [fallbackPayload],
3203
+ roomId,
3204
+ client,
3205
+ runtime,
3206
+ textLimit,
3207
+ replyToMode,
3208
+ threadId: threadTarget,
3209
+ accountId: _route.accountId,
3210
+ mediaLocalRoots,
3211
+ tableMode
3212
+ });
3213
+ if (draftRedacted || deliveredFallback) draftConsumed = true;
3214
+ }
3215
+ if (info.kind === "block") {
3216
+ draftConsumed = false;
3217
+ advanceDraftBlockBoundary({ fallbackToLatestEnd: true });
3218
+ draftStream.reset();
3219
+ currentDraftReplyToId = replyToMode === "all" ? draftReplyToId : void 0;
3220
+ updateDraftFromLatestFullText();
3221
+ const { sendTypingMatrix } = await loadMatrixSendModule();
3222
+ await sendTypingMatrix(roomId, true, void 0, client).catch(() => {});
3223
+ }
3224
+ } else await deliverMatrixReplies({
3225
+ cfg,
3226
+ replies: [payload],
3227
+ roomId,
3228
+ client,
3229
+ runtime,
3230
+ textLimit,
3231
+ replyToMode,
3232
+ threadId: threadTarget,
3233
+ accountId: _route.accountId,
3234
+ mediaLocalRoots,
3235
+ tableMode
3236
+ });
3237
+ },
3238
+ onError: (err, info) => {
3239
+ if (err instanceof MatrixRetryableInboundError) retryableReplyDeliveryFailed = true;
3240
+ if (info.kind === "final") finalReplyDeliveryFailed = true;
3241
+ else nonFinalReplyDeliveryFailed = true;
3242
+ if (info.kind === "block") advanceDraftBlockBoundary({ fallbackToLatestEnd: true });
3243
+ runtime.error?.(`matrix ${info.kind} reply failed: ${String(err)}`);
3244
+ },
3245
+ onReplyStart: typingCallbacks.onReplyStart,
3246
+ onIdle: typingCallbacks.onIdle
3247
+ });
3248
+ const pinnedMainDmOwner = isDirectMessage ? await (async () => {
3249
+ const livePinnedCfg = core.config.current();
3250
+ const livePinnedDmAllowFrom = await resolveCachedLiveAllowlist({
3251
+ cfg: livePinnedCfg,
3252
+ entries: resolveMatrixAccountAllowlistConfig({
3253
+ cfg: livePinnedCfg,
3254
+ accountId
3255
+ }).dmAllowFrom,
3256
+ startupResolvedEntries: allowFromResolvedEntries,
3257
+ cache: liveDmAllowlistCache,
3258
+ updateCache: (next) => {
3259
+ liveDmAllowlistCache = next;
3260
+ }
3261
+ });
3262
+ return resolvePinnedMainDmOwnerFromAllowlist({
3263
+ dmScope: livePinnedCfg.session?.dmScope,
3264
+ allowFrom: livePinnedDmAllowFrom,
3265
+ normalizeEntry: normalizeMatrixUserId
3266
+ });
3267
+ })() : null;
3268
+ const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
3269
+ route: _route,
3270
+ sessionKey: _route.sessionKey
3271
+ });
3272
+ const turnResult = await core.channel.turn.run({
3273
+ channel: "matrix",
3274
+ accountId: _route.accountId,
3275
+ raw: event,
3276
+ adapter: {
3277
+ ingest: () => ({
3278
+ id: messageId,
3279
+ rawText: bodyText,
3280
+ textForAgent: ctxPayload.BodyForAgent,
3281
+ textForCommands: ctxPayload.CommandBody,
3282
+ raw: event
3283
+ }),
3284
+ resolveTurn: () => ({
3285
+ channel: "matrix",
3286
+ accountId: _route.accountId,
3287
+ routeSessionKey: _route.sessionKey,
3288
+ storePath,
3289
+ ctxPayload,
3290
+ recordInboundSession: core.channel.session.recordInboundSession,
3291
+ botLoopProtection,
3292
+ record: {
3293
+ updateLastRoute: isDirectMessage ? {
3294
+ sessionKey: inboundLastRouteSessionKey,
3295
+ channel: "matrix",
3296
+ to: `room:${roomId}`,
3297
+ accountId: _route.accountId,
3298
+ mainDmOwnerPin: inboundLastRouteSessionKey === _route.mainSessionKey && pinnedMainDmOwner ? {
3299
+ ownerRecipient: pinnedMainDmOwner,
3300
+ senderRecipient: normalizeMatrixUserId(senderId),
3301
+ onSkip: ({ ownerRecipient, senderRecipient }) => {
3302
+ logVerboseMessage(`matrix: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
3303
+ }
3304
+ } : void 0
3305
+ } : void 0,
3306
+ onRecordError: (err) => {
3307
+ logger.warn("failed updating session meta", {
3308
+ error: String(err),
3309
+ storePath,
3310
+ sessionKey: ctxPayload.SessionKey ?? _route.sessionKey
3311
+ });
3312
+ }
3313
+ },
3314
+ onPreDispatchFailure: () => core.channel.reply.settleReplyDispatcher({
3315
+ dispatcher,
3316
+ onSettled: () => {
3317
+ markRunComplete();
3318
+ markDispatchIdle();
3319
+ }
3320
+ }),
3321
+ runDispatch: async () => {
3322
+ if (sharedDmContextNotice && markTrackedRoomIfFirst(sharedDmContextNoticeRooms, roomId)) client.sendMessage(roomId, {
3323
+ msgtype: "m.notice",
3324
+ body: sharedDmContextNotice
3325
+ }).catch((err) => {
3326
+ logVerboseMessage(`matrix: failed sending shared DM session notice room=${roomId}: ${String(err)}`);
3327
+ });
3328
+ return await core.channel.reply.withReplyDispatcher({
3329
+ dispatcher,
3330
+ onSettled: () => {
3331
+ markDispatchIdle();
3332
+ },
3333
+ run: async () => {
3334
+ try {
3335
+ return await core.channel.reply.dispatchReplyFromConfig({
3336
+ ctx: ctxPayload,
3337
+ cfg,
3338
+ dispatcher,
3339
+ replyOptions: {
3340
+ ...replyOptions,
3341
+ skillFilter: roomConfig?.skills,
3342
+ disableBlockStreaming: !blockStreamingEnabled,
3343
+ onPartialReply: draftStream ? (payload) => {
3344
+ if (progressDraftStreaming) return;
3345
+ latestDraftFullText = payload.text ?? "";
3346
+ suppressPreviewToolProgressForAnswerText(latestDraftFullText);
3347
+ updateDraftFromLatestFullText();
3348
+ } : void 0,
3349
+ onBlockReplyQueued: draftStream ? (payload, context) => {
3350
+ if (payload.isCompactionNotice === true) return;
3351
+ queueDraftBlockBoundary(payload, context);
3352
+ } : void 0,
3353
+ onAssistantMessageStart: draftStream ? () => {
3354
+ resetDraftBlockOffsets();
3355
+ resetPreviewToolProgress();
3356
+ } : void 0,
3357
+ ...buildPreviewToolProgressReplyOptions(),
3358
+ onModelSelected
3359
+ }
3360
+ });
3361
+ } finally {
3362
+ progressDraftGate.cancel();
3363
+ markRunComplete();
3364
+ }
3365
+ }
3366
+ });
3367
+ }
3368
+ })
3369
+ }
3370
+ });
3371
+ if (!turnResult.dispatched) {
3372
+ if (turnResult.admission.kind === "drop" && turnResult.admission.reason === "bot-loop-protection") await commitInboundEventIfClaimed();
3373
+ return;
3374
+ }
3375
+ const { dispatchResult } = turnResult;
3376
+ const { queuedFinal, counts } = dispatchResult;
3377
+ if (finalReplyDeliveryFailed) {
3378
+ if (retryableReplyDeliveryFailed) {
3379
+ logVerboseMessage(`matrix: final reply delivery failed room=${roomId} id=${messageId}; leaving event uncommitted`);
3380
+ return;
3381
+ }
3382
+ logVerboseMessage(`matrix: final reply delivery failed room=${roomId} id=${messageId}; keeping replay committed`);
3383
+ await commitInboundEventIfClaimed();
3384
+ return;
3385
+ }
3386
+ if (!queuedFinal && nonFinalReplyDeliveryFailed) {
3387
+ if (retryableReplyDeliveryFailed) {
3388
+ logVerboseMessage(`matrix: non-final reply delivery failed room=${roomId} id=${messageId}; leaving event uncommitted`);
3389
+ return;
3390
+ }
3391
+ logVerboseMessage(`matrix: non-final reply delivery failed room=${roomId} id=${messageId}; keeping replay committed`);
3392
+ await commitInboundEventIfClaimed();
3393
+ return;
3394
+ }
3395
+ if (isRoom && triggerSnapshot) roomHistoryTracker.consumeHistory(_route.agentId, roomId, triggerSnapshot, messageId);
3396
+ if (!hasFinalInboundReplyDispatch({
3397
+ queuedFinal,
3398
+ counts
3399
+ })) {
3400
+ await commitInboundEventIfClaimed();
3401
+ return;
3402
+ }
3403
+ const finalCount = counts.final;
3404
+ logVerboseMessage(`matrix: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${replyTarget}`);
3405
+ await commitInboundEventIfClaimed();
3406
+ } catch (err) {
3407
+ runtime.error?.(`matrix handler failed: ${String(err)}`);
3408
+ } finally {
3409
+ if (draftStreamRef) {
3410
+ const draftEventId = await draftStreamRef.stop().catch(() => void 0);
3411
+ if (draftEventId && !draftConsumed) await redactMatrixDraftEvent(client, roomId, draftEventId);
3412
+ }
3413
+ if (claimedInboundEvent && inboundDeduper && eventId) inboundDeduper.releaseEvent({
3414
+ roomId,
3415
+ eventId
3416
+ });
3417
+ }
3418
+ };
3419
+ }
3420
+ //#endregion
3421
+ //#region extensions/matrix/src/matrix/monitor/inbound-dedupe.ts
3422
+ const INBOUND_DEDUPE_FILENAME = "inbound-dedupe.json";
3423
+ const STORE_VERSION = 1;
3424
+ const DEFAULT_MAX_ENTRIES = 2e4;
3425
+ const DEFAULT_TTL_MS = 720 * 60 * 60 * 1e3;
3426
+ const PERSIST_DEBOUNCE_MS = 250;
3427
+ function normalizeEventPart(value) {
3428
+ return value.trim();
3429
+ }
3430
+ function buildEventKey(params) {
3431
+ const roomId = normalizeEventPart(params.roomId);
3432
+ const eventId = normalizeEventPart(params.eventId);
3433
+ return roomId && eventId ? `${roomId}|${eventId}` : "";
3434
+ }
3435
+ function resolveInboundDedupeStatePath(params) {
3436
+ return resolveMatrixStateFilePath({
3437
+ auth: params.auth,
3438
+ env: params.env,
3439
+ stateDir: params.stateDir,
3440
+ filename: INBOUND_DEDUPE_FILENAME
3441
+ });
3442
+ }
3443
+ function normalizeTimestamp(raw) {
3444
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
3445
+ return Math.max(0, Math.floor(raw));
3446
+ }
3447
+ function pruneSeenEvents(params) {
3448
+ const { seen, ttlMs, maxEntries, nowMs } = params;
3449
+ if (ttlMs > 0) {
3450
+ const cutoff = nowMs - ttlMs;
3451
+ for (const [key, ts] of seen) if (ts < cutoff) seen.delete(key);
3452
+ }
3453
+ const max = Math.max(0, Math.floor(maxEntries));
3454
+ if (max <= 0) {
3455
+ seen.clear();
3456
+ return;
3457
+ }
3458
+ while (seen.size > max) {
3459
+ const oldestKey = seen.keys().next().value;
3460
+ if (typeof oldestKey !== "string") break;
3461
+ seen.delete(oldestKey);
3462
+ }
3463
+ }
3464
+ function toStoredState(params) {
3465
+ pruneSeenEvents(params);
3466
+ return {
3467
+ version: STORE_VERSION,
3468
+ entries: Array.from(params.seen.entries()).map(([key, ts]) => ({
3469
+ key,
3470
+ ts
3471
+ }))
3472
+ };
3473
+ }
3474
+ async function readStoredState(storagePath) {
3475
+ const { value } = await readJsonFileWithFallback(storagePath, null);
3476
+ if (value?.version !== STORE_VERSION || !Array.isArray(value.entries)) return null;
3477
+ return value;
3478
+ }
3479
+ async function createMatrixInboundEventDeduper(params) {
3480
+ const nowMs = params.nowMs ?? (() => Date.now());
3481
+ const ttlMs = typeof params.ttlMs === "number" && Number.isFinite(params.ttlMs) ? Math.max(0, Math.floor(params.ttlMs)) : DEFAULT_TTL_MS;
3482
+ const maxEntries = typeof params.maxEntries === "number" && Number.isFinite(params.maxEntries) ? Math.max(0, Math.floor(params.maxEntries)) : DEFAULT_MAX_ENTRIES;
3483
+ const storagePath = params.storagePath ?? resolveInboundDedupeStatePath({
3484
+ auth: params.auth,
3485
+ env: params.env,
3486
+ stateDir: params.stateDir
3487
+ });
3488
+ const seen = /* @__PURE__ */ new Map();
3489
+ const pending = /* @__PURE__ */ new Set();
3490
+ const persistLock = createAsyncLock();
3491
+ try {
3492
+ const stored = await readStoredState(storagePath);
3493
+ for (const entry of stored?.entries ?? []) {
3494
+ if (!entry || typeof entry.key !== "string") continue;
3495
+ const key = entry.key.trim();
3496
+ const ts = normalizeTimestamp(entry.ts);
3497
+ if (!key || ts === null) continue;
3498
+ seen.set(key, ts);
3499
+ }
3500
+ pruneSeenEvents({
3501
+ seen,
3502
+ ttlMs,
3503
+ maxEntries,
3504
+ nowMs: nowMs()
3505
+ });
3506
+ } catch (err) {
3507
+ LogService.warn("MatrixInboundDedupe", "Failed loading Matrix inbound dedupe store:", err);
3508
+ }
3509
+ let dirty = false;
3510
+ let persistTimer = null;
3511
+ let persistPromise = null;
3512
+ const persist = async () => {
3513
+ dirty = false;
3514
+ const payload = toStoredState({
3515
+ seen,
3516
+ ttlMs,
3517
+ maxEntries,
3518
+ nowMs: nowMs()
3519
+ });
3520
+ try {
3521
+ await persistLock(async () => {
3522
+ await writeJsonFileAtomically(storagePath, payload);
3523
+ });
3524
+ } catch (err) {
3525
+ dirty = true;
3526
+ throw err;
3527
+ }
3528
+ };
3529
+ const flush = async () => {
3530
+ if (persistTimer) {
3531
+ clearTimeout(persistTimer);
3532
+ persistTimer = null;
3533
+ }
3534
+ for (;;) {
3535
+ if (!dirty && !persistPromise) break;
3536
+ if (dirty && !persistPromise) persistPromise = persist().finally(() => {
3537
+ persistPromise = null;
3538
+ });
3539
+ await persistPromise;
3540
+ }
3541
+ };
3542
+ const schedulePersist = () => {
3543
+ dirty = true;
3544
+ if (persistTimer) return;
3545
+ persistTimer = setTimeout(() => {
3546
+ persistTimer = null;
3547
+ flush().catch((err) => {
3548
+ LogService.warn("MatrixInboundDedupe", "Failed persisting Matrix inbound dedupe store:", err);
3549
+ });
3550
+ }, PERSIST_DEBOUNCE_MS);
3551
+ persistTimer.unref?.();
3552
+ };
3553
+ return {
3554
+ claimEvent: ({ roomId, eventId }) => {
3555
+ const key = buildEventKey({
3556
+ roomId,
3557
+ eventId
3558
+ });
3559
+ if (!key) return true;
3560
+ pruneSeenEvents({
3561
+ seen,
3562
+ ttlMs,
3563
+ maxEntries,
3564
+ nowMs: nowMs()
3565
+ });
3566
+ if (seen.has(key) || pending.has(key)) return false;
3567
+ pending.add(key);
3568
+ return true;
3569
+ },
3570
+ commitEvent: async ({ roomId, eventId }) => {
3571
+ const key = buildEventKey({
3572
+ roomId,
3573
+ eventId
3574
+ });
3575
+ if (!key) return;
3576
+ pending.delete(key);
3577
+ const ts = nowMs();
3578
+ seen.delete(key);
3579
+ seen.set(key, ts);
3580
+ pruneSeenEvents({
3581
+ seen,
3582
+ ttlMs,
3583
+ maxEntries,
3584
+ nowMs: nowMs()
3585
+ });
3586
+ schedulePersist();
3587
+ },
3588
+ releaseEvent: ({ roomId, eventId }) => {
3589
+ const key = buildEventKey({
3590
+ roomId,
3591
+ eventId
3592
+ });
3593
+ if (!key) return;
3594
+ pending.delete(key);
3595
+ },
3596
+ flush,
3597
+ stop: async () => {
3598
+ try {
3599
+ await flush();
3600
+ } catch (err) {
3601
+ LogService.warn("MatrixInboundDedupe", "Failed to flush Matrix inbound dedupe store during stop():", err);
3602
+ }
3603
+ }
3604
+ };
3605
+ }
3606
+ //#endregion
3607
+ //#region extensions/matrix/src/matrix/monitor/recent-invite.ts
3608
+ function shouldPromoteRecentInviteRoom(params) {
3609
+ if (!params.roomInfo.nameResolved || !params.roomInfo.aliasesResolved) return false;
3610
+ const roomAliases = [params.roomInfo.canonicalAlias ?? "", ...params.roomInfo.altAliases].filter(Boolean);
3611
+ if ((params.roomInfo.name?.trim() ?? "") || roomAliases.length > 0) return false;
3612
+ return resolveMatrixRoomConfig({
3613
+ rooms: params.rooms,
3614
+ roomId: params.roomId,
3615
+ aliases: roomAliases
3616
+ }).matchSource === void 0;
3617
+ }
3618
+ //#endregion
3619
+ //#region extensions/matrix/src/matrix/monitor/room-info.ts
3620
+ const MAX_TRACKED_ROOM_INFO = 1024;
3621
+ const MAX_TRACKED_MEMBER_DISPLAY_NAMES = 4096;
3622
+ function rememberBounded(map, key, value, maxEntries) {
3623
+ map.set(key, value);
3624
+ if (map.size > maxEntries) {
3625
+ const oldest = map.keys().next().value;
3626
+ if (typeof oldest === "string") map.delete(oldest);
3627
+ }
3628
+ }
3629
+ function createMatrixRoomInfoResolver(client) {
3630
+ const roomNameCache = /* @__PURE__ */ new Map();
3631
+ const roomAliasCache = /* @__PURE__ */ new Map();
3632
+ const memberDisplayNameCache = /* @__PURE__ */ new Map();
3633
+ const getRoomName = async (roomId) => {
3634
+ if (roomNameCache.has(roomId)) return roomNameCache.get(roomId) ?? { nameResolved: false };
3635
+ let name;
3636
+ let nameResolved = false;
3637
+ try {
3638
+ const nameState = await client.getRoomStateEvent(roomId, "m.room.name", "");
3639
+ nameResolved = true;
3640
+ if (nameState && typeof nameState.name === "string") name = nameState.name;
3641
+ } catch (err) {
3642
+ if (isMatrixNotFoundError(err)) nameResolved = true;
3643
+ }
3644
+ const info = {
3645
+ name,
3646
+ nameResolved
3647
+ };
3648
+ if (nameResolved) rememberBounded(roomNameCache, roomId, info, MAX_TRACKED_ROOM_INFO);
3649
+ return info;
3650
+ };
3651
+ const getRoomAliases = async (roomId) => {
3652
+ const cached = roomAliasCache.get(roomId);
3653
+ if (cached) return cached;
3654
+ let canonicalAlias;
3655
+ let altAliases = [];
3656
+ let aliasesResolved = false;
3657
+ try {
3658
+ const aliasState = await client.getRoomStateEvent(roomId, "m.room.canonical_alias", "");
3659
+ aliasesResolved = true;
3660
+ if (aliasState && typeof aliasState.alias === "string") canonicalAlias = aliasState.alias;
3661
+ const rawAliases = aliasState?.alt_aliases;
3662
+ if (Array.isArray(rawAliases)) altAliases = rawAliases.filter((entry) => typeof entry === "string");
3663
+ } catch (err) {
3664
+ if (isMatrixNotFoundError(err)) aliasesResolved = true;
3665
+ }
3666
+ const info = {
3667
+ canonicalAlias,
3668
+ altAliases,
3669
+ aliasesResolved
3670
+ };
3671
+ if (aliasesResolved) rememberBounded(roomAliasCache, roomId, info, MAX_TRACKED_ROOM_INFO);
3672
+ return info;
3673
+ };
3674
+ const getRoomInfo = async (roomId, opts = {}) => {
3675
+ const { name, nameResolved } = await getRoomName(roomId);
3676
+ if (!opts.includeAliases) return {
3677
+ name,
3678
+ altAliases: [],
3679
+ nameResolved,
3680
+ aliasesResolved: false
3681
+ };
3682
+ return {
3683
+ name,
3684
+ nameResolved,
3685
+ ...await getRoomAliases(roomId)
3686
+ };
3687
+ };
3688
+ const getMemberDisplayName = async (roomId, userId) => {
3689
+ const cacheKey = `${roomId}:${userId}`;
3690
+ if (memberDisplayNameCache.has(cacheKey)) return memberDisplayNameCache.get(cacheKey) ?? userId;
3691
+ const memberState = await client.getRoomStateEvent(roomId, "m.room.member", userId).catch(() => null);
3692
+ const displayName = memberState && typeof memberState.displayname === "string" ? memberState.displayname : userId;
3693
+ rememberBounded(memberDisplayNameCache, cacheKey, displayName, MAX_TRACKED_MEMBER_DISPLAY_NAMES);
3694
+ return displayName;
3695
+ };
3696
+ return {
3697
+ getRoomInfo,
3698
+ getMemberDisplayName
3699
+ };
3700
+ }
3701
+ //#endregion
3702
+ //#region extensions/matrix/src/matrix/monitor/startup.ts
3703
+ let matrixStartupMaintenanceDepsPromise;
3704
+ async function loadMatrixStartupMaintenanceDeps() {
3705
+ matrixStartupMaintenanceDepsPromise ??= Promise.all([
3706
+ import("./setup-core-BEYoXF3J.js").then((n) => n.s),
3707
+ import("./device-health-Ct2wDSPG.js"),
3708
+ import("./setup-core-BEYoXF3J.js").then((n) => n.a),
3709
+ import("./legacy-crypto-restore-DSFIXuDo.js"),
3710
+ import("./startup-verification-CkD4Cwce.js")
3711
+ ]).then(([configUpdateModule, deviceHealthModule, profileModule, legacyCryptoRestoreModule, startupVerificationModule]) => ({
3712
+ updateMatrixAccountConfig: configUpdateModule.updateMatrixAccountConfig,
3713
+ summarizeMatrixDeviceHealth: deviceHealthModule.summarizeMatrixDeviceHealth,
3714
+ syncMatrixOwnProfile: profileModule.syncMatrixOwnProfile,
3715
+ maybeRestoreLegacyMatrixBackup: legacyCryptoRestoreModule.maybeRestoreLegacyMatrixBackup,
3716
+ ensureMatrixStartupVerification: startupVerificationModule.ensureMatrixStartupVerification
3717
+ }));
3718
+ return await matrixStartupMaintenanceDepsPromise;
3719
+ }
3720
+ async function runMatrixStartupMaintenance(params, deps) {
3721
+ const runtimeDeps = deps ?? await loadMatrixStartupMaintenanceDeps();
3722
+ throwIfMatrixStartupAborted(params.abortSignal);
3723
+ try {
3724
+ const profileSync = await runtimeDeps.syncMatrixOwnProfile({
3725
+ client: params.client,
3726
+ userId: params.auth.userId,
3727
+ displayName: params.accountConfig.name,
3728
+ avatarUrl: params.accountConfig.avatarUrl,
3729
+ loadAvatarFromUrl: async (url, maxBytes) => await params.loadWebMedia(url, maxBytes)
3730
+ });
3731
+ throwIfMatrixStartupAborted(params.abortSignal);
3732
+ if (profileSync.displayNameUpdated) params.logger.info(`matrix: profile display name updated for ${params.auth.userId}`);
3733
+ if (profileSync.avatarUpdated) params.logger.info(`matrix: profile avatar updated for ${params.auth.userId}`);
3734
+ if (profileSync.convertedAvatarFromHttp && profileSync.resolvedAvatarUrl && params.accountConfig.avatarUrl !== profileSync.resolvedAvatarUrl) {
3735
+ const latestCfg = params.getRuntimeConfig();
3736
+ const updatedCfg = runtimeDeps.updateMatrixAccountConfig(latestCfg, params.accountId, { avatarUrl: profileSync.resolvedAvatarUrl });
3737
+ await params.replaceConfigFile(updatedCfg);
3738
+ throwIfMatrixStartupAborted(params.abortSignal);
3739
+ params.logVerboseMessage(`matrix: persisted converted avatar URL for account ${params.accountId} (${profileSync.resolvedAvatarUrl})`);
3740
+ }
3741
+ } catch (err) {
3742
+ if (isMatrixStartupAbortError(err)) throw err;
3743
+ params.logger.warn("matrix: failed to sync profile from config", { error: String(err) });
3744
+ }
3745
+ if (!(params.auth.encryption && params.client.crypto)) return;
3746
+ try {
3747
+ throwIfMatrixStartupAborted(params.abortSignal);
3748
+ const deviceHealth = runtimeDeps.summarizeMatrixDeviceHealth(await params.client.listOwnDevices());
3749
+ if (deviceHealth.staleKlawDevices.length > 0) params.logger.warn(`matrix: stale Klaw devices detected for ${params.auth.userId}: ${deviceHealth.staleKlawDevices.map((device) => device.deviceId).join(", ")}. Run 'klaw matrix devices prune-stale --account ${params.effectiveAccountId}' to keep encrypted-room trust healthy.`);
3750
+ } catch (err) {
3751
+ if (isMatrixStartupAbortError(err)) throw err;
3752
+ params.logger.debug?.("Failed to inspect matrix device hygiene (non-fatal)", { error: String(err) });
3753
+ }
3754
+ try {
3755
+ throwIfMatrixStartupAborted(params.abortSignal);
3756
+ const startupVerification = await runtimeDeps.ensureMatrixStartupVerification({
3757
+ client: params.client,
3758
+ auth: params.auth,
3759
+ accountConfig: params.accountConfig,
3760
+ env: params.env
3761
+ });
3762
+ throwIfMatrixStartupAborted(params.abortSignal);
3763
+ if (startupVerification.kind === "verified") params.logger.info("matrix: device is verified by its owner and ready for encrypted rooms");
3764
+ else if (startupVerification.kind === "disabled" || startupVerification.kind === "cooldown" || startupVerification.kind === "pending" || startupVerification.kind === "request-failed") {
3765
+ params.logger.info("matrix: device not verified — run 'klaw matrix verify device <key>' to enable E2EE");
3766
+ if (startupVerification.kind === "pending") params.logger.info("matrix: startup verification request is already pending; finish it in another Matrix client");
3767
+ else if (startupVerification.kind === "cooldown") params.logVerboseMessage(`matrix: skipped startup verification request due to cooldown (retryAfterMs=${startupVerification.retryAfterMs ?? 0})`);
3768
+ else if (startupVerification.kind === "request-failed") params.logger.debug?.("Matrix startup verification request failed (non-fatal)", { error: startupVerification.error ?? "unknown" });
3769
+ } else if (startupVerification.kind === "requested") params.logger.info("matrix: device not verified — requested verification in another Matrix client");
3770
+ } catch (err) {
3771
+ if (isMatrixStartupAbortError(err)) throw err;
3772
+ params.logger.debug?.("Failed to resolve matrix verification status (non-fatal)", { error: String(err) });
3773
+ }
3774
+ try {
3775
+ throwIfMatrixStartupAborted(params.abortSignal);
3776
+ const legacyCryptoRestore = await runtimeDeps.maybeRestoreLegacyMatrixBackup({
3777
+ client: params.client,
3778
+ auth: params.auth,
3779
+ env: params.env
3780
+ });
3781
+ throwIfMatrixStartupAborted(params.abortSignal);
3782
+ if (legacyCryptoRestore.kind === "restored") {
3783
+ params.logger.info(`matrix: restored ${legacyCryptoRestore.imported}/${legacyCryptoRestore.total} room key(s) from legacy encrypted-state backup`);
3784
+ if (legacyCryptoRestore.localOnlyKeys > 0) params.logger.warn(`matrix: ${legacyCryptoRestore.localOnlyKeys} legacy local-only room key(s) were never backed up and could not be restored automatically`);
3785
+ } else if (legacyCryptoRestore.kind === "failed") {
3786
+ params.logger.warn(`matrix: failed restoring room keys from legacy encrypted-state backup: ${legacyCryptoRestore.error}`);
3787
+ if (legacyCryptoRestore.localOnlyKeys > 0) params.logger.warn(`matrix: ${legacyCryptoRestore.localOnlyKeys} legacy local-only room key(s) were never backed up and may remain unavailable until manually recovered`);
3788
+ }
3789
+ } catch (err) {
3790
+ if (isMatrixStartupAbortError(err)) throw err;
3791
+ params.logger.warn("matrix: failed restoring legacy encrypted-state backup", { error: String(err) });
3792
+ }
3793
+ }
3794
+ //#endregion
3795
+ //#region extensions/matrix/src/matrix/monitor/status.ts
3796
+ function cloneLastDisconnect(value) {
3797
+ if (!value || typeof value === "string") return value ?? null;
3798
+ return { ...value };
3799
+ }
3800
+ function formatSyncError(error) {
3801
+ if (!error) return null;
3802
+ if (error instanceof Error) return error.message || error.name || "unknown";
3803
+ return formatMatrixErrorMessage(error);
3804
+ }
3805
+ function createMatrixMonitorStatusController(params) {
3806
+ const status = {
3807
+ accountId: params.accountId,
3808
+ ...params.baseUrl ? { baseUrl: params.baseUrl } : {},
3809
+ connected: false,
3810
+ lastConnectedAt: null,
3811
+ lastDisconnect: null,
3812
+ lastError: null,
3813
+ healthState: "starting"
3814
+ };
3815
+ const emit = () => {
3816
+ params.statusSink?.({
3817
+ ...status,
3818
+ lastDisconnect: cloneLastDisconnect(status.lastDisconnect)
3819
+ });
3820
+ };
3821
+ const noteConnected = (at = Date.now(), options) => {
3822
+ if (status.connected === true) status.lastEventAt = at;
3823
+ else Object.assign(status, createConnectedChannelStatusPatch(at));
3824
+ if (options?.transportActivity) Object.assign(status, createTransportActivityStatusPatch(at));
3825
+ status.lastError = null;
3826
+ status.lastDisconnect = null;
3827
+ status.healthState = "healthy";
3828
+ emit();
3829
+ };
3830
+ const noteDisconnected = (params) => {
3831
+ const at = params.at ?? Date.now();
3832
+ const error = formatSyncError(params.error);
3833
+ status.connected = false;
3834
+ status.lastEventAt = at;
3835
+ status.lastDisconnect = {
3836
+ at,
3837
+ ...error ? { error } : {}
3838
+ };
3839
+ status.lastError = error;
3840
+ status.healthState = params.state.toLowerCase();
3841
+ emit();
3842
+ };
3843
+ emit();
3844
+ return {
3845
+ noteSyncState(state, error, at = Date.now()) {
3846
+ if (isMatrixReadySyncState(state)) {
3847
+ noteConnected(at, { transportActivity: state === "SYNCING" });
3848
+ return;
3849
+ }
3850
+ if (isMatrixDisconnectedSyncState(state)) {
3851
+ noteDisconnected({
3852
+ state,
3853
+ at,
3854
+ error
3855
+ });
3856
+ return;
3857
+ }
3858
+ status.lastEventAt = at;
3859
+ status.healthState = state.toLowerCase();
3860
+ emit();
3861
+ },
3862
+ noteUnexpectedError(error, at = Date.now()) {
3863
+ noteDisconnected({
3864
+ state: "ERROR",
3865
+ at,
3866
+ error
3867
+ });
3868
+ },
3869
+ markStopped(at = Date.now()) {
3870
+ status.connected = false;
3871
+ status.lastEventAt = at;
3872
+ if (status.healthState !== "error") status.healthState = "stopped";
3873
+ emit();
3874
+ }
3875
+ };
3876
+ }
3877
+ //#endregion
3878
+ //#region extensions/matrix/src/matrix/monitor/sync-lifecycle.ts
3879
+ function formatSyncLifecycleError(state, error) {
3880
+ if (error instanceof Error) return error;
3881
+ const message = typeof error === "string" && error.trim() ? error.trim() : void 0;
3882
+ if (state === "STOPPED") return new Error(message ?? "Matrix sync stopped unexpectedly");
3883
+ if (state === "ERROR") return new Error(message ?? "Matrix sync entered ERROR unexpectedly");
3884
+ return new Error(message ?? `Matrix sync entered ${state} unexpectedly`);
3885
+ }
3886
+ function createMatrixMonitorSyncLifecycle(params) {
3887
+ let fatalError = null;
3888
+ let resolveFatalWait = null;
3889
+ let rejectFatalWait = null;
3890
+ const settleFatal = (error) => {
3891
+ if (fatalError) return;
3892
+ fatalError = error;
3893
+ rejectFatalWait?.(error);
3894
+ resolveFatalWait = null;
3895
+ rejectFatalWait = null;
3896
+ };
3897
+ const onSyncState = (state, _prevState, error) => {
3898
+ if (isMatrixTerminalSyncState(state) && !params.isStopping?.()) {
3899
+ const fatalError = formatSyncLifecycleError(state, error);
3900
+ params.statusController.noteUnexpectedError(fatalError);
3901
+ settleFatal(fatalError);
3902
+ return;
3903
+ }
3904
+ if (fatalError) return;
3905
+ if (params.isStopping?.() && !isMatrixTerminalSyncState(state)) return;
3906
+ params.statusController.noteSyncState(state, error);
3907
+ };
3908
+ const onUnexpectedError = (error) => {
3909
+ if (params.isStopping?.()) return;
3910
+ params.statusController.noteUnexpectedError(error);
3911
+ settleFatal(error);
3912
+ };
3913
+ params.client.on("sync.state", onSyncState);
3914
+ params.client.on("sync.unexpected_error", onUnexpectedError);
3915
+ return {
3916
+ async waitForFatalStop() {
3917
+ if (fatalError) throw fatalError;
3918
+ if (resolveFatalWait || rejectFatalWait) throw new Error("Matrix fatal-stop wait already in progress");
3919
+ await new Promise((resolve, reject) => {
3920
+ resolveFatalWait = resolve;
3921
+ rejectFatalWait = (error) => reject(error);
3922
+ });
3923
+ },
3924
+ dispose() {
3925
+ resolveFatalWait?.();
3926
+ resolveFatalWait = null;
3927
+ rejectFatalWait = null;
3928
+ params.client.off("sync.state", onSyncState);
3929
+ params.client.off("sync.unexpected_error", onUnexpectedError);
3930
+ }
3931
+ };
3932
+ }
3933
+ //#endregion
3934
+ //#region extensions/matrix/src/matrix/monitor/task-runner.ts
3935
+ function createMatrixMonitorTaskRunner(params) {
3936
+ const inFlight = /* @__PURE__ */ new Set();
3937
+ const runDetachedTask = (label, task) => {
3938
+ let trackedTask;
3939
+ trackedTask = Promise.resolve().then(task).catch((error) => {
3940
+ const message = String(error);
3941
+ params.logVerboseMessage(`matrix: ${label} failed (${message})`);
3942
+ params.logger.warn("matrix background task failed", {
3943
+ task: label,
3944
+ error: message
3945
+ });
3946
+ }).finally(() => {
3947
+ inFlight.delete(trackedTask);
3948
+ });
3949
+ inFlight.add(trackedTask);
3950
+ return trackedTask;
3951
+ };
3952
+ const waitForIdle = async () => {
3953
+ while (inFlight.size > 0) await Promise.allSettled(Array.from(inFlight));
3954
+ };
3955
+ return {
3956
+ runDetachedTask,
3957
+ waitForIdle
3958
+ };
3959
+ }
3960
+ //#endregion
3961
+ //#region extensions/matrix/src/matrix/monitor/index.ts
3962
+ function isMatrixStreamingConfig(streaming) {
3963
+ return Boolean(streaming && typeof streaming === "object" && !Array.isArray(streaming));
3964
+ }
3965
+ function resolveMatrixStreamingMode(streaming) {
3966
+ if (streaming === true || streaming === "partial") return "partial";
3967
+ if (streaming === "quiet") return "quiet";
3968
+ if (streaming === "progress") return "progress";
3969
+ if (isMatrixStreamingConfig(streaming)) {
3970
+ if (streaming.mode === "partial" || streaming.mode === "quiet" || streaming.mode === "progress") return streaming.mode;
3971
+ }
3972
+ return "off";
3973
+ }
3974
+ function resolveMatrixPreviewToolProgress(streaming) {
3975
+ if (!isMatrixStreamingConfig(streaming)) return true;
3976
+ if (resolveMatrixStreamingMode(streaming) === "progress") return streaming.progress?.toolProgress ?? streaming.preview?.toolProgress ?? true;
3977
+ return streaming.preview?.toolProgress ?? true;
3978
+ }
3979
+ function resolveMatrixPreviewToolProgressEnabled(streaming) {
3980
+ return resolveMatrixStreamingMode(streaming) !== "off" && resolveMatrixPreviewToolProgress(streaming);
3981
+ }
3982
+ const DEFAULT_MEDIA_MAX_MB = 20;
3983
+ async function monitorMatrixProvider(opts = {}) {
3984
+ if (opts.abortSignal?.aborted) return;
3985
+ if (isBunRuntime()) throw new Error("Matrix provider requires Node (bun runtime not supported)");
3986
+ const core = getMatrixRuntime();
3987
+ let cfg = core.config.current();
3988
+ if (cfg.channels?.["matrix"]?.enabled === false) return;
3989
+ const logger = core.logging.getChildLogger({ module: "matrix-auto-reply" });
3990
+ const formatRuntimeMessage = (...args) => format(...args);
3991
+ const runtime = opts.runtime ?? {
3992
+ log: (...args) => {
3993
+ logger.info(formatRuntimeMessage(...args));
3994
+ },
3995
+ error: (...args) => {
3996
+ logger.error(formatRuntimeMessage(...args));
3997
+ },
3998
+ exit: (code) => {
3999
+ throw new Error(`exit ${code}`);
4000
+ }
4001
+ };
4002
+ const logVerboseMessage = (message) => {
4003
+ if (!core.logging.shouldLogVerbose()) return;
4004
+ logger.debug?.(message);
4005
+ };
4006
+ const effectiveAccountId = resolveMatrixAuthContext({
4007
+ cfg,
4008
+ accountId: opts.accountId
4009
+ }).accountId;
4010
+ const accountConfig = resolveMatrixAccountConfig({
4011
+ cfg,
4012
+ accountId: effectiveAccountId
4013
+ });
4014
+ const allowlistOnly = accountConfig.allowlistOnly === true;
4015
+ const accountAllowBots = accountConfig.allowBots;
4016
+ let allowFrom = (accountConfig.dm?.allowFrom ?? []).map(String);
4017
+ let groupAllowFrom = (accountConfig.groupAllowFrom ?? []).map(String);
4018
+ let allowFromResolvedEntries = [];
4019
+ let groupAllowFromResolvedEntries = [];
4020
+ let roomsConfig = accountConfig.groups ?? accountConfig.rooms;
4021
+ let needsRoomAliasesForConfig = false;
4022
+ const configuredBotUserIds = resolveConfiguredMatrixBotUserIds({
4023
+ cfg,
4024
+ accountId: effectiveAccountId
4025
+ });
4026
+ ({allowFrom, allowFromResolvedEntries, groupAllowFrom, groupAllowFromResolvedEntries, roomsConfig} = await resolveMatrixMonitorConfig({
4027
+ cfg,
4028
+ accountId: effectiveAccountId,
4029
+ allowFrom,
4030
+ groupAllowFrom,
4031
+ roomsConfig,
4032
+ runtime
4033
+ }));
4034
+ needsRoomAliasesForConfig = Boolean(roomsConfig && Object.keys(roomsConfig).some((key) => key.trim().startsWith("#")));
4035
+ cfg = {
4036
+ ...cfg,
4037
+ channels: {
4038
+ ...cfg.channels,
4039
+ matrix: {
4040
+ ...cfg.channels?.["matrix"],
4041
+ dm: {
4042
+ ...cfg.channels?.["matrix"]?.dm,
4043
+ allowFrom
4044
+ },
4045
+ groupAllowFrom,
4046
+ ...roomsConfig ? { groups: roomsConfig } : {}
4047
+ }
4048
+ }
4049
+ };
4050
+ const auth = await resolveMatrixAuth({
4051
+ cfg,
4052
+ accountId: effectiveAccountId
4053
+ });
4054
+ const resolvedInitialSyncLimit = typeof opts.initialSyncLimit === "number" ? Math.max(0, Math.floor(opts.initialSyncLimit)) : auth.initialSyncLimit;
4055
+ const authWithLimit = resolvedInitialSyncLimit === auth.initialSyncLimit ? auth : {
4056
+ ...auth,
4057
+ initialSyncLimit: resolvedInitialSyncLimit
4058
+ };
4059
+ const statusController = createMatrixMonitorStatusController({
4060
+ accountId: auth.accountId,
4061
+ baseUrl: auth.homeserver,
4062
+ statusSink: opts.setStatus
4063
+ });
4064
+ let cleanedUp = false;
4065
+ let client = null;
4066
+ let threadBindingManager = null;
4067
+ let inboundDeduper = null;
4068
+ const monitorTaskRunner = createMatrixMonitorTaskRunner({
4069
+ logger,
4070
+ logVerboseMessage
4071
+ });
4072
+ let syncLifecycle = null;
4073
+ const cleanup = async (mode = "persist") => {
4074
+ if (cleanedUp) return;
4075
+ cleanedUp = true;
4076
+ try {
4077
+ client?.stopSyncWithoutPersist();
4078
+ if (client && mode === "persist") await client.drainPendingDecryptions("matrix monitor shutdown");
4079
+ if (mode === "persist") await monitorTaskRunner.waitForIdle();
4080
+ threadBindingManager?.stop();
4081
+ await inboundDeduper?.stop();
4082
+ if (client) await releaseSharedClientInstance(client, mode);
4083
+ } finally {
4084
+ client?.off("sync.state", onSyncState);
4085
+ syncLifecycle?.dispose();
4086
+ statusController.markStopped();
4087
+ setActiveMatrixClient(null, auth.accountId);
4088
+ }
4089
+ };
4090
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
4091
+ const { groupPolicy: groupPolicyRaw, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
4092
+ providerConfigPresent: cfg.channels?.["matrix"] !== void 0,
4093
+ groupPolicy: accountConfig.groupPolicy,
4094
+ defaultGroupPolicy
4095
+ });
4096
+ warnMissingProviderGroupPolicyFallbackOnce({
4097
+ providerMissingFallbackApplied,
4098
+ providerKey: "matrix",
4099
+ accountId: effectiveAccountId,
4100
+ blockedLabel: GROUP_POLICY_BLOCKED_LABEL.room,
4101
+ log: (message) => logVerboseMessage(message)
4102
+ });
4103
+ const groupPolicy = allowlistOnly && groupPolicyRaw === "open" ? "allowlist" : groupPolicyRaw;
4104
+ const replyToMode = opts.replyToMode ?? accountConfig.replyToMode ?? "off";
4105
+ const threadReplies = accountConfig.threadReplies ?? "inbound";
4106
+ const dmThreadReplies = accountConfig.dm?.threadReplies;
4107
+ const threadBindingIdleTimeoutMs = resolveThreadBindingIdleTimeoutMsForChannel({
4108
+ cfg,
4109
+ channel: "matrix",
4110
+ accountId: effectiveAccountId
4111
+ });
4112
+ const threadBindingMaxAgeMs = resolveThreadBindingMaxAgeMsForChannel({
4113
+ cfg,
4114
+ channel: "matrix",
4115
+ accountId: effectiveAccountId
4116
+ });
4117
+ const dmConfig = accountConfig.dm;
4118
+ const dmEnabled = dmConfig?.enabled ?? true;
4119
+ const dmPolicyRaw = dmConfig?.policy ?? "pairing";
4120
+ const dmPolicy = allowlistOnly && dmPolicyRaw !== "disabled" ? "allowlist" : dmPolicyRaw;
4121
+ const dmSessionScope = dmConfig?.sessionScope ?? "per-user";
4122
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "matrix", effectiveAccountId);
4123
+ const globalGroupChatHistoryLimit = cfg.messages?.groupChat?.historyLimit;
4124
+ const historyLimit = Math.max(0, accountConfig.historyLimit ?? globalGroupChatHistoryLimit ?? 0);
4125
+ const mediaMaxMb = opts.mediaMaxMb ?? accountConfig.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB;
4126
+ const mediaMaxBytes = Math.max(1, mediaMaxMb) * 1024 * 1024;
4127
+ const streaming = resolveMatrixStreamingMode(accountConfig.streaming);
4128
+ const previewToolProgressEnabled = resolveMatrixPreviewToolProgressEnabled(accountConfig.streaming);
4129
+ const blockStreamingEnabled = accountConfig.blockStreaming === true;
4130
+ const startupMs = Date.now();
4131
+ const startupGraceMs = 0;
4132
+ const warnedEncryptedRooms = /* @__PURE__ */ new Set();
4133
+ const warnedCryptoMissingRooms = /* @__PURE__ */ new Set();
4134
+ let healthySyncSinceMs;
4135
+ const noteSyncHealthState = (state, at = Date.now()) => {
4136
+ if (isMatrixReadySyncState(state)) {
4137
+ healthySyncSinceMs ??= at;
4138
+ return;
4139
+ }
4140
+ if (isMatrixDisconnectedSyncState(state)) healthySyncSinceMs = void 0;
4141
+ };
4142
+ const onSyncState = (state) => {
4143
+ noteSyncHealthState(state);
4144
+ };
4145
+ try {
4146
+ client = await resolveSharedMatrixClient({
4147
+ cfg,
4148
+ auth: authWithLimit,
4149
+ startClient: false,
4150
+ accountId: auth.accountId
4151
+ });
4152
+ setActiveMatrixClient(client, auth.accountId);
4153
+ inboundDeduper = await createMatrixInboundEventDeduper({
4154
+ auth,
4155
+ env: process.env
4156
+ });
4157
+ syncLifecycle = createMatrixMonitorSyncLifecycle({
4158
+ client,
4159
+ statusController,
4160
+ isStopping: () => cleanedUp || opts.abortSignal?.aborted === true
4161
+ });
4162
+ client.on("sync.state", onSyncState);
4163
+ const dropPreStartupMessages = !client.hasPersistedSyncState();
4164
+ const { getRoomInfo, getMemberDisplayName } = createMatrixRoomInfoResolver(client);
4165
+ const directTracker = createDirectRoomTracker(client, {
4166
+ log: logVerboseMessage,
4167
+ canPromoteRecentInvite: async (roomId) => shouldPromoteRecentInviteRoom({
4168
+ roomId,
4169
+ roomInfo: await getRoomInfo(roomId, { includeAliases: true }),
4170
+ rooms: roomsConfig
4171
+ }),
4172
+ ...dmSessionScope === "per-room" ? { canPromoteUnmappedStrictRoom: async (roomId) => shouldPromoteRecentInviteRoom({
4173
+ roomId,
4174
+ roomInfo: await getRoomInfo(roomId, { includeAliases: true }),
4175
+ rooms: roomsConfig
4176
+ }) } : {},
4177
+ shouldKeepLocallyPromotedDirectRoom: async (roomId) => {
4178
+ try {
4179
+ const roomInfo = await getRoomInfo(roomId, { includeAliases: true });
4180
+ if (!roomInfo.nameResolved || !roomInfo.aliasesResolved) return;
4181
+ return shouldPromoteRecentInviteRoom({
4182
+ roomId,
4183
+ roomInfo,
4184
+ rooms: roomsConfig
4185
+ });
4186
+ } catch (err) {
4187
+ logVerboseMessage(`matrix: local promotion revalidation failed room=${roomId} (${String(err)})`);
4188
+ return;
4189
+ }
4190
+ }
4191
+ });
4192
+ registerMatrixAutoJoin({
4193
+ client,
4194
+ accountConfig,
4195
+ runtime
4196
+ });
4197
+ const handleRoomMessage = createMatrixRoomMessageHandler({
4198
+ client,
4199
+ core,
4200
+ cfg,
4201
+ accountId: effectiveAccountId,
4202
+ accountConfig,
4203
+ runtime,
4204
+ logger,
4205
+ logVerboseMessage,
4206
+ allowFrom,
4207
+ allowFromResolvedEntries,
4208
+ groupAllowFrom,
4209
+ groupAllowFromResolvedEntries,
4210
+ roomsConfig,
4211
+ accountAllowBots,
4212
+ configuredBotUserIds,
4213
+ groupPolicy,
4214
+ replyToMode,
4215
+ threadReplies,
4216
+ dmThreadReplies,
4217
+ dmSessionScope,
4218
+ streaming,
4219
+ previewToolProgressEnabled,
4220
+ blockStreamingEnabled,
4221
+ dmEnabled,
4222
+ dmPolicy,
4223
+ textLimit,
4224
+ mediaMaxBytes,
4225
+ historyLimit,
4226
+ startupMs,
4227
+ startupGraceMs,
4228
+ dropPreStartupMessages,
4229
+ inboundDeduper,
4230
+ directTracker,
4231
+ getRoomInfo,
4232
+ getMemberDisplayName,
4233
+ needsRoomAliasesForConfig
4234
+ });
4235
+ threadBindingManager = await createMatrixThreadBindingManager({
4236
+ cfg,
4237
+ accountId: effectiveAccountId,
4238
+ auth,
4239
+ client,
4240
+ env: process.env,
4241
+ idleTimeoutMs: threadBindingIdleTimeoutMs,
4242
+ maxAgeMs: threadBindingMaxAgeMs,
4243
+ logVerboseMessage
4244
+ });
4245
+ logVerboseMessage(`matrix: thread bindings ready account=${threadBindingManager.accountId} idleMs=${threadBindingIdleTimeoutMs} maxAgeMs=${threadBindingMaxAgeMs}`);
4246
+ registerMatrixMonitorEvents({
4247
+ cfg,
4248
+ client,
4249
+ auth,
4250
+ allowFrom,
4251
+ dmEnabled,
4252
+ dmPolicy,
4253
+ readStoreAllowFrom: async () => await core.channel.pairing.readAllowFromStore({
4254
+ channel: "matrix",
4255
+ env: process.env,
4256
+ accountId: effectiveAccountId
4257
+ }).catch(() => []),
4258
+ directTracker,
4259
+ logVerboseMessage,
4260
+ warnedEncryptedRooms,
4261
+ warnedCryptoMissingRooms,
4262
+ logger,
4263
+ startupGraceMs,
4264
+ getHealthySyncSinceMs: () => healthySyncSinceMs,
4265
+ formatNativeDependencyHint: core.system.formatNativeDependencyHint,
4266
+ onRoomMessage: handleRoomMessage,
4267
+ runDetachedTask: monitorTaskRunner.runDetachedTask
4268
+ });
4269
+ logVerboseMessage("matrix: starting client");
4270
+ await resolveSharedMatrixClient({
4271
+ cfg,
4272
+ auth: authWithLimit,
4273
+ accountId: auth.accountId,
4274
+ abortSignal: opts.abortSignal
4275
+ });
4276
+ logVerboseMessage("matrix: client started");
4277
+ logger.info(`matrix: logged in as ${auth.userId}`);
4278
+ backfillMatrixAuthDeviceIdAfterStartup({
4279
+ auth,
4280
+ env: process.env,
4281
+ abortSignal: opts.abortSignal
4282
+ }).catch((err) => {
4283
+ logVerboseMessage(`matrix: failed to backfill deviceId after startup (${String(err)})`);
4284
+ });
4285
+ registerChannelRuntimeContext({
4286
+ channelRuntime: opts.channelRuntime,
4287
+ channelId: "matrix",
4288
+ accountId: effectiveAccountId,
4289
+ capability: CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY,
4290
+ context: { client },
4291
+ abortSignal: opts.abortSignal
4292
+ });
4293
+ await runMatrixStartupMaintenance({
4294
+ client,
4295
+ auth,
4296
+ accountId: effectiveAccountId,
4297
+ effectiveAccountId,
4298
+ accountConfig,
4299
+ logger,
4300
+ logVerboseMessage,
4301
+ getRuntimeConfig: () => core.config.current(),
4302
+ replaceConfigFile: async (nextCfg) => {
4303
+ await core.config.replaceConfigFile({
4304
+ nextConfig: nextCfg,
4305
+ afterWrite: { mode: "auto" }
4306
+ });
4307
+ },
4308
+ loadWebMedia: async (url, maxBytes) => await core.media.loadWebMedia(url, maxBytes),
4309
+ env: process.env,
4310
+ abortSignal: opts.abortSignal
4311
+ });
4312
+ await Promise.race([waitUntilAbort(opts.abortSignal, async () => {
4313
+ try {
4314
+ logVerboseMessage("matrix: stopping client");
4315
+ await cleanup();
4316
+ } catch (err) {
4317
+ logger.warn("matrix: failed during monitor shutdown cleanup", { error: String(err) });
4318
+ }
4319
+ }), syncLifecycle.waitForFatalStop()]);
4320
+ } catch (err) {
4321
+ if (opts.abortSignal?.aborted === true && isMatrixStartupAbortError(err)) {
4322
+ await cleanup("stop");
4323
+ return;
4324
+ }
4325
+ statusController.noteUnexpectedError(err);
4326
+ await cleanup();
4327
+ throw err;
4328
+ }
4329
+ }
4330
+ //#endregion
4331
+ export { monitorMatrixProvider };