@kodelyth/matrix 2026.5.42 → 2026.6.2

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 +18 -6
  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
package/src/outbound.ts DELETED
@@ -1,248 +0,0 @@
1
- import {
2
- renderMessagePresentationFallbackText,
3
- type MessagePresentation,
4
- } from "klaw/plugin-sdk/interactive-runtime";
5
- import { createReplyToFanout } from "klaw/plugin-sdk/outbound-runtime";
6
- import { resolvePayloadMediaUrls } from "klaw/plugin-sdk/reply-payload";
7
- import type { ReplyPayload } from "klaw/plugin-sdk/reply-runtime";
8
- import { sendMessageMatrix, sendPollMatrix } from "./matrix/send.js";
9
- import type { MatrixExtraContentFields } from "./matrix/send/types.js";
10
- import {
11
- chunkTextForOutbound,
12
- resolveOutboundSendDep,
13
- type ChannelOutboundAdapter,
14
- } from "./runtime-api.js";
15
-
16
- const MATRIX_KLAW_PRESENTATION_KEY = "com.klaw.presentation" as const;
17
- const MATRIX_KLAW_PRESENTATION_TYPE = "message.presentation" as const;
18
- const MATRIX_EMPTY_PRESENTATION_FALLBACK_TEXT = "---";
19
-
20
- type MatrixChannelData = {
21
- extraContent?: MatrixExtraContentFields;
22
- };
23
-
24
- function toRecord(value: unknown): Record<string, unknown> | undefined {
25
- return value && typeof value === "object" && !Array.isArray(value)
26
- ? (value as Record<string, unknown>)
27
- : undefined;
28
- }
29
-
30
- function resolveMatrixChannelData(payload: ReplyPayload): MatrixChannelData {
31
- const raw = toRecord(payload.channelData)?.matrix;
32
- return (toRecord(raw) as MatrixChannelData | undefined) ?? {};
33
- }
34
-
35
- function buildMatrixPresentationContent(presentation: MessagePresentation) {
36
- return {
37
- ...presentation,
38
- version: 1,
39
- type: MATRIX_KLAW_PRESENTATION_TYPE,
40
- };
41
- }
42
-
43
- function resolveMatrixPresentationContent(
44
- payload: ReplyPayload,
45
- ): Record<string, unknown> | undefined {
46
- const extraContent = toRecord(resolveMatrixChannelData(payload).extraContent);
47
- const presentation = toRecord(extraContent?.[MATRIX_KLAW_PRESENTATION_KEY]);
48
- if (
49
- !presentation ||
50
- presentation.version !== 1 ||
51
- presentation.type !== MATRIX_KLAW_PRESENTATION_TYPE
52
- ) {
53
- return undefined;
54
- }
55
- return presentation;
56
- }
57
-
58
- function renderMatrixPresentationPayload(params: {
59
- payload: ReplyPayload;
60
- presentation: MessagePresentation;
61
- }): ReplyPayload {
62
- const matrixData = resolveMatrixChannelData(params.payload);
63
- const fallbackText = renderMessagePresentationFallbackText({
64
- text: params.payload.text,
65
- presentation: params.presentation,
66
- emptyFallback: MATRIX_EMPTY_PRESENTATION_FALLBACK_TEXT,
67
- });
68
- return {
69
- ...params.payload,
70
- text: fallbackText,
71
- channelData: {
72
- ...params.payload.channelData,
73
- matrix: {
74
- ...matrixData,
75
- extraContent: {
76
- [MATRIX_KLAW_PRESENTATION_KEY]: buildMatrixPresentationContent(params.presentation),
77
- },
78
- },
79
- },
80
- };
81
- }
82
-
83
- function resolveMatrixPayloadText(payload: ReplyPayload): string {
84
- const text = payload.text ?? "";
85
- if (text.trim() || !resolveMatrixPresentationContent(payload)) {
86
- return text;
87
- }
88
- return MATRIX_EMPTY_PRESENTATION_FALLBACK_TEXT;
89
- }
90
-
91
- function resolveMatrixExtraContent(payload: ReplyPayload): MatrixExtraContentFields | undefined {
92
- const presentation = resolveMatrixPresentationContent(payload);
93
- return presentation ? { [MATRIX_KLAW_PRESENTATION_KEY]: presentation } : undefined;
94
- }
95
-
96
- export const matrixOutbound: ChannelOutboundAdapter = {
97
- deliveryMode: "direct",
98
- chunker: chunkTextForOutbound,
99
- chunkerMode: "markdown",
100
- textChunkLimit: 4000,
101
- presentationCapabilities: {
102
- supported: true,
103
- buttons: true,
104
- selects: true,
105
- context: true,
106
- divider: true,
107
- limits: {
108
- text: {
109
- markdownDialect: "markdown",
110
- supportsEdit: true,
111
- },
112
- },
113
- },
114
- renderPresentation: ({ payload, presentation }) =>
115
- renderMatrixPresentationPayload({ payload, presentation }),
116
- sendPayload: async ({
117
- cfg,
118
- to,
119
- payload,
120
- mediaLocalRoots,
121
- mediaReadFile,
122
- mediaAccess,
123
- deps,
124
- replyToId,
125
- replyToIdSource,
126
- replyToMode,
127
- threadId,
128
- accountId,
129
- audioAsVoice,
130
- }) => {
131
- const send =
132
- resolveOutboundSendDep<typeof sendMessageMatrix>(deps, "matrix") ?? sendMessageMatrix;
133
- const resolvedThreadId =
134
- threadId !== undefined && threadId !== null ? String(threadId) : undefined;
135
- const resolveReplyToId = createReplyToFanout({
136
- ...(replyToId != null ? { replyToId } : {}),
137
- ...(replyToIdSource !== undefined ? { replyToIdSource } : {}),
138
- ...(replyToMode !== undefined ? { replyToMode } : {}),
139
- });
140
- const urls = resolvePayloadMediaUrls(payload);
141
- const payloadText = resolveMatrixPayloadText(payload);
142
- if (urls.length > 0) {
143
- let lastResult: Awaited<ReturnType<typeof send>> | undefined;
144
- for (let i = 0; i < urls.length; i++) {
145
- const isFirst = i === 0;
146
- lastResult = await send(to, isFirst ? payloadText : "", {
147
- cfg,
148
- mediaUrl: urls[i],
149
- mediaAccess,
150
- mediaLocalRoots,
151
- mediaReadFile,
152
- replyToId: resolveReplyToId(),
153
- threadId: resolvedThreadId,
154
- accountId: accountId ?? undefined,
155
- audioAsVoice: payload.audioAsVoice ?? audioAsVoice,
156
- extraContent: isFirst ? resolveMatrixExtraContent(payload) : undefined,
157
- });
158
- }
159
- return {
160
- channel: "matrix",
161
- messageId: lastResult!.messageId,
162
- roomId: lastResult!.roomId,
163
- };
164
- }
165
- const result = await send(to, payloadText, {
166
- cfg,
167
- mediaUrl: payload.mediaUrl,
168
- mediaAccess,
169
- mediaLocalRoots,
170
- mediaReadFile,
171
- replyToId: resolveReplyToId(),
172
- threadId: resolvedThreadId,
173
- accountId: accountId ?? undefined,
174
- audioAsVoice: payload.audioAsVoice ?? audioAsVoice,
175
- extraContent: resolveMatrixExtraContent(payload),
176
- });
177
- return {
178
- channel: "matrix",
179
- messageId: result.messageId,
180
- roomId: result.roomId,
181
- };
182
- },
183
- sendText: async ({ cfg, to, text, deps, replyToId, threadId, accountId, audioAsVoice }) => {
184
- const send =
185
- resolveOutboundSendDep<typeof sendMessageMatrix>(deps, "matrix") ?? sendMessageMatrix;
186
- const resolvedThreadId =
187
- threadId !== undefined && threadId !== null ? String(threadId) : undefined;
188
- const result = await send(to, text, {
189
- cfg,
190
- replyToId: replyToId ?? undefined,
191
- threadId: resolvedThreadId,
192
- accountId: accountId ?? undefined,
193
- audioAsVoice,
194
- });
195
- return {
196
- channel: "matrix",
197
- messageId: result.messageId,
198
- roomId: result.roomId,
199
- };
200
- },
201
- sendMedia: async ({
202
- cfg,
203
- to,
204
- text,
205
- mediaUrl,
206
- mediaLocalRoots,
207
- mediaReadFile,
208
- deps,
209
- replyToId,
210
- threadId,
211
- accountId,
212
- audioAsVoice,
213
- }) => {
214
- const send =
215
- resolveOutboundSendDep<typeof sendMessageMatrix>(deps, "matrix") ?? sendMessageMatrix;
216
- const resolvedThreadId =
217
- threadId !== undefined && threadId !== null ? String(threadId) : undefined;
218
- const result = await send(to, text, {
219
- cfg,
220
- mediaUrl,
221
- mediaLocalRoots,
222
- mediaReadFile,
223
- replyToId: replyToId ?? undefined,
224
- threadId: resolvedThreadId,
225
- accountId: accountId ?? undefined,
226
- audioAsVoice,
227
- });
228
- return {
229
- channel: "matrix",
230
- messageId: result.messageId,
231
- roomId: result.roomId,
232
- };
233
- },
234
- sendPoll: async ({ cfg, to, poll, threadId, accountId }) => {
235
- const resolvedThreadId = threadId !== undefined && threadId !== null ? threadId : undefined;
236
- const result = await sendPollMatrix(to, poll, {
237
- cfg,
238
- threadId: resolvedThreadId,
239
- accountId: accountId ?? undefined,
240
- });
241
- return {
242
- channel: "matrix",
243
- messageId: result.eventId,
244
- roomId: result.roomId,
245
- pollId: result.eventId,
246
- };
247
- },
248
- };
@@ -1,115 +0,0 @@
1
- // Thin ESM wrapper so native dynamic import() resolves in source-checkout mode
2
- // while packaged dist builds resolve a distinct runtime entry that cannot loop
3
- // back into this wrapper through the stable root runtime alias.
4
- import fs from "node:fs";
5
- import path from "node:path";
6
- import { fileURLToPath, pathToFileURL } from "node:url";
7
-
8
- const PLUGIN_ID = "matrix";
9
- const PLUGIN_ENTRY_RUNTIME_BASENAME = "plugin-entry.handlers.runtime";
10
- const NATIVE_RUNTIME_EXTENSIONS = [".js", ".mjs", ".cjs"];
11
-
12
- function readPackageJson(packageRoot) {
13
- try {
14
- return JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
15
- } catch {
16
- return null;
17
- }
18
- }
19
-
20
- function normalizeLowercaseStringOrEmpty(value) {
21
- return typeof value === "string" ? value.toLowerCase() : "";
22
- }
23
-
24
- function hasTrustedKlawRootIndicator(packageRoot, packageJson) {
25
- const packageExports = packageJson?.exports ?? {};
26
- if (!Object.prototype.hasOwnProperty.call(packageExports, "./plugin-sdk")) {
27
- return false;
28
- }
29
- const hasCliEntryExport = Object.prototype.hasOwnProperty.call(packageExports, "./cli-entry");
30
- const hasKlawBin =
31
- (typeof packageJson?.bin === "string" &&
32
- normalizeLowercaseStringOrEmpty(packageJson.bin).includes("klaw")) ||
33
- (typeof packageJson?.bin === "object" &&
34
- packageJson.bin !== null &&
35
- typeof packageJson.bin.klaw === "string");
36
- const hasKlawEntrypoint = fs.existsSync(path.join(packageRoot, "klaw.mjs"));
37
- return hasCliEntryExport || hasKlawBin || hasKlawEntrypoint;
38
- }
39
-
40
- function findKlawPackageRoot(startDir) {
41
- let cursor = path.resolve(startDir);
42
- for (let i = 0; i < 12; i += 1) {
43
- const pkg = readPackageJson(cursor);
44
- if (pkg?.name === "klaw" && hasTrustedKlawRootIndicator(cursor, pkg)) {
45
- return { packageRoot: cursor, packageJson: pkg };
46
- }
47
- const parent = path.dirname(cursor);
48
- if (parent === cursor) {
49
- break;
50
- }
51
- cursor = parent;
52
- }
53
- return null;
54
- }
55
-
56
- function resolveExistingFile(basePath, extensions) {
57
- for (const ext of extensions) {
58
- const candidate = `${basePath}${ext}`;
59
- if (fs.existsSync(candidate)) {
60
- return candidate;
61
- }
62
- }
63
- return null;
64
- }
65
-
66
- function resolveBundledPluginRuntimeModulePath(moduleUrl, params) {
67
- const modulePath = fileURLToPath(moduleUrl);
68
- const moduleDir = path.dirname(modulePath);
69
- const localCandidates = [
70
- path.join(moduleDir, "..", params.runtimeBasename),
71
- path.join(moduleDir, "extensions", params.pluginId, params.runtimeBasename),
72
- ];
73
-
74
- for (const candidate of localCandidates) {
75
- const resolved = resolveExistingFile(candidate, NATIVE_RUNTIME_EXTENSIONS);
76
- if (resolved) {
77
- return resolved;
78
- }
79
- }
80
-
81
- const location = findKlawPackageRoot(moduleDir);
82
- if (location) {
83
- const { packageRoot } = location;
84
- const packageCandidates = [
85
- path.join(packageRoot, "extensions", params.pluginId, params.runtimeBasename),
86
- path.join(packageRoot, "dist", "extensions", params.pluginId, params.runtimeBasename),
87
- ];
88
-
89
- for (const candidate of packageCandidates) {
90
- const resolved = resolveExistingFile(candidate, NATIVE_RUNTIME_EXTENSIONS);
91
- if (resolved) {
92
- return resolved;
93
- }
94
- }
95
- }
96
-
97
- throw new Error(
98
- `Cannot resolve ${params.pluginId} plugin runtime module ${params.runtimeBasename} from ${modulePath}`,
99
- );
100
- }
101
-
102
- async function loadRuntimeModule(modulePath) {
103
- return import(pathToFileURL(modulePath).href);
104
- }
105
-
106
- const mod = await loadRuntimeModule(
107
- resolveBundledPluginRuntimeModulePath(import.meta.url, {
108
- pluginId: PLUGIN_ID,
109
- runtimeBasename: PLUGIN_ENTRY_RUNTIME_BASENAME,
110
- }),
111
- );
112
- export const ensureMatrixCryptoRuntime = mod.ensureMatrixCryptoRuntime;
113
- export const handleVerifyRecoveryKey = mod.handleVerifyRecoveryKey;
114
- export const handleVerificationBootstrap = mod.handleVerificationBootstrap;
115
- export const handleVerificationStatus = mod.handleVerificationStatus;
@@ -1,70 +0,0 @@
1
- import type { GatewayRequestHandlerOptions } from "klaw/plugin-sdk/gateway-runtime";
2
- import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
3
- import { formatMatrixErrorMessage } from "./matrix/errors.js";
4
-
5
- type MatrixVerificationRuntime = typeof import("./matrix/actions/verification.js");
6
-
7
- let matrixVerificationRuntimePromise: Promise<MatrixVerificationRuntime> | undefined;
8
-
9
- function loadMatrixVerificationRuntime(): Promise<MatrixVerificationRuntime> {
10
- matrixVerificationRuntimePromise ??= import("./matrix/actions/verification.js");
11
- return matrixVerificationRuntimePromise;
12
- }
13
-
14
- function sendError(respond: (ok: boolean, payload?: unknown) => void, err: unknown) {
15
- respond(false, { error: formatMatrixErrorMessage(err) });
16
- }
17
-
18
- export async function handleVerifyRecoveryKey({
19
- params,
20
- respond,
21
- }: GatewayRequestHandlerOptions): Promise<void> {
22
- try {
23
- const { verifyMatrixRecoveryKey } = await loadMatrixVerificationRuntime();
24
- const key = normalizeOptionalString(params?.key);
25
- if (!key) {
26
- respond(false, { error: "key required" });
27
- return;
28
- }
29
- const accountId = normalizeOptionalString(params?.accountId);
30
- const result = await verifyMatrixRecoveryKey(key, { accountId });
31
- respond(result.success, result);
32
- } catch (err) {
33
- sendError(respond, err);
34
- }
35
- }
36
-
37
- export async function handleVerificationBootstrap({
38
- params,
39
- respond,
40
- }: GatewayRequestHandlerOptions): Promise<void> {
41
- try {
42
- const { bootstrapMatrixVerification } = await loadMatrixVerificationRuntime();
43
- const accountId = normalizeOptionalString(params?.accountId);
44
- const recoveryKey = typeof params?.recoveryKey === "string" ? params.recoveryKey : undefined;
45
- const forceResetCrossSigning = params?.forceResetCrossSigning === true;
46
- const result = await bootstrapMatrixVerification({
47
- accountId,
48
- recoveryKey,
49
- forceResetCrossSigning,
50
- });
51
- respond(result.success, result);
52
- } catch (err) {
53
- sendError(respond, err);
54
- }
55
- }
56
-
57
- export async function handleVerificationStatus({
58
- params,
59
- respond,
60
- }: GatewayRequestHandlerOptions): Promise<void> {
61
- try {
62
- const { getMatrixVerificationStatus } = await loadMatrixVerificationRuntime();
63
- const accountId = normalizeOptionalString(params?.accountId);
64
- const includeRecoveryKey = params?.includeRecoveryKey === true;
65
- const status = await getMatrixVerificationStatus({ accountId, includeRecoveryKey });
66
- respond(true, status);
67
- } catch (err) {
68
- sendError(respond, err);
69
- }
70
- }
@@ -1,71 +0,0 @@
1
- import { normalizeAccountId } from "klaw/plugin-sdk/account-id";
2
- import { updateMatrixOwnProfile } from "./matrix/actions/profile.js";
3
- import { updateMatrixAccountConfig, resolveMatrixConfigPath } from "./matrix/config-update.js";
4
- import { getMatrixRuntime } from "./runtime.js";
5
- import type { CoreConfig } from "./types.js";
6
-
7
- export type MatrixProfileUpdateResult = {
8
- accountId: string;
9
- displayName: string | null;
10
- avatarUrl: string | null;
11
- profile: {
12
- displayNameUpdated: boolean;
13
- avatarUpdated: boolean;
14
- resolvedAvatarUrl: string | null;
15
- uploadedAvatarSource: "http" | "path" | null;
16
- convertedAvatarFromHttp: boolean;
17
- };
18
- configPath: string;
19
- };
20
-
21
- export async function applyMatrixProfileUpdate(params: {
22
- cfg?: CoreConfig;
23
- account?: string;
24
- displayName?: string;
25
- avatarUrl?: string;
26
- avatarPath?: string;
27
- mediaLocalRoots?: readonly string[];
28
- }): Promise<MatrixProfileUpdateResult> {
29
- const runtime = getMatrixRuntime();
30
- const persistedCfg = runtime.config.current() as CoreConfig;
31
- const accountId = normalizeAccountId(params.account);
32
- const displayName = params.displayName?.trim() || null;
33
- const avatarUrl = params.avatarUrl?.trim() || null;
34
- const avatarPath = params.avatarPath?.trim() || null;
35
- if (!displayName && !avatarUrl && !avatarPath) {
36
- throw new Error("Provide name/displayName and/or avatarUrl/avatarPath.");
37
- }
38
-
39
- const synced = await updateMatrixOwnProfile({
40
- cfg: params.cfg,
41
- accountId,
42
- displayName: displayName ?? undefined,
43
- avatarUrl: avatarUrl ?? undefined,
44
- avatarPath: avatarPath ?? undefined,
45
- mediaLocalRoots: params.mediaLocalRoots,
46
- });
47
- const persistedAvatarUrl =
48
- synced.uploadedAvatarSource && synced.resolvedAvatarUrl ? synced.resolvedAvatarUrl : avatarUrl;
49
- const updated = updateMatrixAccountConfig(persistedCfg, accountId, {
50
- name: displayName ?? undefined,
51
- avatarUrl: persistedAvatarUrl ?? undefined,
52
- });
53
- await runtime.config.replaceConfigFile({
54
- nextConfig: updated as never,
55
- afterWrite: { mode: "auto" },
56
- });
57
-
58
- return {
59
- accountId,
60
- displayName,
61
- avatarUrl: persistedAvatarUrl ?? null,
62
- profile: {
63
- displayNameUpdated: synced.displayNameUpdated,
64
- avatarUpdated: synced.avatarUpdated,
65
- resolvedAvatarUrl: synced.resolvedAvatarUrl,
66
- uploadedAvatarSource: synced.uploadedAvatarSource,
67
- convertedAvatarFromHttp: synced.convertedAvatarFromHttp,
68
- },
69
- configPath: resolveMatrixConfigPath(updated, accountId),
70
- };
71
- }
@@ -1,3 +0,0 @@
1
- import { isRecord } from "klaw/plugin-sdk/string-coerce-runtime";
2
-
3
- export { isRecord };
@@ -1,175 +0,0 @@
1
- import { normalizeOptionalLowercaseString } from "klaw/plugin-sdk/string-coerce-runtime";
2
- import { listMatrixDirectoryGroupsLive, listMatrixDirectoryPeersLive } from "./directory-live.js";
3
- import { isMatrixQualifiedUserId, normalizeMatrixMessagingTarget } from "./matrix/target-ids.js";
4
- import type {
5
- ChannelDirectoryEntry,
6
- ChannelResolveKind,
7
- ChannelResolveResult,
8
- RuntimeEnv,
9
- } from "./runtime-api.js";
10
-
11
- function normalizeLookupQuery(query: string): string {
12
- return normalizeOptionalLowercaseString(query) ?? "";
13
- }
14
-
15
- function findExactDirectoryMatches(
16
- matches: ChannelDirectoryEntry[],
17
- query: string,
18
- ): ChannelDirectoryEntry[] {
19
- const normalized = normalizeLookupQuery(query);
20
- if (!normalized) {
21
- return [];
22
- }
23
- return matches.filter((match) => {
24
- const id = normalizeOptionalLowercaseString(match.id);
25
- const name = normalizeOptionalLowercaseString(match.name);
26
- const handle = normalizeOptionalLowercaseString(match.handle);
27
- return normalized === id || normalized === name || normalized === handle;
28
- });
29
- }
30
-
31
- function pickBestGroupMatch(
32
- matches: ChannelDirectoryEntry[],
33
- query: string,
34
- ): { best?: ChannelDirectoryEntry; note?: string } {
35
- if (matches.length === 0) {
36
- return {};
37
- }
38
- const exact = findExactDirectoryMatches(matches, query);
39
- if (exact.length > 1) {
40
- return { best: exact[0], note: "multiple exact matches; chose first" };
41
- }
42
- if (exact.length === 1) {
43
- return { best: exact[0] };
44
- }
45
- return {
46
- best: matches[0],
47
- note: matches.length > 1 ? "multiple matches; chose first" : undefined,
48
- };
49
- }
50
-
51
- function pickBestUserMatch(
52
- matches: ChannelDirectoryEntry[],
53
- query: string,
54
- ): ChannelDirectoryEntry | undefined {
55
- if (matches.length === 0) {
56
- return undefined;
57
- }
58
- const exact = findExactDirectoryMatches(matches, query);
59
- if (exact.length === 1) {
60
- return exact[0];
61
- }
62
- return undefined;
63
- }
64
-
65
- function describeUserMatchFailure(matches: ChannelDirectoryEntry[], query: string): string {
66
- if (matches.length === 0) {
67
- return "no matches";
68
- }
69
- const normalized = normalizeLookupQuery(query);
70
- if (!normalized) {
71
- return "empty input";
72
- }
73
- const exact = findExactDirectoryMatches(matches, normalized);
74
- if (exact.length === 0) {
75
- return "no exact match; use full Matrix ID";
76
- }
77
- if (exact.length > 1) {
78
- return "multiple exact matches; use full Matrix ID";
79
- }
80
- return "no exact match; use full Matrix ID";
81
- }
82
-
83
- async function readCachedMatches(
84
- cache: Map<string, ChannelDirectoryEntry[]>,
85
- query: string,
86
- lookup: (query: string) => Promise<ChannelDirectoryEntry[]>,
87
- ): Promise<ChannelDirectoryEntry[]> {
88
- const key = normalizeLookupQuery(query);
89
- if (!key) {
90
- return [];
91
- }
92
- const cached = cache.get(key);
93
- if (cached) {
94
- return cached;
95
- }
96
- const matches = await lookup(query.trim());
97
- cache.set(key, matches);
98
- return matches;
99
- }
100
-
101
- export async function resolveMatrixTargets(params: {
102
- cfg: unknown;
103
- accountId?: string | null;
104
- inputs: string[];
105
- kind: ChannelResolveKind;
106
- runtime?: RuntimeEnv;
107
- }): Promise<ChannelResolveResult[]> {
108
- const results: ChannelResolveResult[] = [];
109
- const userLookupCache = new Map<string, ChannelDirectoryEntry[]>();
110
- const groupLookupCache = new Map<string, ChannelDirectoryEntry[]>();
111
-
112
- for (const input of params.inputs) {
113
- const trimmed = input.trim();
114
- if (!trimmed) {
115
- results.push({ input, resolved: false, note: "empty input" });
116
- continue;
117
- }
118
- if (params.kind === "user") {
119
- const normalizedTarget = normalizeMatrixMessagingTarget(trimmed);
120
- if (normalizedTarget && isMatrixQualifiedUserId(normalizedTarget)) {
121
- results.push({ input, resolved: true, id: normalizedTarget });
122
- continue;
123
- }
124
- try {
125
- const matches = await readCachedMatches(userLookupCache, trimmed, (query) =>
126
- listMatrixDirectoryPeersLive({
127
- cfg: params.cfg,
128
- accountId: params.accountId,
129
- query,
130
- limit: 5,
131
- }),
132
- );
133
- const best = pickBestUserMatch(matches, trimmed);
134
- results.push({
135
- input,
136
- resolved: Boolean(best?.id),
137
- id: best?.id,
138
- name: best?.name,
139
- note: best ? undefined : describeUserMatchFailure(matches, trimmed),
140
- });
141
- } catch (err) {
142
- params.runtime?.error?.(`matrix resolve failed: ${String(err)}`);
143
- results.push({ input, resolved: false, note: "lookup failed" });
144
- }
145
- continue;
146
- }
147
- const normalizedTarget = normalizeMatrixMessagingTarget(trimmed);
148
- if (normalizedTarget?.startsWith("!")) {
149
- results.push({ input, resolved: true, id: normalizedTarget });
150
- continue;
151
- }
152
- try {
153
- const matches = await readCachedMatches(groupLookupCache, trimmed, (query) =>
154
- listMatrixDirectoryGroupsLive({
155
- cfg: params.cfg,
156
- accountId: params.accountId,
157
- query,
158
- limit: 5,
159
- }),
160
- );
161
- const { best, note } = pickBestGroupMatch(matches, trimmed);
162
- results.push({
163
- input,
164
- resolved: Boolean(best?.id),
165
- id: best?.id,
166
- name: best?.name,
167
- note,
168
- });
169
- } catch (err) {
170
- params.runtime?.error?.(`matrix resolve failed: ${String(err)}`);
171
- results.push({ input, resolved: false, note: "lookup failed" });
172
- }
173
- }
174
- return results;
175
- }
@@ -1,5 +0,0 @@
1
- import { resolveMatrixTargets } from "./resolve-targets.js";
2
-
3
- export const matrixResolverRuntime = {
4
- resolveMatrixTargets,
5
- };