Compare commits

..
15 Commits
15 changed files with 459 additions and 23 deletions

No files matched your search

+23
View File
@@ -1,5 +1,28 @@
# Changelog # Changelog
## 0.1.3 — 2025-11-25
### Features
- Added `cwd` option to command reply config for setting the working directory where commands execute. Essential for Claude Code to have proper project context.
- Added configurable file-based logging (default `/tmp/warelay/warelay.log`) with log level set via `logging.level` in `~/.warelay/warelay.json`; verbose still forces debug.
### Developer notes
- Command auto-replies now pass `{ timeoutMs, cwd }` into the command runner; custom runners/tests that stub `runCommandWithTimeout` should accept the options object as well as the legacy numeric timeout.
## 0.1.2 — 2025-11-25
### CI/build fix
- Fixed commander help configuration (`subcommandTerm`) so TypeScript builds pass in CI.
## 0.1.1 — 2025-11-25
### CLI polish
- Added a proper executable shim so `npx warelay@0.1.x --help` runs the CLI directly.
- Help/version banner now uses the README tagline with color, and the help footer includes colored examples with short explanations.
- `send` and `status` gained a `--verbose` flag for consistent noisy output when debugging.
- Lowercased branding in docs/UA; web provider UA is `warelay/cli/0.1.1`.
## 0.1.0 — 2025-11-25 ## 0.1.0 — 2025-11-25
### CLI & Providers ### CLI & Providers
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+26 -6
View File
@@ -1,7 +1,14 @@
# 📡 warelay — Send, receive, and auto-reply on WhatsApp—Twilio-backed or QR-linked. # 📡 warelay — Send, receive, and auto-reply on WhatsApp.
[![CI](https://github.com/steipete/warelay/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/steipete/warelay/actions/workflows/ci.yml)
[![npm version](https://img.shields.io/npm/v/warelay.svg)](https://www.npmjs.com/package/warelay) <p align="center">
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) <img src="README-header.png" alt="warelay header" width="640">
</p>
<p align="center">
<a href="https://github.com/steipete/warelay/actions/workflows/ci.yml?branch=main"><img src="https://img.shields.io/github/actions/workflow/status/steipete/warelay/ci.yml?branch=main&style=for-the-badge" alt="CI status"></a>
<a href="https://www.npmjs.com/package/warelay"><img src="https://img.shields.io/npm/v/warelay.svg?style=for-the-badge" alt="npm version"></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge" alt="MIT License"></a>
</p>
Send, receive, auto-reply, and inspect WhatsApp messages over **Twilio** or your personal **WhatsApp Web** session. Ships with a one-command webhook setup (Tailscale Funnel + Twilio callback) and a configurable auto-reply engine (plain text or command/Claude driven). Send, receive, auto-reply, and inspect WhatsApp messages over **Twilio** or your personal **WhatsApp Web** session. Ships with a one-command webhook setup (Tailscale Funnel + Twilio callback) and a configurable auto-reply engine (plain text or command/Claude driven).
@@ -84,6 +91,19 @@ Best practice: use a dedicated WhatsApp account (separate SIM/eSIM or business a
} }
``` ```
### Logging (optional)
- File logs are written to `/tmp/warelay/warelay.log` by default. Levels: `silent | fatal | error | warn | info | debug | trace` (CLI `--verbose` forces `debug`). Web-provider inbound/outbound entries include message bodies and auto-reply text for easier auditing.
- Override in `~/.warelay/warelay.json`:
```json5
{
logging: {
level: "warn",
file: "/tmp/warelay/custom.log"
}
}
```
### Claude CLI setup (how we run it) ### Claude CLI setup (how we run it)
1) Install the official Claude CLI (e.g., `brew install anthropic-ai/cli/claude` or follow the Anthropic docs) and run `claude login` so it can read your API key. 1) Install the official Claude CLI (e.g., `brew install anthropic-ai/cli/claude` or follow the Anthropic docs) and run `claude login` so it can read your API key.
2) In `warelay.json`, set `reply.mode` to `"command"` and point `command[0]` to `"claude"`; set `claudeOutputFormat` to `"text"` (or `"json"`/`"stream-json"` if you want warelay to parse and trim the JSON output). 2) In `warelay.json`, set `reply.mode` to `"command"` and point `command[0]` to `"claude"`; set `claudeOutputFormat` to `"text"` (or `"json"`/`"stream-json"` if you want warelay to parse and trim the JSON output).
@@ -122,9 +142,9 @@ Templating tokens: `{{Body}}`, `{{BodyStripped}}`, `{{From}}`, `{{To}}`, `{{Mess
- Web provider dropped: rerun `pnpm warelay login`; credentials live in `~/.warelay/credentials/`. - Web provider dropped: rerun `pnpm warelay login`; credentials live in `~/.warelay/credentials/`.
- Tailscale Funnel errors: update tailscale/tailscaled; check admin console that Funnel is enabled for this device. - Tailscale Funnel errors: update tailscale/tailscaled; check admin console that Funnel is enabled for this device.
## FAQ & Safety (quick answers) ## FAQ & Safety
- Twilio errors: **63016 “permission to send an SMS has not been enabled”** → ensure your number is WhatsApp-enabled; **63007 template not approved** → send a free-form session message within 24h or use an approved template; **63112 policy violation** → adjust content, shorten to <1600 chars, avoid links that trigger spam filters. Re-run `pnpm warelay status` to see the exact Twilio response body. - Twilio errors: **63016 “permission to send an SMS has not been enabled”** → ensure your number is WhatsApp-enabled; **63007 template not approved** → send a free-form session message within 24h or use an approved template; **63112 policy violation** → adjust content, shorten to <1600 chars, avoid links that trigger spam filters. Re-run `pnpm warelay status` to see the exact Twilio response body.
- Does this store my messages? Warelay only writes `~/.warelay/warelay.json` (config), `~/.warelay/credentials/` (WhatsApp Web auth), and `~/.warelay/sessions.json` (session IDs + timestamps). It does **not** persist message bodies beyond the session store. Logs print to stdout/stderr; redirect or rotate if needed. - Does this store my messages? warelay only writes `~/.warelay/warelay.json` (config), `~/.warelay/credentials/` (WhatsApp Web auth), and `~/.warelay/sessions.json` (session IDs + timestamps). It does **not** persist message bodies beyond the session store. Logs stream to stdout/stderr and also `/tmp/warelay/warelay.log` (configurable via `logging.file`).
- Personal WhatsApp safety: Automation on personal accounts can be rate-limited or logged out by WhatsApp. Use `--provider web` sparingly, keep messages human-like, and re-run `login` if the session is dropped. - Personal WhatsApp safety: Automation on personal accounts can be rate-limited or logged out by WhatsApp. Use `--provider web` sparingly, keep messages human-like, and re-run `login` if the session is dropped.
- Limits to remember: WhatsApp text limit ~1600 chars; avoid rapid bursts—space sends by a few seconds; keep webhook replies under a couple seconds for good UX; command auto-replies time out after 600s by default. - Limits to remember: WhatsApp text limit ~1600 chars; avoid rapid bursts—space sends by a few seconds; keep webhook replies under a couple seconds for good UX; command auto-replies time out after 600s by default.
- Deploy / keep running: Use `tmux` or `screen` for ad-hoc (`tmux new -s warelay -- pnpm warelay relay --provider twilio`). For long-running hosts, wrap `pnpm warelay relay ...` or `pnpm warelay webhook --ingress tailscale ...` in a systemd service or macOS LaunchAgent; ensure environment variables are loaded in that context. - Deploy / keep running: Use `tmux` or `screen` for ad-hoc (`tmux new -s warelay -- pnpm warelay relay --provider twilio`). For long-running hosts, wrap `pnpm warelay relay ...` or `pnpm warelay webhook --ingress tailscale ...` in a systemd service or macOS LaunchAgent; ensure environment variables are loaded in that context.
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env node
import("../dist/index.js").then((mod) => {
if (mod?.program?.parseAsync) {
mod.program.parseAsync(process.argv);
}
});
+7 -4
View File
@@ -12,7 +12,7 @@ This guide shows the exact way to wire **warelay** to the Claude CLI so inbound
- Optional: set `ANTHROPIC_API_KEY` in your shell profile for non-interactive use. - Optional: set `ANTHROPIC_API_KEY` in your shell profile for non-interactive use.
## Create your warelay config ## Create your warelay config
Warelay reads `~/.warelay/warelay.json` (JSON5 accepted). Add a command-mode reply that points at the Claude CLI: warelay reads `~/.warelay/warelay.json` (JSON5 accepted). Add a command-mode reply that points at the Claude CLI:
```json5 ```json5
{ {
@@ -21,6 +21,8 @@ Warelay reads `~/.warelay/warelay.json` (JSON5 accepted). Add a command-mode rep
allowFrom: ["+15551234567"], allowFrom: ["+15551234567"],
reply: { reply: {
mode: "command", mode: "command",
// Working directory for command execution (useful for Claude Code project context).
cwd: "/Users/you/Projects/my-project",
// Prepended before the inbound body; good for system prompts. // Prepended before the inbound body; good for system prompts.
bodyPrefix: "You are a concise WhatsApp assistant. Keep replies under 1500 characters.\n\n", bodyPrefix: "You are a concise WhatsApp assistant. Keep replies under 1500 characters.\n\n",
// Claude CLI argv; the final element is the prompt/body provided by warelay. // Claude CLI argv; the final element is the prompt/body provided by warelay.
@@ -38,13 +40,14 @@ Warelay reads `~/.warelay/warelay.json` (JSON5 accepted). Add a command-mode rep
``` ```
Notes on this configuration: Notes on this configuration:
- Warelay automatically injects a Claude identity prefix and the correct `--output-format`/`-p` flags when `command[0]` is `claude` and `claudeOutputFormat` is set. - `cwd` sets the working directory where the command runs. This is essential for Claude Code to have the right project context—Claude will see the project's `CLAUDE.md`, have access to project files, and understand the codebase structure.
- warelay automatically injects a Claude identity prefix and the correct `--output-format`/`-p` flags when `command[0]` is `claude` and `claudeOutputFormat` is set.
- Sessions are stored in `~/.warelay/sessions.json`; `scope: per-sender` keeps separate threads for each contact. - Sessions are stored in `~/.warelay/sessions.json`; `scope: per-sender` keeps separate threads for each contact.
- `bodyPrefix` is added before the inbound message body that reaches Claude. The string above mirrors the built-in 1500-character WhatsApp guardrail. - `bodyPrefix` is added before the inbound message body that reaches Claude. The string above mirrors the built-in 1500-character WhatsApp guardrail.
## How the flow works ## How the flow works
1. An inbound message (Twilio webhook, Twilio poller, or WhatsApp Web listener) arrives. 1. An inbound message (Twilio webhook, Twilio poller, or WhatsApp Web listener) arrives.
2. Warelay enqueues the command in a process-wide FIFO queue so only one Claude run happens at a time (`src/process/command-queue.ts`). 2. warelay enqueues the command in a process-wide FIFO queue so only one Claude run happens at a time (`src/process/command-queue.ts`).
3. Typing indicators are sent (Twilio) or `composing` presence is sent (Web) while Claude runs. 3. Typing indicators are sent (Twilio) or `composing` presence is sent (Web) while Claude runs.
4. Claude stdout is parsed: 4. Claude stdout is parsed:
- JSON mode is handled automatically if you set `claudeOutputFormat: "json"`; otherwise text is used. - JSON mode is handled automatically if you set `claudeOutputFormat: "json"`; otherwise text is used.
@@ -52,7 +55,7 @@ Notes on this configuration:
5. The reply (text and optional media) is sent back via the same provider that received the message. 5. The reply (text and optional media) is sent back via the same provider that received the message.
## Media and attachments ## Media and attachments
- To send an image from Claude, include a line like `MEDIA:https://example.com/pic.jpg` in the output. Warelay will: - To send an image from Claude, include a line like `MEDIA:https://example.com/pic.jpg` in the output. warelay will:
- Host local paths for Twilio using the media server/Tailscale Funnel. - Host local paths for Twilio using the media server/Tailscale Funnel.
- Send buffers directly for the Web provider. - Send buffers directly for the Web provider.
- Inbound media is downloaded (≤5 MB) and exposed to your templates as `{{MediaPath}}`, `{{MediaUrl}}`, and `{{MediaType}}`. You can mention this in your prompt if you want Claude to reason about the attachment. - Inbound media is downloaded (≤5 MB) and exposed to your templates as `{{MediaPath}}`, `{{MediaUrl}}`, and `{{MediaType}}`. You can mention this in your prompt if you want Claude to reason about the attachment.
+4 -4
View File
@@ -1,13 +1,13 @@
{ {
"name": "warelay", "name": "warelay",
"version": "0.1.0", "version": "0.1.3",
"description": "WhatsApp relay CLI (send, monitor, webhook, auto-reply) using Twilio", "description": "WhatsApp relay CLI (send, monitor, webhook, auto-reply) using Twilio",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"bin": { "bin": {
"warelay": "dist/index.js", "warelay": "bin/warelay.js",
"warely": "dist/index.js", "warely": "bin/warelay.js",
"wa": "dist/index.js" "wa": "bin/warelay.js"
}, },
"scripts": { "scripts": {
"dev": "tsx src/index.ts", "dev": "tsx src/index.ts",
+4 -2
View File
@@ -288,11 +288,13 @@ export async function getReplyFromConfig(
[CLAUDE_IDENTITY_PREFIX, existingBody].filter(Boolean).join("\n\n"), [CLAUDE_IDENTITY_PREFIX, existingBody].filter(Boolean).join("\n\n"),
]; ];
} }
logVerbose(`Running command auto-reply: ${finalArgv.join(" ")}`); logVerbose(
`Running command auto-reply: ${finalArgv.join(" ")}${reply.cwd ? ` (cwd: ${reply.cwd})` : ""}`,
);
const started = Date.now(); const started = Date.now();
try { try {
const { stdout, stderr, code, signal, killed } = await enqueueCommand( const { stdout, stderr, code, signal, killed } = await enqueueCommand(
() => commandRunner(finalArgv, timeoutMs), () => commandRunner(finalArgv, { timeoutMs, cwd: reply.cwd }),
{ {
onWait: (waitMs, queuedAhead) => { onWait: (waitMs, queuedAhead) => {
if (isVerbose()) { if (isVerbose()) {
+67 -1
View File
@@ -1,3 +1,4 @@
import chalk from "chalk";
import { Command } from "commander"; import { Command } from "commander";
import { sendCommand } from "../commands/send.js"; import { sendCommand } from "../commands/send.js";
import { statusCommand } from "../commands/status.js"; import { statusCommand } from "../commands/status.js";
@@ -17,11 +18,76 @@ import { spawnRelayTmux } from "./relay_tmux.js";
export function buildProgram() { export function buildProgram() {
const program = new Command(); const program = new Command();
const PROGRAM_VERSION = "0.1.3";
const TAGLINE =
"Send, receive, and auto-reply on WhatsApp—Twilio-backed or QR-linked.";
program program
.name("warelay") .name("warelay")
.description("WhatsApp relay CLI (Twilio or WhatsApp Web session)") .description("WhatsApp relay CLI (Twilio or WhatsApp Web session)")
.version("1.0.0"); .version(PROGRAM_VERSION);
const formatIntroLine = (version: string, rich = true) => {
const base = `📡 warelay ${version} — ${TAGLINE}`;
return rich && chalk.level > 0
? `${chalk.bold.cyan("📡 warelay")} ${chalk.white(version)} ${chalk.gray("—")} ${chalk.green(TAGLINE)}`
: base;
};
program.configureHelp({
optionTerm: (option) => chalk.yellow(option.flags),
subcommandTerm: (cmd) => chalk.green(cmd.name()),
});
program.configureOutput({
writeOut: (str) => {
const colored = str
.replace(/^Usage:/gm, chalk.bold.cyan("Usage:"))
.replace(/^Options:/gm, chalk.bold.cyan("Options:"))
.replace(/^Commands:/gm, chalk.bold.cyan("Commands:"));
process.stdout.write(colored);
},
writeErr: (str) => process.stderr.write(str),
outputError: (str, write) => write(chalk.red(str)),
});
if (process.argv.includes("-V") || process.argv.includes("--version")) {
console.log(formatIntroLine(PROGRAM_VERSION));
process.exit(0);
}
program.addHelpText("beforeAll", `\n${formatIntroLine(PROGRAM_VERSION)}\n`);
const examples = [
[
"warelay login --verbose",
"Link personal WhatsApp Web and show QR + connection logs.",
],
[
'warelay send --to +15551234567 --message "Hi" --provider web --json',
"Send via your web session and print JSON result.",
],
[
"warelay relay --provider auto --interval 5 --lookback 15 --verbose",
"Auto-reply loop: prefer Web when logged in, otherwise Twilio polling.",
],
[
"warelay webhook --ingress tailscale --port 42873 --path /webhook/whatsapp --verbose",
"Start webhook + Tailscale Funnel and update Twilio callbacks.",
],
[
"warelay status --limit 10 --lookback 60 --json",
"Show last 10 messages from the past hour as JSON.",
],
] as const;
const fmtExamples = examples
.map(([cmd, desc]) => ` ${chalk.green(cmd)}\n ${chalk.gray(desc)}`)
.join("\n");
program.addHelpText(
"afterAll",
`\n${chalk.bold.cyan("Examples:")}\n${fmtExamples}\n`,
);
program program
.command("login") .command("login")
+24
View File
@@ -19,13 +19,20 @@ export type SessionConfig = {
sessionArgBeforeBody?: boolean; sessionArgBeforeBody?: boolean;
}; };
export type LoggingConfig = {
level?: "silent" | "fatal" | "error" | "warn" | "info" | "debug" | "trace";
file?: string;
};
export type WarelayConfig = { export type WarelayConfig = {
logging?: LoggingConfig;
inbound?: { inbound?: {
allowFrom?: string[]; // E.164 numbers allowed to trigger auto-reply (without whatsapp:) allowFrom?: string[]; // E.164 numbers allowed to trigger auto-reply (without whatsapp:)
reply?: { reply?: {
mode: ReplyMode; mode: ReplyMode;
text?: string; // for mode=text, can contain {{Body}} text?: string; // for mode=text, can contain {{Body}}
command?: string[]; // for mode=command, argv with templates command?: string[]; // for mode=command, argv with templates
cwd?: string; // working directory for command execution
template?: string; // prepend template string when building command/prompt template?: string; // prepend template string when building command/prompt
timeoutSeconds?: number; // optional command timeout; defaults to 600s timeoutSeconds?: number; // optional command timeout; defaults to 600s
bodyPrefix?: string; // optional string prepended to Body before templating bodyPrefix?: string; // optional string prepended to Body before templating
@@ -43,6 +50,7 @@ const ReplySchema = z
mode: z.union([z.literal("text"), z.literal("command")]), mode: z.union([z.literal("text"), z.literal("command")]),
text: z.string().optional(), text: z.string().optional(),
command: z.array(z.string()).optional(), command: z.array(z.string()).optional(),
cwd: z.string().optional(),
template: z.string().optional(), template: z.string().optional(),
timeoutSeconds: z.number().int().positive().optional(), timeoutSeconds: z.number().int().positive().optional(),
bodyPrefix: z.string().optional(), bodyPrefix: z.string().optional(),
@@ -78,6 +86,22 @@ const ReplySchema = z
); );
const WarelaySchema = z.object({ const WarelaySchema = z.object({
logging: z
.object({
level: z
.union([
z.literal("silent"),
z.literal("fatal"),
z.literal("error"),
z.literal("warn"),
z.literal("info"),
z.literal("debug"),
z.literal("trace"),
])
.optional(),
file: z.string().optional(),
})
.optional(),
inbound: z inbound: z
.object({ .object({
allowFrom: z.array(z.string()).optional(), allowFrom: z.array(z.string()).optional(),
+49 -1
View File
@@ -1,10 +1,22 @@
import { describe, expect, it, vi } from "vitest"; import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { setVerbose } from "./globals.js"; import { setVerbose } from "./globals.js";
import { logDebug, logError, logInfo, logSuccess, logWarn } from "./logger.js"; import { logDebug, logError, logInfo, logSuccess, logWarn } from "./logger.js";
import { resetLogger, setLoggerOverride } from "./logging.js";
import type { RuntimeEnv } from "./runtime.js"; import type { RuntimeEnv } from "./runtime.js";
describe("logger helpers", () => { describe("logger helpers", () => {
afterEach(() => {
resetLogger();
setLoggerOverride(null);
setVerbose(false);
});
it("formats messages through runtime log/error", () => { it("formats messages through runtime log/error", () => {
const log = vi.fn(); const log = vi.fn();
const error = vi.fn(); const error = vi.fn();
@@ -31,4 +43,40 @@ describe("logger helpers", () => {
expect(logVerbose).toHaveBeenCalled(); expect(logVerbose).toHaveBeenCalled();
logVerbose.mockRestore(); logVerbose.mockRestore();
}); });
it("writes to configured log file at configured level", () => {
const logPath = pathForTest();
cleanup(logPath);
setLoggerOverride({ level: "debug", file: logPath });
logInfo("hello");
logDebug("debug-only");
const content = fs.readFileSync(logPath, "utf-8");
expect(content).toContain("hello");
expect(content).toContain("debug-only");
cleanup(logPath);
});
it("filters messages below configured level", () => {
const logPath = pathForTest();
cleanup(logPath);
setLoggerOverride({ level: "warn", file: logPath });
logInfo("info-only");
logWarn("warn-only");
const content = fs.readFileSync(logPath, "utf-8");
expect(content).not.toContain("info-only");
expect(content).toContain("warn-only");
cleanup(logPath);
});
}); });
function pathForTest() {
return path.join(os.tmpdir(), `warelay-log-${crypto.randomUUID()}.log`);
}
function cleanup(file: string) {
try {
fs.rmSync(file, { force: true });
} catch {
// ignore
}
}
+7 -1
View File
@@ -6,14 +6,17 @@ import {
success, success,
warn, warn,
} from "./globals.js"; } from "./globals.js";
import { getLogger } from "./logging.js";
import { defaultRuntime, type RuntimeEnv } from "./runtime.js"; import { defaultRuntime, type RuntimeEnv } from "./runtime.js";
export function logInfo(message: string, runtime: RuntimeEnv = defaultRuntime) { export function logInfo(message: string, runtime: RuntimeEnv = defaultRuntime) {
runtime.log(info(message)); runtime.log(info(message));
getLogger().info(message);
} }
export function logWarn(message: string, runtime: RuntimeEnv = defaultRuntime) { export function logWarn(message: string, runtime: RuntimeEnv = defaultRuntime) {
runtime.log(warn(message)); runtime.log(warn(message));
getLogger().warn(message);
} }
export function logSuccess( export function logSuccess(
@@ -21,6 +24,7 @@ export function logSuccess(
runtime: RuntimeEnv = defaultRuntime, runtime: RuntimeEnv = defaultRuntime,
) { ) {
runtime.log(success(message)); runtime.log(success(message));
getLogger().info(message);
} }
export function logError( export function logError(
@@ -28,9 +32,11 @@ export function logError(
runtime: RuntimeEnv = defaultRuntime, runtime: RuntimeEnv = defaultRuntime,
) { ) {
runtime.error(danger(message)); runtime.error(danger(message));
getLogger().error(message);
} }
export function logDebug(message: string) { export function logDebug(message: string) {
// Verbose helper that respects global verbosity flag. // Always emit to file logger (level-filtered); console only when verbose.
getLogger().debug(message);
if (isVerbose()) logVerbose(message); if (isVerbose()) logVerbose(message);
} }
+101
View File
@@ -0,0 +1,101 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import pino, { type Bindings, type LevelWithSilent, type Logger } from "pino";
import { loadConfig, type WarelayConfig } from "./config/config.js";
import { isVerbose } from "./globals.js";
const DEFAULT_LOG_DIR = path.join(os.tmpdir(), "warelay");
export const DEFAULT_LOG_FILE = path.join(DEFAULT_LOG_DIR, "warelay.log");
const ALLOWED_LEVELS: readonly LevelWithSilent[] = [
"silent",
"fatal",
"error",
"warn",
"info",
"debug",
"trace",
];
export type LoggerSettings = {
level?: LevelWithSilent;
file?: string;
};
type ResolvedSettings = {
level: LevelWithSilent;
file: string;
};
let cachedLogger: Logger | null = null;
let cachedSettings: ResolvedSettings | null = null;
let overrideSettings: LoggerSettings | null = null;
function normalizeLevel(level?: string): LevelWithSilent {
if (isVerbose()) return "debug";
const candidate = level ?? "info";
return ALLOWED_LEVELS.includes(candidate as LevelWithSilent)
? (candidate as LevelWithSilent)
: "info";
}
function resolveSettings(): ResolvedSettings {
const cfg: WarelayConfig["logging"] | undefined =
overrideSettings ?? loadConfig().logging;
const level = normalizeLevel(cfg?.level);
const file = cfg?.file ?? DEFAULT_LOG_FILE;
return { level, file };
}
function settingsChanged(a: ResolvedSettings | null, b: ResolvedSettings) {
if (!a) return true;
return a.level !== b.level || a.file !== b.file;
}
function buildLogger(settings: ResolvedSettings): Logger {
fs.mkdirSync(path.dirname(settings.file), { recursive: true });
const destination = pino.destination({
dest: settings.file,
mkdir: true,
sync: true, // deterministic for tests; log volume is modest.
});
return pino(
{
level: settings.level,
base: undefined,
timestamp: pino.stdTimeFunctions.isoTime,
},
destination,
);
}
export function getLogger(): Logger {
const settings = resolveSettings();
if (!cachedLogger || settingsChanged(cachedSettings, settings)) {
cachedLogger = buildLogger(settings);
cachedSettings = settings;
}
return cachedLogger;
}
export function getChildLogger(
bindings?: Bindings,
opts?: { level?: LevelWithSilent },
): Logger {
return getLogger().child(bindings ?? {}, opts);
}
// Test helpers
export function setLoggerOverride(settings: LoggerSettings | null) {
overrideSettings = settings;
cachedLogger = null;
cachedSettings = null;
}
export function resetLogger() {
cachedLogger = null;
cachedSettings = null;
overrideSettings = null;
}
+13 -1
View File
@@ -43,14 +43,26 @@ export type SpawnResult = {
killed: boolean; killed: boolean;
}; };
export type CommandOptions = {
timeoutMs: number;
cwd?: string;
};
export async function runCommandWithTimeout( export async function runCommandWithTimeout(
argv: string[], argv: string[],
timeoutMs: number, optionsOrTimeout: number | CommandOptions,
): Promise<SpawnResult> { ): Promise<SpawnResult> {
const options: CommandOptions =
typeof optionsOrTimeout === "number"
? { timeoutMs: optionsOrTimeout }
: optionsOrTimeout;
const { timeoutMs, cwd } = options;
// Spawn with inherited stdin (TTY) so tools like `claude` don't hang. // Spawn with inherited stdin (TTY) so tools like `claude` don't hang.
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
const child = spawn(argv[0], argv.slice(1), { const child = spawn(argv[0], argv.slice(1), {
stdio: ["inherit", "pipe", "pipe"], stdio: ["inherit", "pipe", "pipe"],
cwd,
}); });
let stdout = ""; let stdout = "";
let stderr = ""; let stderr = "";
+75
View File
@@ -1,5 +1,8 @@
import crypto from "node:crypto";
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import fsSync from "node:fs"; import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { MockBaileysSocket } from "../test/mocks/baileys.js"; import type { MockBaileysSocket } from "../test/mocks/baileys.js";
import { createMockBaileys } from "../test/mocks/baileys.js"; import { createMockBaileys } from "../test/mocks/baileys.js";
@@ -39,6 +42,7 @@ vi.mock("qrcode-terminal", () => ({
})); }));
import { monitorWebProvider } from "./index.js"; import { monitorWebProvider } from "./index.js";
import { resetLogger, setLoggerOverride } from "./logging.js";
import { import {
createWaSocket, createWaSocket,
loginWeb, loginWeb,
@@ -78,6 +82,8 @@ describe("provider-web", () => {
afterEach(() => { afterEach(() => {
vi.useRealTimers(); vi.useRealTimers();
resetLogger();
setLoggerOverride(null);
}); });
it("creates WA socket with QR handler", async () => { it("creates WA socket with QR handler", async () => {
@@ -230,6 +236,37 @@ describe("provider-web", () => {
await listener.close(); await listener.close();
}); });
it("monitorWebInbox logs inbound bodies to file", async () => {
const logPath = path.join(
os.tmpdir(),
`warelay-log-test-${crypto.randomUUID()}.log`,
);
setLoggerOverride({ level: "trace", file: logPath });
const onMessage = vi.fn();
const listener = await monitorWebInbox({ verbose: false, onMessage });
const sock = getLastSocket();
const upsert = {
type: "notify",
messages: [
{
key: { id: "abc", fromMe: false, remoteJid: "999@s.whatsapp.net" },
message: { conversation: "ping" },
messageTimestamp: 1_700_000_000,
pushName: "Tester",
},
],
};
sock.ev.emit("messages.upsert", upsert);
await new Promise((resolve) => setImmediate(resolve));
const content = fsSync.readFileSync(logPath, "utf-8");
expect(content).toContain('"module":"web-inbound"');
expect(content).toContain('"body":"ping"');
await listener.close();
});
it("monitorWebInbox includes participant when marking group messages read", async () => { it("monitorWebInbox includes participant when marking group messages read", async () => {
const onMessage = vi.fn(); const onMessage = vi.fn();
const listener = await monitorWebInbox({ verbose: false, onMessage }); const listener = await monitorWebInbox({ verbose: false, onMessage });
@@ -310,6 +347,44 @@ describe("provider-web", () => {
fetchMock.mockRestore(); fetchMock.mockRestore();
}); });
it("logs outbound replies to file", async () => {
const logPath = path.join(
os.tmpdir(),
`warelay-log-test-${crypto.randomUUID()}.log`,
);
setLoggerOverride({ level: "trace", file: logPath });
let capturedOnMessage:
| ((msg: import("./provider-web.js").WebInboundMessage) => Promise<void>)
| undefined;
const listenerFactory = async (opts: {
onMessage: (
msg: import("./provider-web.js").WebInboundMessage,
) => Promise<void>;
}) => {
capturedOnMessage = opts.onMessage;
return { close: vi.fn() };
};
const resolver = vi.fn().mockResolvedValue({ text: "auto" });
await monitorWebProvider(false, listenerFactory, false, resolver);
expect(capturedOnMessage).toBeDefined();
await capturedOnMessage?.({
body: "hello",
from: "+1",
to: "+2",
id: "msg1",
sendComposing: vi.fn(),
reply: vi.fn(),
sendMedia: vi.fn(),
});
const content = fsSync.readFileSync(logPath, "utf-8");
expect(content).toContain('"module":"web-auto-reply"');
expect(content).toContain('"text":"auto"');
});
it("logWebSelfId prints cached E.164 when creds exist", () => { it("logWebSelfId prints cached E.164 when creds exist", () => {
const existsSpy = vi const existsSpy = vi
.spyOn(fsSync, "existsSync") .spyOn(fsSync, "existsSync")
+53 -3
View File
@@ -13,12 +13,12 @@ import {
useMultiFileAuthState, useMultiFileAuthState,
type WAMessage, type WAMessage,
} from "@whiskeysockets/baileys"; } from "@whiskeysockets/baileys";
import pino from "pino";
import qrcode from "qrcode-terminal"; import qrcode from "qrcode-terminal";
import { getReplyFromConfig } from "./auto-reply/reply.js"; import { getReplyFromConfig } from "./auto-reply/reply.js";
import { waitForever } from "./cli/wait.js"; import { waitForever } from "./cli/wait.js";
import { danger, info, isVerbose, logVerbose, success } from "./globals.js"; import { danger, info, isVerbose, logVerbose, success } from "./globals.js";
import { logInfo } from "./logger.js"; import { logInfo } from "./logger.js";
import { getChildLogger } from "./logging.js";
import { saveMediaBuffer } from "./media/store.js"; import { saveMediaBuffer } from "./media/store.js";
import { defaultRuntime, type RuntimeEnv } from "./runtime.js"; import { defaultRuntime, type RuntimeEnv } from "./runtime.js";
import type { Provider } from "./utils.js"; import type { Provider } from "./utils.js";
@@ -31,7 +31,12 @@ function formatDuration(ms: number) {
const WA_WEB_AUTH_DIR = path.join(os.homedir(), ".warelay", "credentials"); const WA_WEB_AUTH_DIR = path.join(os.homedir(), ".warelay", "credentials");
export async function createWaSocket(printQr: boolean, verbose: boolean) { export async function createWaSocket(printQr: boolean, verbose: boolean) {
const logger = pino({ level: verbose ? "info" : "silent" }); const logger = getChildLogger(
{ module: "baileys" },
{
level: verbose ? "info" : "silent",
},
);
// Some Baileys internals call logger.trace even when silent; ensure it's present. // Some Baileys internals call logger.trace even when silent; ensure it's present.
const loggerAny = logger as unknown as Record<string, unknown>; const loggerAny = logger as unknown as Record<string, unknown>;
if (typeof loggerAny.trace !== "function") { if (typeof loggerAny.trace !== "function") {
@@ -48,7 +53,7 @@ export async function createWaSocket(printQr: boolean, verbose: boolean) {
version, version,
logger, logger,
printQRInTerminal: false, printQRInTerminal: false,
browser: ["Warelay", "CLI", "1.0.0"], browser: ["warelay", "cli", "0.1.3"],
syncFullHistory: false, syncFullHistory: false,
markOnlineOnConnect: false, markOnlineOnConnect: false,
}); });
@@ -246,6 +251,7 @@ export async function monitorWebInbox(options: {
verbose: boolean; verbose: boolean;
onMessage: (msg: WebInboundMessage) => Promise<void>; onMessage: (msg: WebInboundMessage) => Promise<void>;
}) { }) {
const inboundLogger = getChildLogger({ module: "web-inbound" });
const sock = await createWaSocket(false, options.verbose); const sock = await createWaSocket(false, options.verbose);
await waitForWaConnection(sock); await waitForWaConnection(sock);
try { try {
@@ -333,6 +339,17 @@ export async function monitorWebInbox(options: {
const timestamp = msg.messageTimestamp const timestamp = msg.messageTimestamp
? Number(msg.messageTimestamp) * 1000 ? Number(msg.messageTimestamp) * 1000
: undefined; : undefined;
inboundLogger.info(
{
from,
to: selfE164 ?? "me",
body,
mediaPath,
mediaType,
timestamp,
},
"inbound message",
);
try { try {
await options.onMessage({ await options.onMessage({
id, id,
@@ -373,6 +390,7 @@ export async function monitorWebProvider(
replyResolver: typeof getReplyFromConfig = getReplyFromConfig, replyResolver: typeof getReplyFromConfig = getReplyFromConfig,
runtime: RuntimeEnv = defaultRuntime, runtime: RuntimeEnv = defaultRuntime,
) { ) {
const replyLogger = getChildLogger({ module: "web-auto-reply" });
// Listen for inbound personal WhatsApp Web messages and auto-reply if configured. // Listen for inbound personal WhatsApp Web messages and auto-reply if configured.
const listener = await listenerFactory({ const listener = await listenerFactory({
verbose, verbose,
@@ -420,6 +438,17 @@ export async function monitorWebProvider(
`✅ Sent web media reply to ${msg.from} (${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB)`, `✅ Sent web media reply to ${msg.from} (${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB)`,
runtime, runtime,
); );
replyLogger.info(
{
to: msg.from,
from: msg.to,
text: replyResult.text ?? null,
mediaUrl: replyResult.mediaUrl,
mediaSizeBytes: media.buffer.length,
durationMs: Date.now() - replyStarted,
},
"auto-reply sent (media)",
);
} catch (err) { } catch (err) {
console.error( console.error(
danger(`Failed sending web media to ${msg.from}: ${String(err)}`), danger(`Failed sending web media to ${msg.from}: ${String(err)}`),
@@ -430,6 +459,17 @@ export async function monitorWebProvider(
`⚠️ Media skipped; sent text-only to ${msg.from}`, `⚠️ Media skipped; sent text-only to ${msg.from}`,
runtime, runtime,
); );
replyLogger.info(
{
to: msg.from,
from: msg.to,
text: replyResult.text,
mediaUrl: replyResult.mediaUrl,
durationMs: Date.now() - replyStarted,
mediaSendFailed: true,
},
"auto-reply sent (text fallback)",
);
} }
} }
} else { } else {
@@ -449,6 +489,16 @@ export async function monitorWebProvider(
), ),
); );
} }
replyLogger.info(
{
to: msg.from,
from: msg.to,
text: replyResult.text ?? null,
mediaUrl: replyResult.mediaUrl,
durationMs,
},
"auto-reply sent",
);
} catch (err) { } catch (err) {
console.error( console.error(
danger( danger(