@badgerclaw/connect 1.0.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 (70) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/SETUP.md +131 -0
  3. package/index.ts +23 -0
  4. package/openclaw.plugin.json +1 -0
  5. package/package.json +32 -0
  6. package/src/actions.ts +195 -0
  7. package/src/channel.ts +461 -0
  8. package/src/config-schema.ts +62 -0
  9. package/src/connect.ts +17 -0
  10. package/src/directory-live.ts +209 -0
  11. package/src/group-mentions.ts +52 -0
  12. package/src/matrix/accounts.ts +114 -0
  13. package/src/matrix/actions/client.ts +47 -0
  14. package/src/matrix/actions/limits.ts +6 -0
  15. package/src/matrix/actions/messages.ts +126 -0
  16. package/src/matrix/actions/pins.ts +84 -0
  17. package/src/matrix/actions/reactions.ts +102 -0
  18. package/src/matrix/actions/room.ts +85 -0
  19. package/src/matrix/actions/summary.ts +75 -0
  20. package/src/matrix/actions/types.ts +85 -0
  21. package/src/matrix/actions.ts +15 -0
  22. package/src/matrix/active-client.ts +32 -0
  23. package/src/matrix/client/config.ts +245 -0
  24. package/src/matrix/client/create-client.ts +125 -0
  25. package/src/matrix/client/logging.ts +46 -0
  26. package/src/matrix/client/runtime.ts +4 -0
  27. package/src/matrix/client/shared.ts +210 -0
  28. package/src/matrix/client/startup.ts +29 -0
  29. package/src/matrix/client/storage.ts +131 -0
  30. package/src/matrix/client/types.ts +34 -0
  31. package/src/matrix/client-bootstrap.ts +47 -0
  32. package/src/matrix/client.ts +14 -0
  33. package/src/matrix/credentials.ts +125 -0
  34. package/src/matrix/deps.ts +126 -0
  35. package/src/matrix/format.ts +22 -0
  36. package/src/matrix/index.ts +11 -0
  37. package/src/matrix/monitor/access-policy.ts +126 -0
  38. package/src/matrix/monitor/allowlist.ts +94 -0
  39. package/src/matrix/monitor/auto-join.ts +72 -0
  40. package/src/matrix/monitor/direct.ts +152 -0
  41. package/src/matrix/monitor/events.ts +168 -0
  42. package/src/matrix/monitor/handler.ts +768 -0
  43. package/src/matrix/monitor/inbound-body.ts +28 -0
  44. package/src/matrix/monitor/index.ts +414 -0
  45. package/src/matrix/monitor/location.ts +100 -0
  46. package/src/matrix/monitor/media.ts +118 -0
  47. package/src/matrix/monitor/mentions.ts +62 -0
  48. package/src/matrix/monitor/replies.ts +124 -0
  49. package/src/matrix/monitor/room-info.ts +55 -0
  50. package/src/matrix/monitor/rooms.ts +47 -0
  51. package/src/matrix/monitor/threads.ts +68 -0
  52. package/src/matrix/monitor/types.ts +39 -0
  53. package/src/matrix/poll-types.ts +167 -0
  54. package/src/matrix/probe.ts +69 -0
  55. package/src/matrix/sdk-runtime.ts +18 -0
  56. package/src/matrix/send/client.ts +99 -0
  57. package/src/matrix/send/formatting.ts +93 -0
  58. package/src/matrix/send/media.ts +230 -0
  59. package/src/matrix/send/targets.ts +150 -0
  60. package/src/matrix/send/types.ts +110 -0
  61. package/src/matrix/send-queue.ts +28 -0
  62. package/src/matrix/send.ts +267 -0
  63. package/src/onboarding.ts +331 -0
  64. package/src/outbound.ts +58 -0
  65. package/src/resolve-targets.ts +125 -0
  66. package/src/runtime.ts +6 -0
  67. package/src/secret-input.ts +13 -0
  68. package/src/test-mocks.ts +53 -0
  69. package/src/tool-actions.ts +164 -0
  70. package/src/types.ts +118 -0
@@ -0,0 +1,28 @@
1
+ export function resolveMatrixSenderUsername(senderId: string): string | undefined {
2
+ const username = senderId.split(":")[0]?.replace(/^@/, "").trim();
3
+ return username ? username : undefined;
4
+ }
5
+
6
+ export function resolveMatrixInboundSenderLabel(params: {
7
+ senderName: string;
8
+ senderId: string;
9
+ senderUsername?: string;
10
+ }): string {
11
+ const senderName = params.senderName.trim();
12
+ const senderUsername = params.senderUsername ?? resolveMatrixSenderUsername(params.senderId);
13
+ if (senderName && senderUsername && senderName !== senderUsername) {
14
+ return `${senderName} (${senderUsername})`;
15
+ }
16
+ return senderName || senderUsername || params.senderId;
17
+ }
18
+
19
+ export function resolveMatrixBodyForAgent(params: {
20
+ isDirectMessage: boolean;
21
+ bodyText: string;
22
+ senderLabel: string;
23
+ }): string {
24
+ if (params.isDirectMessage) {
25
+ return params.bodyText;
26
+ }
27
+ return `${params.senderLabel}: ${params.bodyText}`;
28
+ }
@@ -0,0 +1,414 @@
1
+ import {
2
+ GROUP_POLICY_BLOCKED_LABEL,
3
+ mergeAllowlist,
4
+ resolveRuntimeEnv,
5
+ resolveAllowlistProviderRuntimeGroupPolicy,
6
+ resolveDefaultGroupPolicy,
7
+ summarizeMapping,
8
+ warnMissingProviderGroupPolicyFallbackOnce,
9
+ type RuntimeEnv,
10
+ } from "openclaw/plugin-sdk/matrix";
11
+ import { resolveMatrixTargets } from "../../resolve-targets.js";
12
+ import { getMatrixRuntime } from "../../runtime.js";
13
+ import type { CoreConfig, MatrixConfig, MatrixRoomConfig, ReplyToMode } from "../../types.js";
14
+ import { resolveMatrixAccount } from "../accounts.js";
15
+ import { setActiveMatrixClient } from "../active-client.js";
16
+ import {
17
+ isBunRuntime,
18
+ resolveMatrixAuth,
19
+ resolveSharedMatrixClient,
20
+ stopSharedClientForAccount,
21
+ } from "../client.js";
22
+ import { normalizeMatrixUserId } from "./allowlist.js";
23
+ import { registerMatrixAutoJoin } from "./auto-join.js";
24
+ import { createDirectRoomTracker } from "./direct.js";
25
+ import { registerMatrixMonitorEvents } from "./events.js";
26
+ import { createMatrixRoomMessageHandler } from "./handler.js";
27
+ import { createMatrixRoomInfoResolver } from "./room-info.js";
28
+
29
+ export type MonitorMatrixOpts = {
30
+ runtime?: RuntimeEnv;
31
+ abortSignal?: AbortSignal;
32
+ mediaMaxMb?: number;
33
+ initialSyncLimit?: number;
34
+ replyToMode?: ReplyToMode;
35
+ accountId?: string | null;
36
+ };
37
+
38
+ const DEFAULT_MEDIA_MAX_MB = 20;
39
+ export const DEFAULT_STARTUP_GRACE_MS = 5000;
40
+
41
+ export function isConfiguredMatrixRoomEntry(entry: string): boolean {
42
+ return entry.startsWith("!") || (entry.startsWith("#") && entry.includes(":"));
43
+ }
44
+
45
+ function normalizeMatrixUserEntry(raw: string): string {
46
+ return raw
47
+ .replace(/^matrix:/i, "")
48
+ .replace(/^user:/i, "")
49
+ .trim();
50
+ }
51
+
52
+ function normalizeMatrixRoomEntry(raw: string): string {
53
+ return raw
54
+ .replace(/^matrix:/i, "")
55
+ .replace(/^(room|channel):/i, "")
56
+ .trim();
57
+ }
58
+
59
+ function isMatrixUserId(value: string): boolean {
60
+ return value.startsWith("@") && value.includes(":");
61
+ }
62
+
63
+ async function resolveMatrixUserAllowlist(params: {
64
+ cfg: CoreConfig;
65
+ runtime: RuntimeEnv;
66
+ label: string;
67
+ list?: Array<string | number>;
68
+ }): Promise<string[]> {
69
+ let allowList = params.list ?? [];
70
+ if (allowList.length === 0) {
71
+ return allowList.map(String);
72
+ }
73
+ const entries = allowList
74
+ .map((entry) => normalizeMatrixUserEntry(String(entry)))
75
+ .filter((entry) => entry && entry !== "*");
76
+ if (entries.length === 0) {
77
+ return allowList.map(String);
78
+ }
79
+ const mapping: string[] = [];
80
+ const unresolved: string[] = [];
81
+ const additions: string[] = [];
82
+ const pending: string[] = [];
83
+ for (const entry of entries) {
84
+ if (isMatrixUserId(entry)) {
85
+ additions.push(normalizeMatrixUserId(entry));
86
+ continue;
87
+ }
88
+ pending.push(entry);
89
+ }
90
+ if (pending.length > 0) {
91
+ const resolved = await resolveMatrixTargets({
92
+ cfg: params.cfg,
93
+ inputs: pending,
94
+ kind: "user",
95
+ runtime: params.runtime,
96
+ });
97
+ for (const entry of resolved) {
98
+ if (entry.resolved && entry.id) {
99
+ const normalizedId = normalizeMatrixUserId(entry.id);
100
+ additions.push(normalizedId);
101
+ mapping.push(`${entry.input}→${normalizedId}`);
102
+ } else {
103
+ unresolved.push(entry.input);
104
+ }
105
+ }
106
+ }
107
+ allowList = mergeAllowlist({ existing: allowList, additions });
108
+ summarizeMapping(params.label, mapping, unresolved, params.runtime);
109
+ if (unresolved.length > 0) {
110
+ params.runtime.log?.(
111
+ `${params.label} entries must be full BadgerClaw user IDs (example: @user:server). Unresolved entries are ignored.`,
112
+ );
113
+ }
114
+ return allowList.map(String);
115
+ }
116
+
117
+ async function resolveMatrixRoomsConfig(params: {
118
+ cfg: CoreConfig;
119
+ runtime: RuntimeEnv;
120
+ roomsConfig?: Record<string, MatrixRoomConfig>;
121
+ }): Promise<Record<string, MatrixRoomConfig> | undefined> {
122
+ let roomsConfig = params.roomsConfig;
123
+ if (!roomsConfig || Object.keys(roomsConfig).length === 0) {
124
+ return roomsConfig;
125
+ }
126
+ const mapping: string[] = [];
127
+ const unresolved: string[] = [];
128
+ const nextRooms: Record<string, MatrixRoomConfig> = {};
129
+ if (roomsConfig["*"]) {
130
+ nextRooms["*"] = roomsConfig["*"];
131
+ }
132
+ const pending: Array<{ input: string; query: string; config: MatrixRoomConfig }> = [];
133
+ for (const [entry, roomConfig] of Object.entries(roomsConfig)) {
134
+ if (entry === "*") {
135
+ continue;
136
+ }
137
+ const trimmed = entry.trim();
138
+ if (!trimmed) {
139
+ continue;
140
+ }
141
+ const cleaned = normalizeMatrixRoomEntry(trimmed);
142
+ if (isConfiguredMatrixRoomEntry(cleaned)) {
143
+ if (!nextRooms[cleaned]) {
144
+ nextRooms[cleaned] = roomConfig;
145
+ }
146
+ if (cleaned !== entry) {
147
+ mapping.push(`${entry}→${cleaned}`);
148
+ }
149
+ continue;
150
+ }
151
+ pending.push({ input: entry, query: trimmed, config: roomConfig });
152
+ }
153
+ if (pending.length > 0) {
154
+ const resolved = await resolveMatrixTargets({
155
+ cfg: params.cfg,
156
+ inputs: pending.map((entry) => entry.query),
157
+ kind: "group",
158
+ runtime: params.runtime,
159
+ });
160
+ resolved.forEach((entry, index) => {
161
+ const source = pending[index];
162
+ if (!source) {
163
+ return;
164
+ }
165
+ if (entry.resolved && entry.id) {
166
+ if (!nextRooms[entry.id]) {
167
+ nextRooms[entry.id] = source.config;
168
+ }
169
+ mapping.push(`${source.input}→${entry.id}`);
170
+ } else {
171
+ unresolved.push(source.input);
172
+ }
173
+ });
174
+ }
175
+ roomsConfig = nextRooms;
176
+ summarizeMapping("badgerclaw rooms", mapping, unresolved, params.runtime);
177
+ if (unresolved.length > 0) {
178
+ params.runtime.log?.(
179
+ "badgerclaw rooms must be room IDs or aliases (example: !room:server or #alias:server). Unresolved entries are ignored.",
180
+ );
181
+ }
182
+ if (Object.keys(roomsConfig).length === 0) {
183
+ return roomsConfig;
184
+ }
185
+ const nextRoomsWithUsers = { ...roomsConfig };
186
+ for (const [roomKey, roomConfig] of Object.entries(roomsConfig)) {
187
+ const users = roomConfig?.users ?? [];
188
+ if (users.length === 0) {
189
+ continue;
190
+ }
191
+ const resolvedUsers = await resolveMatrixUserAllowlist({
192
+ cfg: params.cfg,
193
+ runtime: params.runtime,
194
+ label: `badgerclaw room users (${roomKey})`,
195
+ list: users,
196
+ });
197
+ if (resolvedUsers !== users) {
198
+ nextRoomsWithUsers[roomKey] = { ...roomConfig, users: resolvedUsers };
199
+ }
200
+ }
201
+ return nextRoomsWithUsers;
202
+ }
203
+
204
+ async function resolveMatrixMonitorConfig(params: {
205
+ cfg: CoreConfig;
206
+ runtime: RuntimeEnv;
207
+ accountConfig: MatrixConfig;
208
+ }): Promise<{
209
+ allowFrom: string[];
210
+ groupAllowFrom: string[];
211
+ roomsConfig?: Record<string, MatrixRoomConfig>;
212
+ }> {
213
+ const allowFrom = await resolveMatrixUserAllowlist({
214
+ cfg: params.cfg,
215
+ runtime: params.runtime,
216
+ label: "badgerclaw dm allowlist",
217
+ list: params.accountConfig.dm?.allowFrom ?? [],
218
+ });
219
+ const groupAllowFrom = await resolveMatrixUserAllowlist({
220
+ cfg: params.cfg,
221
+ runtime: params.runtime,
222
+ label: "badgerclaw group allowlist",
223
+ list: params.accountConfig.groupAllowFrom ?? [],
224
+ });
225
+ const roomsConfig = await resolveMatrixRoomsConfig({
226
+ cfg: params.cfg,
227
+ runtime: params.runtime,
228
+ roomsConfig: params.accountConfig.groups ?? params.accountConfig.rooms,
229
+ });
230
+ return { allowFrom, groupAllowFrom, roomsConfig };
231
+ }
232
+
233
+ export async function monitorMatrixProvider(opts: MonitorMatrixOpts = {}): Promise<void> {
234
+ if (isBunRuntime()) {
235
+ throw new Error("BadgerClaw provider requires Node (bun runtime not supported)");
236
+ }
237
+ const core = getMatrixRuntime();
238
+ let cfg = core.config.loadConfig() as CoreConfig;
239
+ if (cfg.channels?.badgerclaw?.enabled === false) {
240
+ return;
241
+ }
242
+
243
+ const logger = core.logging.getChildLogger({ module: "matrix-auto-reply" });
244
+ const runtime: RuntimeEnv = resolveRuntimeEnv({
245
+ runtime: opts.runtime,
246
+ logger,
247
+ });
248
+ const logVerboseMessage = (message: string) => {
249
+ if (!core.logging.shouldLogVerbose()) {
250
+ return;
251
+ }
252
+ logger.debug?.(message);
253
+ };
254
+
255
+ // Resolve account-specific config for multi-account support
256
+ const account = resolveMatrixAccount({ cfg, accountId: opts.accountId });
257
+ const accountConfig = account.config;
258
+ const allowlistOnly = accountConfig.allowlistOnly === true;
259
+ const { allowFrom, groupAllowFrom, roomsConfig } = await resolveMatrixMonitorConfig({
260
+ cfg,
261
+ runtime,
262
+ accountConfig,
263
+ });
264
+
265
+ cfg = {
266
+ ...cfg,
267
+ channels: {
268
+ ...cfg.channels,
269
+ badgerclaw: {
270
+ ...cfg.channels?.badgerclaw,
271
+ dm: {
272
+ ...cfg.channels?.badgerclaw?.dm,
273
+ allowFrom,
274
+ },
275
+ groupAllowFrom,
276
+ ...(roomsConfig ? { groups: roomsConfig } : {}),
277
+ },
278
+ },
279
+ };
280
+
281
+ const auth = await resolveMatrixAuth({ cfg, accountId: opts.accountId });
282
+ const resolvedInitialSyncLimit =
283
+ typeof opts.initialSyncLimit === "number"
284
+ ? Math.max(0, Math.floor(opts.initialSyncLimit))
285
+ : auth.initialSyncLimit;
286
+ const authWithLimit =
287
+ resolvedInitialSyncLimit === auth.initialSyncLimit
288
+ ? auth
289
+ : { ...auth, initialSyncLimit: resolvedInitialSyncLimit };
290
+ const client = await resolveSharedMatrixClient({
291
+ cfg,
292
+ auth: authWithLimit,
293
+ startClient: false,
294
+ accountId: opts.accountId,
295
+ });
296
+ setActiveMatrixClient(client, opts.accountId);
297
+
298
+ const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg);
299
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
300
+ const { groupPolicy: groupPolicyRaw, providerMissingFallbackApplied } =
301
+ resolveAllowlistProviderRuntimeGroupPolicy({
302
+ providerConfigPresent: cfg.channels?.badgerclaw !== undefined,
303
+ groupPolicy: accountConfig.groupPolicy,
304
+ defaultGroupPolicy,
305
+ });
306
+ warnMissingProviderGroupPolicyFallbackOnce({
307
+ providerMissingFallbackApplied,
308
+ providerKey: "badgerclaw",
309
+ accountId: account.accountId,
310
+ blockedLabel: GROUP_POLICY_BLOCKED_LABEL.room,
311
+ log: (message) => logVerboseMessage(message),
312
+ });
313
+ const groupPolicy = allowlistOnly && groupPolicyRaw === "open" ? "allowlist" : groupPolicyRaw;
314
+ const replyToMode = opts.replyToMode ?? accountConfig.replyToMode ?? "off";
315
+ const threadReplies = accountConfig.threadReplies ?? "inbound";
316
+ const dmConfig = accountConfig.dm;
317
+ const dmEnabled = dmConfig?.enabled ?? true;
318
+ const dmPolicyRaw = dmConfig?.policy ?? "pairing";
319
+ const dmPolicy = allowlistOnly && dmPolicyRaw !== "disabled" ? "allowlist" : dmPolicyRaw;
320
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "badgerclaw");
321
+ const mediaMaxMb = opts.mediaMaxMb ?? accountConfig.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB;
322
+ const mediaMaxBytes = Math.max(1, mediaMaxMb) * 1024 * 1024;
323
+ const startupMs = Date.now();
324
+ const startupGraceMs = DEFAULT_STARTUP_GRACE_MS;
325
+ const directTracker = createDirectRoomTracker(client, {
326
+ log: logVerboseMessage,
327
+ includeMemberCountInLogs: core.logging.shouldLogVerbose(),
328
+ });
329
+ registerMatrixAutoJoin({ client, cfg, runtime });
330
+ const warnedEncryptedRooms = new Set<string>();
331
+ const warnedCryptoMissingRooms = new Set<string>();
332
+
333
+ const { getRoomInfo, getMemberDisplayName } = createMatrixRoomInfoResolver(client);
334
+ const handleRoomMessage = createMatrixRoomMessageHandler({
335
+ client,
336
+ core,
337
+ cfg,
338
+ runtime,
339
+ logger,
340
+ logVerboseMessage,
341
+ allowFrom,
342
+ roomsConfig,
343
+ mentionRegexes,
344
+ groupPolicy,
345
+ replyToMode,
346
+ threadReplies,
347
+ dmEnabled,
348
+ dmPolicy,
349
+ textLimit,
350
+ mediaMaxBytes,
351
+ startupMs,
352
+ startupGraceMs,
353
+ directTracker,
354
+ getRoomInfo,
355
+ getMemberDisplayName,
356
+ accountId: opts.accountId,
357
+ });
358
+
359
+ registerMatrixMonitorEvents({
360
+ client,
361
+ auth,
362
+ logVerboseMessage,
363
+ warnedEncryptedRooms,
364
+ warnedCryptoMissingRooms,
365
+ logger,
366
+ formatNativeDependencyHint: core.system.formatNativeDependencyHint,
367
+ onRoomMessage: handleRoomMessage,
368
+ });
369
+
370
+ logVerboseMessage("badgerclaw: starting client");
371
+ await resolveSharedMatrixClient({
372
+ cfg,
373
+ auth: authWithLimit,
374
+ accountId: opts.accountId,
375
+ });
376
+ logVerboseMessage("badgerclaw: client started");
377
+
378
+ // @vector-im/matrix-bot-sdk client is already started via resolveSharedMatrixClient
379
+ logger.info(`badgerclaw: logged in as ${auth.userId}`);
380
+
381
+ // If E2EE is enabled, trigger device verification
382
+ if (auth.encryption && client.crypto) {
383
+ try {
384
+ // Request verification from other sessions
385
+ const verificationRequest = await (
386
+ client.crypto as { requestOwnUserVerification?: () => Promise<unknown> }
387
+ ).requestOwnUserVerification?.();
388
+ if (verificationRequest) {
389
+ logger.info("badgerclaw: device verification requested - please verify in another client");
390
+ }
391
+ } catch (err) {
392
+ logger.debug?.("Device verification request failed (may already be verified)", {
393
+ error: String(err),
394
+ });
395
+ }
396
+ }
397
+
398
+ await new Promise<void>((resolve) => {
399
+ const onAbort = () => {
400
+ try {
401
+ logVerboseMessage("badgerclaw: stopping client");
402
+ stopSharedClientForAccount(auth, opts.accountId);
403
+ } finally {
404
+ setActiveMatrixClient(null, opts.accountId);
405
+ resolve();
406
+ }
407
+ };
408
+ if (opts.abortSignal?.aborted) {
409
+ onAbort();
410
+ return;
411
+ }
412
+ opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
413
+ });
414
+ }
@@ -0,0 +1,100 @@
1
+ import type { LocationMessageEventContent } from "@vector-im/matrix-bot-sdk";
2
+ import {
3
+ formatLocationText,
4
+ toLocationContext,
5
+ type NormalizedLocation,
6
+ } from "openclaw/plugin-sdk/matrix";
7
+ import { EventType } from "./types.js";
8
+
9
+ export type MatrixLocationPayload = {
10
+ text: string;
11
+ context: ReturnType<typeof toLocationContext>;
12
+ };
13
+
14
+ type GeoUriParams = {
15
+ latitude: number;
16
+ longitude: number;
17
+ accuracy?: number;
18
+ };
19
+
20
+ function parseGeoUri(value: string): GeoUriParams | null {
21
+ const trimmed = value.trim();
22
+ if (!trimmed) {
23
+ return null;
24
+ }
25
+ if (!trimmed.toLowerCase().startsWith("geo:")) {
26
+ return null;
27
+ }
28
+ const payload = trimmed.slice(4);
29
+ const [coordsPart, ...paramParts] = payload.split(";");
30
+ const coords = coordsPart.split(",");
31
+ if (coords.length < 2) {
32
+ return null;
33
+ }
34
+ const latitude = Number.parseFloat(coords[0] ?? "");
35
+ const longitude = Number.parseFloat(coords[1] ?? "");
36
+ if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
37
+ return null;
38
+ }
39
+
40
+ const params = new Map<string, string>();
41
+ for (const part of paramParts) {
42
+ const segment = part.trim();
43
+ if (!segment) {
44
+ continue;
45
+ }
46
+ const eqIndex = segment.indexOf("=");
47
+ const rawKey = eqIndex === -1 ? segment : segment.slice(0, eqIndex);
48
+ const rawValue = eqIndex === -1 ? "" : segment.slice(eqIndex + 1);
49
+ const key = rawKey.trim().toLowerCase();
50
+ if (!key) {
51
+ continue;
52
+ }
53
+ const valuePart = rawValue.trim();
54
+ params.set(key, valuePart ? decodeURIComponent(valuePart) : "");
55
+ }
56
+
57
+ const accuracyRaw = params.get("u");
58
+ const accuracy = accuracyRaw ? Number.parseFloat(accuracyRaw) : undefined;
59
+
60
+ return {
61
+ latitude,
62
+ longitude,
63
+ accuracy: Number.isFinite(accuracy) ? accuracy : undefined,
64
+ };
65
+ }
66
+
67
+ export function resolveMatrixLocation(params: {
68
+ eventType: string;
69
+ content: LocationMessageEventContent;
70
+ }): MatrixLocationPayload | null {
71
+ const { eventType, content } = params;
72
+ const isLocation =
73
+ eventType === EventType.Location ||
74
+ (eventType === EventType.RoomMessage && content.msgtype === EventType.Location);
75
+ if (!isLocation) {
76
+ return null;
77
+ }
78
+ const geoUri = typeof content.geo_uri === "string" ? content.geo_uri.trim() : "";
79
+ if (!geoUri) {
80
+ return null;
81
+ }
82
+ const parsed = parseGeoUri(geoUri);
83
+ if (!parsed) {
84
+ return null;
85
+ }
86
+ const caption = typeof content.body === "string" ? content.body.trim() : "";
87
+ const location: NormalizedLocation = {
88
+ latitude: parsed.latitude,
89
+ longitude: parsed.longitude,
90
+ accuracy: parsed.accuracy,
91
+ caption: caption || undefined,
92
+ source: "pin",
93
+ isLive: false,
94
+ };
95
+
96
+ return {
97
+ text: formatLocationText(location),
98
+ context: toLocationContext(location),
99
+ };
100
+ }
@@ -0,0 +1,118 @@
1
+ import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2
+ import { getMatrixRuntime } from "../../runtime.js";
3
+
4
+ // Type for encrypted file info
5
+ type EncryptedFile = {
6
+ url: string;
7
+ key: {
8
+ kty: string;
9
+ key_ops: string[];
10
+ alg: string;
11
+ k: string;
12
+ ext: boolean;
13
+ };
14
+ iv: string;
15
+ hashes: Record<string, string>;
16
+ v: string;
17
+ };
18
+
19
+ async function fetchMatrixMediaBuffer(params: {
20
+ client: MatrixClient;
21
+ mxcUrl: string;
22
+ maxBytes: number;
23
+ }): Promise<{ buffer: Buffer; headerType?: string } | null> {
24
+ // @vector-im/matrix-bot-sdk provides mxcToHttp helper
25
+ const url = params.client.mxcToHttp(params.mxcUrl);
26
+ if (!url) {
27
+ return null;
28
+ }
29
+
30
+ // Use the client's download method which handles auth
31
+ try {
32
+ const result = await params.client.downloadContent(params.mxcUrl);
33
+ const raw = result.data ?? result;
34
+ const buffer = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
35
+
36
+ if (buffer.byteLength > params.maxBytes) {
37
+ throw new Error("BadgerClaw media exceeds configured size limit");
38
+ }
39
+ return { buffer, headerType: result.contentType };
40
+ } catch (err) {
41
+ throw new Error(`BadgerClaw media download failed: ${String(err)}`, { cause: err });
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Download and decrypt encrypted media from a Matrix room.
47
+ * Uses @vector-im/matrix-bot-sdk's decryptMedia which handles both download and decryption.
48
+ */
49
+ async function fetchEncryptedMediaBuffer(params: {
50
+ client: MatrixClient;
51
+ file: EncryptedFile;
52
+ maxBytes: number;
53
+ }): Promise<{ buffer: Buffer } | null> {
54
+ if (!params.client.crypto) {
55
+ throw new Error("Cannot decrypt media: crypto not enabled");
56
+ }
57
+
58
+ // decryptMedia handles downloading and decrypting the encrypted content internally
59
+ const decrypted = await params.client.crypto.decryptMedia(
60
+ params.file as Parameters<typeof params.client.crypto.decryptMedia>[0],
61
+ );
62
+
63
+ if (decrypted.byteLength > params.maxBytes) {
64
+ throw new Error("BadgerClaw media exceeds configured size limit");
65
+ }
66
+
67
+ return { buffer: decrypted };
68
+ }
69
+
70
+ export async function downloadMatrixMedia(params: {
71
+ client: MatrixClient;
72
+ mxcUrl: string;
73
+ contentType?: string;
74
+ sizeBytes?: number;
75
+ maxBytes: number;
76
+ file?: EncryptedFile;
77
+ }): Promise<{
78
+ path: string;
79
+ contentType?: string;
80
+ placeholder: string;
81
+ } | null> {
82
+ let fetched: { buffer: Buffer; headerType?: string } | null;
83
+ if (typeof params.sizeBytes === "number" && params.sizeBytes > params.maxBytes) {
84
+ throw new Error("BadgerClaw media exceeds configured size limit");
85
+ }
86
+
87
+ if (params.file) {
88
+ // Encrypted media
89
+ fetched = await fetchEncryptedMediaBuffer({
90
+ client: params.client,
91
+ file: params.file,
92
+ maxBytes: params.maxBytes,
93
+ });
94
+ } else {
95
+ // Unencrypted media
96
+ fetched = await fetchMatrixMediaBuffer({
97
+ client: params.client,
98
+ mxcUrl: params.mxcUrl,
99
+ maxBytes: params.maxBytes,
100
+ });
101
+ }
102
+
103
+ if (!fetched) {
104
+ return null;
105
+ }
106
+ const headerType = fetched.headerType ?? params.contentType ?? undefined;
107
+ const saved = await getMatrixRuntime().channel.media.saveMediaBuffer(
108
+ fetched.buffer,
109
+ headerType,
110
+ "inbound",
111
+ params.maxBytes,
112
+ );
113
+ return {
114
+ path: saved.path,
115
+ contentType: saved.contentType,
116
+ placeholder: "[badgerclaw media]",
117
+ };
118
+ }