@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,349 +0,0 @@
1
- import { KeyedAsyncQueue } from "klaw/plugin-sdk/keyed-async-queue";
2
- import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
3
- import { inspectMatrixDirectRoomEvidence } from "./direct-room.js";
4
- import type { MatrixClient } from "./sdk.js";
5
- import { EventType, type MatrixDirectAccountData } from "./send/types.js";
6
- import { isMatrixQualifiedUserId } from "./target-ids.js";
7
-
8
- export type MatrixDirectRoomCandidate = {
9
- roomId: string;
10
- joinedMembers: string[] | null;
11
- strict: boolean;
12
- explicit: boolean;
13
- source: "account-data" | "joined";
14
- };
15
-
16
- export type MatrixDirectRoomInspection = {
17
- selfUserId: string | null;
18
- remoteUserId: string;
19
- mappedRoomIds: string[];
20
- mappedRooms: MatrixDirectRoomCandidate[];
21
- discoveredStrictRoomIds: string[];
22
- activeRoomId: string | null;
23
- };
24
-
25
- export type MatrixDirectRoomRepairResult = MatrixDirectRoomInspection & {
26
- createdRoomId: string | null;
27
- changed: boolean;
28
- directContentBefore: MatrixDirectAccountData;
29
- directContentAfter: MatrixDirectAccountData;
30
- };
31
-
32
- export type MatrixDirectRoomPromotionResult =
33
- | {
34
- classifyAsDirect: true;
35
- repaired: boolean;
36
- roomId: string;
37
- reason: "promoted" | "already-mapped" | "repair-failed";
38
- }
39
- | {
40
- classifyAsDirect: false;
41
- repaired: false;
42
- reason: "not-strict" | "local-explicit-false";
43
- };
44
-
45
- type MatrixDirectRoomMappingWriteResult = {
46
- changed: boolean;
47
- directContentBefore: MatrixDirectAccountData;
48
- directContentAfter: MatrixDirectAccountData;
49
- };
50
-
51
- const DIRECT_ACCOUNT_DATA_QUEUE_KEY = EventType.Direct;
52
- const directAccountDataWriteQueues = new WeakMap<MatrixClient, KeyedAsyncQueue>();
53
-
54
- async function readMatrixDirectAccountData(client: MatrixClient): Promise<MatrixDirectAccountData> {
55
- try {
56
- const direct = (await client.getAccountData(EventType.Direct)) as MatrixDirectAccountData;
57
- return direct && typeof direct === "object" && !Array.isArray(direct) ? direct : {};
58
- } catch {
59
- return {};
60
- }
61
- }
62
-
63
- function normalizeRemoteUserId(remoteUserId: string): string {
64
- const normalized = normalizeOptionalString(remoteUserId) ?? "";
65
- if (!isMatrixQualifiedUserId(normalized)) {
66
- throw new Error(`Matrix user IDs must be fully qualified (got "${remoteUserId}")`);
67
- }
68
- return normalized;
69
- }
70
-
71
- function normalizeMappedRoomIds(direct: MatrixDirectAccountData, remoteUserId: string): string[] {
72
- const current = direct[remoteUserId];
73
- if (!Array.isArray(current)) {
74
- return [];
75
- }
76
- const seen = new Set<string>();
77
- const normalized: string[] = [];
78
- for (const value of current) {
79
- const roomId = normalizeOptionalString(value) ?? "";
80
- if (!roomId || seen.has(roomId)) {
81
- continue;
82
- }
83
- seen.add(roomId);
84
- normalized.push(roomId);
85
- }
86
- return normalized;
87
- }
88
-
89
- function normalizeRoomIdList(values: readonly string[]): string[] {
90
- const seen = new Set<string>();
91
- const normalized: string[] = [];
92
- for (const value of values) {
93
- const roomId = value.trim();
94
- if (!roomId || seen.has(roomId)) {
95
- continue;
96
- }
97
- seen.add(roomId);
98
- normalized.push(roomId);
99
- }
100
- return normalized;
101
- }
102
-
103
- function hasMatrixDirectRoomMappings(params: {
104
- directContent: MatrixDirectAccountData;
105
- remoteUserId: string;
106
- roomIds: readonly string[];
107
- }): boolean {
108
- const current = normalizeMappedRoomIds(params.directContent, params.remoteUserId);
109
- const next = normalizeRoomIdList([...params.roomIds, ...current]);
110
- return current.length === next.length && current.every((roomId, index) => roomId === next[index]);
111
- }
112
-
113
- function resolveDirectAccountDataWriteQueue(client: MatrixClient): KeyedAsyncQueue {
114
- const existing = directAccountDataWriteQueues.get(client);
115
- if (existing) {
116
- return existing;
117
- }
118
- const created = new KeyedAsyncQueue();
119
- directAccountDataWriteQueues.set(client, created);
120
- return created;
121
- }
122
-
123
- async function writeMatrixDirectRoomMappings(params: {
124
- client: MatrixClient;
125
- remoteUserId: string;
126
- roomIds: readonly string[];
127
- }): Promise<MatrixDirectRoomMappingWriteResult> {
128
- return await resolveDirectAccountDataWriteQueue(params.client).enqueue(
129
- DIRECT_ACCOUNT_DATA_QUEUE_KEY,
130
- async () => {
131
- const directContentBefore = await readMatrixDirectAccountData(params.client);
132
- const directContentAfter = buildNextDirectContent({
133
- directContent: directContentBefore,
134
- remoteUserId: params.remoteUserId,
135
- roomIds: params.roomIds,
136
- });
137
- const changed = !hasMatrixDirectRoomMappings({
138
- directContent: directContentBefore,
139
- remoteUserId: params.remoteUserId,
140
- roomIds: params.roomIds,
141
- });
142
- if (changed) {
143
- await params.client.setAccountData(EventType.Direct, directContentAfter);
144
- }
145
- return {
146
- changed,
147
- directContentBefore,
148
- directContentAfter,
149
- };
150
- },
151
- );
152
- }
153
-
154
- async function classifyDirectRoomCandidate(params: {
155
- client: MatrixClient;
156
- roomId: string;
157
- remoteUserId: string;
158
- selfUserId: string | null;
159
- source: "account-data" | "joined";
160
- }): Promise<MatrixDirectRoomCandidate> {
161
- const evidence = await inspectMatrixDirectRoomEvidence({
162
- client: params.client,
163
- roomId: params.roomId,
164
- remoteUserId: params.remoteUserId,
165
- selfUserId: params.selfUserId,
166
- });
167
- return {
168
- roomId: params.roomId,
169
- joinedMembers: evidence.joinedMembers,
170
- strict:
171
- evidence.strict && (params.source === "account-data" || evidence.memberStateFlag !== false),
172
- explicit:
173
- evidence.strict &&
174
- (params.source === "account-data" || evidence.memberStateFlag !== false) &&
175
- (params.source === "account-data" || evidence.viaMemberState),
176
- source: params.source,
177
- };
178
- }
179
-
180
- function buildNextDirectContent(params: {
181
- directContent: MatrixDirectAccountData;
182
- remoteUserId: string;
183
- roomIds: readonly string[];
184
- }): MatrixDirectAccountData {
185
- const current = normalizeMappedRoomIds(params.directContent, params.remoteUserId);
186
- const nextRooms = normalizeRoomIdList([...params.roomIds, ...current]);
187
- return {
188
- ...params.directContent,
189
- [params.remoteUserId]: nextRooms,
190
- };
191
- }
192
-
193
- export async function persistMatrixDirectRoomMapping(params: {
194
- client: MatrixClient;
195
- remoteUserId: string;
196
- roomId: string;
197
- }): Promise<boolean> {
198
- const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
199
- return (
200
- await writeMatrixDirectRoomMappings({
201
- client: params.client,
202
- remoteUserId,
203
- roomIds: [params.roomId],
204
- })
205
- ).changed;
206
- }
207
-
208
- export async function promoteMatrixDirectRoomCandidate(params: {
209
- client: MatrixClient;
210
- remoteUserId: string;
211
- roomId: string;
212
- selfUserId?: string | null;
213
- }): Promise<MatrixDirectRoomPromotionResult> {
214
- const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
215
- const evidence = await inspectMatrixDirectRoomEvidence({
216
- client: params.client,
217
- roomId: params.roomId,
218
- remoteUserId,
219
- selfUserId: params.selfUserId,
220
- });
221
- if (!evidence.strict) {
222
- return {
223
- classifyAsDirect: false,
224
- repaired: false,
225
- reason: "not-strict",
226
- };
227
- }
228
- if (evidence.memberStateFlag === false) {
229
- return {
230
- classifyAsDirect: false,
231
- repaired: false,
232
- reason: "local-explicit-false",
233
- };
234
- }
235
-
236
- try {
237
- const repaired = await persistMatrixDirectRoomMapping({
238
- client: params.client,
239
- remoteUserId,
240
- roomId: params.roomId,
241
- });
242
- return {
243
- classifyAsDirect: true,
244
- repaired,
245
- roomId: params.roomId,
246
- reason: repaired ? "promoted" : "already-mapped",
247
- };
248
- } catch {
249
- return {
250
- classifyAsDirect: true,
251
- repaired: false,
252
- roomId: params.roomId,
253
- reason: "repair-failed",
254
- };
255
- }
256
- }
257
-
258
- export async function inspectMatrixDirectRooms(params: {
259
- client: MatrixClient;
260
- remoteUserId: string;
261
- }): Promise<MatrixDirectRoomInspection> {
262
- const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
263
- const selfUserId =
264
- normalizeOptionalString(await params.client.getUserId().catch(() => null)) ?? null;
265
- const directContent = await readMatrixDirectAccountData(params.client);
266
- const mappedRoomIds = normalizeMappedRoomIds(directContent, remoteUserId);
267
- const mappedRooms = await Promise.all(
268
- mappedRoomIds.map(
269
- async (roomId) =>
270
- await classifyDirectRoomCandidate({
271
- client: params.client,
272
- roomId,
273
- remoteUserId,
274
- selfUserId,
275
- source: "account-data",
276
- }),
277
- ),
278
- );
279
- const mappedStrict = mappedRooms.find((room) => room.strict);
280
-
281
- let joinedRooms: string[] = [];
282
- if (typeof params.client.getJoinedRooms === "function") {
283
- try {
284
- const resolved = await params.client.getJoinedRooms();
285
- joinedRooms = Array.isArray(resolved) ? resolved : [];
286
- } catch {
287
- joinedRooms = [];
288
- }
289
- }
290
- const discoveredStrictRooms: MatrixDirectRoomCandidate[] = [];
291
- for (const roomId of normalizeRoomIdList(joinedRooms)) {
292
- if (mappedRoomIds.includes(roomId)) {
293
- continue;
294
- }
295
- const candidate = await classifyDirectRoomCandidate({
296
- client: params.client,
297
- roomId,
298
- remoteUserId,
299
- selfUserId,
300
- source: "joined",
301
- });
302
- if (candidate.strict) {
303
- discoveredStrictRooms.push(candidate);
304
- }
305
- }
306
- const discoveredStrictRoomIds = discoveredStrictRooms.map((room) => room.roomId);
307
- const discoveredExplicit = discoveredStrictRooms.find((room) => room.explicit);
308
-
309
- return {
310
- selfUserId,
311
- remoteUserId,
312
- mappedRoomIds,
313
- mappedRooms,
314
- discoveredStrictRoomIds,
315
- activeRoomId:
316
- mappedStrict?.roomId ?? discoveredExplicit?.roomId ?? discoveredStrictRoomIds[0] ?? null,
317
- };
318
- }
319
-
320
- export async function repairMatrixDirectRooms(params: {
321
- client: MatrixClient;
322
- remoteUserId: string;
323
- encrypted?: boolean;
324
- }): Promise<MatrixDirectRoomRepairResult> {
325
- const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
326
- const inspected = await inspectMatrixDirectRooms({
327
- client: params.client,
328
- remoteUserId,
329
- });
330
- const activeRoomId =
331
- inspected.activeRoomId ??
332
- (await params.client.createDirectRoom(remoteUserId, {
333
- encrypted: params.encrypted === true,
334
- }));
335
- const createdRoomId = inspected.activeRoomId ? null : activeRoomId;
336
- const mappingWrite = await writeMatrixDirectRoomMappings({
337
- client: params.client,
338
- remoteUserId,
339
- roomIds: [activeRoomId, ...inspected.discoveredStrictRoomIds],
340
- });
341
- return {
342
- ...inspected,
343
- activeRoomId,
344
- createdRoomId,
345
- changed: mappingWrite.changed,
346
- directContentBefore: mappingWrite.directContentBefore,
347
- directContentAfter: mappingWrite.directContentAfter,
348
- };
349
- }
@@ -1,128 +0,0 @@
1
- import type { MatrixClient } from "./sdk.js";
2
-
3
- function trimMaybeString(value: unknown): string | null {
4
- if (typeof value !== "string") {
5
- return null;
6
- }
7
- const trimmed = value.trim();
8
- return trimmed.length > 0 ? trimmed : null;
9
- }
10
-
11
- export function normalizeJoinedMatrixMembers(joinedMembers: unknown): string[] {
12
- if (!Array.isArray(joinedMembers)) {
13
- return [];
14
- }
15
- return joinedMembers
16
- .map((entry) => trimMaybeString(entry))
17
- .filter((entry): entry is string => Boolean(entry));
18
- }
19
-
20
- export function isStrictDirectMembership(params: {
21
- selfUserId?: string | null;
22
- remoteUserId?: string | null;
23
- joinedMembers?: readonly string[] | null;
24
- }): boolean {
25
- const selfUserId = trimMaybeString(params.selfUserId);
26
- const remoteUserId = trimMaybeString(params.remoteUserId);
27
- const joinedMembers = params.joinedMembers ?? [];
28
- return Boolean(
29
- selfUserId &&
30
- remoteUserId &&
31
- joinedMembers.length === 2 &&
32
- joinedMembers.includes(selfUserId) &&
33
- joinedMembers.includes(remoteUserId),
34
- );
35
- }
36
-
37
- export async function readJoinedMatrixMembers(
38
- client: MatrixClient,
39
- roomId: string,
40
- ): Promise<string[] | null> {
41
- try {
42
- return normalizeJoinedMatrixMembers(await client.getJoinedRoomMembers(roomId));
43
- } catch {
44
- return null;
45
- }
46
- }
47
-
48
- export async function hasDirectMatrixMemberFlag(
49
- client: MatrixClient,
50
- roomId: string,
51
- userId?: string | null,
52
- ): Promise<boolean | null> {
53
- const normalizedUserId = trimMaybeString(userId);
54
- if (!normalizedUserId) {
55
- return null;
56
- }
57
- try {
58
- const state = await client.getRoomStateEvent(roomId, "m.room.member", normalizedUserId);
59
- // Return true if is_direct is explicitly true, false if explicitly false, null if absent
60
- if (state?.is_direct === true) {
61
- return true;
62
- }
63
- if (state?.is_direct === false) {
64
- return false;
65
- }
66
- // is_direct field is absent from the membership event
67
- return null;
68
- } catch {
69
- // API/network error - treat as unavailable
70
- return null;
71
- }
72
- }
73
-
74
- export type MatrixDirectRoomEvidence = {
75
- joinedMembers: string[] | null;
76
- strict: boolean;
77
- viaMemberState: boolean;
78
- memberStateFlag: boolean | null;
79
- };
80
-
81
- export async function inspectMatrixDirectRoomEvidence(params: {
82
- client: MatrixClient;
83
- roomId: string;
84
- remoteUserId: string;
85
- selfUserId?: string | null;
86
- }): Promise<MatrixDirectRoomEvidence> {
87
- const selfUserId =
88
- params.selfUserId !== undefined
89
- ? trimMaybeString(params.selfUserId)
90
- : trimMaybeString(await params.client.getUserId().catch(() => null));
91
- const joinedMembers = await readJoinedMatrixMembers(params.client, params.roomId);
92
- const strict = isStrictDirectMembership({
93
- selfUserId,
94
- remoteUserId: params.remoteUserId,
95
- joinedMembers,
96
- });
97
- if (!strict) {
98
- return {
99
- joinedMembers,
100
- strict: false,
101
- viaMemberState: false,
102
- memberStateFlag: null,
103
- };
104
- }
105
- const memberStateFlag = await hasDirectMatrixMemberFlag(params.client, params.roomId, selfUserId);
106
- return {
107
- joinedMembers,
108
- strict,
109
- viaMemberState: memberStateFlag === true,
110
- memberStateFlag,
111
- };
112
- }
113
-
114
- export async function isStrictDirectRoom(params: {
115
- client: MatrixClient;
116
- roomId: string;
117
- remoteUserId: string;
118
- selfUserId?: string | null;
119
- }): Promise<boolean> {
120
- return (
121
- await inspectMatrixDirectRoomEvidence({
122
- client: params.client,
123
- roomId: params.roomId,
124
- remoteUserId: params.remoteUserId,
125
- selfUserId: params.selfUserId,
126
- })
127
- ).strict;
128
- }
@@ -1,225 +0,0 @@
1
- import { createDraftStreamLoop } from "klaw/plugin-sdk/channel-lifecycle";
2
- import type { CoreConfig } from "../types.js";
3
- import type { MatrixClient } from "./sdk.js";
4
- import { editMessageMatrix, prepareMatrixSingleText, sendSingleTextMessageMatrix } from "./send.js";
5
- import { MsgType } from "./send/types.js";
6
-
7
- const DEFAULT_THROTTLE_MS = 1000;
8
- type MatrixDraftPreviewMode = "partial" | "quiet";
9
-
10
- function resolveDraftPreviewOptions(mode: MatrixDraftPreviewMode): {
11
- msgtype: typeof MsgType.Text | typeof MsgType.Notice;
12
- includeMentions?: boolean;
13
- } {
14
- if (mode === "quiet") {
15
- return {
16
- msgtype: MsgType.Notice,
17
- includeMentions: false,
18
- };
19
- }
20
- return {
21
- msgtype: MsgType.Text,
22
- };
23
- }
24
-
25
- export type MatrixDraftStream = {
26
- /** Update the draft with the latest accumulated text for the current block. */
27
- update: (text: string) => void;
28
- /** Ensure the last pending update has been sent. */
29
- flush: () => Promise<void>;
30
- /** Flush and mark this block as done. Returns the event ID if a message was sent. */
31
- stop: () => Promise<string | undefined>;
32
- /** Cancel pending draft updates without creating a new preview event. */
33
- discardPending: () => Promise<void>;
34
- /** Clear the MSC4357 live marker in place when the draft is kept as final text. */
35
- finalizeLive: () => Promise<boolean>;
36
- /** Reset state for the next text block (after tool calls). */
37
- reset: () => void;
38
- /** The event ID of the current draft message, if any. */
39
- eventId: () => string | undefined;
40
- /** True when the provided text matches the last rendered draft payload. */
41
- matchesPreparedText: (text: string) => boolean;
42
- /** True when preview streaming must fall back to normal final delivery. */
43
- mustDeliverFinalNormally: () => boolean;
44
- };
45
-
46
- export function createMatrixDraftStream(params: {
47
- roomId: string;
48
- client: MatrixClient;
49
- cfg: CoreConfig;
50
- mode?: MatrixDraftPreviewMode;
51
- threadId?: string;
52
- replyToId?: string;
53
- /** When true, reset() restores the original replyToId instead of clearing it. */
54
- preserveReplyId?: boolean;
55
- accountId?: string;
56
- log?: (message: string) => void;
57
- }): MatrixDraftStream {
58
- const { roomId, client, cfg, threadId, accountId, log } = params;
59
- const preview = resolveDraftPreviewOptions(params.mode ?? "partial");
60
- // MSC4357 live markers are only useful for "partial" mode where users see
61
- // the draft evolve. "quiet" mode uses m.notice for background previews
62
- // where a streaming animation would be unexpected.
63
- const useLive = params.mode !== "quiet";
64
-
65
- let currentEventId: string | undefined;
66
- let lastSentText = "";
67
- let stopped = false;
68
- let sendFailed = false;
69
- let finalizeInPlaceBlocked = false;
70
- let liveFinalized = false;
71
- let replyToId = params.replyToId;
72
-
73
- const sendOrEdit = async (text: string): Promise<boolean> => {
74
- const trimmed = text.trimEnd();
75
- if (!trimmed) {
76
- return false;
77
- }
78
- const preparedText = prepareMatrixSingleText(trimmed, { cfg, accountId });
79
- if (!preparedText.fitsInSingleEvent) {
80
- finalizeInPlaceBlocked = true;
81
- if (!currentEventId) {
82
- sendFailed = true;
83
- }
84
- stopped = true;
85
- log?.(
86
- `draft-stream: preview exceeded single-event limit (${preparedText.convertedText.length} > ${preparedText.singleEventLimit})`,
87
- );
88
- return false;
89
- }
90
- if (sendFailed) {
91
- return false;
92
- }
93
- if (preparedText.trimmedText === lastSentText) {
94
- return true;
95
- }
96
- try {
97
- if (!currentEventId) {
98
- const result = await sendSingleTextMessageMatrix(roomId, preparedText.trimmedText, {
99
- client,
100
- cfg,
101
- replyToId,
102
- threadId,
103
- accountId,
104
- msgtype: preview.msgtype,
105
- includeMentions: preview.includeMentions,
106
- live: useLive,
107
- });
108
- currentEventId = result.messageId;
109
- lastSentText = preparedText.trimmedText;
110
- log?.(`draft-stream: created message ${currentEventId}${useLive ? " (MSC4357 live)" : ""}`);
111
- } else {
112
- await editMessageMatrix(roomId, currentEventId, preparedText.trimmedText, {
113
- client,
114
- cfg,
115
- threadId,
116
- accountId,
117
- msgtype: preview.msgtype,
118
- includeMentions: preview.includeMentions,
119
- live: useLive,
120
- });
121
- lastSentText = preparedText.trimmedText;
122
- }
123
- return true;
124
- } catch (err) {
125
- log?.(`draft-stream: send/edit failed: ${String(err)}`);
126
- const isPreviewLimitError =
127
- err instanceof Error && err.message.startsWith("Matrix single-message text exceeds limit");
128
- if (isPreviewLimitError) {
129
- finalizeInPlaceBlocked = true;
130
- }
131
- if (!currentEventId) {
132
- sendFailed = true;
133
- }
134
- stopped = true;
135
- return false;
136
- }
137
- };
138
-
139
- const loop = createDraftStreamLoop({
140
- throttleMs: DEFAULT_THROTTLE_MS,
141
- isStopped: () => stopped,
142
- sendOrEditStreamMessage: sendOrEdit,
143
- });
144
-
145
- log?.(`draft-stream: ready (throttleMs=${DEFAULT_THROTTLE_MS})`);
146
-
147
- const finalizeLive = async (): Promise<boolean> => {
148
- // Send a final edit without the MSC4357 live marker to signal that
149
- // the stream is complete. Supporting clients will stop the streaming
150
- // animation and display the final content.
151
- if (useLive && !liveFinalized && currentEventId && lastSentText) {
152
- liveFinalized = true;
153
- try {
154
- await editMessageMatrix(roomId, currentEventId, lastSentText, {
155
- client,
156
- cfg,
157
- threadId,
158
- accountId,
159
- msgtype: preview.msgtype,
160
- includeMentions: preview.includeMentions,
161
- live: false,
162
- });
163
- log?.(`draft-stream: finalized ${currentEventId} (MSC4357 stream ended)`);
164
- return true;
165
- } catch (err) {
166
- log?.(`draft-stream: finalize edit failed: ${String(err)}`);
167
- // If the finalize edit fails, the live marker remains on the last
168
- // successful edit. Flag the stream so callers can fall back to
169
- // normal final delivery or redaction instead of leaving the message
170
- // stuck in a "still streaming" state for MSC4357 clients.
171
- finalizeInPlaceBlocked = true;
172
- return false;
173
- }
174
- }
175
- return true;
176
- };
177
-
178
- const stop = async (): Promise<string | undefined> => {
179
- // Flush before marking stopped so the loop can drain pending text.
180
- await loop.flush();
181
- stopped = true;
182
- return currentEventId;
183
- };
184
-
185
- const discardPending = async (): Promise<void> => {
186
- stopped = true;
187
- loop.stop();
188
- await loop.waitForInFlight();
189
- };
190
-
191
- const reset = (): void => {
192
- // Clear reply context unless preserveReplyId is set (replyToMode "all"),
193
- // in which case subsequent blocks should keep replying to the original.
194
- replyToId = params.preserveReplyId ? params.replyToId : undefined;
195
- currentEventId = undefined;
196
- lastSentText = "";
197
- stopped = false;
198
- sendFailed = false;
199
- finalizeInPlaceBlocked = false;
200
- liveFinalized = false;
201
- loop.resetPending();
202
- loop.resetThrottleWindow();
203
- };
204
-
205
- return {
206
- update: (text: string) => {
207
- if (stopped) {
208
- return;
209
- }
210
- loop.update(text);
211
- },
212
- flush: loop.flush,
213
- stop,
214
- discardPending,
215
- finalizeLive,
216
- reset,
217
- eventId: () => currentEventId,
218
- matchesPreparedText: (text: string) =>
219
- prepareMatrixSingleText(text, {
220
- cfg,
221
- accountId,
222
- }).trimmedText === lastSentText,
223
- mustDeliverFinalNormally: () => sendFailed || finalizeInPlaceBlocked,
224
- };
225
- }