@gakr-gakr/matrix 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/CHANGELOG.md +285 -0
  2. package/SPEC-SUPPORT.md +116 -0
  3. package/api.ts +38 -0
  4. package/auth-presence.ts +56 -0
  5. package/autobot.plugin.json +28 -0
  6. package/channel-plugin-api.ts +3 -0
  7. package/cli-metadata.ts +11 -0
  8. package/contract-api.ts +17 -0
  9. package/doctor-contract-api.ts +1 -0
  10. package/helper-api.ts +3 -0
  11. package/index.ts +55 -0
  12. package/package.json +101 -0
  13. package/plugin-entry.handlers.runtime.ts +1 -0
  14. package/runtime-api.ts +72 -0
  15. package/runtime-heavy-api.ts +1 -0
  16. package/runtime-setter-api.ts +3 -0
  17. package/secret-contract-api.ts +5 -0
  18. package/setup-entry.ts +17 -0
  19. package/setup-plugin-api.ts +3 -0
  20. package/src/account-selection.ts +223 -0
  21. package/src/actions.ts +346 -0
  22. package/src/approval-auth.ts +25 -0
  23. package/src/approval-handler.runtime.ts +595 -0
  24. package/src/approval-ids.ts +6 -0
  25. package/src/approval-native.ts +348 -0
  26. package/src/approval-reaction-auth.ts +45 -0
  27. package/src/approval-reactions.ts +313 -0
  28. package/src/auth-precedence.ts +61 -0
  29. package/src/channel-account-paths.ts +97 -0
  30. package/src/channel.runtime.ts +17 -0
  31. package/src/channel.setup.ts +48 -0
  32. package/src/channel.ts +667 -0
  33. package/src/cli-metadata.ts +19 -0
  34. package/src/cli.ts +2298 -0
  35. package/src/config-adapter.ts +41 -0
  36. package/src/config-schema.ts +159 -0
  37. package/src/config-ui-hints.ts +56 -0
  38. package/src/directory-live.ts +238 -0
  39. package/src/doctor-contract.ts +287 -0
  40. package/src/doctor.ts +262 -0
  41. package/src/env-vars.ts +92 -0
  42. package/src/exec-approval-resolver.ts +23 -0
  43. package/src/exec-approvals.ts +293 -0
  44. package/src/group-mentions.ts +41 -0
  45. package/src/legacy-crypto-inspector-availability.ts +60 -0
  46. package/src/legacy-crypto.ts +531 -0
  47. package/src/legacy-state.ts +156 -0
  48. package/src/matrix/account-config.ts +175 -0
  49. package/src/matrix/accounts.ts +194 -0
  50. package/src/matrix/actions/client.ts +31 -0
  51. package/src/matrix/actions/devices.ts +34 -0
  52. package/src/matrix/actions/limits.ts +6 -0
  53. package/src/matrix/actions/messages.ts +129 -0
  54. package/src/matrix/actions/pins.ts +63 -0
  55. package/src/matrix/actions/polls.ts +109 -0
  56. package/src/matrix/actions/profile.ts +37 -0
  57. package/src/matrix/actions/reactions.ts +59 -0
  58. package/src/matrix/actions/room.ts +71 -0
  59. package/src/matrix/actions/summary.ts +88 -0
  60. package/src/matrix/actions/types.ts +63 -0
  61. package/src/matrix/actions/verification.ts +589 -0
  62. package/src/matrix/actions.ts +37 -0
  63. package/src/matrix/active-client.ts +26 -0
  64. package/src/matrix/async-lock.ts +18 -0
  65. package/src/matrix/backup-health.ts +124 -0
  66. package/src/matrix/client/config-runtime-api.ts +9 -0
  67. package/src/matrix/client/config-secret-input.runtime.ts +1 -0
  68. package/src/matrix/client/config.ts +853 -0
  69. package/src/matrix/client/create-client.ts +105 -0
  70. package/src/matrix/client/env-auth.ts +95 -0
  71. package/src/matrix/client/file-sync-store.ts +289 -0
  72. package/src/matrix/client/logging.ts +140 -0
  73. package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
  74. package/src/matrix/client/private-network-host.ts +1 -0
  75. package/src/matrix/client/runtime.ts +4 -0
  76. package/src/matrix/client/shared.ts +316 -0
  77. package/src/matrix/client/storage.ts +543 -0
  78. package/src/matrix/client/types.ts +50 -0
  79. package/src/matrix/client/url-validation.ts +76 -0
  80. package/src/matrix/client-bootstrap.ts +173 -0
  81. package/src/matrix/client.ts +23 -0
  82. package/src/matrix/config-paths.ts +31 -0
  83. package/src/matrix/config-update.ts +292 -0
  84. package/src/matrix/credentials-read.ts +207 -0
  85. package/src/matrix/credentials-write.runtime.ts +35 -0
  86. package/src/matrix/credentials.ts +95 -0
  87. package/src/matrix/deps.ts +309 -0
  88. package/src/matrix/device-health.ts +31 -0
  89. package/src/matrix/direct-management.ts +349 -0
  90. package/src/matrix/direct-room.ts +128 -0
  91. package/src/matrix/draft-stream.ts +225 -0
  92. package/src/matrix/encryption-guidance.ts +24 -0
  93. package/src/matrix/errors.ts +21 -0
  94. package/src/matrix/format.ts +426 -0
  95. package/src/matrix/legacy-crypto-inspector.ts +95 -0
  96. package/src/matrix/media-errors.ts +20 -0
  97. package/src/matrix/media-text.ts +162 -0
  98. package/src/matrix/monitor/access-state.ts +145 -0
  99. package/src/matrix/monitor/ack-config.ts +27 -0
  100. package/src/matrix/monitor/allowlist.ts +92 -0
  101. package/src/matrix/monitor/auto-join.ts +86 -0
  102. package/src/matrix/monitor/config.ts +569 -0
  103. package/src/matrix/monitor/context-summary.ts +43 -0
  104. package/src/matrix/monitor/direct.ts +296 -0
  105. package/src/matrix/monitor/events.ts +397 -0
  106. package/src/matrix/monitor/handler.ts +2271 -0
  107. package/src/matrix/monitor/inbound-dedupe.ts +267 -0
  108. package/src/matrix/monitor/index.ts +540 -0
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
  110. package/src/matrix/monitor/location.ts +108 -0
  111. package/src/matrix/monitor/media.ts +119 -0
  112. package/src/matrix/monitor/mentions.ts +256 -0
  113. package/src/matrix/monitor/reaction-events.ts +197 -0
  114. package/src/matrix/monitor/recent-invite.ts +30 -0
  115. package/src/matrix/monitor/replies.ts +136 -0
  116. package/src/matrix/monitor/reply-context.ts +92 -0
  117. package/src/matrix/monitor/room-history.ts +301 -0
  118. package/src/matrix/monitor/room-info.ts +126 -0
  119. package/src/matrix/monitor/rooms.ts +52 -0
  120. package/src/matrix/monitor/route.ts +179 -0
  121. package/src/matrix/monitor/runtime-api.ts +28 -0
  122. package/src/matrix/monitor/startup-verification.ts +237 -0
  123. package/src/matrix/monitor/startup.ts +218 -0
  124. package/src/matrix/monitor/status.ts +120 -0
  125. package/src/matrix/monitor/sync-lifecycle.ts +91 -0
  126. package/src/matrix/monitor/task-runner.ts +38 -0
  127. package/src/matrix/monitor/test-events.ts +21 -0
  128. package/src/matrix/monitor/thread-context.ts +108 -0
  129. package/src/matrix/monitor/threads.ts +85 -0
  130. package/src/matrix/monitor/types.ts +30 -0
  131. package/src/matrix/monitor/verification-events.ts +643 -0
  132. package/src/matrix/monitor/verification-utils.ts +46 -0
  133. package/src/matrix/outbound-media-runtime.ts +1 -0
  134. package/src/matrix/poll-summary.ts +110 -0
  135. package/src/matrix/poll-types.ts +429 -0
  136. package/src/matrix/probe.runtime.ts +4 -0
  137. package/src/matrix/probe.ts +97 -0
  138. package/src/matrix/profile.ts +184 -0
  139. package/src/matrix/reaction-common.ts +147 -0
  140. package/src/matrix/sdk/crypto-bootstrap.ts +438 -0
  141. package/src/matrix/sdk/crypto-facade.ts +242 -0
  142. package/src/matrix/sdk/crypto-node.runtime.ts +17 -0
  143. package/src/matrix/sdk/crypto-runtime.ts +14 -0
  144. package/src/matrix/sdk/decrypt-bridge.ts +410 -0
  145. package/src/matrix/sdk/event-helpers.ts +83 -0
  146. package/src/matrix/sdk/http-client.ts +87 -0
  147. package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
  148. package/src/matrix/sdk/idb-persistence.ts +286 -0
  149. package/src/matrix/sdk/logger.ts +108 -0
  150. package/src/matrix/sdk/read-response-with-limit.ts +19 -0
  151. package/src/matrix/sdk/recovery-key-store.ts +453 -0
  152. package/src/matrix/sdk/timeout-abort-signal.ts +1 -0
  153. package/src/matrix/sdk/transport-runtime-api.ts +18 -0
  154. package/src/matrix/sdk/transport.ts +352 -0
  155. package/src/matrix/sdk/types.ts +245 -0
  156. package/src/matrix/sdk/verification-manager.ts +795 -0
  157. package/src/matrix/sdk/verification-status.ts +23 -0
  158. package/src/matrix/sdk.ts +2152 -0
  159. package/src/matrix/send/client.ts +93 -0
  160. package/src/matrix/send/formatting.ts +189 -0
  161. package/src/matrix/send/media.ts +244 -0
  162. package/src/matrix/send/targets.ts +104 -0
  163. package/src/matrix/send/types.ts +131 -0
  164. package/src/matrix/send.ts +660 -0
  165. package/src/matrix/session-store-metadata.ts +108 -0
  166. package/src/matrix/startup-abort.ts +44 -0
  167. package/src/matrix/subagent-hooks.ts +308 -0
  168. package/src/matrix/sync-state.ts +27 -0
  169. package/src/matrix/target-ids.ts +79 -0
  170. package/src/matrix/thread-bindings-shared.ts +206 -0
  171. package/src/matrix/thread-bindings.ts +580 -0
  172. package/src/matrix-migration.runtime.ts +9 -0
  173. package/src/migration-config.ts +243 -0
  174. package/src/migration-snapshot-backup.ts +116 -0
  175. package/src/migration-snapshot.ts +53 -0
  176. package/src/onboarding.ts +775 -0
  177. package/src/outbound.ts +248 -0
  178. package/src/plugin-entry.runtime.js +115 -0
  179. package/src/plugin-entry.runtime.ts +70 -0
  180. package/src/profile-update.ts +71 -0
  181. package/src/record-shared.ts +3 -0
  182. package/src/resolve-targets.ts +175 -0
  183. package/src/resolver.runtime.ts +5 -0
  184. package/src/resolver.ts +21 -0
  185. package/src/runtime-api.ts +106 -0
  186. package/src/runtime.ts +13 -0
  187. package/src/secret-contract.ts +174 -0
  188. package/src/session-route.ts +126 -0
  189. package/src/setup-bootstrap.ts +102 -0
  190. package/src/setup-config.ts +222 -0
  191. package/src/setup-contract.ts +90 -0
  192. package/src/setup-core.ts +146 -0
  193. package/src/setup-dm-policy.ts +15 -0
  194. package/src/setup-surface.ts +4 -0
  195. package/src/startup-maintenance.ts +114 -0
  196. package/src/storage-paths.ts +92 -0
  197. package/src/thread-binding-api.ts +23 -0
  198. package/src/tool-actions.runtime.ts +1 -0
  199. package/src/tool-actions.ts +498 -0
  200. package/src/types.ts +257 -0
  201. package/subagent-hooks-api.ts +31 -0
  202. package/test-api.ts +21 -0
  203. package/thread-binding-api.ts +4 -0
  204. package/thread-bindings-runtime.ts +4 -0
  205. package/tsconfig.json +16 -0
@@ -0,0 +1,540 @@
1
+ import { format } from "node:util";
2
+ import { CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "autobot/plugin-sdk/approval-handler-adapter-runtime";
3
+ import type { ChannelRuntimeSurface } from "autobot/plugin-sdk/channel-contract";
4
+ import { waitUntilAbort } from "autobot/plugin-sdk/channel-lifecycle";
5
+ import { registerChannelRuntimeContext } from "autobot/plugin-sdk/channel-runtime-context";
6
+ import {
7
+ GROUP_POLICY_BLOCKED_LABEL,
8
+ resolveThreadBindingIdleTimeoutMsForChannel,
9
+ resolveThreadBindingMaxAgeMsForChannel,
10
+ resolveAllowlistProviderRuntimeGroupPolicy,
11
+ resolveDefaultGroupPolicy,
12
+ warnMissingProviderGroupPolicyFallbackOnce,
13
+ type RuntimeEnv,
14
+ } from "../../runtime-api.js";
15
+ import { getMatrixRuntime } from "../../runtime.js";
16
+ import type {
17
+ CoreConfig,
18
+ MatrixConfig,
19
+ MatrixStreamingConfig,
20
+ MatrixStreamingMode,
21
+ ReplyToMode,
22
+ } from "../../types.js";
23
+ import { resolveMatrixAccountConfig } from "../account-config.js";
24
+ import { resolveConfiguredMatrixBotUserIds } from "../accounts.js";
25
+ import { setActiveMatrixClient } from "../active-client.js";
26
+ import {
27
+ backfillMatrixAuthDeviceIdAfterStartup,
28
+ isBunRuntime,
29
+ resolveMatrixAuth,
30
+ resolveMatrixAuthContext,
31
+ resolveSharedMatrixClient,
32
+ } from "../client.js";
33
+ import { releaseSharedClientInstance } from "../client/shared.js";
34
+ import type { MatrixClient } from "../sdk.js";
35
+ import { isMatrixStartupAbortError } from "../startup-abort.js";
36
+ import {
37
+ isMatrixDisconnectedSyncState,
38
+ isMatrixReadySyncState,
39
+ type MatrixSyncState,
40
+ } from "../sync-state.js";
41
+ import { createMatrixThreadBindingManager } from "../thread-bindings.js";
42
+ import { registerMatrixAutoJoin } from "./auto-join.js";
43
+ import { resolveMatrixMonitorConfig, type MatrixResolvedAllowlistEntry } from "./config.js";
44
+ import { createDirectRoomTracker } from "./direct.js";
45
+ import { registerMatrixMonitorEvents } from "./events.js";
46
+ import { createMatrixRoomMessageHandler } from "./handler.js";
47
+ import {
48
+ createMatrixInboundEventDeduper,
49
+ type MatrixInboundEventDeduper,
50
+ } from "./inbound-dedupe.js";
51
+ import { shouldPromoteRecentInviteRoom } from "./recent-invite.js";
52
+ import { createMatrixRoomInfoResolver } from "./room-info.js";
53
+ import { runMatrixStartupMaintenance } from "./startup.js";
54
+ import { createMatrixMonitorStatusController } from "./status.js";
55
+ import { createMatrixMonitorSyncLifecycle } from "./sync-lifecycle.js";
56
+ import { createMatrixMonitorTaskRunner } from "./task-runner.js";
57
+
58
+ export type MonitorMatrixOpts = {
59
+ runtime?: RuntimeEnv;
60
+ channelRuntime?: ChannelRuntimeSurface;
61
+ abortSignal?: AbortSignal;
62
+ mediaMaxMb?: number;
63
+ initialSyncLimit?: number;
64
+ replyToMode?: ReplyToMode;
65
+ accountId?: string | null;
66
+ setStatus?: (next: import("autobot/plugin-sdk/channel-contract").ChannelAccountSnapshot) => void;
67
+ };
68
+
69
+ function isMatrixStreamingConfig(
70
+ streaming: MatrixConfig["streaming"],
71
+ ): streaming is MatrixStreamingConfig {
72
+ return Boolean(streaming && typeof streaming === "object" && !Array.isArray(streaming));
73
+ }
74
+
75
+ function resolveMatrixStreamingMode(streaming: MatrixConfig["streaming"]): MatrixStreamingMode {
76
+ if (streaming === true || streaming === "partial") {
77
+ return "partial";
78
+ }
79
+ if (streaming === "quiet") {
80
+ return "quiet";
81
+ }
82
+ if (streaming === "progress") {
83
+ return "progress";
84
+ }
85
+ if (isMatrixStreamingConfig(streaming)) {
86
+ if (
87
+ streaming.mode === "partial" ||
88
+ streaming.mode === "quiet" ||
89
+ streaming.mode === "progress"
90
+ ) {
91
+ return streaming.mode;
92
+ }
93
+ }
94
+ return "off";
95
+ }
96
+
97
+ function resolveMatrixPreviewToolProgress(streaming: MatrixConfig["streaming"]): boolean {
98
+ if (!isMatrixStreamingConfig(streaming)) {
99
+ return true;
100
+ }
101
+ if (resolveMatrixStreamingMode(streaming) === "progress") {
102
+ return streaming.progress?.toolProgress ?? streaming.preview?.toolProgress ?? true;
103
+ }
104
+ return streaming.preview?.toolProgress ?? true;
105
+ }
106
+
107
+ function resolveMatrixPreviewToolProgressEnabled(streaming: MatrixConfig["streaming"]): boolean {
108
+ return (
109
+ resolveMatrixStreamingMode(streaming) !== "off" && resolveMatrixPreviewToolProgress(streaming)
110
+ );
111
+ }
112
+
113
+ export const testing = {
114
+ resolveMatrixPreviewToolProgress,
115
+ resolveMatrixPreviewToolProgressEnabled,
116
+ resolveMatrixStreamingMode,
117
+ };
118
+
119
+ const DEFAULT_MEDIA_MAX_MB = 20;
120
+
121
+ export async function monitorMatrixProvider(opts: MonitorMatrixOpts = {}): Promise<void> {
122
+ // Fast-cancel callers should not pay the full Matrix startup/import cost.
123
+ if (opts.abortSignal?.aborted) {
124
+ return;
125
+ }
126
+ if (isBunRuntime()) {
127
+ throw new Error("Matrix provider requires Node (bun runtime not supported)");
128
+ }
129
+ const core = getMatrixRuntime();
130
+ let cfg = core.config.current() as CoreConfig;
131
+ if (cfg.channels?.["matrix"]?.enabled === false) {
132
+ return;
133
+ }
134
+
135
+ const logger = core.logging.getChildLogger({ module: "matrix-auto-reply" });
136
+ const formatRuntimeMessage = (...args: Parameters<RuntimeEnv["log"]>) => format(...args);
137
+ const runtime: RuntimeEnv = opts.runtime ?? {
138
+ log: (...args) => {
139
+ logger.info(formatRuntimeMessage(...args));
140
+ },
141
+ error: (...args) => {
142
+ logger.error(formatRuntimeMessage(...args));
143
+ },
144
+ exit: (code: number): never => {
145
+ throw new Error(`exit ${code}`);
146
+ },
147
+ };
148
+ const logVerboseMessage = (message: string) => {
149
+ if (!core.logging.shouldLogVerbose()) {
150
+ return;
151
+ }
152
+ logger.debug?.(message);
153
+ };
154
+
155
+ const authContext = resolveMatrixAuthContext({
156
+ cfg,
157
+ accountId: opts.accountId,
158
+ });
159
+ const effectiveAccountId = authContext.accountId;
160
+
161
+ // Resolve account-specific config for multi-account support
162
+ const accountConfig = resolveMatrixAccountConfig({
163
+ cfg,
164
+ accountId: effectiveAccountId,
165
+ });
166
+
167
+ const allowlistOnly = accountConfig.allowlistOnly === true;
168
+ const accountAllowBots = accountConfig.allowBots;
169
+ let allowFrom: string[] = (accountConfig.dm?.allowFrom ?? []).map(String);
170
+ let groupAllowFrom: string[] = (accountConfig.groupAllowFrom ?? []).map(String);
171
+ let allowFromResolvedEntries: MatrixResolvedAllowlistEntry[] = [];
172
+ let groupAllowFromResolvedEntries: MatrixResolvedAllowlistEntry[] = [];
173
+ let roomsConfig = accountConfig.groups ?? accountConfig.rooms;
174
+ let needsRoomAliasesForConfig = false;
175
+ const configuredBotUserIds = resolveConfiguredMatrixBotUserIds({
176
+ cfg,
177
+ accountId: effectiveAccountId,
178
+ });
179
+
180
+ ({
181
+ allowFrom,
182
+ allowFromResolvedEntries,
183
+ groupAllowFrom,
184
+ groupAllowFromResolvedEntries,
185
+ roomsConfig,
186
+ } = await resolveMatrixMonitorConfig({
187
+ cfg,
188
+ accountId: effectiveAccountId,
189
+ allowFrom,
190
+ groupAllowFrom,
191
+ roomsConfig,
192
+ runtime,
193
+ }));
194
+ needsRoomAliasesForConfig = Boolean(
195
+ roomsConfig && Object.keys(roomsConfig).some((key) => key.trim().startsWith("#")),
196
+ );
197
+
198
+ cfg = {
199
+ ...cfg,
200
+ channels: {
201
+ ...cfg.channels,
202
+ matrix: {
203
+ ...cfg.channels?.["matrix"],
204
+ dm: {
205
+ ...cfg.channels?.["matrix"]?.dm,
206
+ allowFrom,
207
+ },
208
+ groupAllowFrom,
209
+ ...(roomsConfig ? { groups: roomsConfig } : {}),
210
+ },
211
+ },
212
+ };
213
+
214
+ const auth = await resolveMatrixAuth({ cfg, accountId: effectiveAccountId });
215
+ const resolvedInitialSyncLimit =
216
+ typeof opts.initialSyncLimit === "number"
217
+ ? Math.max(0, Math.floor(opts.initialSyncLimit))
218
+ : auth.initialSyncLimit;
219
+ const authWithLimit =
220
+ resolvedInitialSyncLimit === auth.initialSyncLimit
221
+ ? auth
222
+ : { ...auth, initialSyncLimit: resolvedInitialSyncLimit };
223
+ const statusController = createMatrixMonitorStatusController({
224
+ accountId: auth.accountId,
225
+ baseUrl: auth.homeserver,
226
+ statusSink: opts.setStatus,
227
+ });
228
+ let cleanedUp = false;
229
+ let client: MatrixClient | null = null;
230
+ let threadBindingManager: { accountId: string; stop: () => void } | null = null;
231
+ let inboundDeduper: MatrixInboundEventDeduper | null = null;
232
+ const monitorTaskRunner = createMatrixMonitorTaskRunner({
233
+ logger,
234
+ logVerboseMessage,
235
+ });
236
+ let syncLifecycle: ReturnType<typeof createMatrixMonitorSyncLifecycle> | null = null;
237
+ const cleanup = async (mode: "persist" | "stop" = "persist") => {
238
+ if (cleanedUp) {
239
+ return;
240
+ }
241
+ cleanedUp = true;
242
+ try {
243
+ client?.stopSyncWithoutPersist();
244
+ if (client && mode === "persist") {
245
+ await client.drainPendingDecryptions("matrix monitor shutdown");
246
+ }
247
+ if (mode === "persist") {
248
+ await monitorTaskRunner.waitForIdle();
249
+ }
250
+ threadBindingManager?.stop();
251
+ await inboundDeduper?.stop();
252
+ if (client) {
253
+ await releaseSharedClientInstance(client, mode);
254
+ }
255
+ } finally {
256
+ client?.off("sync.state", onSyncState);
257
+ syncLifecycle?.dispose();
258
+ statusController.markStopped();
259
+ setActiveMatrixClient(null, auth.accountId);
260
+ }
261
+ };
262
+
263
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
264
+ const { groupPolicy: groupPolicyRaw, providerMissingFallbackApplied } =
265
+ resolveAllowlistProviderRuntimeGroupPolicy({
266
+ providerConfigPresent: cfg.channels?.["matrix"] !== undefined,
267
+ groupPolicy: accountConfig.groupPolicy,
268
+ defaultGroupPolicy,
269
+ });
270
+ warnMissingProviderGroupPolicyFallbackOnce({
271
+ providerMissingFallbackApplied,
272
+ providerKey: "matrix",
273
+ accountId: effectiveAccountId,
274
+ blockedLabel: GROUP_POLICY_BLOCKED_LABEL.room,
275
+ log: (message) => logVerboseMessage(message),
276
+ });
277
+ const groupPolicy = allowlistOnly && groupPolicyRaw === "open" ? "allowlist" : groupPolicyRaw;
278
+ const replyToMode = opts.replyToMode ?? accountConfig.replyToMode ?? "off";
279
+ const threadReplies = accountConfig.threadReplies ?? "inbound";
280
+ const dmThreadReplies = accountConfig.dm?.threadReplies;
281
+ const threadBindingIdleTimeoutMs = resolveThreadBindingIdleTimeoutMsForChannel({
282
+ cfg,
283
+ channel: "matrix",
284
+ accountId: effectiveAccountId,
285
+ });
286
+ const threadBindingMaxAgeMs = resolveThreadBindingMaxAgeMsForChannel({
287
+ cfg,
288
+ channel: "matrix",
289
+ accountId: effectiveAccountId,
290
+ });
291
+ const dmConfig = accountConfig.dm;
292
+ const dmEnabled = dmConfig?.enabled ?? true;
293
+ const dmPolicyRaw = dmConfig?.policy ?? "pairing";
294
+ const dmPolicy = allowlistOnly && dmPolicyRaw !== "disabled" ? "allowlist" : dmPolicyRaw;
295
+ const dmSessionScope = dmConfig?.sessionScope ?? "per-user";
296
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "matrix", effectiveAccountId);
297
+ const globalGroupChatHistoryLimit = (
298
+ cfg.messages as { groupChat?: { historyLimit?: number } } | undefined
299
+ )?.groupChat?.historyLimit;
300
+ const historyLimit = Math.max(0, accountConfig.historyLimit ?? globalGroupChatHistoryLimit ?? 0);
301
+ const mediaMaxMb = opts.mediaMaxMb ?? accountConfig.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB;
302
+ const mediaMaxBytes = Math.max(1, mediaMaxMb) * 1024 * 1024;
303
+ const streaming = resolveMatrixStreamingMode(accountConfig.streaming);
304
+ const previewToolProgressEnabled = resolveMatrixPreviewToolProgressEnabled(
305
+ accountConfig.streaming,
306
+ );
307
+ const blockStreamingEnabled = accountConfig.blockStreaming === true;
308
+ const startupMs = Date.now();
309
+ const startupGraceMs = 0;
310
+ const warnedEncryptedRooms = new Set<string>();
311
+ const warnedCryptoMissingRooms = new Set<string>();
312
+ let healthySyncSinceMs: number | undefined;
313
+ const noteSyncHealthState = (state: MatrixSyncState, at = Date.now()) => {
314
+ if (isMatrixReadySyncState(state)) {
315
+ healthySyncSinceMs ??= at;
316
+ return;
317
+ }
318
+ if (isMatrixDisconnectedSyncState(state)) {
319
+ healthySyncSinceMs = undefined;
320
+ }
321
+ };
322
+ const onSyncState = (state: MatrixSyncState) => {
323
+ noteSyncHealthState(state);
324
+ };
325
+
326
+ try {
327
+ client = await resolveSharedMatrixClient({
328
+ cfg,
329
+ auth: authWithLimit,
330
+ startClient: false,
331
+ accountId: auth.accountId,
332
+ });
333
+ setActiveMatrixClient(client, auth.accountId);
334
+ inboundDeduper = await createMatrixInboundEventDeduper({
335
+ auth,
336
+ env: process.env,
337
+ });
338
+ syncLifecycle = createMatrixMonitorSyncLifecycle({
339
+ client,
340
+ statusController,
341
+ isStopping: () => cleanedUp || opts.abortSignal?.aborted === true,
342
+ });
343
+ client.on("sync.state", onSyncState);
344
+ // Cold starts should ignore old room history, but once we have a persisted
345
+ // /sync cursor we want restart backlogs to replay just like other channels.
346
+ const dropPreStartupMessages = !client.hasPersistedSyncState();
347
+ const { getRoomInfo, getMemberDisplayName } = createMatrixRoomInfoResolver(client);
348
+ const directTracker = createDirectRoomTracker(client, {
349
+ log: logVerboseMessage,
350
+ canPromoteRecentInvite: async (roomId) =>
351
+ shouldPromoteRecentInviteRoom({
352
+ roomId,
353
+ roomInfo: await getRoomInfo(roomId, { includeAliases: true }),
354
+ rooms: roomsConfig,
355
+ }),
356
+ ...(dmSessionScope === "per-room"
357
+ ? {
358
+ canPromoteUnmappedStrictRoom: async (roomId) =>
359
+ shouldPromoteRecentInviteRoom({
360
+ roomId,
361
+ roomInfo: await getRoomInfo(roomId, { includeAliases: true }),
362
+ rooms: roomsConfig,
363
+ }),
364
+ }
365
+ : {}),
366
+ shouldKeepLocallyPromotedDirectRoom: async (roomId) => {
367
+ try {
368
+ const roomInfo = await getRoomInfo(roomId, { includeAliases: true });
369
+ if (!roomInfo.nameResolved || !roomInfo.aliasesResolved) {
370
+ return undefined;
371
+ }
372
+ return shouldPromoteRecentInviteRoom({
373
+ roomId,
374
+ roomInfo,
375
+ rooms: roomsConfig,
376
+ });
377
+ } catch (err) {
378
+ logVerboseMessage(
379
+ `matrix: local promotion revalidation failed room=${roomId} (${String(err)})`,
380
+ );
381
+ return undefined;
382
+ }
383
+ },
384
+ });
385
+ registerMatrixAutoJoin({ client, accountConfig, runtime });
386
+ const handleRoomMessage = createMatrixRoomMessageHandler({
387
+ client,
388
+ core,
389
+ cfg,
390
+ accountId: effectiveAccountId,
391
+ accountConfig,
392
+ runtime,
393
+ logger,
394
+ logVerboseMessage,
395
+ allowFrom,
396
+ allowFromResolvedEntries,
397
+ groupAllowFrom,
398
+ groupAllowFromResolvedEntries,
399
+ roomsConfig,
400
+ accountAllowBots,
401
+ configuredBotUserIds,
402
+ groupPolicy,
403
+ replyToMode,
404
+ threadReplies,
405
+ dmThreadReplies,
406
+ dmSessionScope,
407
+ streaming,
408
+ previewToolProgressEnabled,
409
+ blockStreamingEnabled,
410
+ dmEnabled,
411
+ dmPolicy,
412
+ textLimit,
413
+ mediaMaxBytes,
414
+ historyLimit,
415
+ startupMs,
416
+ startupGraceMs,
417
+ dropPreStartupMessages,
418
+ inboundDeduper,
419
+ directTracker,
420
+ getRoomInfo,
421
+ getMemberDisplayName,
422
+ needsRoomAliasesForConfig,
423
+ });
424
+ threadBindingManager = await createMatrixThreadBindingManager({
425
+ cfg,
426
+ accountId: effectiveAccountId,
427
+ auth,
428
+ client,
429
+ env: process.env,
430
+ idleTimeoutMs: threadBindingIdleTimeoutMs,
431
+ maxAgeMs: threadBindingMaxAgeMs,
432
+ logVerboseMessage,
433
+ });
434
+ logVerboseMessage(
435
+ `matrix: thread bindings ready account=${threadBindingManager.accountId} idleMs=${threadBindingIdleTimeoutMs} maxAgeMs=${threadBindingMaxAgeMs}`,
436
+ );
437
+
438
+ registerMatrixMonitorEvents({
439
+ cfg,
440
+ client,
441
+ auth,
442
+ allowFrom,
443
+ dmEnabled,
444
+ dmPolicy,
445
+ readStoreAllowFrom: async () =>
446
+ await core.channel.pairing
447
+ .readAllowFromStore({
448
+ channel: "matrix",
449
+ env: process.env,
450
+ accountId: effectiveAccountId,
451
+ })
452
+ .catch(() => []),
453
+ directTracker,
454
+ logVerboseMessage,
455
+ warnedEncryptedRooms,
456
+ warnedCryptoMissingRooms,
457
+ logger,
458
+ startupGraceMs,
459
+ getHealthySyncSinceMs: () => healthySyncSinceMs,
460
+ formatNativeDependencyHint: core.system.formatNativeDependencyHint,
461
+ onRoomMessage: handleRoomMessage,
462
+ runDetachedTask: monitorTaskRunner.runDetachedTask,
463
+ });
464
+
465
+ // Register Matrix thread bindings before the client starts syncing so threaded
466
+ // commands during startup never observe Matrix as "unavailable".
467
+ logVerboseMessage("matrix: starting client");
468
+ await resolveSharedMatrixClient({
469
+ cfg,
470
+ auth: authWithLimit,
471
+ accountId: auth.accountId,
472
+ abortSignal: opts.abortSignal,
473
+ });
474
+ logVerboseMessage("matrix: client started");
475
+
476
+ // Shared client is already started via resolveSharedMatrixClient.
477
+ logger.info(`matrix: logged in as ${auth.userId}`);
478
+ void backfillMatrixAuthDeviceIdAfterStartup({
479
+ auth,
480
+ env: process.env,
481
+ abortSignal: opts.abortSignal,
482
+ }).catch((err) => {
483
+ logVerboseMessage(`matrix: failed to backfill deviceId after startup (${String(err)})`);
484
+ });
485
+
486
+ registerChannelRuntimeContext({
487
+ channelRuntime: opts.channelRuntime,
488
+ channelId: "matrix",
489
+ accountId: effectiveAccountId,
490
+ capability: CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY,
491
+ context: {
492
+ client,
493
+ },
494
+ abortSignal: opts.abortSignal,
495
+ });
496
+
497
+ await runMatrixStartupMaintenance({
498
+ client,
499
+ auth,
500
+ accountId: effectiveAccountId,
501
+ effectiveAccountId,
502
+ accountConfig,
503
+ logger,
504
+ logVerboseMessage,
505
+ getRuntimeConfig: () => core.config.current() as CoreConfig,
506
+ replaceConfigFile: async (nextCfg) => {
507
+ await core.config.replaceConfigFile({
508
+ nextConfig: nextCfg,
509
+ afterWrite: { mode: "auto" },
510
+ });
511
+ },
512
+ loadWebMedia: async (url, maxBytes) => await core.media.loadWebMedia(url, maxBytes),
513
+ env: process.env,
514
+ abortSignal: opts.abortSignal,
515
+ });
516
+
517
+ await Promise.race([
518
+ waitUntilAbort(opts.abortSignal, async () => {
519
+ try {
520
+ logVerboseMessage("matrix: stopping client");
521
+ await cleanup();
522
+ } catch (err) {
523
+ logger.warn("matrix: failed during monitor shutdown cleanup", {
524
+ error: String(err),
525
+ });
526
+ }
527
+ }),
528
+ syncLifecycle.waitForFatalStop(),
529
+ ]);
530
+ } catch (err) {
531
+ if (opts.abortSignal?.aborted === true && isMatrixStartupAbortError(err)) {
532
+ await cleanup("stop");
533
+ return;
534
+ }
535
+ statusController.noteUnexpectedError(err);
536
+ await cleanup();
537
+ throw err;
538
+ }
539
+ }
540
+ export { testing as __testing };
@@ -0,0 +1,139 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { readJsonFileWithFallback, writeJsonFileAtomically } from "autobot/plugin-sdk/json-store";
5
+ import { getMatrixRuntime } from "../../runtime.js";
6
+ import { resolveMatrixStoragePaths } from "../client/storage.js";
7
+ import type { MatrixAuth } from "../client/types.js";
8
+ import type { MatrixClient } from "../sdk.js";
9
+
10
+ type MatrixLegacyCryptoMigrationState = {
11
+ version: 1;
12
+ accountId: string;
13
+ roomKeyCounts: {
14
+ total: number;
15
+ backedUp: number;
16
+ } | null;
17
+ restoreStatus: "pending" | "completed" | "manual-action-required";
18
+ restoredAt?: string;
19
+ importedCount?: number;
20
+ totalCount?: number;
21
+ lastError?: string | null;
22
+ };
23
+
24
+ export type MatrixLegacyCryptoRestoreResult =
25
+ | { kind: "skipped" }
26
+ | {
27
+ kind: "restored";
28
+ imported: number;
29
+ total: number;
30
+ localOnlyKeys: number;
31
+ }
32
+ | {
33
+ kind: "failed";
34
+ error: string;
35
+ localOnlyKeys: number;
36
+ };
37
+
38
+ function isMigrationState(value: unknown): value is MatrixLegacyCryptoMigrationState {
39
+ return (
40
+ Boolean(value) && typeof value === "object" && (value as { version?: unknown }).version === 1
41
+ );
42
+ }
43
+
44
+ async function resolvePendingMigrationStatePath(params: {
45
+ stateDir: string;
46
+ auth: Pick<MatrixAuth, "homeserver" | "userId" | "accessToken" | "accountId" | "deviceId">;
47
+ }): Promise<{
48
+ statePath: string;
49
+ value: MatrixLegacyCryptoMigrationState | null;
50
+ }> {
51
+ const { rootDir } = resolveMatrixStoragePaths({
52
+ homeserver: params.auth.homeserver,
53
+ userId: params.auth.userId,
54
+ accessToken: params.auth.accessToken,
55
+ accountId: params.auth.accountId,
56
+ deviceId: params.auth.deviceId,
57
+ stateDir: params.stateDir,
58
+ });
59
+ const directStatePath = path.join(rootDir, "legacy-crypto-migration.json");
60
+ const { value: directValue } =
61
+ await readJsonFileWithFallback<MatrixLegacyCryptoMigrationState | null>(directStatePath, null);
62
+ if (isMigrationState(directValue) && directValue.restoreStatus === "pending") {
63
+ return { statePath: directStatePath, value: directValue };
64
+ }
65
+
66
+ const accountStorageDir = path.dirname(rootDir);
67
+ let siblingEntries: string[] = [];
68
+ try {
69
+ siblingEntries = (await fs.readdir(accountStorageDir, { withFileTypes: true }))
70
+ .filter((entry) => entry.isDirectory())
71
+ .map((entry) => entry.name)
72
+ .filter((entry) => path.join(accountStorageDir, entry) !== rootDir)
73
+ .toSorted((left, right) => left.localeCompare(right));
74
+ } catch {
75
+ return { statePath: directStatePath, value: directValue };
76
+ }
77
+
78
+ for (const sibling of siblingEntries) {
79
+ const siblingStatePath = path.join(accountStorageDir, sibling, "legacy-crypto-migration.json");
80
+ const { value } = await readJsonFileWithFallback<MatrixLegacyCryptoMigrationState | null>(
81
+ siblingStatePath,
82
+ null,
83
+ );
84
+ if (isMigrationState(value) && value.restoreStatus === "pending") {
85
+ return { statePath: siblingStatePath, value };
86
+ }
87
+ }
88
+ return { statePath: directStatePath, value: directValue };
89
+ }
90
+
91
+ export async function maybeRestoreLegacyMatrixBackup(params: {
92
+ client: Pick<MatrixClient, "restoreRoomKeyBackup">;
93
+ auth: Pick<MatrixAuth, "homeserver" | "userId" | "accessToken" | "accountId" | "deviceId">;
94
+ env?: NodeJS.ProcessEnv;
95
+ stateDir?: string;
96
+ }): Promise<MatrixLegacyCryptoRestoreResult> {
97
+ const env = params.env ?? process.env;
98
+ const stateDir = params.stateDir ?? getMatrixRuntime().state.resolveStateDir(env, os.homedir);
99
+ const { statePath, value } = await resolvePendingMigrationStatePath({
100
+ stateDir,
101
+ auth: params.auth,
102
+ });
103
+ if (!isMigrationState(value) || value.restoreStatus !== "pending") {
104
+ return { kind: "skipped" };
105
+ }
106
+
107
+ const restore = await params.client.restoreRoomKeyBackup();
108
+ const localOnlyKeys =
109
+ value.roomKeyCounts && value.roomKeyCounts.total > value.roomKeyCounts.backedUp
110
+ ? value.roomKeyCounts.total - value.roomKeyCounts.backedUp
111
+ : 0;
112
+
113
+ if (restore.success) {
114
+ await writeJsonFileAtomically(statePath, {
115
+ ...value,
116
+ restoreStatus: "completed",
117
+ restoredAt: restore.restoredAt ?? new Date().toISOString(),
118
+ importedCount: restore.imported,
119
+ totalCount: restore.total,
120
+ lastError: null,
121
+ } satisfies MatrixLegacyCryptoMigrationState);
122
+ return {
123
+ kind: "restored",
124
+ imported: restore.imported,
125
+ total: restore.total,
126
+ localOnlyKeys,
127
+ };
128
+ }
129
+
130
+ await writeJsonFileAtomically(statePath, {
131
+ ...value,
132
+ lastError: restore.error ?? "unknown",
133
+ } satisfies MatrixLegacyCryptoMigrationState);
134
+ return {
135
+ kind: "failed",
136
+ error: restore.error ?? "unknown",
137
+ localOnlyKeys,
138
+ };
139
+ }