Skip to content

Commit bb4ba42

Browse files
Fix WhatsApp session stability and self-reply loops (anomalyco#245)
* feat: keep CLI output readable while preserving full logs * fix: stabilize inbound handling and WhatsApp sessions * fix: prevent WhatsApp self-reply loops
1 parent db9d7fe commit bb4ba42

8 files changed

Lines changed: 529 additions & 197 deletions

File tree

‎packages/owpenbot/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "owpenwork",
3-
"version": "0.1.11",
3+
"version": "0.1.12",
44
"description": "WhatsApp bridge for a running OpenCode server",
55
"private": false,
66
"type": "module",

‎packages/owpenbot/src/bridge.ts‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ type Adapter = {
2020
sendText(peerId: string, text: string): Promise<void>;
2121
};
2222

23+
type OutboundKind = "reply" | "system" | "tool";
24+
25+
export type BridgeReporter = {
26+
onStatus?: (message: string) => void;
27+
onInbound?: (message: { channel: ChannelName; peerId: string; text: string; fromMe?: boolean }) => void;
28+
onOutbound?: (message: { channel: ChannelName; peerId: string; text: string; kind: OutboundKind }) => void;
29+
};
30+
2331
type InboundMessage = {
2432
channel: ChannelName;
2533
peerId: string;
@@ -49,7 +57,8 @@ const TOOL_LABELS: Record<string, string> = {
4957
webfetch: "webfetch",
5058
};
5159

52-
export async function startBridge(config: Config, logger: Logger) {
60+
export async function startBridge(config: Config, logger: Logger, reporter?: BridgeReporter) {
61+
const reportStatus = reporter?.onStatus;
5362
const client = createClient(config);
5463
const store = new BridgeStore(config.dbPath);
5564
store.seedAllowlist("telegram", config.allowlist.telegram);
@@ -64,12 +73,17 @@ export async function startBridge(config: Config, logger: Logger) {
6473
adapters.set("telegram", createTelegramAdapter(config, logger, handleInbound));
6574
} else {
6675
logger.info("telegram adapter disabled");
76+
reportStatus?.("Telegram adapter disabled.");
6777
}
6878

6979
if (config.whatsappEnabled) {
70-
adapters.set("whatsapp", createWhatsAppAdapter(config, logger, handleInbound, { printQr: true }));
80+
adapters.set(
81+
"whatsapp",
82+
createWhatsAppAdapter(config, logger, handleInbound, { printQr: true, onStatus: reportStatus }),
83+
);
7184
} else {
7285
logger.info("whatsapp adapter disabled");
86+
reportStatus?.("WhatsApp adapter disabled.");
7387
}
7488

7589
const sessionQueue = new Map<string, Promise<void>>();
@@ -142,7 +156,7 @@ export async function startBridge(config: Config, logger: Logger) {
142156
if (output) message += `\n${output}`;
143157
}
144158

145-
await sendText(run.channel, run.peerId, message);
159+
await sendText(run.channel, run.peerId, message, { kind: "tool" });
146160
}
147161

148162
if (event.type === "permission.asked") {
@@ -157,7 +171,9 @@ export async function startBridge(config: Config, logger: Logger) {
157171
if (response === "reject") {
158172
const run = activeRuns.get(permission.sessionID);
159173
if (run) {
160-
await sendText(run.channel, run.peerId, "Permission denied. Update configuration to allow tools.");
174+
await sendText(run.channel, run.peerId, "Permission denied. Update configuration to allow tools.", {
175+
kind: "system",
176+
});
161177
}
162178
}
163179
}
@@ -166,9 +182,18 @@ export async function startBridge(config: Config, logger: Logger) {
166182
logger.error({ error }, "event stream closed");
167183
});
168184

169-
async function sendText(channel: ChannelName, peerId: string, text: string) {
185+
async function sendText(
186+
channel: ChannelName,
187+
peerId: string,
188+
text: string,
189+
options: { kind?: OutboundKind; display?: boolean } = {},
190+
) {
170191
const adapter = adapters.get(channel);
171192
if (!adapter) return;
193+
const kind = options.kind ?? "system";
194+
if (options.display !== false) {
195+
reporter?.onOutbound?.({ channel, peerId, text, kind });
196+
}
172197
const chunks = chunkText(text, adapter.maxTextLength);
173198
for (const chunk of chunks) {
174199
logger.info({ channel, peerId, length: chunk.length }, "sending message");
@@ -199,6 +224,7 @@ export async function startBridge(config: Config, logger: Logger) {
199224
inbound.channel,
200225
inbound.peerId,
201226
"Access denied. Ask the owner to allowlist your number.",
227+
{ kind: "system" },
202228
);
203229
return;
204230
}
@@ -211,6 +237,7 @@ export async function startBridge(config: Config, logger: Logger) {
211237
inbound.channel,
212238
inbound.peerId,
213239
"Pairing queue full. Ask the owner to approve pending requests.",
240+
{ kind: "system" },
214241
);
215242
return;
216243
}
@@ -223,16 +250,24 @@ export async function startBridge(config: Config, logger: Logger) {
223250
inbound.channel,
224251
inbound.peerId,
225252
`Pairing required. Ask the owner to approve code: ${code}`,
253+
{ kind: "system" },
226254
);
227255
return;
228256
}
229257
} else if (config.allowlist[inbound.channel].size > 0) {
230258
if (!store.isAllowed(inbound.channel, peerKey)) {
231-
await sendText(inbound.channel, inbound.peerId, "Access denied.");
259+
await sendText(inbound.channel, inbound.peerId, "Access denied.", { kind: "system" });
232260
return;
233261
}
234262
}
235263

264+
reporter?.onInbound?.({
265+
channel: inbound.channel,
266+
peerId: inbound.peerId,
267+
text: inbound.text,
268+
fromMe: inbound.fromMe,
269+
});
270+
236271
const session = store.getSession(inbound.channel, peerKey);
237272
const sessionID = session?.session_id ?? (await createSession({ ...inbound, peerId: peerKey }));
238273

@@ -258,13 +293,17 @@ export async function startBridge(config: Config, logger: Logger) {
258293
.trim();
259294

260295
if (reply) {
261-
await sendText(inbound.channel, inbound.peerId, reply);
296+
await sendText(inbound.channel, inbound.peerId, reply, { kind: "reply" });
262297
} else {
263-
await sendText(inbound.channel, inbound.peerId, "No response generated. Try again.");
298+
await sendText(inbound.channel, inbound.peerId, "No response generated. Try again.", {
299+
kind: "system",
300+
});
264301
}
265302
} catch (error) {
266303
logger.error({ error }, "prompt failed");
267-
await sendText(inbound.channel, inbound.peerId, "Error: failed to reach OpenCode.");
304+
await sendText(inbound.channel, inbound.peerId, "Error: failed to reach OpenCode.", {
305+
kind: "system",
306+
});
268307
} finally {
269308
activeRuns.delete(sessionID);
270309
}
@@ -301,9 +340,11 @@ export async function startBridge(config: Config, logger: Logger) {
301340

302341
for (const adapter of adapters.values()) {
303342
await adapter.start();
343+
reportStatus?.(`${adapter.name === "whatsapp" ? "WhatsApp" : "Telegram"} adapter started.`);
304344
}
305345

306346
logger.info({ channels: Array.from(adapters.keys()) }, "bridge started");
347+
reportStatus?.(`Bridge running. Logs: ${config.logFile}`);
307348

308349
return {
309350
async stop() {

‎packages/owpenbot/src/cli.ts‎

Lines changed: 64 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,23 @@ import {
1616
} from "@clack/prompts";
1717
import { Command } from "commander";
1818

19-
import { startBridge } from "./bridge.js";
19+
import { startBridge, type BridgeReporter } from "./bridge.js";
2020
import {
2121
loadConfig,
2222
normalizeWhatsAppId,
2323
readConfigFile,
2424
writeConfigFile,
25+
type ChannelName,
2526
type DmPolicy,
2627
type OwpenbotConfigFile,
2728
} from "./config.js";
2829
import { BridgeStore } from "./db.js";
2930
import { createLogger } from "./logger.js";
3031
import { createClient } from "./opencode.js";
32+
import { truncateText } from "./text.js";
3133
import { loginWhatsApp, unpairWhatsApp } from "./whatsapp.js";
3234

33-
const VERSION = "0.1.11";
35+
const VERSION = "0.1.12";
3436

3537
type SetupStep = "config" | "whatsapp" | "telegram" | "start";
3638

@@ -89,6 +91,42 @@ function defaultSelections(configExists: boolean, whatsappLinked: boolean): Setu
8991
return selections;
9092
}
9193

94+
function createAppLogger(config: ReturnType<typeof loadConfig>) {
95+
return createLogger(config.logLevel, { logFile: config.logFile });
96+
}
97+
98+
function createConsoleReporter(): BridgeReporter {
99+
const formatChannel = (channel: ChannelName) => (channel === "whatsapp" ? "WhatsApp" : "Telegram");
100+
const formatPeer = (channel: ChannelName, peerId: string, fromMe?: boolean) => {
101+
const base = channel === "whatsapp" ? normalizeWhatsAppId(peerId) : peerId;
102+
return fromMe ? `${base} (me)` : base;
103+
};
104+
105+
const printBlock = (prefix: string, text: string) => {
106+
const lines = text.split(/\r?\n/).map((line) => truncateText(line.trim(), 240));
107+
const [first, ...rest] = lines.length ? lines : ["(empty)"];
108+
console.log(`${prefix} ${first}`);
109+
for (const line of rest) {
110+
console.log(`${" ".repeat(prefix.length)} ${line}`);
111+
}
112+
};
113+
114+
return {
115+
onStatus(message) {
116+
console.log(message);
117+
},
118+
onInbound({ channel, peerId, text, fromMe }) {
119+
const prefix = `[${formatChannel(channel)}] ${formatPeer(channel, peerId, fromMe)} >`;
120+
printBlock(prefix, text);
121+
},
122+
onOutbound({ channel, peerId, text, kind }) {
123+
const marker = kind === "reply" ? "<" : kind === "tool" ? "*" : "!";
124+
const prefix = `[${formatChannel(channel)}] ${formatPeer(channel, peerId)} ${marker}`;
125+
printBlock(prefix, text);
126+
},
127+
};
128+
}
129+
92130
function updateConfig(configPath: string, updater: (cfg: OwpenbotConfigFile) => OwpenbotConfigFile) {
93131
const { config } = readConfigFile(configPath);
94132
const base = config ?? { version: 1 };
@@ -244,12 +282,13 @@ async function runStart(pathOverride?: string) {
244282
process.env.OPENCODE_DIRECTORY = pathOverride.trim();
245283
}
246284
const config = loadConfig();
247-
const logger = createLogger(config.logLevel);
285+
const logger = createAppLogger(config);
286+
const reporter = createConsoleReporter();
248287
if (!process.env.OPENCODE_DIRECTORY) {
249288
process.env.OPENCODE_DIRECTORY = config.opencodeDirectory;
250289
}
251-
const bridge = await startBridge(config, logger);
252-
logger.info("Commands: owpenwork whatsapp login, owpenwork pairing list, owpenwork status");
290+
const bridge = await startBridge(config, logger, reporter);
291+
reporter.onStatus?.("Commands: owpenwork whatsapp login, owpenwork pairing list, owpenwork status");
253292

254293
const shutdown = async () => {
255294
logger.info("shutting down");
@@ -331,21 +370,21 @@ async function runGuidedFlow(pathArg: string | undefined, opts: { nonInteractive
331370
}
332371

333372
if (step === "whatsapp") {
334-
await runStep("Link WhatsApp", async () => {
335-
const alreadyLinked = fs.existsSync(authPath);
336-
if (alreadyLinked) {
337-
const relink = unwrap(
338-
await confirm({
339-
message: "WhatsApp already linked. Relink?",
340-
initialValue: false,
341-
}),
342-
) as boolean;
343-
if (!relink) return;
344-
}
345-
await loginWhatsApp(config, createLogger(config.logLevel));
346-
});
347-
continue;
348-
}
373+
await runStep("Link WhatsApp", async () => {
374+
const alreadyLinked = fs.existsSync(authPath);
375+
if (alreadyLinked) {
376+
const relink = unwrap(
377+
await confirm({
378+
message: "WhatsApp already linked. Relink?",
379+
initialValue: false,
380+
}),
381+
) as boolean;
382+
if (!relink) return;
383+
}
384+
await loginWhatsApp(config, createAppLogger(config), { onStatus: console.log });
385+
});
386+
continue;
387+
}
349388

350389
if (step === "telegram") {
351390
await runStep("Link Telegram", async () => {
@@ -413,7 +452,7 @@ login
413452
.description("Login to WhatsApp via QR code")
414453
.action(async () => {
415454
const config = loadConfig(process.env, { requireOpencode: false });
416-
await loginWhatsApp(config, createLogger(config.logLevel));
455+
await loginWhatsApp(config, createAppLogger(config), { onStatus: console.log });
417456
});
418457

419458
login
@@ -450,31 +489,31 @@ whatsapp
450489
.description("Login to WhatsApp via QR code")
451490
.action(async () => {
452491
const config = loadConfig(process.env, { requireOpencode: false });
453-
await loginWhatsApp(config, createLogger(config.logLevel));
492+
await loginWhatsApp(config, createAppLogger(config), { onStatus: console.log });
454493
});
455494

456495
whatsapp
457496
.command("logout")
458497
.description("Logout of WhatsApp and clear auth state")
459498
.action(() => {
460499
const config = loadConfig(process.env, { requireOpencode: false });
461-
unpairWhatsApp(config, createLogger(config.logLevel));
500+
unpairWhatsApp(config, createAppLogger(config));
462501
});
463502

464503
program
465504
.command("qr")
466505
.description("Print a WhatsApp QR code to pair")
467506
.action(async () => {
468507
const config = loadConfig(process.env, { requireOpencode: false });
469-
await loginWhatsApp(config, createLogger(config.logLevel));
508+
await loginWhatsApp(config, createAppLogger(config), { onStatus: console.log });
470509
});
471510

472511
program
473512
.command("unpair")
474513
.description("Clear WhatsApp pairing data")
475514
.action(() => {
476515
const config = loadConfig(process.env, { requireOpencode: false });
477-
unpairWhatsApp(config, createLogger(config.logLevel));
516+
unpairWhatsApp(config, createAppLogger(config));
478517
});
479518

480519
const pairing = program.command("pairing").description("Pairing requests");

‎packages/owpenbot/src/config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ export type Config = {
5353
whatsappEnabled: boolean;
5454
dataDir: string;
5555
dbPath: string;
56+
logFile: string;
5657
allowlist: Record<ChannelName, Set<string>>;
5758
toolUpdatesEnabled: boolean;
5859
groupsEnabled: boolean;
@@ -188,6 +189,7 @@ export function loadConfig(
188189

189190
const dataDir = expandHome(env.OWPENBOT_DATA_DIR ?? "~/.owpenbot");
190191
const dbPath = expandHome(env.OWPENBOT_DB_PATH ?? path.join(dataDir, "owpenbot.db"));
192+
const logFile = expandHome(env.OWPENBOT_LOG_FILE ?? path.join(dataDir, "logs", "owpenbot.log"));
191193
const configPath = resolveConfigPath(dataDir, env);
192194
const { config: configFile } = readConfigFile(configPath);
193195
const whatsappFile = configFile.channels?.whatsapp ?? {};
@@ -234,6 +236,7 @@ export function loadConfig(
234236
whatsappEnabled: parseBoolean(env.WHATSAPP_ENABLED, true),
235237
dataDir,
236238
dbPath,
239+
logFile,
237240
allowlist: envAllowlist,
238241
toolUpdatesEnabled: parseBoolean(env.TOOL_UPDATES_ENABLED, false),
239242
groupsEnabled: parseBoolean(env.GROUPS_ENABLED, false),

‎packages/owpenbot/src/logger.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
14
import pino from "pino";
25

3-
export function createLogger(level: string) {
6+
export function createLogger(level: string, options?: { logFile?: string }) {
7+
if (options?.logFile) {
8+
fs.mkdirSync(path.dirname(options.logFile), { recursive: true });
9+
const destination = pino.destination({ dest: options.logFile, sync: false });
10+
return pino({ level, base: undefined }, destination);
11+
}
12+
413
return pino({
514
level,
615
base: undefined,

‎packages/owpenbot/src/telegram.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,16 @@ export function createTelegramAdapter(
5050
const text = msg.text ?? msg.caption ?? "";
5151
if (!text.trim()) return;
5252

53-
await onMessage({
54-
channel: "telegram",
55-
peerId: String(msg.chat.id),
56-
text,
57-
raw: msg,
58-
});
53+
try {
54+
await onMessage({
55+
channel: "telegram",
56+
peerId: String(msg.chat.id),
57+
text,
58+
raw: msg,
59+
});
60+
} catch (error) {
61+
logger.error({ error, peerId: msg.chat.id }, "telegram inbound handler failed");
62+
}
5963
});
6064

6165
return {

0 commit comments

Comments
 (0)