@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,660 +0,0 @@
1
- import {
2
- createMessageReceiptFromOutboundResults,
3
- type MessageReceiptPartKind,
4
- } from "klaw/plugin-sdk/channel-message";
5
- import type { MarkdownTableMode } from "klaw/plugin-sdk/markdown-table-runtime";
6
- import { requireRuntimeConfig } from "klaw/plugin-sdk/plugin-config-runtime";
7
- import type { PollInput } from "../runtime-api.js";
8
- import { getMatrixRuntime } from "../runtime.js";
9
- import type { CoreConfig } from "../types.js";
10
- import { loadOutboundMediaFromUrl } from "./outbound-media-runtime.js";
11
- import { buildPollStartContent, M_POLL_START } from "./poll-types.js";
12
- import { buildMatrixReactionContent } from "./reaction-common.js";
13
- import type { MatrixClient } from "./sdk.js";
14
- import {
15
- resolveMediaMaxBytes,
16
- withResolvedMatrixControlClient,
17
- withResolvedMatrixSendClient,
18
- } from "./send/client.js";
19
- import {
20
- buildReplyRelation,
21
- buildTextContent,
22
- buildThreadRelation,
23
- diffMatrixMentions,
24
- enrichMatrixFormattedContent,
25
- extractMatrixMentions,
26
- resolveMatrixMentionsForBody,
27
- resolveMatrixMsgType,
28
- resolveMatrixVoiceDecision,
29
- } from "./send/formatting.js";
30
- import {
31
- buildMediaContent,
32
- prepareImageInfo,
33
- resolveMediaDurationMs,
34
- uploadMediaMaybeEncrypted,
35
- } from "./send/media.js";
36
- import { normalizeThreadId, resolveMatrixRoomId } from "./send/targets.js";
37
- import {
38
- EventType,
39
- MSC4357_LIVE_KEY,
40
- MsgType,
41
- RelationType,
42
- type MatrixExtraContentFields,
43
- type MatrixOutboundContent,
44
- type MatrixSendOpts,
45
- type MatrixSendResult,
46
- type MatrixTextMsgType,
47
- } from "./send/types.js";
48
-
49
- const MATRIX_TEXT_LIMIT = 4000;
50
- const getCore = () => getMatrixRuntime();
51
-
52
- export type { MatrixSendOpts, MatrixSendResult } from "./send/types.js";
53
- export { resolveMatrixRoomId } from "./send/targets.js";
54
-
55
- export type MatrixPreparedSingleText = {
56
- trimmedText: string;
57
- convertedText: string;
58
- singleEventLimit: number;
59
- fitsInSingleEvent: boolean;
60
- };
61
-
62
- export type MatrixPreparedChunkedText = MatrixPreparedSingleText & {
63
- chunks: string[];
64
- };
65
-
66
- type MatrixClientResolveOpts = {
67
- client?: MatrixClient;
68
- cfg?: CoreConfig;
69
- timeoutMs?: number;
70
- accountId?: string | null;
71
- };
72
-
73
- function createMatrixSendReceipt(params: {
74
- roomId: string;
75
- platformMessageIds: readonly string[];
76
- kind: MessageReceiptPartKind;
77
- replyToId?: string;
78
- threadId?: string | null;
79
- }) {
80
- return createMessageReceiptFromOutboundResults({
81
- kind: params.kind,
82
- ...(params.replyToId ? { replyToId: params.replyToId } : {}),
83
- ...(params.threadId ? { threadId: params.threadId } : {}),
84
- results: params.platformMessageIds.map((messageId) => ({
85
- channel: "matrix",
86
- messageId,
87
- roomId: params.roomId,
88
- })),
89
- });
90
- }
91
-
92
- function isMatrixClient(value: MatrixClient | MatrixClientResolveOpts): value is MatrixClient {
93
- return typeof (value as { sendEvent?: unknown }).sendEvent === "function";
94
- }
95
-
96
- function normalizeMatrixClientResolveOpts(
97
- opts?: MatrixClient | MatrixClientResolveOpts,
98
- ): MatrixClientResolveOpts {
99
- if (!opts) {
100
- return {};
101
- }
102
- if (isMatrixClient(opts)) {
103
- return { client: opts };
104
- }
105
- return {
106
- client: opts.client,
107
- cfg: opts.cfg,
108
- timeoutMs: opts.timeoutMs,
109
- accountId: opts.accountId,
110
- };
111
- }
112
-
113
- function resolvePreviousEditContent(previousEvent: unknown): Record<string, unknown> | undefined {
114
- if (!previousEvent || typeof previousEvent !== "object") {
115
- return undefined;
116
- }
117
- const eventRecord = previousEvent as { content?: unknown };
118
- if (!eventRecord.content || typeof eventRecord.content !== "object") {
119
- return undefined;
120
- }
121
- const content = eventRecord.content as Record<string, unknown>;
122
- const newContent = content["m.new_content"];
123
- return newContent && typeof newContent === "object"
124
- ? (newContent as Record<string, unknown>)
125
- : content;
126
- }
127
-
128
- function hasMatrixMentionsMetadata(content: Record<string, unknown> | undefined): boolean {
129
- return Boolean(content && Object.hasOwn(content, "m.mentions"));
130
- }
131
-
132
- function withMatrixExtraContentFields<T extends Record<string, unknown>>(
133
- content: T,
134
- extraContent?: MatrixExtraContentFields,
135
- ): T {
136
- if (!extraContent) {
137
- return content;
138
- }
139
- return { ...content, ...extraContent };
140
- }
141
-
142
- async function resolvePreviousEditMentions(params: {
143
- client: MatrixClient;
144
- content: Record<string, unknown> | undefined;
145
- }) {
146
- if (hasMatrixMentionsMetadata(params.content)) {
147
- return extractMatrixMentions(params.content);
148
- }
149
- const body = typeof params.content?.body === "string" ? params.content.body : "";
150
- if (!body) {
151
- return {};
152
- }
153
- return await resolveMatrixMentionsForBody({
154
- client: params.client,
155
- body,
156
- });
157
- }
158
-
159
- export function prepareMatrixSingleText(
160
- text: string,
161
- opts: {
162
- cfg: CoreConfig;
163
- accountId?: string;
164
- tableMode?: MarkdownTableMode;
165
- },
166
- ): MatrixPreparedSingleText {
167
- const trimmedText = text.trim();
168
- const cfg = requireRuntimeConfig(opts.cfg, "Matrix text preparation") as CoreConfig;
169
- const tableMode =
170
- opts.tableMode ??
171
- getCore().channel.text.resolveMarkdownTableMode({
172
- cfg,
173
- channel: "matrix",
174
- accountId: opts.accountId,
175
- });
176
- const convertedText = getCore().channel.text.convertMarkdownTables(trimmedText, tableMode);
177
- const singleEventLimit = Math.min(
178
- getCore().channel.text.resolveTextChunkLimit(cfg, "matrix", opts.accountId),
179
- MATRIX_TEXT_LIMIT,
180
- );
181
- return {
182
- trimmedText,
183
- convertedText,
184
- singleEventLimit,
185
- fitsInSingleEvent: convertedText.length <= singleEventLimit,
186
- };
187
- }
188
-
189
- export function chunkMatrixText(
190
- text: string,
191
- opts: {
192
- cfg: CoreConfig;
193
- accountId?: string;
194
- tableMode?: MarkdownTableMode;
195
- },
196
- ): MatrixPreparedChunkedText {
197
- const preparedText = prepareMatrixSingleText(text, opts);
198
- const cfg = requireRuntimeConfig(opts.cfg, "Matrix text chunking") as CoreConfig;
199
- const chunkMode = getCore().channel.text.resolveChunkMode(cfg, "matrix", opts.accountId);
200
- return {
201
- ...preparedText,
202
- chunks: getCore().channel.text.chunkMarkdownTextWithMode(
203
- preparedText.convertedText,
204
- preparedText.singleEventLimit,
205
- chunkMode,
206
- ),
207
- };
208
- }
209
-
210
- export async function sendMessageMatrix(
211
- to: string,
212
- message: string | undefined,
213
- opts: MatrixSendOpts,
214
- ): Promise<MatrixSendResult> {
215
- const trimmedMessage = message?.trim() ?? "";
216
- if (!trimmedMessage && !opts.mediaUrl) {
217
- throw new Error("Matrix send requires text or media");
218
- }
219
- return await withResolvedMatrixSendClient(
220
- {
221
- client: opts.client,
222
- cfg: opts.cfg,
223
- timeoutMs: opts.timeoutMs,
224
- accountId: opts.accountId,
225
- },
226
- async (client) => {
227
- const roomId = await resolveMatrixRoomId(client, to);
228
- const cfg = requireRuntimeConfig(opts.cfg, "Matrix send") as CoreConfig;
229
- const { chunks } = chunkMatrixText(trimmedMessage, {
230
- cfg,
231
- accountId: opts.accountId,
232
- });
233
- const threadId = normalizeThreadId(opts.threadId);
234
- const relation = threadId
235
- ? buildThreadRelation(threadId, opts.replyToId)
236
- : buildReplyRelation(opts.replyToId);
237
- let pendingExtraContent = opts.extraContent;
238
- const sendContent = async (content: MatrixOutboundContent) => {
239
- const contentWithExtra = withMatrixExtraContentFields(content, pendingExtraContent);
240
- pendingExtraContent = undefined;
241
- const eventId = await client.sendMessage(roomId, contentWithExtra);
242
- return eventId;
243
- };
244
-
245
- const platformMessageIds: string[] = [];
246
- let lastMessageId = "";
247
- let receiptKind: MessageReceiptPartKind = "text";
248
- if (opts.mediaUrl) {
249
- const maxBytes = resolveMediaMaxBytes(opts.accountId, cfg);
250
- const media = await loadOutboundMediaFromUrl(opts.mediaUrl, {
251
- maxBytes,
252
- mediaAccess: opts.mediaAccess,
253
- mediaLocalRoots: opts.mediaLocalRoots,
254
- mediaReadFile: opts.mediaReadFile,
255
- });
256
- const uploaded = await uploadMediaMaybeEncrypted(client, roomId, media.buffer, {
257
- contentType: media.contentType,
258
- filename: media.fileName,
259
- });
260
- const durationMs = await resolveMediaDurationMs({
261
- buffer: media.buffer,
262
- contentType: media.contentType,
263
- fileName: media.fileName,
264
- kind: media.kind ?? "unknown",
265
- });
266
- const baseMsgType = resolveMatrixMsgType(media.contentType, media.fileName);
267
- const { useVoice } = resolveMatrixVoiceDecision({
268
- wantsVoice: opts.audioAsVoice === true,
269
- contentType: media.contentType,
270
- fileName: media.fileName,
271
- });
272
- const msgtype = useVoice ? MsgType.Audio : baseMsgType;
273
- receiptKind = useVoice ? "voice" : "media";
274
- const isImage = msgtype === MsgType.Image;
275
- const imageInfo = isImage
276
- ? await prepareImageInfo({
277
- buffer: media.buffer,
278
- client,
279
- encrypted: Boolean(uploaded.file),
280
- })
281
- : undefined;
282
- const [firstChunk, ...rest] = chunks;
283
- const captionMarkdown = useVoice ? "" : (firstChunk ?? "");
284
- const body = useVoice ? "Voice message" : captionMarkdown || media.fileName || "(file)";
285
- const content = buildMediaContent({
286
- msgtype,
287
- body,
288
- url: uploaded.url,
289
- file: uploaded.file,
290
- filename: media.fileName,
291
- mimetype: media.contentType,
292
- size: media.buffer.byteLength,
293
- durationMs,
294
- relation,
295
- isVoice: useVoice,
296
- imageInfo,
297
- });
298
- await enrichMatrixFormattedContent({
299
- client,
300
- content,
301
- markdown: captionMarkdown,
302
- });
303
- const eventId = await sendContent(content);
304
- lastMessageId = eventId ?? lastMessageId;
305
- if (eventId) {
306
- platformMessageIds.push(eventId);
307
- }
308
- const textChunks = useVoice ? chunks : rest;
309
- // Voice messages use a generic media body ("Voice message"), so keep any
310
- // transcript follow-up attached to the same reply/thread context.
311
- const followupRelation = useVoice || threadId ? relation : undefined;
312
- for (const chunk of textChunks) {
313
- const text = chunk.trim();
314
- if (!text) {
315
- continue;
316
- }
317
- const followup = buildTextContent(text, followupRelation);
318
- await enrichMatrixFormattedContent({
319
- client,
320
- content: followup,
321
- markdown: text,
322
- });
323
- const followupEventId = await sendContent(followup);
324
- lastMessageId = followupEventId ?? lastMessageId;
325
- if (followupEventId) {
326
- platformMessageIds.push(followupEventId);
327
- }
328
- }
329
- } else {
330
- for (const chunk of chunks.length ? chunks : [""]) {
331
- const text = chunk.trim();
332
- if (!text) {
333
- continue;
334
- }
335
- const content = buildTextContent(text, relation);
336
- await enrichMatrixFormattedContent({
337
- client,
338
- content,
339
- markdown: text,
340
- });
341
- const eventId = await sendContent(content);
342
- lastMessageId = eventId ?? lastMessageId;
343
- if (eventId) {
344
- platformMessageIds.push(eventId);
345
- }
346
- }
347
- }
348
-
349
- return {
350
- messageId: lastMessageId || "unknown",
351
- roomId,
352
- primaryMessageId: platformMessageIds[0] ?? (lastMessageId || "unknown"),
353
- receipt: createMatrixSendReceipt({
354
- roomId,
355
- platformMessageIds,
356
- kind: receiptKind,
357
- replyToId: opts.replyToId,
358
- threadId,
359
- }),
360
- };
361
- },
362
- );
363
- }
364
-
365
- export async function sendPollMatrix(
366
- to: string,
367
- poll: PollInput,
368
- opts: MatrixSendOpts,
369
- ): Promise<{ eventId: string; roomId: string }> {
370
- if (!poll.question?.trim()) {
371
- throw new Error("Matrix poll requires a question");
372
- }
373
- if (!poll.options?.length) {
374
- throw new Error("Matrix poll requires options");
375
- }
376
- return await withResolvedMatrixSendClient(
377
- {
378
- client: opts.client,
379
- cfg: opts.cfg,
380
- timeoutMs: opts.timeoutMs,
381
- accountId: opts.accountId,
382
- },
383
- async (client) => {
384
- const roomId = await resolveMatrixRoomId(client, to);
385
- const pollContent = buildPollStartContent(poll);
386
- const fallbackText =
387
- pollContent["m.text"] ?? pollContent["org.matrix.msc1767.text"] ?? poll.question ?? "";
388
- const mentions = await resolveMatrixMentionsForBody({
389
- client,
390
- body: fallbackText,
391
- });
392
- const threadId = normalizeThreadId(opts.threadId);
393
- const pollPayload: Record<string, unknown> = threadId
394
- ? { ...pollContent, "m.relates_to": buildThreadRelation(threadId) }
395
- : { ...pollContent };
396
- pollPayload["m.mentions"] = mentions;
397
- const eventId = await client.sendEvent(roomId, M_POLL_START, pollPayload);
398
-
399
- return {
400
- eventId: eventId ?? "unknown",
401
- roomId,
402
- };
403
- },
404
- );
405
- }
406
-
407
- export async function sendTypingMatrix(
408
- roomId: string,
409
- typing: boolean,
410
- optsOrTimeoutMs?: number | MatrixClientResolveOpts,
411
- client?: MatrixClient,
412
- ): Promise<void> {
413
- const opts =
414
- typeof optsOrTimeoutMs === "number"
415
- ? { timeoutMs: optsOrTimeoutMs, ...(client ? { client } : {}) }
416
- : {
417
- ...normalizeMatrixClientResolveOpts(optsOrTimeoutMs),
418
- ...(client ? { client } : {}),
419
- };
420
- await withResolvedMatrixControlClient(
421
- {
422
- client: opts.client,
423
- cfg: opts.cfg,
424
- timeoutMs: opts.timeoutMs,
425
- accountId: opts.accountId,
426
- },
427
- async (resolved) => {
428
- const resolvedRoom = await resolveMatrixRoomId(resolved, roomId);
429
- const resolvedTimeoutMs = typeof opts.timeoutMs === "number" ? opts.timeoutMs : 30_000;
430
- await resolved.setTyping(resolvedRoom, typing, resolvedTimeoutMs);
431
- },
432
- );
433
- }
434
-
435
- export async function sendReadReceiptMatrix(
436
- roomId: string,
437
- eventId: string,
438
- client?: MatrixClient,
439
- ): Promise<void> {
440
- if (!eventId?.trim()) {
441
- return;
442
- }
443
- await withResolvedMatrixControlClient({ client }, async (resolved) => {
444
- const resolvedRoom = await resolveMatrixRoomId(resolved, roomId);
445
- await resolved.sendReadReceipt(resolvedRoom, eventId.trim());
446
- });
447
- }
448
-
449
- export async function sendSingleTextMessageMatrix(
450
- roomId: string,
451
- text: string,
452
- opts: {
453
- client?: MatrixClient;
454
- cfg: CoreConfig;
455
- replyToId?: string;
456
- threadId?: string;
457
- accountId?: string;
458
- msgtype?: MatrixTextMsgType;
459
- includeMentions?: boolean;
460
- extraContent?: MatrixExtraContentFields;
461
- /** When true, marks the message as a live/streaming update (MSC4357). */
462
- live?: boolean;
463
- },
464
- ): Promise<MatrixSendResult> {
465
- const { trimmedText, convertedText, singleEventLimit, fitsInSingleEvent } =
466
- prepareMatrixSingleText(text, {
467
- cfg: opts.cfg,
468
- accountId: opts.accountId,
469
- });
470
- if (!trimmedText) {
471
- throw new Error("Matrix single-message send requires text");
472
- }
473
- if (!fitsInSingleEvent) {
474
- throw new Error(
475
- `Matrix single-message text exceeds limit (${convertedText.length} > ${singleEventLimit})`,
476
- );
477
- }
478
- return await withResolvedMatrixSendClient(
479
- {
480
- client: opts.client,
481
- cfg: opts.cfg,
482
- accountId: opts.accountId,
483
- },
484
- async (client) => {
485
- const resolvedRoom = await resolveMatrixRoomId(client, roomId);
486
- const normalizedThreadId = normalizeThreadId(opts.threadId);
487
- const relation = normalizedThreadId
488
- ? buildThreadRelation(normalizedThreadId, opts.replyToId)
489
- : buildReplyRelation(opts.replyToId);
490
- const content = withMatrixExtraContentFields(
491
- buildTextContent(convertedText, relation, {
492
- msgtype: opts.msgtype,
493
- }),
494
- opts.extraContent,
495
- );
496
- await enrichMatrixFormattedContent({
497
- client,
498
- content,
499
- markdown: convertedText,
500
- includeMentions: opts.includeMentions,
501
- });
502
- // MSC4357: mark the initial message as live so supporting clients start
503
- // rendering a streaming animation immediately.
504
- if (opts.live) {
505
- (content as Record<string, unknown>)[MSC4357_LIVE_KEY] = {};
506
- }
507
- const eventId = await client.sendMessage(resolvedRoom, content);
508
- const platformMessageIds = eventId ? [eventId] : [];
509
- return {
510
- messageId: eventId ?? "unknown",
511
- roomId: resolvedRoom,
512
- primaryMessageId: eventId ?? "unknown",
513
- receipt: createMatrixSendReceipt({
514
- roomId: resolvedRoom,
515
- platformMessageIds,
516
- kind: "text",
517
- replyToId: opts.replyToId,
518
- threadId: normalizedThreadId,
519
- }),
520
- };
521
- },
522
- );
523
- }
524
-
525
- async function getPreviousMatrixEvent(
526
- client: MatrixClient,
527
- roomId: string,
528
- eventId: string,
529
- ): Promise<Record<string, unknown> | null> {
530
- const getEvent = (
531
- client as {
532
- getEvent?: (roomId: string, eventId: string) => Promise<Record<string, unknown>>;
533
- }
534
- ).getEvent;
535
- if (typeof getEvent !== "function") {
536
- return null;
537
- }
538
- return await Promise.resolve(getEvent.call(client, roomId, eventId)).catch(() => null);
539
- }
540
-
541
- export async function editMessageMatrix(
542
- roomId: string,
543
- originalEventId: string,
544
- newText: string,
545
- opts: {
546
- client?: MatrixClient;
547
- cfg: CoreConfig;
548
- threadId?: string;
549
- accountId?: string;
550
- timeoutMs?: number;
551
- msgtype?: MatrixTextMsgType;
552
- includeMentions?: boolean;
553
- extraContent?: MatrixExtraContentFields;
554
- /** When true, marks the edit as a live/streaming update (MSC4357). */
555
- live?: boolean;
556
- },
557
- ): Promise<string> {
558
- return await withResolvedMatrixSendClient(
559
- {
560
- client: opts.client,
561
- cfg: opts.cfg,
562
- accountId: opts.accountId,
563
- timeoutMs: opts.timeoutMs,
564
- },
565
- async (client) => {
566
- const resolvedRoom = await resolveMatrixRoomId(client, roomId);
567
- const cfg = requireRuntimeConfig(opts.cfg, "Matrix message edit") as CoreConfig;
568
- const tableMode = getCore().channel.text.resolveMarkdownTableMode({
569
- cfg,
570
- channel: "matrix",
571
- accountId: opts.accountId,
572
- });
573
- const convertedText = getCore().channel.text.convertMarkdownTables(newText, tableMode);
574
- const newContent = withMatrixExtraContentFields(
575
- buildTextContent(convertedText, undefined, {
576
- msgtype: opts.msgtype,
577
- }),
578
- opts.extraContent,
579
- );
580
- await enrichMatrixFormattedContent({
581
- client,
582
- content: newContent,
583
- markdown: convertedText,
584
- includeMentions: opts.includeMentions,
585
- });
586
- const replaceMentions =
587
- opts.includeMentions === false
588
- ? undefined
589
- : diffMatrixMentions(
590
- extractMatrixMentions(newContent),
591
- await resolvePreviousEditMentions({
592
- client,
593
- content: resolvePreviousEditContent(
594
- await getPreviousMatrixEvent(client, resolvedRoom, originalEventId),
595
- ),
596
- }),
597
- );
598
-
599
- const replaceRelation: Record<string, unknown> = {
600
- rel_type: RelationType.Replace,
601
- event_id: originalEventId,
602
- };
603
- const threadId = normalizeThreadId(opts.threadId);
604
- if (threadId) {
605
- // Thread-aware replace: Synapse needs the thread context to keep the
606
- // edited event visible in the thread timeline.
607
- replaceRelation["m.in_reply_to"] = { event_id: threadId };
608
- }
609
-
610
- // Spread newContent into the outer event so clients that don't support
611
- // m.new_content still see properly formatted text (with HTML).
612
- const content: Record<string, unknown> = {
613
- ...newContent,
614
- body: `* ${convertedText}`,
615
- ...(typeof newContent.formatted_body === "string"
616
- ? { formatted_body: `* ${newContent.formatted_body}` }
617
- : {}),
618
- "m.new_content": newContent,
619
- "m.relates_to": replaceRelation,
620
- };
621
- if (replaceMentions !== undefined) {
622
- content["m.mentions"] = replaceMentions;
623
- }
624
-
625
- // MSC4357: mark in-progress edits so supporting clients can render a
626
- // streaming animation. The marker is placed in both the outer content
627
- // (for unencrypted rooms / server-side aggregation) and inside
628
- // m.new_content (for E2EE rooms where only decrypted content is read).
629
- if (opts.live) {
630
- content[MSC4357_LIVE_KEY] = {};
631
- (content["m.new_content"] as Record<string, unknown>)[MSC4357_LIVE_KEY] = {};
632
- }
633
-
634
- const eventId = await client.sendMessage(resolvedRoom, content);
635
- return eventId ?? "";
636
- },
637
- );
638
- }
639
-
640
- export async function reactMatrixMessage(
641
- roomId: string,
642
- messageId: string,
643
- emoji: string,
644
- opts?: MatrixClient | MatrixClientResolveOpts,
645
- ): Promise<void> {
646
- const clientOpts = normalizeMatrixClientResolveOpts(opts);
647
- await withResolvedMatrixSendClient(
648
- {
649
- client: clientOpts.client,
650
- cfg: clientOpts.cfg,
651
- timeoutMs: clientOpts.timeoutMs,
652
- accountId: clientOpts.accountId ?? undefined,
653
- },
654
- async (resolved) => {
655
- const resolvedRoom = await resolveMatrixRoomId(resolved, roomId);
656
- const reaction = buildMatrixReactionContent(messageId, emoji);
657
- await resolved.sendEvent(resolvedRoom, EventType.Reaction, reaction);
658
- },
659
- );
660
- }