@openclaw/matrix 2026.3.13 → 2026.5.10-beta.1

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