@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,580 @@
1
+ import path from "node:path";
2
+ import type { AutoBotConfig } from "autobot/plugin-sdk/config-contracts";
3
+ import { readJsonFileWithFallback, writeJsonFileAtomically } from "autobot/plugin-sdk/json-store";
4
+ import { resolveAgentIdFromSessionKey } from "autobot/plugin-sdk/session-key-runtime";
5
+ import { normalizeOptionalString } from "autobot/plugin-sdk/string-coerce-runtime";
6
+ import {
7
+ registerSessionBindingAdapter,
8
+ resolveThreadBindingFarewellText,
9
+ type SessionBindingAdapter,
10
+ unregisterSessionBindingAdapter,
11
+ } from "autobot/plugin-sdk/thread-bindings-session-runtime";
12
+ import { claimCurrentTokenStorageState, resolveMatrixStateFilePath } from "./client/storage.js";
13
+ import type { MatrixAuth } from "./client/types.js";
14
+ import type { MatrixClient } from "./sdk.js";
15
+ import { sendMessageMatrix } from "./send.js";
16
+ import {
17
+ deleteMatrixThreadBindingManagerEntry,
18
+ getMatrixThreadBindingManager,
19
+ getMatrixThreadBindingManagerEntry,
20
+ listBindingsForAccount,
21
+ removeBindingRecord,
22
+ resetMatrixThreadBindingsForTests,
23
+ resolveBindingKey,
24
+ resolveEffectiveBindingExpiry,
25
+ setBindingRecord,
26
+ setMatrixThreadBindingIdleTimeoutBySessionKey,
27
+ setMatrixThreadBindingManagerEntry,
28
+ setMatrixThreadBindingMaxAgeBySessionKey,
29
+ toMatrixBindingTargetKind,
30
+ toSessionBindingRecord,
31
+ type MatrixThreadBindingManager,
32
+ type MatrixThreadBindingRecord,
33
+ } from "./thread-bindings-shared.js";
34
+
35
+ const STORE_VERSION = 1;
36
+ const THREAD_BINDINGS_SWEEP_INTERVAL_MS = 60_000;
37
+ const TOUCH_PERSIST_DELAY_MS = 30_000;
38
+
39
+ type StoredMatrixThreadBindingState = {
40
+ version: number;
41
+ bindings: MatrixThreadBindingRecord[];
42
+ };
43
+
44
+ function resolveBindingsPath(params: {
45
+ auth: MatrixAuth;
46
+ accountId: string;
47
+ env?: NodeJS.ProcessEnv;
48
+ stateDir?: string;
49
+ }): string {
50
+ return resolveMatrixStateFilePath({
51
+ auth: params.auth,
52
+ accountId: params.accountId,
53
+ env: params.env,
54
+ stateDir: params.stateDir,
55
+ filename: "thread-bindings.json",
56
+ });
57
+ }
58
+
59
+ async function loadBindingsFromDisk(filePath: string, accountId: string) {
60
+ const { value } = await readJsonFileWithFallback<StoredMatrixThreadBindingState | null>(
61
+ filePath,
62
+ null,
63
+ );
64
+ if (value?.version !== STORE_VERSION || !Array.isArray(value.bindings)) {
65
+ return [];
66
+ }
67
+ const loaded: MatrixThreadBindingRecord[] = [];
68
+ for (const entry of value.bindings) {
69
+ const conversationId = normalizeOptionalString(entry?.conversationId);
70
+ const parentConversationId = normalizeOptionalString(entry?.parentConversationId);
71
+ const targetSessionKey = normalizeOptionalString(entry?.targetSessionKey) ?? "";
72
+ if (!conversationId || !targetSessionKey) {
73
+ continue;
74
+ }
75
+ const boundAt =
76
+ typeof entry?.boundAt === "number" && Number.isFinite(entry.boundAt)
77
+ ? Math.floor(entry.boundAt)
78
+ : Date.now();
79
+ const lastActivityAt =
80
+ typeof entry?.lastActivityAt === "number" && Number.isFinite(entry.lastActivityAt)
81
+ ? Math.floor(entry.lastActivityAt)
82
+ : boundAt;
83
+ loaded.push({
84
+ accountId,
85
+ conversationId,
86
+ ...(parentConversationId ? { parentConversationId } : {}),
87
+ targetKind: entry?.targetKind === "subagent" ? "subagent" : "acp",
88
+ targetSessionKey,
89
+ agentId: normalizeOptionalString(entry?.agentId) || undefined,
90
+ label: normalizeOptionalString(entry?.label) || undefined,
91
+ boundBy: normalizeOptionalString(entry?.boundBy) || undefined,
92
+ boundAt,
93
+ lastActivityAt: Math.max(lastActivityAt, boundAt),
94
+ idleTimeoutMs:
95
+ typeof entry?.idleTimeoutMs === "number" && Number.isFinite(entry.idleTimeoutMs)
96
+ ? Math.max(0, Math.floor(entry.idleTimeoutMs))
97
+ : undefined,
98
+ maxAgeMs:
99
+ typeof entry?.maxAgeMs === "number" && Number.isFinite(entry.maxAgeMs)
100
+ ? Math.max(0, Math.floor(entry.maxAgeMs))
101
+ : undefined,
102
+ });
103
+ }
104
+ return loaded;
105
+ }
106
+
107
+ function toStoredBindingsState(
108
+ bindings: MatrixThreadBindingRecord[],
109
+ ): StoredMatrixThreadBindingState {
110
+ return {
111
+ version: STORE_VERSION,
112
+ bindings: [...bindings].toSorted((a, b) => a.boundAt - b.boundAt),
113
+ };
114
+ }
115
+
116
+ async function persistBindingsSnapshot(
117
+ filePath: string,
118
+ bindings: MatrixThreadBindingRecord[],
119
+ ): Promise<void> {
120
+ await writeJsonFileAtomically(filePath, toStoredBindingsState(bindings));
121
+ claimCurrentTokenStorageState({
122
+ rootDir: path.dirname(filePath),
123
+ });
124
+ }
125
+
126
+ function buildMatrixBindingIntroText(params: {
127
+ metadata?: Record<string, unknown>;
128
+ targetSessionKey: string;
129
+ }): string {
130
+ const introText = normalizeOptionalString(params.metadata?.introText);
131
+ if (introText) {
132
+ return introText;
133
+ }
134
+ const label = normalizeOptionalString(params.metadata?.label);
135
+ const agentId =
136
+ normalizeOptionalString(params.metadata?.agentId) ||
137
+ resolveAgentIdFromSessionKey(params.targetSessionKey);
138
+ const base = label || agentId || "session";
139
+ return `⚙️ ${base} session active. Messages here go directly to this session.`;
140
+ }
141
+
142
+ async function sendBindingMessage(params: {
143
+ cfg: AutoBotConfig;
144
+ client: MatrixClient;
145
+ accountId: string;
146
+ roomId: string;
147
+ threadId?: string;
148
+ text: string;
149
+ }): Promise<string | null> {
150
+ const trimmed = params.text.trim();
151
+ if (!trimmed) {
152
+ return null;
153
+ }
154
+ const result = await sendMessageMatrix(`room:${params.roomId}`, trimmed, {
155
+ cfg: params.cfg,
156
+ client: params.client,
157
+ accountId: params.accountId,
158
+ ...(params.threadId ? { threadId: params.threadId } : {}),
159
+ });
160
+ return result.messageId || null;
161
+ }
162
+
163
+ async function sendFarewellMessage(params: {
164
+ cfg: AutoBotConfig;
165
+ client: MatrixClient;
166
+ accountId: string;
167
+ record: MatrixThreadBindingRecord;
168
+ defaultIdleTimeoutMs: number;
169
+ defaultMaxAgeMs: number;
170
+ reason?: string;
171
+ }): Promise<void> {
172
+ const roomId = params.record.parentConversationId ?? params.record.conversationId;
173
+ const idleTimeoutMs =
174
+ typeof params.record.idleTimeoutMs === "number"
175
+ ? params.record.idleTimeoutMs
176
+ : params.defaultIdleTimeoutMs;
177
+ const maxAgeMs =
178
+ typeof params.record.maxAgeMs === "number" ? params.record.maxAgeMs : params.defaultMaxAgeMs;
179
+ const farewellText = resolveThreadBindingFarewellText({
180
+ reason: params.reason,
181
+ idleTimeoutMs,
182
+ maxAgeMs,
183
+ });
184
+ await sendBindingMessage({
185
+ cfg: params.cfg,
186
+ client: params.client,
187
+ accountId: params.accountId,
188
+ roomId,
189
+ threadId:
190
+ params.record.parentConversationId &&
191
+ params.record.parentConversationId !== params.record.conversationId
192
+ ? params.record.conversationId
193
+ : undefined,
194
+ text: farewellText,
195
+ }).catch(() => {});
196
+ }
197
+
198
+ export async function createMatrixThreadBindingManager(params: {
199
+ cfg: AutoBotConfig;
200
+ accountId: string;
201
+ auth: MatrixAuth;
202
+ client: MatrixClient;
203
+ env?: NodeJS.ProcessEnv;
204
+ stateDir?: string;
205
+ idleTimeoutMs: number;
206
+ maxAgeMs: number;
207
+ enableSweeper?: boolean;
208
+ logVerboseMessage?: (message: string) => void;
209
+ }): Promise<MatrixThreadBindingManager> {
210
+ if (params.auth.accountId !== params.accountId) {
211
+ throw new Error(
212
+ `Matrix thread binding account mismatch: requested ${params.accountId}, auth resolved ${params.auth.accountId}`,
213
+ );
214
+ }
215
+ const filePath = resolveBindingsPath({
216
+ auth: params.auth,
217
+ accountId: params.accountId,
218
+ env: params.env,
219
+ stateDir: params.stateDir,
220
+ });
221
+ const existingEntry = getMatrixThreadBindingManagerEntry(params.accountId);
222
+ if (existingEntry) {
223
+ if (existingEntry.filePath === filePath) {
224
+ return existingEntry.manager;
225
+ }
226
+ existingEntry.manager.stop();
227
+ }
228
+ const loaded = await loadBindingsFromDisk(filePath, params.accountId);
229
+ for (const record of loaded) {
230
+ setBindingRecord(record);
231
+ }
232
+
233
+ let persistQueue: Promise<void> = Promise.resolve();
234
+ const enqueuePersist = (bindings?: MatrixThreadBindingRecord[]) => {
235
+ const snapshot = bindings ?? listBindingsForAccount(params.accountId);
236
+ const next = persistQueue
237
+ .catch(() => {})
238
+ .then(async () => {
239
+ await persistBindingsSnapshot(filePath, snapshot);
240
+ });
241
+ persistQueue = next;
242
+ return next;
243
+ };
244
+ const persist = async () => await enqueuePersist();
245
+ const persistSafely = (reason: string, bindings?: MatrixThreadBindingRecord[]) => {
246
+ void enqueuePersist(bindings).catch((err) => {
247
+ params.logVerboseMessage?.(
248
+ `matrix: failed persisting thread bindings account=${params.accountId} action=${reason}: ${String(err)}`,
249
+ );
250
+ });
251
+ };
252
+ const defaults = {
253
+ idleTimeoutMs: params.idleTimeoutMs,
254
+ maxAgeMs: params.maxAgeMs,
255
+ };
256
+ let persistTimer: NodeJS.Timeout | null = null;
257
+ const schedulePersist = (delayMs: number) => {
258
+ if (persistTimer) {
259
+ return;
260
+ }
261
+ persistTimer = setTimeout(() => {
262
+ persistTimer = null;
263
+ persistSafely("delayed-touch");
264
+ }, delayMs);
265
+ persistTimer.unref?.();
266
+ };
267
+ const updateBindingsBySessionKey = (input: {
268
+ targetSessionKey: string;
269
+ update: (entry: MatrixThreadBindingRecord, now: number) => MatrixThreadBindingRecord;
270
+ persistReason: string;
271
+ }): MatrixThreadBindingRecord[] => {
272
+ const targetSessionKey = input.targetSessionKey.trim();
273
+ if (!targetSessionKey) {
274
+ return [];
275
+ }
276
+ const now = Date.now();
277
+ const nextBindings = listBindingsForAccount(params.accountId)
278
+ .filter((entry) => entry.targetSessionKey === targetSessionKey)
279
+ .map((entry) => input.update(entry, now));
280
+ if (nextBindings.length === 0) {
281
+ return [];
282
+ }
283
+ for (const entry of nextBindings) {
284
+ setBindingRecord(entry);
285
+ }
286
+ persistSafely(input.persistReason);
287
+ return nextBindings;
288
+ };
289
+
290
+ const manager: MatrixThreadBindingManager = {
291
+ accountId: params.accountId,
292
+ getIdleTimeoutMs: () => defaults.idleTimeoutMs,
293
+ getMaxAgeMs: () => defaults.maxAgeMs,
294
+ persist,
295
+ getByConversation: ({ conversationId, parentConversationId }) =>
296
+ listBindingsForAccount(params.accountId).find((entry) => {
297
+ if (entry.conversationId !== conversationId.trim()) {
298
+ return false;
299
+ }
300
+ if (!parentConversationId) {
301
+ return true;
302
+ }
303
+ return (entry.parentConversationId ?? "") === parentConversationId.trim();
304
+ }),
305
+ listBySessionKey: (targetSessionKey) =>
306
+ listBindingsForAccount(params.accountId).filter(
307
+ (entry) => entry.targetSessionKey === targetSessionKey.trim(),
308
+ ),
309
+ listBindings: () => listBindingsForAccount(params.accountId),
310
+ touchBinding: (bindingId, at) => {
311
+ const record = listBindingsForAccount(params.accountId).find(
312
+ (entry) => resolveBindingKey(entry) === bindingId.trim(),
313
+ );
314
+ if (!record) {
315
+ return null;
316
+ }
317
+ const nextRecord = {
318
+ ...record,
319
+ lastActivityAt:
320
+ typeof at === "number" && Number.isFinite(at)
321
+ ? Math.max(record.lastActivityAt, Math.floor(at))
322
+ : Date.now(),
323
+ };
324
+ setBindingRecord(nextRecord);
325
+ schedulePersist(TOUCH_PERSIST_DELAY_MS);
326
+ return nextRecord;
327
+ },
328
+ setIdleTimeoutBySessionKey: ({ targetSessionKey, idleTimeoutMs }) => {
329
+ return updateBindingsBySessionKey({
330
+ targetSessionKey,
331
+ persistReason: "idle-timeout-update",
332
+ update: (entry, now) => ({
333
+ ...entry,
334
+ idleTimeoutMs: Math.max(0, Math.floor(idleTimeoutMs)),
335
+ lastActivityAt: now,
336
+ }),
337
+ });
338
+ },
339
+ setMaxAgeBySessionKey: ({ targetSessionKey, maxAgeMs }) => {
340
+ return updateBindingsBySessionKey({
341
+ targetSessionKey,
342
+ persistReason: "max-age-update",
343
+ update: (entry, now) => ({
344
+ ...entry,
345
+ maxAgeMs: Math.max(0, Math.floor(maxAgeMs)),
346
+ lastActivityAt: now,
347
+ }),
348
+ });
349
+ },
350
+ stop: () => {
351
+ if (sweepTimer) {
352
+ clearInterval(sweepTimer);
353
+ }
354
+ if (persistTimer) {
355
+ clearTimeout(persistTimer);
356
+ persistTimer = null;
357
+ persistSafely("shutdown-flush");
358
+ }
359
+ unregisterSessionBindingAdapter({
360
+ channel: "matrix",
361
+ accountId: params.accountId,
362
+ adapter: sessionBindingAdapter,
363
+ });
364
+ if (getMatrixThreadBindingManagerEntry(params.accountId)?.manager === manager) {
365
+ deleteMatrixThreadBindingManagerEntry(params.accountId);
366
+ }
367
+ for (const record of listBindingsForAccount(params.accountId)) {
368
+ removeBindingRecord(record);
369
+ }
370
+ },
371
+ };
372
+
373
+ let sweepTimer: NodeJS.Timeout | null = null;
374
+ const removeRecords = (records: MatrixThreadBindingRecord[]) => {
375
+ if (records.length === 0) {
376
+ return [];
377
+ }
378
+ return records
379
+ .map((record) => removeBindingRecord(record))
380
+ .filter((record): record is MatrixThreadBindingRecord => Boolean(record));
381
+ };
382
+ const sendFarewellMessages = async (
383
+ removed: MatrixThreadBindingRecord[],
384
+ reason: string | ((record: MatrixThreadBindingRecord) => string | undefined),
385
+ ) => {
386
+ await Promise.all(
387
+ removed.map(async (record) => {
388
+ await sendFarewellMessage({
389
+ cfg: params.cfg,
390
+ client: params.client,
391
+ accountId: params.accountId,
392
+ record,
393
+ defaultIdleTimeoutMs: defaults.idleTimeoutMs,
394
+ defaultMaxAgeMs: defaults.maxAgeMs,
395
+ reason: typeof reason === "function" ? reason(record) : reason,
396
+ });
397
+ }),
398
+ );
399
+ };
400
+ const unbindRecords = async (records: MatrixThreadBindingRecord[], reason: string) => {
401
+ const removed = removeRecords(records);
402
+ if (removed.length === 0) {
403
+ return [];
404
+ }
405
+ await persist();
406
+ await sendFarewellMessages(removed, reason);
407
+ return removed.map((record) => toSessionBindingRecord(record, defaults));
408
+ };
409
+
410
+ const sessionBindingAdapter: SessionBindingAdapter = {
411
+ channel: "matrix",
412
+ accountId: params.accountId,
413
+ capabilities: { placements: ["current", "child"], bindSupported: true, unbindSupported: true },
414
+ bind: async (input) => {
415
+ const conversationId = input.conversation.conversationId.trim();
416
+ const parentConversationId = normalizeOptionalString(input.conversation.parentConversationId);
417
+ const targetSessionKey = input.targetSessionKey.trim();
418
+ if (!conversationId || !targetSessionKey) {
419
+ return null;
420
+ }
421
+
422
+ let boundConversationId = conversationId;
423
+ let boundParentConversationId = parentConversationId;
424
+ const introText = buildMatrixBindingIntroText({
425
+ metadata: input.metadata,
426
+ targetSessionKey,
427
+ });
428
+
429
+ if (input.placement === "child") {
430
+ const roomId = parentConversationId || conversationId;
431
+ const rootEventId = await sendBindingMessage({
432
+ cfg: params.cfg,
433
+ client: params.client,
434
+ accountId: params.accountId,
435
+ roomId,
436
+ text: introText,
437
+ });
438
+ if (!rootEventId) {
439
+ return null;
440
+ }
441
+ boundConversationId = rootEventId;
442
+ boundParentConversationId = roomId;
443
+ }
444
+
445
+ const now = Date.now();
446
+ const record: MatrixThreadBindingRecord = {
447
+ accountId: params.accountId,
448
+ conversationId: boundConversationId,
449
+ ...(boundParentConversationId ? { parentConversationId: boundParentConversationId } : {}),
450
+ targetKind: toMatrixBindingTargetKind(input.targetKind),
451
+ targetSessionKey,
452
+ agentId:
453
+ normalizeOptionalString(input.metadata?.agentId) ||
454
+ resolveAgentIdFromSessionKey(targetSessionKey),
455
+ label: normalizeOptionalString(input.metadata?.label) || undefined,
456
+ boundBy: normalizeOptionalString(input.metadata?.boundBy) || "system",
457
+ boundAt: now,
458
+ lastActivityAt: now,
459
+ idleTimeoutMs: defaults.idleTimeoutMs,
460
+ maxAgeMs: defaults.maxAgeMs,
461
+ };
462
+ setBindingRecord(record);
463
+ await persist();
464
+
465
+ if (input.placement === "current" && introText) {
466
+ const roomId = boundParentConversationId || boundConversationId;
467
+ const threadId =
468
+ boundParentConversationId && boundParentConversationId !== boundConversationId
469
+ ? boundConversationId
470
+ : undefined;
471
+ await sendBindingMessage({
472
+ cfg: params.cfg,
473
+ client: params.client,
474
+ accountId: params.accountId,
475
+ roomId,
476
+ threadId,
477
+ text: introText,
478
+ }).catch(() => {});
479
+ }
480
+
481
+ return toSessionBindingRecord(record, defaults);
482
+ },
483
+ listBySession: (targetSessionKey) =>
484
+ manager
485
+ .listBySessionKey(targetSessionKey)
486
+ .map((record) => toSessionBindingRecord(record, defaults)),
487
+ resolveByConversation: (ref) => {
488
+ const record = manager.getByConversation({
489
+ conversationId: ref.conversationId,
490
+ parentConversationId: ref.parentConversationId,
491
+ });
492
+ return record ? toSessionBindingRecord(record, defaults) : null;
493
+ },
494
+ touch: (bindingId, at) => {
495
+ manager.touchBinding(bindingId, at);
496
+ },
497
+ unbind: async (input) => {
498
+ const removed = await unbindRecords(
499
+ listBindingsForAccount(params.accountId).filter((record) => {
500
+ if (input.bindingId?.trim()) {
501
+ return resolveBindingKey(record) === input.bindingId.trim();
502
+ }
503
+ if (input.targetSessionKey?.trim()) {
504
+ return record.targetSessionKey === input.targetSessionKey.trim();
505
+ }
506
+ return false;
507
+ }),
508
+ input.reason,
509
+ );
510
+ return removed;
511
+ },
512
+ };
513
+
514
+ registerSessionBindingAdapter(sessionBindingAdapter);
515
+
516
+ if (params.enableSweeper !== false) {
517
+ sweepTimer = setInterval(() => {
518
+ const now = Date.now();
519
+ const expired = listBindingsForAccount(params.accountId)
520
+ .map((record) => ({
521
+ record,
522
+ lifecycle: resolveEffectiveBindingExpiry({
523
+ record,
524
+ defaultIdleTimeoutMs: defaults.idleTimeoutMs,
525
+ defaultMaxAgeMs: defaults.maxAgeMs,
526
+ }),
527
+ }))
528
+ .filter(
529
+ (
530
+ entry,
531
+ ): entry is {
532
+ record: MatrixThreadBindingRecord;
533
+ lifecycle: { expiresAt: number; reason: "idle-expired" | "max-age-expired" };
534
+ } =>
535
+ typeof entry.lifecycle.expiresAt === "number" &&
536
+ entry.lifecycle.expiresAt <= now &&
537
+ Boolean(entry.lifecycle.reason),
538
+ );
539
+ if (expired.length === 0) {
540
+ return;
541
+ }
542
+ const reasonByBindingKey = new Map(
543
+ expired.map(({ record, lifecycle }) => [resolveBindingKey(record), lifecycle.reason]),
544
+ );
545
+ void (async () => {
546
+ const removed = removeRecords(expired.map(({ record }) => record));
547
+ if (removed.length === 0) {
548
+ return;
549
+ }
550
+ for (const record of removed) {
551
+ const reason = reasonByBindingKey.get(resolveBindingKey(record));
552
+ params.logVerboseMessage?.(
553
+ `matrix: auto-unbinding ${record.conversationId} due to ${reason}`,
554
+ );
555
+ }
556
+ await persist();
557
+ await sendFarewellMessages(removed, (record) =>
558
+ reasonByBindingKey.get(resolveBindingKey(record)),
559
+ );
560
+ })().catch((err) => {
561
+ params.logVerboseMessage?.(
562
+ `matrix: failed auto-unbinding expired bindings account=${params.accountId}: ${String(err)}`,
563
+ );
564
+ });
565
+ }, THREAD_BINDINGS_SWEEP_INTERVAL_MS);
566
+ sweepTimer.unref?.();
567
+ }
568
+
569
+ setMatrixThreadBindingManagerEntry(params.accountId, {
570
+ filePath,
571
+ manager,
572
+ });
573
+ return manager;
574
+ }
575
+ export {
576
+ getMatrixThreadBindingManager,
577
+ resetMatrixThreadBindingsForTests,
578
+ setMatrixThreadBindingIdleTimeoutBySessionKey,
579
+ setMatrixThreadBindingMaxAgeBySessionKey,
580
+ };
@@ -0,0 +1,9 @@
1
+ export { autoMigrateLegacyMatrixState, detectLegacyMatrixState } from "./legacy-state.js";
2
+ export { autoPrepareLegacyMatrixCrypto, detectLegacyMatrixCrypto } from "./legacy-crypto.js";
3
+ export {
4
+ hasActionableMatrixMigration,
5
+ hasPendingMatrixMigration,
6
+ resolveMatrixMigrationStatus,
7
+ type MatrixMigrationStatus,
8
+ } from "./migration-snapshot.js";
9
+ export { maybeCreateMatrixMigrationSnapshot } from "./migration-snapshot-backup.js";