@badgerclaw/connect 1.1.3 → 1.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@badgerclaw/connect",
3
- "version": "1.1.3",
3
+ "version": "1.3.0",
4
4
  "description": "BadgerClaw channel plugin for OpenClaw",
5
5
  "type": "module",
6
6
  "dependencies": {
@@ -31,4 +31,4 @@
31
31
  "defaultChoice": "npm"
32
32
  }
33
33
  }
34
- }
34
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "!oVrHNyMFgnOCfmjlLU:badger.signout.io": {
3
+ "autoReply": true
4
+ }
5
+ }
@@ -29,6 +29,39 @@ function resolveMatrixRoomConfigForGroup(params: ChannelGroupContext) {
29
29
  }
30
30
 
31
31
  export function resolveMatrixGroupRequireMention(params: ChannelGroupContext): boolean {
32
+ // Check per-room config first (set by /bot talk on|off)
33
+ try {
34
+ const fs = require("fs");
35
+ const path = require("path");
36
+ const configPath = path.join(
37
+ process.env.HOME || "/tmp",
38
+ ".openclaw/extensions/badgerclaw/room-config.json"
39
+ );
40
+ const raw = fs.readFileSync(configPath, "utf-8");
41
+ const roomConfig = JSON.parse(raw) as Record<string, { autoReply?: boolean }>;
42
+ const rawGroupId = params.groupId?.trim() ?? "";
43
+ // Try multiple formats: raw, stripped prefixes, just the room ID part
44
+ const variants = [
45
+ rawGroupId,
46
+ rawGroupId.replace(/^badgerclaw:/, ""),
47
+ rawGroupId.replace(/^channel:/, ""),
48
+ rawGroupId.replace(/^room:/, ""),
49
+ ];
50
+ for (const variant of variants) {
51
+ if (variant && roomConfig[variant]?.autoReply === true) {
52
+ console.log(`[badgerclaw] room-config autoReply=true for ${variant}`);
53
+ return false;
54
+ }
55
+ if (variant && roomConfig[variant]?.autoReply === false) {
56
+ console.log(`[badgerclaw] room-config autoReply=false for ${variant}`);
57
+ return true;
58
+ }
59
+ }
60
+ console.log(`[badgerclaw] room-config: no match for groupId="${rawGroupId}", keys=${Object.keys(roomConfig).join(",")}`);
61
+ } catch (err) {
62
+ console.log(`[badgerclaw] room-config error: ${err}`);
63
+ }
64
+
32
65
  const resolved = resolveMatrixRoomConfigForGroup(params);
33
66
  if (resolved) {
34
67
  if (resolved.autoReply === true) {
@@ -39,6 +39,24 @@ export function registerMatrixAutoJoin(params: {
39
39
  const { AutojoinRoomsMixin } = loadMatrixSdk();
40
40
  AutojoinRoomsMixin.setupOnClient(client);
41
41
  logVerbose("badgerclaw: auto-join enabled for all invites");
42
+
43
+ // Also join any rooms with pending invites from before startup
44
+ (async () => {
45
+ try {
46
+ const syncData = await client.doRequest("GET", "/_matrix/client/v3/sync", { timeout: "0" });
47
+ const invitedRooms = Object.keys(syncData?.rooms?.invite ?? {});
48
+ for (const roomId of invitedRooms) {
49
+ try {
50
+ await client.joinRoom(roomId);
51
+ logVerbose(`badgerclaw: joined pending invite room ${roomId}`);
52
+ } catch (err) {
53
+ logVerbose(`badgerclaw: failed to join pending invite ${roomId}: ${err}`);
54
+ }
55
+ }
56
+ } catch {
57
+ // Ignore sync errors
58
+ }
59
+ })();
42
60
  return;
43
61
  }
44
62
 
@@ -0,0 +1,197 @@
1
+ import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+
5
+ const ROOM_CONFIG_PATH = path.join(
6
+ process.env.HOME || "/tmp",
7
+ ".openclaw/extensions/badgerclaw/room-config.json"
8
+ );
9
+
10
+ // Session store path for core groupActivation
11
+ const SESSION_STORE_PATH = path.join(
12
+ process.env.HOME || "/tmp",
13
+ ".openclaw/agents/main/sessions/sessions.json"
14
+ );
15
+
16
+ function loadRoomConfig(): Record<string, { autoReply?: boolean }> {
17
+ try {
18
+ return JSON.parse(fs.readFileSync(ROOM_CONFIG_PATH, "utf-8"));
19
+ } catch {
20
+ return {};
21
+ }
22
+ }
23
+
24
+ function saveRoomConfig(config: Record<string, { autoReply?: boolean }>): void {
25
+ fs.writeFileSync(ROOM_CONFIG_PATH, JSON.stringify(config, null, 2));
26
+ }
27
+
28
+ function setGroupActivation(roomId: string, activation: "always" | "mention"): void {
29
+ try {
30
+ const store = JSON.parse(fs.readFileSync(SESSION_STORE_PATH, "utf-8"));
31
+ // Session key format: agent:main:badgerclaw:channel:!roomid (lowercase)
32
+ const sessionKey = `agent:main:badgerclaw:channel:${roomId.toLowerCase()}`;
33
+ if (!store[sessionKey]) {
34
+ store[sessionKey] = {};
35
+ }
36
+ store[sessionKey].groupActivation = activation;
37
+ fs.writeFileSync(SESSION_STORE_PATH, JSON.stringify(store, null, 2));
38
+ console.log(`[badgerclaw] set groupActivation=${activation} for ${sessionKey}`);
39
+ } catch (err) {
40
+ console.error(`[badgerclaw] failed to set groupActivation: ${err}`);
41
+ }
42
+ }
43
+
44
+ export function getRoomAutoReply(roomId: string): boolean | undefined {
45
+ const config = loadRoomConfig();
46
+ return config[roomId]?.autoReply;
47
+ }
48
+
49
+ export async function handleBotCommand(params: {
50
+ client: MatrixClient;
51
+ roomId: string;
52
+ senderId: string;
53
+ body: string;
54
+ selfUserId: string;
55
+ }): Promise<boolean> {
56
+ const { client, roomId, senderId, body, selfUserId } = params;
57
+ const trimmed = body.trim();
58
+
59
+ if (!trimmed.startsWith("/bot")) {
60
+ return false;
61
+ }
62
+
63
+ const parts = trimmed.split(/\s+/);
64
+ const command = parts[1]?.toLowerCase();
65
+ const arg = parts[2]?.toLowerCase();
66
+ const arg2 = parts[3];
67
+
68
+ try {
69
+ switch (command) {
70
+ case "help": {
71
+ await client.sendMessage(roomId, {
72
+ msgtype: "m.text",
73
+ body: [
74
+ "🦡 BadgerClaw Bot Commands",
75
+ "",
76
+ "━━━ Available Everywhere ━━━",
77
+ "",
78
+ "/bot help",
79
+ " Show this help message with all available commands.",
80
+ " Works in: Any room or DM",
81
+ "",
82
+ "/bot talk on",
83
+ " Enable auto-reply mode. The bot will respond to every",
84
+ " message in this room without needing an @mention.",
85
+ " Perfect for 1-on-1 rooms with your AI assistant.",
86
+ " Works in: Any room or DM",
87
+ "",
88
+ "/bot talk off",
89
+ " Disable auto-reply mode. The bot will only respond",
90
+ " when @mentioned. Use this in busy group rooms where",
91
+ " you don't want the bot responding to everything.",
92
+ " Works in: Any room or DM",
93
+ "",
94
+ "/bot add <botname>",
95
+ " Invite a bot to the current room. The bot username",
96
+ " will be @<botname>_bot on this server.",
97
+ " Example: /bot add jarvis → invites @jarvis_bot",
98
+ " Works in: Any room",
99
+ "",
100
+ "━━━ BotBadger DM Only ━━━",
101
+ "",
102
+ "/bot new",
103
+ " Create a new bot. Starts a guided flow to set up",
104
+ " a bot name, username, and generate a pairing code",
105
+ " for connecting to an OpenClaw instance.",
106
+ " Works in: Direct message with BotBadger only",
107
+ "",
108
+ "/bot pair <name>",
109
+ " Generate a new pairing code for an existing bot.",
110
+ " Use this to connect or reconnect a bot to OpenClaw.",
111
+ " Works in: Direct message with BotBadger only",
112
+ "",
113
+ "/bot delete <name>",
114
+ " Permanently delete a bot and remove it from all rooms.",
115
+ " This action cannot be undone.",
116
+ " Works in: Direct message with BotBadger only",
117
+ "",
118
+ "/bot list",
119
+ " List all your bots and their connection status.",
120
+ " 🟢 Connected — bot is online and responding",
121
+ " 🔴 Not connected — bot needs pairing",
122
+ " Works in: Any room or DM",
123
+ ].join("\n"),
124
+ });
125
+ return true;
126
+ }
127
+
128
+ case "talk": {
129
+ if (arg === "on") {
130
+ const config = loadRoomConfig();
131
+ config[roomId] = { ...config[roomId], autoReply: true };
132
+ saveRoomConfig(config);
133
+ setGroupActivation(roomId, "always");
134
+ await client.sendMessage(roomId, {
135
+ msgtype: "m.text",
136
+ body: "✅ Auto-reply enabled — I'll respond to every message in this room.",
137
+ });
138
+ return true;
139
+ }
140
+ if (arg === "off") {
141
+ const config = loadRoomConfig();
142
+ config[roomId] = { ...config[roomId], autoReply: false };
143
+ saveRoomConfig(config);
144
+ setGroupActivation(roomId, "mention");
145
+ await client.sendMessage(roomId, {
146
+ msgtype: "m.text",
147
+ body: "✅ Auto-reply disabled — I'll only respond when @mentioned.",
148
+ });
149
+ return true;
150
+ }
151
+ await client.sendMessage(roomId, {
152
+ msgtype: "m.text",
153
+ body: "Usage: /bot talk on or /bot talk off",
154
+ });
155
+ return true;
156
+ }
157
+
158
+ case "add": {
159
+ const botName = arg;
160
+ if (!botName) {
161
+ await client.sendMessage(roomId, {
162
+ msgtype: "m.text",
163
+ body: "Usage: /bot add <botname>",
164
+ });
165
+ return true;
166
+ }
167
+ const botUserId = `@${botName}_bot:badger.signout.io`;
168
+ try {
169
+ await client.inviteUser(botUserId, roomId);
170
+ await client.sendMessage(roomId, {
171
+ msgtype: "m.text",
172
+ body: `✅ Invited ${botUserId} to this room.`,
173
+ });
174
+ } catch (err) {
175
+ const msg = err instanceof Error ? err.message : String(err);
176
+ await client.sendMessage(roomId, {
177
+ msgtype: "m.text",
178
+ body: `❌ Failed to invite ${botUserId}: ${msg}`,
179
+ });
180
+ }
181
+ return true;
182
+ }
183
+
184
+ default: {
185
+ // Unknown /bot command — show help hint
186
+ await client.sendMessage(roomId, {
187
+ msgtype: "m.text",
188
+ body: "Unknown command. Type /bot help for available commands.",
189
+ });
190
+ return true;
191
+ }
192
+ }
193
+ } catch (err) {
194
+ console.error("badgerclaw: bot command error:", err);
195
+ return true; // Still consumed the command
196
+ }
197
+ }
@@ -410,6 +410,19 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
410
410
  return;
411
411
  }
412
412
 
413
+ // Handle /bot commands before anything else
414
+ if (bodyText.trim().startsWith("/bot")) {
415
+ const { handleBotCommand } = await import("./bot-commands.js");
416
+ const handled = await handleBotCommand({
417
+ client,
418
+ roomId,
419
+ senderId,
420
+ body: bodyText,
421
+ selfUserId,
422
+ });
423
+ if (handled) return;
424
+ }
425
+
413
426
  const { wasMentioned, hasExplicitMention } = resolveMentions({
414
427
  content,
415
428
  userId: selfUserId,