@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
@@ -1,41 +0,0 @@
1
- import { DEFAULT_ACCOUNT_ID } from "klaw/plugin-sdk/account-id";
2
- import {
3
- adaptScopedAccountAccessor,
4
- createScopedChannelConfigAdapter,
5
- } from "klaw/plugin-sdk/channel-config-helpers";
6
- import {
7
- listMatrixAccountIds,
8
- resolveDefaultMatrixAccountId,
9
- resolveMatrixAccount,
10
- resolveMatrixAccountConfig,
11
- type ResolvedMatrixAccount,
12
- } from "./matrix/accounts.js";
13
- import { normalizeMatrixAllowList } from "./matrix/monitor/allowlist.js";
14
-
15
- export { DEFAULT_ACCOUNT_ID };
16
-
17
- export const matrixConfigAdapter = createScopedChannelConfigAdapter<
18
- ResolvedMatrixAccount,
19
- ReturnType<typeof resolveMatrixAccountConfig>
20
- >({
21
- sectionKey: "matrix",
22
- listAccountIds: listMatrixAccountIds,
23
- resolveAccount: adaptScopedAccountAccessor(resolveMatrixAccount),
24
- resolveAccessorAccount: ({ cfg, accountId }) => resolveMatrixAccountConfig({ cfg, accountId }),
25
- defaultAccountId: resolveDefaultMatrixAccountId,
26
- clearBaseFields: [
27
- "name",
28
- "homeserver",
29
- "network",
30
- "proxy",
31
- "userId",
32
- "accessToken",
33
- "password",
34
- "deviceId",
35
- "deviceName",
36
- "avatarUrl",
37
- "initialSyncLimit",
38
- ],
39
- resolveAllowFrom: (account) => account.dm?.allowFrom,
40
- formatAllowFrom: (allowFrom) => normalizeMatrixAllowList(allowFrom),
41
- });
@@ -1,159 +0,0 @@
1
- import { buildChannelConfigSchema } from "klaw/plugin-sdk/channel-config-primitives";
2
- import {
3
- AllowFromListSchema,
4
- buildNestedDmConfigSchema,
5
- ContextVisibilityModeSchema,
6
- GroupPolicySchema,
7
- MarkdownConfigSchema,
8
- ToolPolicySchema,
9
- } from "klaw/plugin-sdk/channel-config-schema";
10
- import { buildSecretInputSchema } from "klaw/plugin-sdk/secret-input";
11
- import { z } from "zod";
12
- import { matrixChannelConfigUiHints } from "./config-ui-hints.js";
13
-
14
- const matrixActionSchema = z
15
- .object({
16
- reactions: z.boolean().optional(),
17
- messages: z.boolean().optional(),
18
- pins: z.boolean().optional(),
19
- profile: z.boolean().optional(),
20
- memberInfo: z.boolean().optional(),
21
- channelInfo: z.boolean().optional(),
22
- verification: z.boolean().optional(),
23
- })
24
- .optional();
25
-
26
- const matrixThreadBindingsSchema = z
27
- .object({
28
- enabled: z.boolean().optional(),
29
- idleHours: z.number().nonnegative().optional(),
30
- maxAgeHours: z.number().nonnegative().optional(),
31
- spawnSessions: z.boolean().optional(),
32
- defaultSpawnContext: z.enum(["isolated", "fork"]).optional(),
33
- spawnSubagentSessions: z.boolean().optional(),
34
- spawnAcpSessions: z.boolean().optional(),
35
- })
36
- .optional();
37
-
38
- const matrixExecApprovalsSchema = z
39
- .object({
40
- enabled: z.boolean().optional(),
41
- approvers: AllowFromListSchema,
42
- agentFilter: z.array(z.string()).optional(),
43
- sessionFilter: z.array(z.string()).optional(),
44
- target: z.enum(["dm", "channel", "both"]).optional(),
45
- })
46
- .optional();
47
-
48
- const botLoopProtectionSchema = z
49
- .object({
50
- enabled: z.boolean().optional(),
51
- maxEventsPerWindow: z.number().int().positive().optional(),
52
- windowSeconds: z.number().int().positive().optional(),
53
- cooldownSeconds: z.number().int().positive().optional(),
54
- })
55
- .strict()
56
- .optional();
57
-
58
- const matrixRoomSchema = z
59
- .object({
60
- account: z.string().optional(),
61
- enabled: z.boolean().optional(),
62
- requireMention: z.boolean().optional(),
63
- allowBots: z.union([z.boolean(), z.literal("mentions")]).optional(),
64
- botLoopProtection: botLoopProtectionSchema,
65
- tools: ToolPolicySchema,
66
- autoReply: z.boolean().optional(),
67
- users: AllowFromListSchema,
68
- skills: z.array(z.string()).optional(),
69
- systemPrompt: z.string().optional(),
70
- })
71
- .optional();
72
-
73
- const matrixNetworkSchema = z
74
- .object({
75
- dangerouslyAllowPrivateNetwork: z.boolean().optional(),
76
- })
77
- .strict()
78
- .optional();
79
-
80
- const matrixStreamingSchema = z
81
- .object({
82
- mode: z.enum(["partial", "quiet", "progress", "off"]).optional(),
83
- progress: z
84
- .object({
85
- label: z.union([z.string(), z.literal(false)]).optional(),
86
- labels: z.array(z.string()).optional(),
87
- maxLines: z.number().int().positive().optional(),
88
- maxLineChars: z.number().int().positive().optional(),
89
- toolProgress: z.boolean().optional(),
90
- })
91
- .strict()
92
- .optional(),
93
- preview: z
94
- .object({
95
- toolProgress: z.boolean().optional(),
96
- })
97
- .strict()
98
- .optional(),
99
- })
100
- .strict();
101
-
102
- export const MatrixConfigSchema = z.object({
103
- name: z.string().optional(),
104
- enabled: z.boolean().optional(),
105
- defaultAccount: z.string().optional(),
106
- accounts: z.record(z.string(), z.unknown()).optional(),
107
- markdown: MarkdownConfigSchema,
108
- homeserver: z.string().optional(),
109
- network: matrixNetworkSchema,
110
- proxy: z.string().optional(),
111
- userId: z.string().optional(),
112
- accessToken: buildSecretInputSchema().optional(),
113
- password: buildSecretInputSchema().optional(),
114
- deviceId: z.string().optional(),
115
- deviceName: z.string().optional(),
116
- avatarUrl: z.string().optional(),
117
- initialSyncLimit: z.number().optional(),
118
- encryption: z.boolean().optional(),
119
- allowlistOnly: z.boolean().optional(),
120
- dangerouslyAllowNameMatching: z.boolean().optional(),
121
- allowBots: z.union([z.boolean(), z.literal("mentions")]).optional(),
122
- botLoopProtection: botLoopProtectionSchema,
123
- groupPolicy: GroupPolicySchema.optional(),
124
- contextVisibility: ContextVisibilityModeSchema.optional(),
125
- blockStreaming: z.boolean().optional(),
126
- streaming: z
127
- .union([z.enum(["partial", "quiet", "progress", "off"]), z.boolean(), matrixStreamingSchema])
128
- .optional(),
129
- replyToMode: z.enum(["off", "first", "all", "batched"]).optional(),
130
- threadReplies: z.enum(["off", "inbound", "always"]).optional(),
131
- textChunkLimit: z.number().optional(),
132
- chunkMode: z.enum(["length", "newline"]).optional(),
133
- responsePrefix: z.string().optional(),
134
- ackReaction: z.string().optional(),
135
- ackReactionScope: z
136
- .enum(["group-mentions", "group-all", "direct", "all", "none", "off"])
137
- .optional(),
138
- reactionNotifications: z.enum(["off", "own"]).optional(),
139
- threadBindings: matrixThreadBindingsSchema,
140
- startupVerification: z.enum(["off", "if-unverified"]).optional(),
141
- startupVerificationCooldownHours: z.number().optional(),
142
- mediaMaxMb: z.number().optional(),
143
- historyLimit: z.number().int().min(0).optional(),
144
- autoJoin: z.enum(["always", "allowlist", "off"]).optional(),
145
- autoJoinAllowlist: AllowFromListSchema,
146
- groupAllowFrom: AllowFromListSchema,
147
- dm: buildNestedDmConfigSchema({
148
- sessionScope: z.enum(["per-user", "per-room"]).optional(),
149
- threadReplies: z.enum(["off", "inbound", "always"]).optional(),
150
- }),
151
- execApprovals: matrixExecApprovalsSchema,
152
- groups: z.object({}).catchall(matrixRoomSchema).optional(),
153
- rooms: z.object({}).catchall(matrixRoomSchema).optional(),
154
- actions: matrixActionSchema,
155
- });
156
-
157
- export const MatrixChannelConfigSchema = buildChannelConfigSchema(MatrixConfigSchema, {
158
- uiHints: matrixChannelConfigUiHints,
159
- });
@@ -1,56 +0,0 @@
1
- import type { ChannelConfigUiHint } from "klaw/plugin-sdk/channel-core";
2
-
3
- export const matrixChannelConfigUiHints = {
4
- allowBots: {
5
- label: "Matrix Allow Bot Messages",
6
- help: 'Allow messages from other configured Matrix bot accounts to trigger replies (default: false). Set "mentions" to require a visible room mention.',
7
- },
8
- botLoopProtection: {
9
- label: "Matrix Bot Loop Protection",
10
- help: "Sliding-window guard for accepted Matrix configured-bot loops. Default is enabled whenever allowBots lets configured bot messages reach dispatch.",
11
- },
12
- "botLoopProtection.enabled": {
13
- label: "Matrix Bot Loop Protection Enabled",
14
- help: 'Enable the bot-pair loop guard. Defaults to true when allowBots is true or "mentions", and false when configured bot messages are ignored.',
15
- },
16
- "botLoopProtection.maxEventsPerWindow": {
17
- label: "Matrix Bot Loop Events per Window",
18
- help: "Maximum accepted bot-pair messages within the sliding window before suppression starts. Default: 20.",
19
- },
20
- "botLoopProtection.windowSeconds": {
21
- label: "Matrix Bot Loop Window Seconds",
22
- help: "Sliding window length for counting bot-pair messages. Default: 60.",
23
- },
24
- "botLoopProtection.cooldownSeconds": {
25
- label: "Matrix Bot Loop Cooldown Seconds",
26
- help: "How long to suppress the bot pair after it exceeds the budget. Default: 60.",
27
- },
28
- dangerouslyAllowNameMatching: {
29
- label: "Matrix Display Name Matching",
30
- help: "Compatibility opt-in for resolving Matrix display names and joined room names in allowlists. Prefer full @user:server IDs and room IDs or aliases because names are mutable.",
31
- },
32
- "streaming.progress.label": {
33
- label: "Matrix Progress Label",
34
- help: 'Initial progress draft title. Use "auto" for built-in single-word labels, a custom string, or false to hide the title.',
35
- },
36
- "streaming.progress.labels": {
37
- label: "Matrix Progress Label Pool",
38
- help: 'Candidate labels for streaming.progress.label="auto". Leave unset to use Klaw built-in progress labels.',
39
- },
40
- "streaming.progress.maxLines": {
41
- label: "Matrix Progress Max Lines",
42
- help: "Maximum number of compact progress lines to keep below the draft label (default: 8).",
43
- },
44
- "streaming.progress.maxLineChars": {
45
- label: "Matrix Progress Max Line Chars",
46
- help: "Maximum characters per compact progress line before truncation (default: 120). Prose cuts at word boundaries; commands and paths keep useful suffixes.",
47
- },
48
- "streaming.progress.toolProgress": {
49
- label: "Matrix Progress Tool Lines",
50
- help: "Show compact tool/progress lines in progress draft mode (default: true). Set false to keep only the label until final delivery.",
51
- },
52
- "streaming.progress.commandText": {
53
- label: "Matrix Progress Command Text",
54
- help: 'Command/exec detail in progress draft lines: "raw" preserves released behavior; "status" shows only the tool label.',
55
- },
56
- } satisfies Record<string, ChannelConfigUiHint>;
@@ -1,238 +0,0 @@
1
- import {
2
- normalizeLowercaseStringOrEmpty,
3
- normalizeOptionalString,
4
- } from "klaw/plugin-sdk/string-coerce-runtime";
5
- import { resolveMatrixAuth } from "./matrix/client.js";
6
- import { MatrixAuthedHttpClient } from "./matrix/sdk/http-client.js";
7
- import { isMatrixQualifiedUserId, normalizeMatrixMessagingTarget } from "./matrix/target-ids.js";
8
- import type { ChannelDirectoryEntry } from "./runtime-api.js";
9
-
10
- type MatrixUserResult = {
11
- user_id?: string;
12
- display_name?: string;
13
- };
14
-
15
- type MatrixUserDirectoryResponse = {
16
- results?: MatrixUserResult[];
17
- };
18
-
19
- type MatrixJoinedRoomsResponse = {
20
- joined_rooms?: string[];
21
- };
22
-
23
- type MatrixRoomNameState = {
24
- name?: string;
25
- };
26
-
27
- type MatrixAliasLookup = {
28
- room_id?: string;
29
- };
30
-
31
- type MatrixDirectoryLiveParams = {
32
- cfg: unknown;
33
- accountId?: string | null;
34
- query?: string | null;
35
- limit?: number | null;
36
- };
37
-
38
- type MatrixResolvedAuth = Awaited<ReturnType<typeof resolveMatrixAuth>>;
39
-
40
- const MATRIX_DIRECTORY_TIMEOUT_MS = 10_000;
41
-
42
- function resolveMatrixDirectoryLimit(limit?: number | null): number {
43
- return typeof limit === "number" && Number.isFinite(limit) && limit > 0
44
- ? Math.max(1, Math.floor(limit))
45
- : 20;
46
- }
47
-
48
- function createMatrixDirectoryClient(auth: MatrixResolvedAuth): MatrixAuthedHttpClient {
49
- return new MatrixAuthedHttpClient({
50
- homeserver: auth.homeserver,
51
- accessToken: auth.accessToken,
52
- ssrfPolicy: auth.ssrfPolicy,
53
- dispatcherPolicy: auth.dispatcherPolicy,
54
- });
55
- }
56
-
57
- async function resolveMatrixDirectoryContext(params: MatrixDirectoryLiveParams): Promise<{
58
- auth: MatrixResolvedAuth;
59
- client: MatrixAuthedHttpClient;
60
- query: string;
61
- queryLower: string;
62
- } | null> {
63
- const query = normalizeOptionalString(params.query) ?? "";
64
- if (!query) {
65
- return null;
66
- }
67
- const auth = await resolveMatrixAuth({ cfg: params.cfg as never, accountId: params.accountId });
68
- return {
69
- auth,
70
- client: createMatrixDirectoryClient(auth),
71
- query,
72
- queryLower: normalizeLowercaseStringOrEmpty(query),
73
- };
74
- }
75
-
76
- function createGroupDirectoryEntry(params: {
77
- id: string;
78
- name: string;
79
- handle?: string;
80
- }): ChannelDirectoryEntry {
81
- return {
82
- kind: "group",
83
- id: params.id,
84
- name: params.name,
85
- handle: params.handle,
86
- } satisfies ChannelDirectoryEntry;
87
- }
88
-
89
- async function requestMatrixJson<T>(
90
- client: MatrixAuthedHttpClient,
91
- params: {
92
- method: "GET" | "POST";
93
- endpoint: string;
94
- body?: unknown;
95
- },
96
- ): Promise<T> {
97
- return (await client.requestJson({
98
- method: params.method,
99
- endpoint: params.endpoint,
100
- body: params.body,
101
- timeoutMs: MATRIX_DIRECTORY_TIMEOUT_MS,
102
- })) as T;
103
- }
104
-
105
- export async function listMatrixDirectoryPeersLive(
106
- params: MatrixDirectoryLiveParams,
107
- ): Promise<ChannelDirectoryEntry[]> {
108
- const query = normalizeOptionalString(params.query) ?? "";
109
- if (!query) {
110
- return [];
111
- }
112
- const directUserId = normalizeMatrixMessagingTarget(query);
113
- if (directUserId && isMatrixQualifiedUserId(directUserId)) {
114
- return [{ kind: "user", id: directUserId }];
115
- }
116
- const context = await resolveMatrixDirectoryContext({
117
- ...params,
118
- query,
119
- });
120
- if (!context) {
121
- return [];
122
- }
123
-
124
- const res = await requestMatrixJson<MatrixUserDirectoryResponse>(context.client, {
125
- method: "POST",
126
- endpoint: "/_matrix/client/v3/user_directory/search",
127
- body: {
128
- search_term: context.query,
129
- limit: resolveMatrixDirectoryLimit(params.limit),
130
- },
131
- });
132
- const results = res.results ?? [];
133
- return results
134
- .map((entry) => {
135
- const userId = normalizeOptionalString(entry.user_id);
136
- if (!userId) {
137
- return null;
138
- }
139
- const displayName = normalizeOptionalString(entry.display_name);
140
- return {
141
- kind: "user",
142
- id: userId,
143
- name: displayName,
144
- handle: displayName ? `@${displayName}` : undefined,
145
- raw: entry,
146
- } satisfies ChannelDirectoryEntry;
147
- })
148
- .filter(Boolean) as ChannelDirectoryEntry[];
149
- }
150
-
151
- async function resolveMatrixRoomAlias(
152
- client: MatrixAuthedHttpClient,
153
- alias: string,
154
- ): Promise<string | null> {
155
- try {
156
- const res = await requestMatrixJson<MatrixAliasLookup>(client, {
157
- method: "GET",
158
- endpoint: `/_matrix/client/v3/directory/room/${encodeURIComponent(alias)}`,
159
- });
160
- return normalizeOptionalString(res.room_id) ?? null;
161
- } catch {
162
- return null;
163
- }
164
- }
165
-
166
- async function fetchMatrixRoomName(
167
- client: MatrixAuthedHttpClient,
168
- roomId: string,
169
- ): Promise<string | null> {
170
- try {
171
- const res = await requestMatrixJson<MatrixRoomNameState>(client, {
172
- method: "GET",
173
- endpoint: `/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/state/m.room.name`,
174
- });
175
- return normalizeOptionalString(res.name) ?? null;
176
- } catch {
177
- return null;
178
- }
179
- }
180
-
181
- export async function listMatrixDirectoryGroupsLive(
182
- params: MatrixDirectoryLiveParams,
183
- ): Promise<ChannelDirectoryEntry[]> {
184
- const query = normalizeOptionalString(params.query) ?? "";
185
- if (!query) {
186
- return [];
187
- }
188
- const directTarget = normalizeMatrixMessagingTarget(query);
189
-
190
- if (directTarget?.startsWith("!")) {
191
- return [createGroupDirectoryEntry({ id: directTarget, name: directTarget })];
192
- }
193
-
194
- const context = await resolveMatrixDirectoryContext({
195
- ...params,
196
- query,
197
- });
198
- if (!context) {
199
- return [];
200
- }
201
- const { client, queryLower } = context;
202
- const limit = resolveMatrixDirectoryLimit(params.limit);
203
-
204
- if (directTarget?.startsWith("#")) {
205
- const roomId = await resolveMatrixRoomAlias(client, directTarget);
206
- if (!roomId) {
207
- return [];
208
- }
209
- return [createGroupDirectoryEntry({ id: roomId, name: directTarget, handle: directTarget })];
210
- }
211
-
212
- const joined = await requestMatrixJson<MatrixJoinedRoomsResponse>(client, {
213
- method: "GET",
214
- endpoint: "/_matrix/client/v3/joined_rooms",
215
- });
216
- const rooms = (joined.joined_rooms ?? [])
217
- .map((roomId) => normalizeOptionalString(roomId))
218
- .filter((roomId): roomId is string => Boolean(roomId));
219
- const results: ChannelDirectoryEntry[] = [];
220
-
221
- for (const roomId of rooms) {
222
- const name = await fetchMatrixRoomName(client, roomId);
223
- if (!name || !normalizeLowercaseStringOrEmpty(name).includes(queryLower)) {
224
- continue;
225
- }
226
- results.push({
227
- kind: "group",
228
- id: roomId,
229
- name,
230
- handle: `#${name}`,
231
- });
232
- if (results.length >= limit) {
233
- break;
234
- }
235
- }
236
-
237
- return results;
238
- }