@kodelyth/matrix 2026.5.42 → 2026.6.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 (205) hide show
  1. package/klaw.plugin.json +891 -3
  2. package/package.json +16 -4
  3. package/CHANGELOG.md +0 -321
  4. package/SPEC-SUPPORT.md +0 -116
  5. package/api.ts +0 -38
  6. package/auth-presence.ts +0 -56
  7. package/channel-plugin-api.ts +0 -3
  8. package/cli-metadata.ts +0 -11
  9. package/contract-api.ts +0 -17
  10. package/doctor-contract-api.ts +0 -1
  11. package/helper-api.ts +0 -3
  12. package/index.ts +0 -55
  13. package/plugin-entry.handlers.runtime.ts +0 -1
  14. package/runtime-api.ts +0 -72
  15. package/runtime-heavy-api.ts +0 -1
  16. package/runtime-setter-api.ts +0 -3
  17. package/secret-contract-api.ts +0 -5
  18. package/setup-entry.ts +0 -17
  19. package/setup-plugin-api.ts +0 -3
  20. package/src/account-selection.ts +0 -223
  21. package/src/actions.ts +0 -346
  22. package/src/approval-auth.ts +0 -25
  23. package/src/approval-handler.runtime.ts +0 -592
  24. package/src/approval-ids.ts +0 -6
  25. package/src/approval-native.ts +0 -345
  26. package/src/approval-reaction-auth.ts +0 -45
  27. package/src/approval-reactions.ts +0 -313
  28. package/src/auth-precedence.ts +0 -61
  29. package/src/channel-account-paths.ts +0 -97
  30. package/src/channel.runtime.ts +0 -17
  31. package/src/channel.setup.ts +0 -48
  32. package/src/channel.ts +0 -667
  33. package/src/cli-metadata.ts +0 -19
  34. package/src/cli.ts +0 -2298
  35. package/src/config-adapter.ts +0 -41
  36. package/src/config-schema.ts +0 -159
  37. package/src/config-ui-hints.ts +0 -56
  38. package/src/directory-live.ts +0 -238
  39. package/src/doctor-contract.ts +0 -287
  40. package/src/doctor.ts +0 -262
  41. package/src/env-vars.ts +0 -92
  42. package/src/exec-approval-resolver.ts +0 -23
  43. package/src/exec-approvals.ts +0 -287
  44. package/src/group-mentions.ts +0 -41
  45. package/src/legacy-crypto-inspector-availability.ts +0 -60
  46. package/src/legacy-crypto.ts +0 -531
  47. package/src/legacy-state.ts +0 -156
  48. package/src/matrix/account-config.ts +0 -175
  49. package/src/matrix/accounts.ts +0 -194
  50. package/src/matrix/actions/client.ts +0 -31
  51. package/src/matrix/actions/devices.ts +0 -34
  52. package/src/matrix/actions/limits.ts +0 -6
  53. package/src/matrix/actions/messages.ts +0 -129
  54. package/src/matrix/actions/pins.ts +0 -63
  55. package/src/matrix/actions/polls.ts +0 -109
  56. package/src/matrix/actions/profile.ts +0 -37
  57. package/src/matrix/actions/reactions.ts +0 -59
  58. package/src/matrix/actions/room.ts +0 -71
  59. package/src/matrix/actions/summary.ts +0 -88
  60. package/src/matrix/actions/types.ts +0 -63
  61. package/src/matrix/actions/verification.ts +0 -589
  62. package/src/matrix/actions.ts +0 -37
  63. package/src/matrix/active-client.ts +0 -26
  64. package/src/matrix/async-lock.ts +0 -18
  65. package/src/matrix/backup-health.ts +0 -124
  66. package/src/matrix/client/config-runtime-api.ts +0 -9
  67. package/src/matrix/client/config-secret-input.runtime.ts +0 -1
  68. package/src/matrix/client/config.ts +0 -853
  69. package/src/matrix/client/create-client.ts +0 -105
  70. package/src/matrix/client/env-auth.ts +0 -95
  71. package/src/matrix/client/file-sync-store.ts +0 -289
  72. package/src/matrix/client/logging.ts +0 -140
  73. package/src/matrix/client/migration-snapshot.runtime.ts +0 -1
  74. package/src/matrix/client/private-network-host.ts +0 -1
  75. package/src/matrix/client/runtime.ts +0 -4
  76. package/src/matrix/client/shared.ts +0 -316
  77. package/src/matrix/client/storage.ts +0 -543
  78. package/src/matrix/client/types.ts +0 -50
  79. package/src/matrix/client/url-validation.ts +0 -73
  80. package/src/matrix/client-bootstrap.ts +0 -173
  81. package/src/matrix/client.ts +0 -23
  82. package/src/matrix/config-paths.ts +0 -31
  83. package/src/matrix/config-update.ts +0 -292
  84. package/src/matrix/credentials-read.ts +0 -208
  85. package/src/matrix/credentials-write.runtime.ts +0 -35
  86. package/src/matrix/credentials.ts +0 -95
  87. package/src/matrix/deps.ts +0 -309
  88. package/src/matrix/device-health.ts +0 -29
  89. package/src/matrix/direct-management.ts +0 -349
  90. package/src/matrix/direct-room.ts +0 -128
  91. package/src/matrix/draft-stream.ts +0 -225
  92. package/src/matrix/encryption-guidance.ts +0 -24
  93. package/src/matrix/errors.ts +0 -21
  94. package/src/matrix/format.ts +0 -426
  95. package/src/matrix/legacy-crypto-inspector.ts +0 -95
  96. package/src/matrix/media-errors.ts +0 -20
  97. package/src/matrix/media-text.ts +0 -162
  98. package/src/matrix/monitor/access-state.ts +0 -145
  99. package/src/matrix/monitor/ack-config.ts +0 -27
  100. package/src/matrix/monitor/allowlist.ts +0 -89
  101. package/src/matrix/monitor/auto-join.ts +0 -86
  102. package/src/matrix/monitor/config.ts +0 -569
  103. package/src/matrix/monitor/context-summary.ts +0 -43
  104. package/src/matrix/monitor/direct.ts +0 -296
  105. package/src/matrix/monitor/events.ts +0 -397
  106. package/src/matrix/monitor/handler.ts +0 -2266
  107. package/src/matrix/monitor/inbound-dedupe.ts +0 -267
  108. package/src/matrix/monitor/index.ts +0 -540
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +0 -139
  110. package/src/matrix/monitor/location.ts +0 -108
  111. package/src/matrix/monitor/media.ts +0 -119
  112. package/src/matrix/monitor/mentions.ts +0 -256
  113. package/src/matrix/monitor/reaction-events.ts +0 -197
  114. package/src/matrix/monitor/recent-invite.ts +0 -30
  115. package/src/matrix/monitor/replies.ts +0 -136
  116. package/src/matrix/monitor/reply-context.ts +0 -92
  117. package/src/matrix/monitor/room-history.ts +0 -301
  118. package/src/matrix/monitor/room-info.ts +0 -126
  119. package/src/matrix/monitor/rooms.ts +0 -52
  120. package/src/matrix/monitor/route.ts +0 -179
  121. package/src/matrix/monitor/runtime-api.ts +0 -28
  122. package/src/matrix/monitor/startup-verification.ts +0 -237
  123. package/src/matrix/monitor/startup.ts +0 -218
  124. package/src/matrix/monitor/status.ts +0 -120
  125. package/src/matrix/monitor/sync-lifecycle.ts +0 -91
  126. package/src/matrix/monitor/task-runner.ts +0 -38
  127. package/src/matrix/monitor/test-events.ts +0 -21
  128. package/src/matrix/monitor/thread-context.ts +0 -108
  129. package/src/matrix/monitor/threads.ts +0 -85
  130. package/src/matrix/monitor/types.ts +0 -30
  131. package/src/matrix/monitor/verification-events.ts +0 -643
  132. package/src/matrix/monitor/verification-utils.ts +0 -46
  133. package/src/matrix/outbound-media-runtime.ts +0 -1
  134. package/src/matrix/poll-summary.ts +0 -110
  135. package/src/matrix/poll-types.ts +0 -429
  136. package/src/matrix/probe.runtime.ts +0 -4
  137. package/src/matrix/probe.ts +0 -97
  138. package/src/matrix/profile.ts +0 -184
  139. package/src/matrix/reaction-common.ts +0 -147
  140. package/src/matrix/sdk/crypto-bootstrap.ts +0 -438
  141. package/src/matrix/sdk/crypto-facade.ts +0 -242
  142. package/src/matrix/sdk/crypto-node.runtime.ts +0 -17
  143. package/src/matrix/sdk/crypto-runtime.ts +0 -14
  144. package/src/matrix/sdk/decrypt-bridge.ts +0 -410
  145. package/src/matrix/sdk/event-helpers.ts +0 -83
  146. package/src/matrix/sdk/http-client.ts +0 -87
  147. package/src/matrix/sdk/idb-persistence-lock.ts +0 -51
  148. package/src/matrix/sdk/idb-persistence.ts +0 -288
  149. package/src/matrix/sdk/logger.ts +0 -108
  150. package/src/matrix/sdk/read-response-with-limit.ts +0 -19
  151. package/src/matrix/sdk/recovery-key-store.ts +0 -453
  152. package/src/matrix/sdk/timeout-abort-signal.ts +0 -1
  153. package/src/matrix/sdk/transport-runtime-api.ts +0 -18
  154. package/src/matrix/sdk/transport.ts +0 -352
  155. package/src/matrix/sdk/types.ts +0 -245
  156. package/src/matrix/sdk/verification-manager.ts +0 -795
  157. package/src/matrix/sdk/verification-status.ts +0 -23
  158. package/src/matrix/sdk.ts +0 -2152
  159. package/src/matrix/send/client.ts +0 -93
  160. package/src/matrix/send/formatting.ts +0 -189
  161. package/src/matrix/send/media.ts +0 -244
  162. package/src/matrix/send/targets.ts +0 -104
  163. package/src/matrix/send/types.ts +0 -131
  164. package/src/matrix/send.ts +0 -660
  165. package/src/matrix/session-store-metadata.ts +0 -108
  166. package/src/matrix/startup-abort.ts +0 -44
  167. package/src/matrix/subagent-hooks.ts +0 -308
  168. package/src/matrix/sync-state.ts +0 -27
  169. package/src/matrix/target-ids.ts +0 -79
  170. package/src/matrix/thread-bindings-shared.ts +0 -206
  171. package/src/matrix/thread-bindings.ts +0 -580
  172. package/src/matrix-migration.runtime.ts +0 -9
  173. package/src/migration-config.ts +0 -243
  174. package/src/migration-snapshot-backup.ts +0 -116
  175. package/src/migration-snapshot.ts +0 -53
  176. package/src/onboarding.ts +0 -775
  177. package/src/outbound.ts +0 -248
  178. package/src/plugin-entry.runtime.js +0 -115
  179. package/src/plugin-entry.runtime.ts +0 -70
  180. package/src/profile-update.ts +0 -71
  181. package/src/record-shared.ts +0 -3
  182. package/src/resolve-targets.ts +0 -175
  183. package/src/resolver.runtime.ts +0 -5
  184. package/src/resolver.ts +0 -21
  185. package/src/runtime-api.ts +0 -106
  186. package/src/runtime.ts +0 -13
  187. package/src/secret-contract.ts +0 -174
  188. package/src/session-route.ts +0 -126
  189. package/src/setup-bootstrap.ts +0 -102
  190. package/src/setup-config.ts +0 -222
  191. package/src/setup-contract.ts +0 -90
  192. package/src/setup-core.ts +0 -146
  193. package/src/setup-dm-policy.ts +0 -15
  194. package/src/setup-surface.ts +0 -4
  195. package/src/startup-maintenance.ts +0 -114
  196. package/src/storage-paths.ts +0 -92
  197. package/src/thread-binding-api.ts +0 -23
  198. package/src/tool-actions.runtime.ts +0 -1
  199. package/src/tool-actions.ts +0 -498
  200. package/src/types.ts +0 -257
  201. package/subagent-hooks-api.ts +0 -31
  202. package/test-api.ts +0 -21
  203. package/thread-binding-api.ts +0 -4
  204. package/thread-bindings-runtime.ts +0 -4
  205. package/tsconfig.json +0 -16
@@ -1,540 +0,0 @@
1
- import { format } from "node:util";
2
- import { CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "klaw/plugin-sdk/approval-handler-adapter-runtime";
3
- import type { ChannelRuntimeSurface } from "klaw/plugin-sdk/channel-contract";
4
- import { waitUntilAbort } from "klaw/plugin-sdk/channel-lifecycle";
5
- import { registerChannelRuntimeContext } from "klaw/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("klaw/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 };
@@ -1,139 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { readJsonFileWithFallback, writeJsonFileAtomically } from "klaw/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
- }