@gakr-gakr/matrix 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/CHANGELOG.md +285 -0
  2. package/SPEC-SUPPORT.md +116 -0
  3. package/api.ts +38 -0
  4. package/auth-presence.ts +56 -0
  5. package/autobot.plugin.json +28 -0
  6. package/channel-plugin-api.ts +3 -0
  7. package/cli-metadata.ts +11 -0
  8. package/contract-api.ts +17 -0
  9. package/doctor-contract-api.ts +1 -0
  10. package/helper-api.ts +3 -0
  11. package/index.ts +55 -0
  12. package/package.json +101 -0
  13. package/plugin-entry.handlers.runtime.ts +1 -0
  14. package/runtime-api.ts +72 -0
  15. package/runtime-heavy-api.ts +1 -0
  16. package/runtime-setter-api.ts +3 -0
  17. package/secret-contract-api.ts +5 -0
  18. package/setup-entry.ts +17 -0
  19. package/setup-plugin-api.ts +3 -0
  20. package/src/account-selection.ts +223 -0
  21. package/src/actions.ts +346 -0
  22. package/src/approval-auth.ts +25 -0
  23. package/src/approval-handler.runtime.ts +595 -0
  24. package/src/approval-ids.ts +6 -0
  25. package/src/approval-native.ts +348 -0
  26. package/src/approval-reaction-auth.ts +45 -0
  27. package/src/approval-reactions.ts +313 -0
  28. package/src/auth-precedence.ts +61 -0
  29. package/src/channel-account-paths.ts +97 -0
  30. package/src/channel.runtime.ts +17 -0
  31. package/src/channel.setup.ts +48 -0
  32. package/src/channel.ts +667 -0
  33. package/src/cli-metadata.ts +19 -0
  34. package/src/cli.ts +2298 -0
  35. package/src/config-adapter.ts +41 -0
  36. package/src/config-schema.ts +159 -0
  37. package/src/config-ui-hints.ts +56 -0
  38. package/src/directory-live.ts +238 -0
  39. package/src/doctor-contract.ts +287 -0
  40. package/src/doctor.ts +262 -0
  41. package/src/env-vars.ts +92 -0
  42. package/src/exec-approval-resolver.ts +23 -0
  43. package/src/exec-approvals.ts +293 -0
  44. package/src/group-mentions.ts +41 -0
  45. package/src/legacy-crypto-inspector-availability.ts +60 -0
  46. package/src/legacy-crypto.ts +531 -0
  47. package/src/legacy-state.ts +156 -0
  48. package/src/matrix/account-config.ts +175 -0
  49. package/src/matrix/accounts.ts +194 -0
  50. package/src/matrix/actions/client.ts +31 -0
  51. package/src/matrix/actions/devices.ts +34 -0
  52. package/src/matrix/actions/limits.ts +6 -0
  53. package/src/matrix/actions/messages.ts +129 -0
  54. package/src/matrix/actions/pins.ts +63 -0
  55. package/src/matrix/actions/polls.ts +109 -0
  56. package/src/matrix/actions/profile.ts +37 -0
  57. package/src/matrix/actions/reactions.ts +59 -0
  58. package/src/matrix/actions/room.ts +71 -0
  59. package/src/matrix/actions/summary.ts +88 -0
  60. package/src/matrix/actions/types.ts +63 -0
  61. package/src/matrix/actions/verification.ts +589 -0
  62. package/src/matrix/actions.ts +37 -0
  63. package/src/matrix/active-client.ts +26 -0
  64. package/src/matrix/async-lock.ts +18 -0
  65. package/src/matrix/backup-health.ts +124 -0
  66. package/src/matrix/client/config-runtime-api.ts +9 -0
  67. package/src/matrix/client/config-secret-input.runtime.ts +1 -0
  68. package/src/matrix/client/config.ts +853 -0
  69. package/src/matrix/client/create-client.ts +105 -0
  70. package/src/matrix/client/env-auth.ts +95 -0
  71. package/src/matrix/client/file-sync-store.ts +289 -0
  72. package/src/matrix/client/logging.ts +140 -0
  73. package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
  74. package/src/matrix/client/private-network-host.ts +1 -0
  75. package/src/matrix/client/runtime.ts +4 -0
  76. package/src/matrix/client/shared.ts +316 -0
  77. package/src/matrix/client/storage.ts +543 -0
  78. package/src/matrix/client/types.ts +50 -0
  79. package/src/matrix/client/url-validation.ts +76 -0
  80. package/src/matrix/client-bootstrap.ts +173 -0
  81. package/src/matrix/client.ts +23 -0
  82. package/src/matrix/config-paths.ts +31 -0
  83. package/src/matrix/config-update.ts +292 -0
  84. package/src/matrix/credentials-read.ts +207 -0
  85. package/src/matrix/credentials-write.runtime.ts +35 -0
  86. package/src/matrix/credentials.ts +95 -0
  87. package/src/matrix/deps.ts +309 -0
  88. package/src/matrix/device-health.ts +31 -0
  89. package/src/matrix/direct-management.ts +349 -0
  90. package/src/matrix/direct-room.ts +128 -0
  91. package/src/matrix/draft-stream.ts +225 -0
  92. package/src/matrix/encryption-guidance.ts +24 -0
  93. package/src/matrix/errors.ts +21 -0
  94. package/src/matrix/format.ts +426 -0
  95. package/src/matrix/legacy-crypto-inspector.ts +95 -0
  96. package/src/matrix/media-errors.ts +20 -0
  97. package/src/matrix/media-text.ts +162 -0
  98. package/src/matrix/monitor/access-state.ts +145 -0
  99. package/src/matrix/monitor/ack-config.ts +27 -0
  100. package/src/matrix/monitor/allowlist.ts +92 -0
  101. package/src/matrix/monitor/auto-join.ts +86 -0
  102. package/src/matrix/monitor/config.ts +569 -0
  103. package/src/matrix/monitor/context-summary.ts +43 -0
  104. package/src/matrix/monitor/direct.ts +296 -0
  105. package/src/matrix/monitor/events.ts +397 -0
  106. package/src/matrix/monitor/handler.ts +2271 -0
  107. package/src/matrix/monitor/inbound-dedupe.ts +267 -0
  108. package/src/matrix/monitor/index.ts +540 -0
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
  110. package/src/matrix/monitor/location.ts +108 -0
  111. package/src/matrix/monitor/media.ts +119 -0
  112. package/src/matrix/monitor/mentions.ts +256 -0
  113. package/src/matrix/monitor/reaction-events.ts +197 -0
  114. package/src/matrix/monitor/recent-invite.ts +30 -0
  115. package/src/matrix/monitor/replies.ts +136 -0
  116. package/src/matrix/monitor/reply-context.ts +92 -0
  117. package/src/matrix/monitor/room-history.ts +301 -0
  118. package/src/matrix/monitor/room-info.ts +126 -0
  119. package/src/matrix/monitor/rooms.ts +52 -0
  120. package/src/matrix/monitor/route.ts +179 -0
  121. package/src/matrix/monitor/runtime-api.ts +28 -0
  122. package/src/matrix/monitor/startup-verification.ts +237 -0
  123. package/src/matrix/monitor/startup.ts +218 -0
  124. package/src/matrix/monitor/status.ts +120 -0
  125. package/src/matrix/monitor/sync-lifecycle.ts +91 -0
  126. package/src/matrix/monitor/task-runner.ts +38 -0
  127. package/src/matrix/monitor/test-events.ts +21 -0
  128. package/src/matrix/monitor/thread-context.ts +108 -0
  129. package/src/matrix/monitor/threads.ts +85 -0
  130. package/src/matrix/monitor/types.ts +30 -0
  131. package/src/matrix/monitor/verification-events.ts +643 -0
  132. package/src/matrix/monitor/verification-utils.ts +46 -0
  133. package/src/matrix/outbound-media-runtime.ts +1 -0
  134. package/src/matrix/poll-summary.ts +110 -0
  135. package/src/matrix/poll-types.ts +429 -0
  136. package/src/matrix/probe.runtime.ts +4 -0
  137. package/src/matrix/probe.ts +97 -0
  138. package/src/matrix/profile.ts +184 -0
  139. package/src/matrix/reaction-common.ts +147 -0
  140. package/src/matrix/sdk/crypto-bootstrap.ts +438 -0
  141. package/src/matrix/sdk/crypto-facade.ts +242 -0
  142. package/src/matrix/sdk/crypto-node.runtime.ts +17 -0
  143. package/src/matrix/sdk/crypto-runtime.ts +14 -0
  144. package/src/matrix/sdk/decrypt-bridge.ts +410 -0
  145. package/src/matrix/sdk/event-helpers.ts +83 -0
  146. package/src/matrix/sdk/http-client.ts +87 -0
  147. package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
  148. package/src/matrix/sdk/idb-persistence.ts +286 -0
  149. package/src/matrix/sdk/logger.ts +108 -0
  150. package/src/matrix/sdk/read-response-with-limit.ts +19 -0
  151. package/src/matrix/sdk/recovery-key-store.ts +453 -0
  152. package/src/matrix/sdk/timeout-abort-signal.ts +1 -0
  153. package/src/matrix/sdk/transport-runtime-api.ts +18 -0
  154. package/src/matrix/sdk/transport.ts +352 -0
  155. package/src/matrix/sdk/types.ts +245 -0
  156. package/src/matrix/sdk/verification-manager.ts +795 -0
  157. package/src/matrix/sdk/verification-status.ts +23 -0
  158. package/src/matrix/sdk.ts +2152 -0
  159. package/src/matrix/send/client.ts +93 -0
  160. package/src/matrix/send/formatting.ts +189 -0
  161. package/src/matrix/send/media.ts +244 -0
  162. package/src/matrix/send/targets.ts +104 -0
  163. package/src/matrix/send/types.ts +131 -0
  164. package/src/matrix/send.ts +660 -0
  165. package/src/matrix/session-store-metadata.ts +108 -0
  166. package/src/matrix/startup-abort.ts +44 -0
  167. package/src/matrix/subagent-hooks.ts +308 -0
  168. package/src/matrix/sync-state.ts +27 -0
  169. package/src/matrix/target-ids.ts +79 -0
  170. package/src/matrix/thread-bindings-shared.ts +206 -0
  171. package/src/matrix/thread-bindings.ts +580 -0
  172. package/src/matrix-migration.runtime.ts +9 -0
  173. package/src/migration-config.ts +243 -0
  174. package/src/migration-snapshot-backup.ts +116 -0
  175. package/src/migration-snapshot.ts +53 -0
  176. package/src/onboarding.ts +775 -0
  177. package/src/outbound.ts +248 -0
  178. package/src/plugin-entry.runtime.js +115 -0
  179. package/src/plugin-entry.runtime.ts +70 -0
  180. package/src/profile-update.ts +71 -0
  181. package/src/record-shared.ts +3 -0
  182. package/src/resolve-targets.ts +175 -0
  183. package/src/resolver.runtime.ts +5 -0
  184. package/src/resolver.ts +21 -0
  185. package/src/runtime-api.ts +106 -0
  186. package/src/runtime.ts +13 -0
  187. package/src/secret-contract.ts +174 -0
  188. package/src/session-route.ts +126 -0
  189. package/src/setup-bootstrap.ts +102 -0
  190. package/src/setup-config.ts +222 -0
  191. package/src/setup-contract.ts +90 -0
  192. package/src/setup-core.ts +146 -0
  193. package/src/setup-dm-policy.ts +15 -0
  194. package/src/setup-surface.ts +4 -0
  195. package/src/startup-maintenance.ts +114 -0
  196. package/src/storage-paths.ts +92 -0
  197. package/src/thread-binding-api.ts +23 -0
  198. package/src/tool-actions.runtime.ts +1 -0
  199. package/src/tool-actions.ts +498 -0
  200. package/src/types.ts +257 -0
  201. package/subagent-hooks-api.ts +31 -0
  202. package/test-api.ts +21 -0
  203. package/thread-binding-api.ts +4 -0
  204. package/thread-bindings-runtime.ts +4 -0
  205. package/tsconfig.json +16 -0
@@ -0,0 +1,248 @@
1
+ import {
2
+ renderMessagePresentationFallbackText,
3
+ type MessagePresentation,
4
+ } from "autobot/plugin-sdk/interactive-runtime";
5
+ import { createReplyToFanout } from "autobot/plugin-sdk/outbound-runtime";
6
+ import { resolvePayloadMediaUrls } from "autobot/plugin-sdk/reply-payload";
7
+ import type { ReplyPayload } from "autobot/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_AUTOBOT_PRESENTATION_KEY = "com.autobot.presentation" as const;
17
+ const MATRIX_AUTOBOT_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_AUTOBOT_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_AUTOBOT_PRESENTATION_KEY]);
48
+ if (
49
+ !presentation ||
50
+ presentation.version !== 1 ||
51
+ presentation.type !== MATRIX_AUTOBOT_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_AUTOBOT_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_AUTOBOT_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
+ };
@@ -0,0 +1,115 @@
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 hasTrustedAutoBotRootIndicator(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 hasAutoBotBin =
31
+ (typeof packageJson?.bin === "string" &&
32
+ normalizeLowercaseStringOrEmpty(packageJson.bin).includes("autobot")) ||
33
+ (typeof packageJson?.bin === "object" &&
34
+ packageJson.bin !== null &&
35
+ typeof packageJson.bin.autobot === "string");
36
+ const hasAutoBotEntrypoint = fs.existsSync(path.join(packageRoot, "autobot.mjs"));
37
+ return hasCliEntryExport || hasAutoBotBin || hasAutoBotEntrypoint;
38
+ }
39
+
40
+ function findAutoBotPackageRoot(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 === "autobot" && hasTrustedAutoBotRootIndicator(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 = findAutoBotPackageRoot(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;
@@ -0,0 +1,70 @@
1
+ import type { GatewayRequestHandlerOptions } from "autobot/plugin-sdk/gateway-runtime";
2
+ import { normalizeOptionalString } from "autobot/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
+ }
@@ -0,0 +1,71 @@
1
+ import { normalizeAccountId } from "autobot/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
+ }
@@ -0,0 +1,3 @@
1
+ import { isRecord } from "autobot/plugin-sdk/string-coerce-runtime";
2
+
3
+ export { isRecord };
@@ -0,0 +1,175 @@
1
+ import { normalizeOptionalLowercaseString } from "autobot/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
+ }
@@ -0,0 +1,5 @@
1
+ import { resolveMatrixTargets } from "./resolve-targets.js";
2
+
3
+ export const matrixResolverRuntime = {
4
+ resolveMatrixTargets,
5
+ };