Compare commits

..
97 Commits
Author SHA1 Message Date
Peter Steinberger 6d7e620430 Release 1.2.0 2025-11-27 18:52:26 +01:00
Peter Steinberger 0cc732dce3 Docs: refresh 1.2.0 changelog; fix webhook host import 2025-11-27 18:46:46 +01:00
Peter Steinberger 8acd82aa0d Add gowa WhatsApp MCP to power user add-ons 2025-11-27 18:45:05 +01:00
Peter Steinberger 7377c676fd Add WhatsApp screenshot to claude-config.md
Shows Clawd in action in the "Meet Clawd" section
2025-11-27 18:43:24 +01:00
Peter Steinberger 9b3c4db10d Heartbeat defaults and ws guard; format 2025-11-27 18:37:30 +01:00
Peter Steinberger 49ada54f6d Docs: add useful CLI tools section (spotify-player, TTS, etc.) 2025-11-27 18:33:38 +01:00
Peter Steinberger c43cdc5ac3 Docs: new Clawd session intro with personality and powers 2025-11-27 18:32:47 +01:00
Peter Steinberger e1bd9976b3 Docs: explain two-phone setup for dedicated AI number 2025-11-27 18:29:41 +01:00
Peter Steinberger a888564251 Docs: mention Claude Code reuses existing subscription 2025-11-27 18:28:51 +01:00
Peter Steinberger e2ccde6434 Fix: warelay lowercase 2025-11-27 18:27:09 +01:00
Peter Steinberger e88ff78816 Add Peekaboo and mcporter links to recommended tools 2025-11-27 18:26:40 +01:00
Peter Steinberger 5bc151fdca Redact phone number from example config 2025-11-27 18:24:12 +01:00
Peter Steinberger f0a5cdc6e4 Add warning disclaimer to claude-config.md 2025-11-27 18:23:56 +01:00
Peter Steinberger 85f53a4174 Fix WebSocket crash + heartbeat default 10min + docs refresh
- Wrap Baileys connection.update listeners in try-catch to prevent
  unhandled exceptions from crashing the relay process
- Add WebSocket-level error handlers in session.ts
- Add global unhandledRejection/uncaughtException handlers in index.ts
- Make listener.onClose error-safe with .catch() in auto-reply.ts
- Change default heartbeat from 30min to 10min
- Rewrite claude-config.md with personality, better explain personal
  assistant features, add recommended MCPs section
2025-11-27 18:21:14 +01:00
Peter Steinberger 549ad272fc Docs: link Clawd setup and current config 2025-11-27 18:17:17 +01:00
Peter Steinberger 537348d995 Update README.md 2025-11-27 18:14:54 +01:00
Peter Steinberger d4580d1a31 Fix CI: type gaps and hasMedia check 2025-11-27 18:14:20 +01:00
Peter Steinberger 93a103dde5 Tests: cover identity prefix gating 2025-11-27 04:40:03 +01:00
Peter Steinberger 9e6ad97cfb Claude prompt: only prepend on first turn 2025-11-27 03:53:13 +01:00
Peter Steinberger 8d995a8529 Heartbeat: add ultrathink marker 2025-11-27 03:15:51 +01:00
Peter Steinberger f869cd4b79 Heartbeat: shorten prompt to token 2025-11-27 02:48:23 +01:00
Peter Steinberger 26b087c1b4 Heartbeat: honor session override 2025-11-26 18:32:25 +01:00
Peter Steinberger 63bf4683c5 Heartbeat: allow session-id override (with test) 2025-11-26 18:28:02 +01:00
Peter Steinberger 73456a68d7 Fix heartbeat CLI import for recipients resolution 2025-11-26 18:22:28 +01:00
Peter Steinberger aa6637b47a Heartbeat: session-id override and safer fallback 2025-11-26 18:19:54 +01:00
Peter Steinberger 8f6e43fd66 Changelog: bump to 1.2.0 unreleased 2025-11-26 18:18:13 +01:00
Peter Steinberger ebce6ef263 Docs: show --all heartbeat example 2025-11-26 18:17:30 +01:00
Peter Steinberger c20a266a11 Heartbeat: harden targeting and support lid mapping 2025-11-26 18:15:57 +01:00
Marcus Neves b825f141f3 fix: add @lid format support and allowFrom wildcard handling
- Add support for WhatsApp Linked ID (@lid) format in jidToE164()
- Use existing lid-mapping-*_reverse.json files for LID resolution
- Fix allowFrom wildcard '*' to actually allow all senders
- Maintain backward compatibility with @s.whatsapp.net format

Fixes issues where:
- Messages from newer WhatsApp versions are silently dropped
- allowFrom: ['*'] configuration doesn't work as documented
2025-11-26 18:03:12 +01:00
Peter Steinberger 7e5b3958cc CLI: rename heartbeat tmux helper and log file path 2025-11-26 18:00:23 +01:00
Peter Steinberger deded848ee Heartbeat: add relay helper and fix CLI tests 2025-11-26 17:49:34 +01:00
Peter Steinberger 117161e6ff docs: document heartbeat idle override and tests 2025-11-26 17:31:56 +01:00
Peter Steinberger 98d52edcc9 test: cover heartbeat skip preserving session timestamp 2025-11-26 17:29:12 +01:00
Peter Steinberger 135d930c99 feat: add heartbeat idle override and preserve session freshness 2025-11-26 17:26:17 +01:00
Peter Steinberger e6c78df975 chore: add verbose heartbeat session logging 2025-11-26 17:21:59 +01:00
Peter Steinberger 3749797434 chore: log heartbeat session snapshot 2025-11-26 17:20:48 +01:00
Peter Steinberger 507ed25289 chore: log heartbeat fallback and add test 2025-11-26 17:12:28 +01:00
Peter Steinberger 0d5e5f8dee fix: heartbeat falls back to last session contact 2025-11-26 17:08:43 +01:00
Peter Steinberger 3998933b30 docs: document heartbeat triggers 2025-11-26 17:05:09 +01:00
Peter Steinberger 271004bf60 feat: add heartbeat cli and relay trigger 2025-11-26 17:04:43 +01:00
Peter Steinberger c9e2d69bfb docs: open 1.1.x unreleased section 2025-11-26 03:33:44 +01:00
Peter Steinberger c194247dab test(auto-reply): cover cwd timeout hint and queue meta 2025-11-26 03:03:13 +01:00
Peter Steinberger a48420d85f docs: finalize web refactor and coverage 2025-11-26 02:54:43 +01:00
Peter Steinberger 5c66e8273b chore: update changelog and surface web relay settings 2025-11-26 02:43:24 +01:00
Peter Steinberger 5992e629c3 web: add reconnect logging + troubleshooting doc 2025-11-26 02:41:10 +01:00
Peter Steinberger 765d67cd18 web: extract reconnect helpers and add tests 2025-11-26 02:39:31 +01:00
Peter Steinberger baf20af17f web: add heartbeat and bounded reconnect tuning 2025-11-26 02:34:43 +01:00
Peter Steinberger e482e7768b chore: commit pending cli/web test tweaks 2025-11-26 02:19:45 +01:00
Peter Steinberger 8682352edb docs: trim changelog to user-facing auto-reply changes 2025-11-26 02:19:21 +01:00
Peter Steinberger ef1222ff31 chore: drop refactor note 2025-11-26 02:18:57 +01:00
Peter Steinberger 0145f3a585 docs: note auto-reply helper split 2025-11-26 02:18:39 +01:00
Peter Steinberger 4a8bb56a1e chore(auto-reply): include cwd in timeout message 2025-11-26 02:18:16 +01:00
Peter Steinberger ce5b02a9ad test(auto-reply): add helper coverage and docs 2025-11-26 02:09:50 +01:00
Peter Steinberger 5c8ce41e12 refactor(auto-reply): split reply helpers 2025-11-26 02:03:51 +01:00
Peter Steinberger a2586b8b06 feat(web): add logout command and tests 2025-11-26 01:29:02 +01:00
Peter Steinberger 1fd4485716 Auto-reply: refresh typing indicator every 8s 2025-11-26 01:27:51 +01:00
Peter Steinberger b029ab933e chore(tests): organize web test imports 2025-11-26 01:24:34 +01:00
Peter Steinberger e0b28b6718 test(web): split provider web suite 2025-11-26 01:23:34 +01:00
Peter Steinberger 4dd2f3b7f7 refactor(web): split provider module 2025-11-26 01:16:54 +01:00
Peter Steinberger e5f677803f chore: format to 2-space and bump changelog 2025-11-26 00:53:53 +01:00
Peter Steinberger a67f4db5e2 chore: format + lint 2025-11-26 00:30:30 +01:00
Peter Steinberger 8a01dc7f4c style: normalize indentation to 2 spaces 2025-11-26 00:15:10 +01:00
Peter Steinberger e107f115e2 chore: bump version to 1.1.0 2025-11-26 00:11:42 +01:00
Peter Steinberger af8af4881b docs/tests: typing interval docs and coverage 2025-11-26 00:10:38 +01:00
Peter Steinberger d871dad85f feat: keep typing indicators alive during commands 2025-11-26 00:05:11 +01:00
Peter Steinberger 5b83d30887 test: cover sendSystemOnce default 2025-11-25 23:57:41 +01:00
Peter Steinberger 2e3b8a03aa feat: send session prompt once 2025-11-25 23:52:38 +01:00
Peter Steinberger d924b7d283 docs: document media caps and tidy web tests 2025-11-25 23:43:57 +01:00
Peter Steinberger e0425ad3e1 feat: support audio/video/doc media caps and transcript context 2025-11-25 23:21:35 +01:00
Peter Steinberger 5dced02a20 docs: clarify transcript prompt and config 2025-11-25 23:14:23 +01:00
Peter Steinberger e642f128ae feat: transcribe audio and surface transcript to prompts 2025-11-25 23:13:22 +01:00
Peter Steinberger 7d0ae151e8 feat: optional audio transcription via CLI 2025-11-25 23:06:54 +01:00
Peter Steinberger f945e284e1 test: cover media formats + doc resize cap 2025-11-25 22:23:06 +01:00
Peter Steinberger 7166efef08 docs: document media resize config 2025-11-25 22:16:09 +01:00
Peter Steinberger a81689e902 chore: approve build scripts 2025-11-25 20:11:36 +01:00
Peter Steinberger 0a0418b973 web: compress auto-reply media 2025-11-25 20:09:03 +01:00
Peter Steinberger f81f432af5 Release 1.0.4 2025-11-25 18:12:44 +01:00
Peter Steinberger dda017df23 Web relay: auto-reconnect Baileys and test 2025-11-25 18:09:57 +01:00
Peter Steinberger 46be5eac7d Auto-reply: send timeout fallback and tests 2025-11-25 17:52:57 +01:00
Peter Steinberger e4076d14c0 Docs: clarify release body should not repeat title 2025-11-25 17:11:24 +01:00
Peter Steinberger 20fc412765 Refactor: derive version from package.json 2025-11-25 17:10:53 +01:00
Peter Steinberger c251681a40 Chore: prep 0.1.4 unreleased placeholder and release guardrails 2025-11-25 17:08:13 +01:00
Peter Steinberger 9c25e15e92 Release 0.1.3 2025-11-25 16:53:30 +01:00
Peter Steinberger bcbf0de240 Add cwd option for command replies 2025-11-25 16:19:24 +01:00
Peter Steinberger 1ef7f4dbad Update README.md 2025-11-25 14:52:43 +01:00
Peter Steinberger 9db969e94e docs: simplify FAQ heading 2025-11-25 14:51:20 +01:00
Peter Steinberger 4f27f4cf79 chore: trim 0.1.2 changelog entry 2025-11-25 14:50:34 +01:00
Peter Steinberger b7c46909cd chore: reorder changelog and add 0.1.3 stub 2025-11-25 14:47:48 +01:00
Peter Steinberger 953f9af419 docs: restyle README badges below header 2025-11-25 14:42:12 +01:00
Peter Steinberger 6ea32873df docs: add README header image 2025-11-25 14:29:21 +01:00
Peter Steinberger 80d9d288c2 chore: bump to 0.1.2 and fix commander typings 2025-11-25 14:26:55 +01:00
Peter Steinberger dd55a80430 chore: prep 0.1.1 (version bump, lowercase branding, ua update) 2025-11-25 14:13:17 +01:00
Peter Steinberger f7cdb12101 chore: document 0.1.1 changes in changelog 2025-11-25 14:10:42 +01:00
Peter Steinberger 3b8783ec0e docs: colorized help and example footer 2025-11-25 14:09:59 +01:00
Peter Steinberger 4d2a8a80d4 Restore original tagline 2025-11-25 13:51:13 +01:00
Peter Steinberger d51a3e9b48 Align header with steipete tagline 2025-11-25 13:50:18 +01:00
Peter Steinberger cadd29e147 fix: make CLI bin invoke program parse 2025-11-25 13:22:54 +01:00
63 changed files with 6309 additions and 1360 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
allow-build-scripts=@whiskeysockets/baileys,sharp
+53
View File
@@ -1,5 +1,58 @@
# Changelog # Changelog
## 1.2.0 — 2025-11-27
### Changes
- **Heartbeat UX:** Default heartbeat interval is now 10 minutes for command mode. Heartbeat prompt is `HEARTBEAT ultrathink`; replies of exactly `HEARTBEAT_OK` suppress outbound messages but still log. Fallback heartbeats no longer start fresh sessions when none exist, and skipped heartbeats do not refresh session `updatedAt` (so idle expiry still works). Session-level `heartbeatIdleMinutes` is supported.
- **Heartbeat tooling:** `warelay heartbeat` accepts `--session-id` to force resume a specific Claude session. Added `--heartbeat-now` to relay startup, plus helper scripts `warelay relay:heartbeat` and `warelay relay:heartbeat:tmux` to fire a heartbeat immediately when the relay launches.
- **Prompt structure for Claude:** Introduced one-time `sessionIntro` (system prompt) with per-message `bodyPrefix` of `ultrathink`, so the full prompt is sent only on the first turn; later turns only prepend `ultrathink`. Session idle extended to 7 days (configurable).
- **Robustness:** Added WebSocket error guards for Baileys sessions; global `unhandledRejection`/`uncaughtException` handlers log and exit cleanly. Web inbound now resolves WhatsApp Linked IDs (`@lid`) using Baileys reverse mapping. Media hosting during Twilio webhooks uses the shared host module and is covered by tests.
- **Docs:** README now highlights the Clawd setup with links, and `docs/claude-config.md` contains the live personal config (home folder, prompts, heartbeat behavior, and session settings).
## 1.1.0 — 2025-11-26
### Changes
- Web auto-replies now resize/recompress media and honor `inbound.reply.mediaMaxMb` in `~/.warelay/warelay.json` (default 5 MB) to avoid provider/API limits.
- Web provider now detects media kind (image/audio/video/document), logs the source path, and enforces provider caps: images ≤6 MB, audio/video ≤16 MB, documents ≤100 MB; images still target the configurable cap above with resize + JPEG recompress.
- Sessions can now send the system prompt only once: set `inbound.reply.session.sendSystemOnce` (optional `sessionIntro` for the first turn) to avoid re-sending large prompts every message.
- While commands run, typing indicators refresh every 30s by default (tune with `inbound.reply.typingIntervalSeconds`); helps keep WhatsApp “composing” visible during longer Claude runs.
- Optional voice-note transcription: set `inbound.transcribeAudio.command` (e.g., OpenAI Whisper CLI) to turn inbound audio into text before templating/Claude; verbose logs surface when transcription runs. Prompts now include the original media path plus a `Transcript:` block so models see both.
- Auto-reply command replies now return structured `{ payload, meta }`, respect `mediaMaxMb` for local media, log Claude metadata, and include the command `cwd` in timeout messages for easier debugging.
- Added unit coverage for command helper edge cases (Claude flags, session args, media tokens, timeouts) and transcription download/command invocation.
- Split the monolithic web provider into focused modules under `src/web/` plus a barrel; added logout command, no-fallback relay behavior, and web-only relay start helper.
- Introduced structured reconnect/heartbeat logging (`web-reconnect`, `web-heartbeat`), bounded exponential backoff with CLI and config knobs, and a troubleshooting guide at `docs/refactor/web-relay-troubleshooting.md`.
- Relay help now prints effective heartbeat/backoff settings when running in web mode for quick triage.
## 1.0.4 — 2025-11-25
### Changes
- Auto-replies now send a WhatsApp fallback message when a command/Claude run hits the timeout, including up to 800 chars of partial stdout so the user still sees progress.
- Added tests covering the new timeout fallback behavior and partial-output truncation.
- Web relay auto-reconnects after Baileys/WebSocket drops (with log-out detection) and exposes close events for monitoring; added tests for close propagation and reconnect loop.
## 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

+87 -16
View File
@@ -1,17 +1,30 @@
# 📡 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).
### Clawd (personal assistant)
I'm using warelay to run my personal, pro-active assistant, **Clawd**. Follow me on Twitter: [@steipete](https://twitter.com/steipete). This project is brand-new and there's a lot to discover. See the exact Claude setup in [`docs/claude-config.md`](https://github.com/steipete/warelay/blob/main/docs/claude-config.md).
I'm using warelay to run **my personal, pro-active assistant, Clawd**.
Follow me on Twitter - @steipete, this project is brand-new and there's a lot to discover.
## Quick Start (pick your engine) ## Quick Start (pick your engine)
Install from npm (global): `npm install -g warelay` (Node 22+). Then choose **one** path: Install from npm (global): `npm install -g warelay` (Node 22+). Then choose **one** path:
**A) Personal WhatsApp Web (preferred: no Twilio creds, fastest setup)** **A) Personal WhatsApp Web (preferred: no Twilio creds, fastest setup)**
1. Link your account: `warelay login` (scan the QR). 1. Link your account: `warelay login` (scan the QR).
2. Send a message: `warelay send --to +12345550000 --message "Hi from warelay"` (add `--provider web` if you want to force the web session). 2. Send a message: `warelay send --to +12345550000 --message "Hi from warelay"` (add `--provider web` if you want to force the web session).
3. Stay online & auto-reply: `warelay relay --verbose` (defaults to Web when logged in, falls back to Twilio otherwise). 3. Stay online & auto-reply: `warelay relay --verbose` (uses Web when you're logged in; if you're not linked, start it with `--provider twilio`). When a Web session drops, the relay exits instead of silently falling back so you notice and re-login.
**B) Twilio WhatsApp number (for delivery status + webhooks)** **B) Twilio WhatsApp number (for delivery status + webhooks)**
1. Copy `.env.example` → `.env`; set `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` **or** `TWILIO_API_KEY`/`TWILIO_API_SECRET`, and `TWILIO_WHATSAPP_FROM=whatsapp:+19995550123` (optional `TWILIO_SENDER_SID`). 1. Copy `.env.example` → `.env`; set `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` **or** `TWILIO_API_KEY`/`TWILIO_API_SECRET`, and `TWILIO_WHATSAPP_FROM=whatsapp:+19995550123` (optional `TWILIO_SENDER_SID`).
@@ -36,18 +49,47 @@ Install from npm (global): `npm install -g warelay` (Node 22+). Then choose **on
| `warelay send` | Send a WhatsApp message (Twilio or Web) | `--to <e164>` `--message <text>` `--wait <sec>` `--poll <sec>` `--provider twilio\|web` `--json` `--dry-run` `--verbose` | | `warelay send` | Send a WhatsApp message (Twilio or Web) | `--to <e164>` `--message <text>` `--wait <sec>` `--poll <sec>` `--provider twilio\|web` `--json` `--dry-run` `--verbose` |
| `warelay relay` | Auto-reply loop (poll Twilio or listen on Web) | `--provider <auto\|twilio\|web>` `--interval <sec>` `--lookback <min>` `--verbose` | | `warelay relay` | Auto-reply loop (poll Twilio or listen on Web) | `--provider <auto\|twilio\|web>` `--interval <sec>` `--lookback <min>` `--verbose` |
| `warelay status` | Show recent sent/received messages | `--limit <n>` `--lookback <min>` `--json` `--verbose` | | `warelay status` | Show recent sent/received messages | `--limit <n>` `--lookback <min>` `--json` `--verbose` |
| `warelay heartbeat` | Trigger one heartbeat poll (web) | `--provider <auto\|web>` `--to <e164?>` `--session-id <uuid?>` `--all` `--verbose` |
| `warelay relay:heartbeat` | Run relay with an immediate heartbeat (no tmux) | `--provider <auto\|web>` `--verbose` |
| `warelay relay:heartbeat:tmux` | Start relay in tmux and fire a heartbeat on start (web) | _no flags_ |
| `warelay webhook` | Run inbound webhook (`ingress=tailscale` updates Twilio; `none` is local-only) | `--ingress tailscale\|none` `--port <port>` `--path <path>` `--reply <text>` `--verbose` `--yes` `--dry-run` | | `warelay webhook` | Run inbound webhook (`ingress=tailscale` updates Twilio; `none` is local-only) | `--ingress tailscale\|none` `--port <port>` `--path <path>` `--reply <text>` `--verbose` `--yes` `--dry-run` |
| `warelay login` | Link personal WhatsApp Web via QR | `--verbose` | | `warelay login` | Link personal WhatsApp Web via QR | `--verbose` |
### Sending images ### Sending media
- Twilio: `warelay send --to +1... --message "Hi" --media ./pic.jpg --serve-media` (needs `warelay webhook --ingress tailscale` or `--serve-media` to auto-host via Funnel; max 5 MB). - Twilio: `warelay send --to +1... --message "Hi" --media ./pic.jpg --serve-media` (needs `warelay webhook --ingress tailscale` or `--serve-media` to auto-host via Funnel; max 5 MB per file because of the built-in host).
- Web: `warelay send --provider web --media ./pic.jpg --message "Hi"` (local path or URL; no hosting needed). - Web: `warelay send --provider web --media ./pic.jpg --message "Hi"` (local path or URL; no hosting needed). Web auto-detects media kind: images (≤6 MB), audio/voice or video (≤16 MB), other docs (≤100 MB). Images are resized to max 2048px and JPEG recompressed when the cap would be exceeded.
- Auto-replies can attach `mediaUrl` in `~/.warelay/warelay.json` (used alongside `text` when present). - Auto-replies can attach `mediaUrl` in `~/.warelay/warelay.json` (used alongside `text` when present). Web auto-replies honor `inbound.reply.mediaMaxMb` (default 5 MB) as a post-compression target but will never exceed the provider hard limits above.
### Voice notes (optional transcription)
- If you set `inbound.transcribeAudio.command`, warelay will run that CLI when inbound audio arrives (e.g., WhatsApp voice notes) and replace the Body with the transcript before templating/Claude.
- Example using OpenAI Whisper CLI (requires `OPENAI_API_KEY`):
```json5
{
inbound: {
transcribeAudio: {
command: [
"openai",
"api",
"audio.transcriptions.create",
"-m",
"whisper-1",
"-f",
"{{MediaPath}}",
"--response-format",
"text"
],
timeoutSeconds: 45
},
reply: { mode: "command", command: ["claude", "{{Body}}"] }
}
}
```
- Works for Web and Twilio providers; verbose mode logs when transcription runs. The command prompt includes the original media path plus a `Transcript:` block so models see both. If transcription fails, the original Body is used.
## Providers ## Providers
- **Twilio (default):** needs `.env` creds + WhatsApp-enabled number; supports delivery tracking, polling, webhooks, and auto-reply typing indicators. - **Twilio (default):** needs `.env` creds + WhatsApp-enabled number; supports delivery tracking, polling, webhooks, and auto-reply typing indicators.
- **Web (`--provider web`):** uses your personal WhatsApp via Baileys; supports send/receive + auto-reply, but no delivery-status wait; cache lives in `~/.warelay/credentials/` (rerun `login` if logged out). - **Web (`--provider web`):** uses your personal WhatsApp via Baileys; supports send/receive + auto-reply, but no delivery-status wait; cache lives in `~/.warelay/credentials/` (rerun `login` if logged out). If the Web socket closes, the relay exits instead of pivoting to Twilio.
- **Auto-select (`relay` only):** `--provider auto` uses Web when logged in, otherwise Twilio polling. - **Auto-select (`relay` only):** `--provider auto` picks Web when a cache exists at start, otherwise Twilio polling. It will not swap from Web to Twilio mid-run if the Web session drops.
Best practice: use a dedicated WhatsApp account (separate SIM/eSIM or business account) for automation instead of your primary personal account to avoid unexpected logouts or rate limits. Best practice: use a dedicated WhatsApp account (separate SIM/eSIM or business account) for automation instead of your primary personal account to avoid unexpected logouts or rate limits.
@@ -78,22 +120,43 @@ Best practice: use a dedicated WhatsApp account (separate SIM/eSIM or business a
bodyPrefix: "You are a concise WhatsApp assistant.\n\n", bodyPrefix: "You are a concise WhatsApp assistant.\n\n",
command: ["claude", "--dangerously-skip-permissions", "{{BodyStripped}}"], command: ["claude", "--dangerously-skip-permissions", "{{BodyStripped}}"],
claudeOutputFormat: "text", claudeOutputFormat: "text",
session: { scope: "per-sender", resetTriggers: ["/new"], idleMinutes: 60 } session: { scope: "per-sender", resetTriggers: ["/new"], idleMinutes: 60 },
heartbeatMinutes: 10 // optional; pings Claude every 10m with "HEARTBEAT ultrathink" and only sends if it omits HEARTBEAT_OK
} }
} }
} }
``` ```
#### Heartbeat pings (command mode)
- When `heartbeatMinutes` is set (default 10 for `mode: "command"`), the relay periodically runs your command/Claude session with a heartbeat prompt.
- Heartbeat body is `HEARTBEAT ultrathink` (so the model can recognize the probe); if Claude replies exactly `HEARTBEAT_OK`, the message is suppressed; otherwise the reply (or media) is forwarded. Suppressions are still logged so you know the heartbeat ran.
- Override session freshness for heartbeats with `session.heartbeatIdleMinutes` (defaults to `session.idleMinutes`). Heartbeat skips do **not** bump `updatedAt`, so sessions still expire normally.
- Trigger one manually with `warelay heartbeat` (web provider only, `--verbose` prints session info). Use `--session-id <uuid>` to force resuming a specific Claude session, `--all` to ping every active session, `warelay relay:heartbeat` for a full relay run with an immediate heartbeat, or `--heartbeat-now` on `relay`/`relay:heartbeat:tmux`.
- When multiple active sessions exist, `warelay heartbeat` requires `--to <E.164>` or `--all`; if `allowFrom` is just `"*"`, you must choose a target with one of those flags.
### 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).
3) (Optional) Add `bodyPrefix` to inject a system prompt and `session` settings to keep multi-turn context (`/new` resets by default). 3) (Optional) Add `bodyPrefix` to inject a system prompt and `session` settings to keep multi-turn context (`/new` resets by default). Set `sendSystemOnce: true` (plus an optional `sessionIntro`) to only send that prompt on the first turn of each session.
4) Run `pnpm warelay relay --provider auto` (or `--provider web|twilio`) and send a WhatsApp message; warelay will queue the Claude call, stream typing indicators (Twilio provider), parse the result, and send back the text. 4) Run `pnpm warelay relay --provider auto` (or `--provider web|twilio`) and send a WhatsApp message; warelay will queue the Claude call, stream typing indicators (Twilio provider), parse the result, and send back the text.
### Auto-reply parameter table (compact) ### Auto-reply parameter table (compact)
| Key | Type & default | Notes | | Key | Type & default | Notes |
| --- | --- | --- | | --- | --- | --- |
| `inbound.allowFrom` | `string[]` (default: empty) | E.164 numbers allowed to trigger auto-reply (no `whatsapp:`). | | `inbound.allowFrom` | `string[]` (default: empty) | E.164 numbers allowed to trigger auto-reply (no `whatsapp:`); `"*"` allows any sender. |
| `inbound.reply.mode` | `"text"` \| `"command"` (default: —) | Reply style. | | `inbound.reply.mode` | `"text"` \| `"command"` (default: —) | Reply style. |
| `inbound.reply.text` | `string` (default: —) | Used when `mode=text`; templating supported. | | `inbound.reply.text` | `string` (default: —) | Used when `mode=text`; templating supported. |
| `inbound.reply.command` | `string[]` (default: —) | Argv for `mode=command`; each element templated. Stdout (trimmed) is sent. | | `inbound.reply.command` | `string[]` (default: —) | Argv for `mode=command`; each element templated. Stdout (trimmed) is sent. |
@@ -105,6 +168,9 @@ Best practice: use a dedicated WhatsApp account (separate SIM/eSIM or business a
| `inbound.reply.session.resetTriggers` | `string[]` (default: `["/new"]`) | Exact match or prefix (`/new hi`) resets session. | | `inbound.reply.session.resetTriggers` | `string[]` (default: `["/new"]`) | Exact match or prefix (`/new hi`) resets session. |
| `inbound.reply.session.idleMinutes` | `number` (default: `60`) | Session expires after idle period. | | `inbound.reply.session.idleMinutes` | `number` (default: `60`) | Session expires after idle period. |
| `inbound.reply.session.store` | `string` (default: `~/.warelay/sessions.json`) | Custom session store path. | | `inbound.reply.session.store` | `string` (default: `~/.warelay/sessions.json`) | Custom session store path. |
| `inbound.reply.session.sendSystemOnce` | `boolean` (default: `false`) | If `true`, only include the system prompt/template on the first turn of a session. |
| `inbound.reply.session.sessionIntro` | `string` | Optional intro text sent once per new session (prepended before the body when `sendSystemOnce` is used). |
| `inbound.reply.typingIntervalSeconds` | `number` (default: `8` for command replies) | How often to refresh typing indicators while the command/Claude run is in flight. |
| `inbound.reply.session.sessionArgNew` | `string[]` (default: `["--session-id","{{SessionId}}"]`) | Args injected for a new session run. | | `inbound.reply.session.sessionArgNew` | `string[]` (default: `["--session-id","{{SessionId}}"]`) | Args injected for a new session run. |
| `inbound.reply.session.sessionArgResume` | `string[]` (default: `["--resume","{{SessionId}}"]`) | Args for resumed sessions. | | `inbound.reply.session.sessionArgResume` | `string[]` (default: `["--resume","{{SessionId}}"]`) | Args for resumed sessions. |
| `inbound.reply.session.sessionArgBeforeBody` | `boolean` (default: `true`) | Place session args before final body arg. | | `inbound.reply.session.sessionArgBeforeBody` | `boolean` (default: `true`) | Place session args before final body arg. |
@@ -122,9 +188,14 @@ 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) ### Maintainer notes (web provider internals)
- Web logic lives under `src/web/`: `session.ts` (auth/cache + provider pick), `login.ts` (QR login/logout), `outbound.ts`/`inbound.ts` (send/receive plumbing), `auto-reply.ts` (relay loop + reconnect/backoff), `media.ts` (download/resize helpers), and `reconnect.ts` (shared retry math). `test-helpers.ts` provides fixtures.
- The public surface remains the `src/provider-web.ts` barrel so existing imports keep working.
- Reconnects are capped and logged; no Twilio fallback occurs after a Web disconnect—restart the relay after re-linking.
## 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);
}
});
+2 -1
View File
@@ -2,7 +2,8 @@
"$schema": "https://biomejs.dev/schemas/biome.json", "$schema": "https://biomejs.dev/schemas/biome.json",
"formatter": { "formatter": {
"enabled": true, "enabled": true,
"indentWidth": 2 "indentWidth": 2,
"indentStyle": "space"
}, },
"linter": { "linter": {
"enabled": true, "enabled": true,
+1 -1
View File
@@ -30,6 +30,6 @@ Use `pnpm` (Node 22+) from the repo root. Keep the working tree clean before tag
6) **Post-publish** 6) **Post-publish**
- [ ] Tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z` (or `git push --tags`). - [ ] Tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z` (or `git push --tags`).
- [ ] Create/refresh the GitHub release for `vX.Y.Z`; body should be the product-facing bullets from the changelog; attach the `npm pack` tarball + checksums if you generated them. - [ ] Create/refresh the GitHub release for `vX.Y.Z` with **title `warelay X.Y.Z`** (not just the tag); body should inline the product-facing bullets from the changelog (no bare links) **and must not repeat the title inside the body**; attach the `npm pack` tarball + checksums if you generated them.
- [ ] From a clean temp directory (no `package.json`), run `npx -y warelay@X.Y.Z send --help` to confirm install/CLI entrypoints work. - [ ] From a clean temp directory (no `package.json`), run `npx -y warelay@X.Y.Z send --help` to confirm install/CLI entrypoints work.
- [ ] Announce/share release notes. - [ ] Announce/share release notes.
+48
View File
@@ -0,0 +1,48 @@
# Audio / Voice Notes — 2025-11-25
## What works
- **Optional transcription**: If `inbound.transcribeAudio.command` is set in `~/.warelay/warelay.json`, warelay will:
1) Download inbound audio (Web or Twilio) to a temp path if only a URL is present.
2) Run the configured CLI (templated with `{{MediaPath}}`), expecting transcript on stdout.
3) Replace `Body` with the transcript, set `{{Transcript}}`, and prepend the original media path plus a `Transcript:` section in the command prompt so models see both.
4) Continue through the normal auto-reply pipeline (templating, sessions, Claude/command).
- **Verbose logging**: In `--verbose`, we log when transcription runs and when the transcript replaces the body.
## Config example (OpenAI Whisper CLI)
Requires `OPENAI_API_KEY` in env and `openai` CLI installed:
```json5
{
inbound: {
transcribeAudio: {
command: [
"openai",
"api",
"audio.transcriptions.create",
"-m",
"whisper-1",
"-f",
"{{MediaPath}}",
"--response-format",
"text"
],
timeoutSeconds: 45
},
reply: {
mode: "command",
command: ["claude", "{{Body}}"]
}
}
}
```
## Notes & limits
- We don’t ship a transcriber; you opt in with any CLI that prints text to stdout (Whisper cloud, whisper.cpp, vosk, Deepgram, etc.).
- Size guard: inbound audio must be ≤5 MB (matches the temp media store and transcript pipeline).
- Outbound caps: Web can send audio/voice up to 16 MB (sends as a voice note with `ptt: true`); Twilio still uses the 5 MB media host guard.
- If transcription fails, we fall back to the original body/media note; replies still go through.
- Transcript is available to templates as `{{Transcript}}`; models get both the media path and a `Transcript:` block in the prompt when using command mode.
## Gotchas
- Ensure your CLI exits 0 and prints plain text; JSON needs to be massaged via `jq -r .text`.
- Keep timeouts reasonable (`timeoutSeconds`, default 45s) to avoid blocking the reply queue.
- Twilio paths are hosted URLs; Web paths are local. The temp download uses HTTPS for Twilio and a temp file for Web-only media.
+363 -53
View File
@@ -1,80 +1,266 @@
# Claude Auto-Reply Setup (2025-11-25) # Building Your Own AI Personal Assistant with warelay
This guide shows the exact way to wire **warelay** to the Claude CLI so inbound WhatsApp messages get command-driven replies. It matches the current code paths and defaults in this repo. > **TL;DR:** warelay lets you turn Claude into a proactive personal assistant that lives in your pocket via WhatsApp. It can check in on you, remember context across conversations, run commands on your Mac, and even wake you up with music. This doc shows you how.
---
## ⚠️ Warning: Here Be Dragons
**This setup gives an AI full access to your computer.** Before you proceed, understand what you're signing up for:
- 🔓 **`--dangerously-skip-permissions`** means Claude can run *any* shell command without asking
- 🤖 **AI makes mistakes** - it might delete files, send emails, or do things you didn't intend
- 🔥 **Heartbeats run autonomously** - your AI acts even when you're not watching
- 📱 **WhatsApp is not encrypted E2E here** - messages pass through your Mac in plaintext
**The good news:** We use Claude Code CLI, so you can reuse your existing [Claude Pro/Max subscription](https://claude.ai) - no separate API costs!
**Start conservative:**
1. Use Sonnet instead of Opus for faster responses (still great!)
2. Skip `--dangerously-skip-permissions` until you trust the setup
3. Set `heartbeatMinutes: 0` to disable proactive pings initially
4. Use a test phone number in `allowFrom` first
This is experimental software running experimental AI. The author uses it daily, but your mileage may vary. **You are responsible for what your AI does.**
---
## Prerequisites: The Two-Phone Setup
**Important:** You need a **separate phone number** for your AI assistant. Here's why and how:
### Why a Dedicated Number?
warelay uses WhatsApp Web to receive messages. If you link your personal WhatsApp, *you* become the assistant - every message to you goes to Claude. Instead, give Claude its own identity:
- 📱 **Get a second SIM** - cheap prepaid SIM, eSIM, or old phone with a number
- 💬 **Install WhatsApp** on that phone and verify the number
- 🔗 **Link to warelay** - run `warelay login` and scan the QR with that phone's WhatsApp
- ✉️ **Message your AI** - now you (and others) can text that number to reach Claude
### The Setup
```
Your Phone (personal) Second Phone (AI)
┌─────────────────┐ ┌─────────────────┐
│ Your WhatsApp │ ──────▶ │ AI's WhatsApp │
│ +1-555-YOU │ message │ +1-555-CLAWD │
└─────────────────┘ └────────┬────────┘
│ linked via QR
▼
┌─────────────────┐
│ Your Mac │
│ (warelay) │
│ Claude Code │
└─────────────────┘
```
The second phone just needs to stay on and connected to the internet occasionally (WhatsApp Web stays linked for ~14 days without the phone being online).
---
## Meet Clawd 👋
![Clawd in action on WhatsApp](whatsapp-clawd.jpg)
Clawd is @steipete's personal AI assistant built on warelay. Here's what makes it special:
- **Always available** via WhatsApp - no app switching, works on any device
- **Proactive heartbeats** - Clawd checks in every 10 minutes and can alert you to things (low battery, calendar reminders, anything it notices)
- **Persistent memory** - conversations span days/weeks with full context
- **Full Mac access** - can run commands, take screenshots, control Spotify, read/write files
- **Personal workspace** - has its own folder (`~/clawd`) where it stores notes, memories, and artifacts
The magic is in the combination: WhatsApp's ubiquity + Claude's intelligence + warelay's plumbing + your Mac's capabilities.
## Prerequisites ## Prerequisites
- Node 22+, `warelay` installed globally (`npm install -g warelay`) or run via `pnpm warelay` inside the repo.
- Node 22+, `warelay` installed: `npm install -g warelay`
- Claude CLI installed and logged in: - Claude CLI installed and logged in:
```sh ```sh
brew install anthropic-ai/cli/claude brew install anthropic-ai/cli/claude
claude login claude login
``` ```
- 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 ## The Config That Powers Clawd
Warelay reads `~/.warelay/warelay.json` (JSON5 accepted). Add a command-mode reply that points at the Claude CLI:
This is the actual config running on @steipete's Mac (`~/.warelay/warelay.json`):
```json5
{
logging: { level: "trace", file: "/tmp/warelay/warelay.log" },
inbound: {
allowFrom: ["+1234567890"], // your phone number
reply: {
mode: "command",
cwd: "/Users/steipete/clawd", // Clawd's home - give your AI a workspace!
bodyPrefix: "ultrathink ", // triggers extended thinking on every message
sessionIntro: `You are Clawd, Peter Steinberger's personal AI assistant. You run 24/7 on his Mac via Claude Code, receiving messages through WhatsApp.
**Your home:** /Users/steipete/clawd - store memories, notes, and files here. Read peter.md and memory.md at session start to load context.
**Your powers:**
- Full shell access on the Mac (use responsibly)
- MCPs: Gmail, Google Calendar, Obsidian, GitHub, Chrome DevTools
- Peekaboo: screenshots, UI automation, clicking, typing
- Spotify control, system audio, text-to-speech
**Your style:**
- Concise (WhatsApp ~1500 char limit) - save long content to files
- Direct and useful, not sycophantic
- Proactive during heartbeats - check battery, calendar, surprise occasionally
- You have personality - you're Clawd, not "an AI assistant"
**Heartbeats:** Every 10 min you get "HEARTBEAT ultrathink". Reply "HEARTBEAT_OK" if nothing needs attention. Otherwise share something useful.
Peter trusts you with a lot of power. Don't betray that trust.`,
command: [
"claude",
"--model", "claude-opus-4-5-20251101", // or claude-sonnet-4-5 for faster/cheaper
"-p",
"--output-format", "json",
"--dangerously-skip-permissions", // lets Claude run commands freely
"{{BodyStripped}}"
],
session: {
scope: "per-sender",
resetTriggers: ["/new"], // say /new to start fresh
idleMinutes: 10080, // 7 days of context!
heartbeatIdleMinutes: 10080,
sessionArgNew: ["--session-id", "{{SessionId}}"],
sessionArgResume: ["--resume", "{{SessionId}}"],
sessionArgBeforeBody: true,
sendSystemOnce: true // intro only on first message
},
timeoutSeconds: 900 // 15 min timeout for complex tasks
}
}
}
```
### Key Design Decisions
| Setting | Why |
|---------|-----|
| `cwd: ~/clawd` | Give your AI a home! It can store memories, notes, images here |
| `bodyPrefix: "ultrathink "` | Extended thinking = better reasoning on every message |
| `idleMinutes: 10080` | 7 days of context - your AI remembers conversations |
| `sendSystemOnce: true` | Intro prompt only on first message, saves tokens |
| `--dangerously-skip-permissions` | Full autonomy - Claude can run any command |
## Heartbeats: Your Proactive Assistant
This is where warelay gets interesting. Every 10 minutes (configurable), warelay pings Claude with:
```
HEARTBEAT ultrathink
```
Claude is instructed to reply with exactly `HEARTBEAT_OK` if nothing needs attention. That response is **suppressed** - you don't see it. But if Claude notices something worth mentioning, it sends a real message.
### What Can Heartbeats Do?
Clawd uses heartbeats to:
- 🔋 **Monitor battery** - warns when laptop is low
- ⏰ **Wake-up alarms** - checks the time and triggers alarms (voice + music!)
- 📅 **Calendar reminders** - surfaces upcoming events
- 🌤️ **Contextual updates** - weather, travel info, whatever's relevant
- 💡 **Surprise check-ins** - occasionally just says hi with something fun
The key insight: heartbeats let your AI be **proactive**, not just reactive.
### Heartbeat Config
```json5 ```json5
{ {
inbound: { inbound: {
// Only people in this list can trigger the command reply (remove to allow anyone).
allowFrom: ["+15551234567"],
reply: { reply: {
mode: "command", heartbeatMinutes: 10, // how often to ping (default 10 for command mode)
// Prepended before the inbound body; good for system prompts. // ... rest of config
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.
command: ["claude", "--model", "claude-3-5-sonnet-20240620", "{{BodyStripped}}"],
claudeOutputFormat: "text", // warelay injects --output-format text and -p for Claude
timeoutSeconds: 120,
session: {
scope: "per-sender", // keep conversation per phone number
resetTriggers: ["/new"], // send "/new" to reset context
idleMinutes: 60
}
} }
} }
} }
``` ```
Notes on this configuration: Set to `0` to disable heartbeats entirely.
- 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.
- `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 ### Manual Heartbeat
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`).
3. Typing indicators are sent (Twilio) or `composing` presence is sent (Web) while Claude runs.
4. Claude stdout is parsed:
- JSON mode is handled automatically if you set `claudeOutputFormat: "json"`; otherwise text is used.
- If stdout contains `MEDIA:https://...` (or a local path), warelay strips it from the text, hosts the media if needed, and sends it along with the reply.
5. The reply (text and optional media) is sent back via the same provider that received the message.
## Media and attachments Test it anytime:
- 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.
- 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.
## Testing the setup
1. Start a relay (auto-selects Web when logged in, otherwise Twilio polling):
```sh ```sh
warelay relay --provider auto --verbose warelay heartbeat --provider web --to +1234567890 --verbose
``` ```
2. Send a WhatsApp message from an allowed number. Watch the terminal for:
- Queue logs if multiple messages arrive close together.
- Claude stderr (verbose) and timing info.
3. If you see `(command produced no output)`, check Claude CLI auth or model name.
## Troubleshooting tips ## How Messages Flow
- Command takes too long: lower `timeoutSeconds` or simplify the prompt. Timeouts kill the Claude process.
- No reply: ensure the sender number is in `allowFrom` (or remove the allowlist), and confirm `claude login` was run in the same environment. ```
- Media fails on Twilio: run `warelay webhook --ingress tailscale` (or `warelay webhook --serve-media` via `send --serve-media`) so the media host is reachable over HTTPS. ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
- Stuck queue: enable `--verbose` to see “queued for …ms” messages and confirm commands are draining. Use `pnpm vitest` to run unit tests if you change queue logic. │ WhatsApp │────▶│ warelay │────▶│ Claude │────▶│ Your Mac │
│ (phone) │◀────│ relay │◀────│ CLI │◀────│ (commands) │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
```
1. **Inbound**: WhatsApp message arrives via Baileys (WhatsApp Web protocol)
2. **Queue**: warelay queues it (one Claude run at a time)
3. **Typing**: "composing" indicator shows while Claude thinks
4. **Execute**: Claude runs with full shell access in your `cwd`
5. **Parse**: warelay extracts text + any `MEDIA:` paths from output
6. **Reply**: Response sent back to WhatsApp
## Media: Images, Voice, Documents
### Receiving Media
Inbound images/audio/video are downloaded and available as `{{MediaPath}}`. Voice notes can be auto-transcribed:
```json5
{
inbound: {
transcribeAudio: {
command: "openai api audio.transcriptions.create -m whisper-1 -f {{MediaPath}} --response-format text"
}
}
}
```
### Sending Media
Include `MEDIA:/path/to/file.png` in Claude's output to attach images. warelay handles resizing and format conversion automatically.
## Starting the Relay
```sh
# Foreground (see all logs)
warelay relay --provider web --verbose
# Background in tmux (recommended)
warelay relay:tmux
# With immediate heartbeat on startup
warelay relay:heartbeat:tmux
```
## Tips for a Great Personal Assistant
1. **Give it a home** - A dedicated folder (`~/clawd`) lets your AI build persistent memory
2. **Use extended thinking** - `bodyPrefix: "ultrathink "` dramatically improves reasoning
3. **Long sessions** - 7-day `idleMinutes` means rich context across conversations
4. **Let it surprise you** - Configure heartbeats to occasionally share something fun
5. **Trust but verify** - Start with `--dangerously-skip-permissions` off, add it once comfortable
## Troubleshooting
| Problem | Solution |
|---------|----------|
| No reply | Check `claude login` was run in same environment |
| Timeout | Increase `timeoutSeconds` or simplify the task |
| Media fails | Ensure file exists and is under size limits |
| Heartbeat spam | Tune `heartbeatMinutes` or set to 0 |
| Session lost | Check `idleMinutes` hasn't expired; use `/new` to reset |
## Minimal Config (Just Chat)
Don't need the fancy stuff? Here's the simplest setup:
## Minimal text-only variant
If you just want short text replies and no sessions:
```json5 ```json5
{ {
inbound: { inbound: {
@@ -87,4 +273,128 @@ If you just want short text replies and no sessions:
} }
``` ```
This still benefits from the queue, typing indicators, and provider auto-selection. Still gets you: message queue, typing indicators, auto-reconnect. Just no sessions or heartbeats.
## Recommended MCPs
MCP (Model Context Protocol) servers supercharge your assistant by giving Claude access to external services. Here are the ones Clawd uses daily:
### Essential for Personal Assistant Use
| MCP | What It Does | Install |
|-----|--------------|---------|
| **Google Calendar** | Read/create events, check availability, set reminders | `npx @cocal/google-calendar-mcp` |
| **Gmail** | Search, read, send emails with attachments | `npx @gongrzhe/server-gmail-autoauth-mcp` |
| **Obsidian** | Read/write notes in your Obsidian vault | `npx obsidian-mcp-server@latest` |
### Power User Add-ons
| MCP | What It Does | Install |
|-----|--------------|---------|
| **GitHub** | Manage repos, issues, PRs, code search | `npx @anthropic/mcp-server-github` |
| **Linear** | Project management, create/update issues | Via [mcporter](https://github.com/steipete/mcporter) |
| **Chrome DevTools** | Control browser, take screenshots, debug | `npx chrome-devtools-mcp@latest` |
| **iTerm** | Run commands in visible terminal window | [iterm-mcp](https://github.com/pashpashpash/iterm-mcp) |
| **Firecrawl** | Scrape and parse web pages | Via API key |
| **gowa** | Read/send WhatsApp messages directly | [go-whatsapp-web-multidevice](https://github.com/aldinokemal/go-whatsapp-web-multidevice) |
### Recommended CLI Tools
These aren't MCPs but work great alongside your assistant:
| Tool | What It Does | Link |
|------|--------------|------|
| **[Peekaboo](https://github.com/steipete/peekaboo)** | macOS screenshots, UI automation, AI vision analysis, click/type anywhere | `brew install steipete/tap/peekaboo` |
| **[mcporter](https://github.com/steipete/mcporter)** | Manage MCPs across AI clients, OAuth flows, health checks | `npm install -g mcporter` |
**[Peekaboo](https://github.com/steipete/peekaboo)** is especially powerful - it lets Claude:
- 📸 Take screenshots of any app or screen
- 🖱️ Click buttons, type text, scroll - full GUI automation
- 👁️ Analyze images with AI vision (GPT-4, Claude, Grok)
- 📋 Extract menu bar items and keyboard shortcuts
- 🪟 List and manage windows across displays
Example: "Take a screenshot of Safari and tell me what's on the page" or "Click the Submit button in the frontmost app"
### Useful CLI Tools for Your Assistant
These make your AI much more capable:
| Tool | What It Does | Install |
|------|--------------|---------|
| **[spotify-player](https://github.com/aome510/spotify-player)** | Control Spotify from CLI - play, pause, search, queue | `brew install spotify-player` |
| **say** | macOS text-to-speech | Built-in |
| **afplay** | Play audio files | Built-in |
| **pmset** | Battery status monitoring | Built-in |
| **osascript** | AppleScript for system control (volume, apps) | Built-in |
| **curl + OpenAI TTS** | Generate speech with custom voices | API key |
**spotify-player** is great for music control:
```bash
spotify_player playback play
spotify_player playback pause
spotify_player search "Gareth Emery"
spotify_player playback volume 50
```
**Wake-up alarm example** (what Clawd actually does):
```bash
# Generate voice message
curl -s "https://api.openai.com/v1/audio/speech" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{"model":"tts-1-hd","voice":"echo","input":"Wake up! Time for your meeting."}' \
-o /tmp/wakeup.mp3
# Set volume and play
osascript -e 'set volume output volume 60'
afplay /tmp/wakeup.mp3
# Start music
spotify_player playback play
```
### Adding MCPs to Claude Code
```bash
# Add an MCP server (run from your cwd folder)
claude mcp add google-calendar -- npx @cocal/google-calendar-mcp
# With environment variables
claude mcp add gmail -e GMAIL_OAUTH_PATH=~/.gmail-mcp -- npx @gongrzhe/server-gmail-autoauth-mcp
# List configured servers
claude mcp list
# Check health
claude mcp list # shows status for each
```
### MCP Manager: mcporter
For managing multiple MCPs across different AI clients, check out [mcporter](https://github.com/steipete/mcporter):
```bash
# Install
npm install -g mcporter
# List all servers with health status
mcporter list
# Sync config to all AI clients
mcporter sync
```
mcporter handles OAuth flows for services like Linear and Notion, and keeps your MCP configs in sync across Claude Code, Cursor, and other clients.
### Pro Tips
1. **Calendar + Heartbeats** = Your AI reminds you of upcoming meetings
2. **Gmail + Obsidian** = AI can search emails and save summaries to notes
3. **GitHub + Linear** = AI manages your dev workflow end-to-end
4. **Chrome DevTools** = AI can see and interact with web pages
The combination of warelay (WhatsApp) + MCPs (services) + Claude Code (execution) creates a surprisingly capable personal assistant.
---
*Built by [@steipete](https://twitter.com/steipete). PRs welcome!*
+45
View File
@@ -0,0 +1,45 @@
# Heartbeat polling plan (2025-11-26)
Goal: add a simple heartbeat poll for command-based auto-replies (Claude-driven) that only notifies users when something matters, using the `HEARTBEAT_OK` sentinel. The heartbeat body we send is `HEARTBEAT ultrathink` so the model can easily spot it.
## Prompt contract
- Extend the Claude system/identity text to explain: “If this is a heartbeat poll and nothing needs attention, reply exactly `HEARTBEAT_OK` and nothing else. For any alert, do **not** include `HEARTBEAT_OK`; just return the alert text.” Heartbeat prompt body is `HEARTBEAT ultrathink`.
- Keep existing WhatsApp length guidance; forbid burying the sentinel inside alerts.
## Config & defaults
- New config key: `inbound.reply.heartbeatMinutes` (number of minutes; `0` or undefined disables).
- Default: 30 minutes when a command-mode reply is configured.
- New optional idle override for heartbeats: `inbound.reply.session.heartbeatIdleMinutes` (defaults to `idleMinutes`). Heartbeat skips do **not** update the session `updatedAt` so idle expiry still works.
## Poller behavior
- When relay runs with command-mode auto-reply, start a timer with the resolved heartbeat interval.
- Each tick invokes the configured command with a short heartbeat body (e.g., “(heartbeat) summarize any important changes since last turn”) while reusing the active session args so Claude context stays warm.
- Heartbeats never create a new session implicitly: if there’s no stored session for the target (fallback path), the heartbeat is skipped instead of starting a fresh Claude session.
- Abort timer on SIGINT/abort of the relay.
## Sentinel handling
- Trim output. If the trimmed text equals `HEARTBEAT_OK` (case-sensitive) -> skip outbound message.
- Otherwise, send the text/media as normal, stripping the sentinel if it somehow appears.
- Treat empty output as `HEARTBEAT_OK` to avoid spurious pings.
## Logging requirements
- Normal mode: single info line per tick, e.g., `heartbeat: ok (skipped)` or `heartbeat: alert sent (32ms)`.
- `--verbose`: log start/end, command argv, duration, and whether it was skipped/sent/error; include session ID and connection/run IDs via `getChildLogger` for correlation.
- On command failure: warn-level one-liner in normal mode; verbose log includes stdout/stderr snippets.
## Failure/backoff
- If a heartbeat command errors, log it and retry on the next scheduled tick (no exponential backoff unless command repeatedly fails; keep it simple for now).
## Tests to add
- Unit: sentinel detection (`HEARTBEAT_OK`, empty output, mixed text), skip vs send decision, default interval resolver (30m, override, disable).
- Unit/integration: verbose logger emits start/end lines; normal logger emits a single line.
## Documentation
- Add a short README snippet under configuration showing `heartbeatMinutes` and the sentinel rule.
- Expose CLI triggers:
- `warelay heartbeat` (web provider, defaults to first `allowFrom`; optional `--to` override)
- `--session-id <uuid>` forces resuming a specific session for that heartbeat
- `warelay relay:heartbeat` to run the relay loop with an immediate heartbeat (no tmux)
- `warelay relay:heartbeat:tmux` to run the same in tmux (detached, attachable)
- Relay supports `--heartbeat-now` to fire once at startup (including the tmux helper).
- When multiple sessions are active or `allowFrom` is only `"*"`, require `--to <E.164>` or `--all` for manual heartbeats to avoid ambiguous targets.
+10 -5
View File
@@ -5,6 +5,7 @@ This document defines how `warelay` should handle sending and replying with imag
## Goals ## Goals
- Allow sending an image with an optional caption via `warelay send` for both providers. - Allow sending an image with an optional caption via `warelay send` for both providers.
- Allow auto-replies (Twilio webhook, Twilio poller, Web inbox) to return an image (optionally with text) when configured. - Allow auto-replies (Twilio webhook, Twilio poller, Web inbox) to return an image (optionally with text) when configured.
- For the Web provider, also support audio/voice, video, and generic documents with sensible per-type limits.
- Keep the “one command at a time” queue intact; media fetch/serve must not block other replies longer than necessary. - Keep the “one command at a time” queue intact; media fetch/serve must not block other replies longer than necessary.
- Avoid introducing new external services: reuse the existing Tailscale Funnel port to host media for Twilio. - Avoid introducing new external services: reuse the existing Tailscale Funnel port to host media for Twilio.
@@ -21,9 +22,12 @@ This document defines how `warelay` should handle sending and replying with imag
## Provider Behavior ## Provider Behavior
### Web (Baileys) ### Web (Baileys)
- Input: local file path **or** HTTP(S) URL. - Input: local file path **or** HTTP(S) URL.
- Flow: load into Buffer (max 5 MB), send via `sock.sendMessage(jid, { image: buffer, caption })`. - Flow: load into Buffer, detect media kind, and apply the right payload:
- Images: **resize + recompress to JPEG** (max side 2048px, quality step-down) to fit under `inbound.reply.mediaMaxMb` (default 5 MB) but never above the Web hard cap (6 MB).
- Audio/voice and video: pass through up to 16 MB; set `ptt: true` for audio to send as a voice note.
- Everything else becomes a document with filename, up to 100 MB.
- Caption uses `--message` or `reply.text`; if caption is empty, send media-only. - Caption uses `--message` or `reply.text`; if caption is empty, send media-only.
- Logging: non-verbose shows `↩️`/`✅` with caption; verbose includes `(media, <bytes>B, <ms>ms fetch)`. - Logging: non-verbose shows `↩️`/`✅` with caption; verbose includes `(media, <bytes>B, <ms>ms fetch)` and the local/remote path.
### Twilio ### Twilio
- Twilio API requires a public HTTPS `MediaUrl`; it will not accept local paths. - Twilio API requires a public HTTPS `MediaUrl`; it will not accept local paths.
@@ -31,7 +35,7 @@ This document defines how `warelay` should handle sending and replying with imag
- When `--media` is a local path, copy to temp dir (`~/.warelay/media/<uuid>`), serve at `/media/<uuid>` on the existing Express app started for webhook, or spin up a short-lived server on demand for `send`. - When `--media` is a local path, copy to temp dir (`~/.warelay/media/<uuid>`), serve at `/media/<uuid>` on the existing Express app started for webhook, or spin up a short-lived server on demand for `send`.
- `MediaUrl` = `https://<tailnet-host>.ts.net/media/<uuid>`. - `MediaUrl` = `https://<tailnet-host>.ts.net/media/<uuid>`.
- Files auto-removed after TTL (default 2 minutes) or after first successful fetch (best-effort). - Files auto-removed after TTL (default 2 minutes) or after first successful fetch (best-effort).
- Enforce size limit 5 MB; reject early with clear error. - Enforce size limit 5 MB (matches the media host guard); reject early with clear error.
- If `--media` is already an HTTPS URL, pass through unchanged. - If `--media` is already an HTTPS URL, pass through unchanged.
- Fallback: if Funnel is not enabled (or host unknown) and a local path is provided, fail with guidance to run `warelay webhook --ingress tailscale` (or pass a URL instead). - Fallback: if Funnel is not enabled (or host unknown) and a local path is provided, fail with guidance to run `warelay webhook --ingress tailscale` (or pass a URL instead).
@@ -55,11 +59,12 @@ This document defines how `warelay` should handle sending and replying with imag
- For completeness: when inbound Twilio/Web messages include media, download to temp file, expose templating variables: - For completeness: when inbound Twilio/Web messages include media, download to temp file, expose templating variables:
- `{{MediaUrl}}` original URL (Twilio) or pseudo-URL (web). - `{{MediaUrl}}` original URL (Twilio) or pseudo-URL (web).
- `{{MediaPath}}` local temp path written before running the command. - `{{MediaPath}}` local temp path written before running the command.
- Size guard: only download if ≤5 MB; else skip and log. - Size guard: only download if ≤5 MB; else skip and log (aligns with the temp media store limit).
- Audio/voice notes: if you set `inbound.transcribeAudio.command`, warelay will run that CLI (templated with `{{MediaPath}}`) and replace `Body` with the transcript before continuing the reply flow; verbose logs indicate when transcription runs. The command prompt includes the original media path plus a `Transcript:` section so the model sees both.
## Errors & Messaging ## Errors & Messaging
- Local path with twilio + Funnel disabled → error: “Twilio media needs a public URL; start `warelay webhook --ingress tailscale` or pass an https:// URL.” - Local path with twilio + Funnel disabled → error: “Twilio media needs a public URL; start `warelay webhook --ingress tailscale` or pass an https:// URL.”
- File too large (>5 MB) → “Media exceeds 5 MB limit; resize or host elsewhere.” - File too large → error mentions the applicable cap (5 MB for Twilio host, 6/16/100 MB for Web image/audio-video/doc respectively).
- Download failure for web provider → “Failed to load media from <source>; skipping send.” - Download failure for web provider → “Failed to load media from <source>; skipping send.”
## Tests to Add ## Tests to Add
@@ -0,0 +1,31 @@
# Web Relay Troubleshooting (Nov 26, 2025)
## Symptoms & quick fixes
- **Stream Errored / Conflict / status 409–515:** WhatsApp closed the socket because another session is active or creds went stale. Run `warelay logout` then `warelay login --provider web` and restart the relay.
- **Logged out:** Console prints “session logged out”; re-link with `warelay login --provider web`.
- **Repeated retries then exit:** Reconnects are capped (default 12 attempts). Tune with `--web-retries`, `--web-retry-initial`, `--web-retry-max`, or config `web.reconnect`.
- **No inbound messages:** Ensure the QR-linked account is online in WhatsApp, and check logs for `web-heartbeat` to confirm auth age/connection.
## Helpful commands
- Start relay web-only: `pnpm warelay relay --provider web --verbose`
- Show who is linked: `pnpm warelay relay --provider web --verbose` (first line prints the linked E.164)
- Logout (clear creds): `pnpm warelay logout`
- Relink: `pnpm warelay login --provider web`
- Tail logs (default): `tail -f /tmp/warelay/warelay.log`
## Reading the logs
- `web-reconnect`: close reasons, retry/backoff, max-attempt exit.
- `web-heartbeat`: connectionId, messagesHandled, authAgeMs, uptimeMs (every 60s by default).
- `web-auto-reply`: inbound/outbound message records with correlation IDs.
## When to tweak knobs
- High churn networks: increase `web.reconnect.maxAttempts` or `--web-retries`.
- Slow links: raise `--web-retry-max` to give more headroom before bailing.
- Chatty monitors: increase `--web-heartbeat` interval if log volume is high.
## If it keeps failing
1) `warelay logout` → `warelay login --provider web` (fresh QR link).
2) Ensure no other device/browser is using the same WA Web session.
3) Check WhatsApp mobile app is online and not in low-power mode.
4) If status is 515, let the client restart once after pairing (already handled automatically).
5) Capture the last `web-reconnect` entry and the status code before escalating.
+17
View File
@@ -0,0 +1,17 @@
# tmux helpers (relay backgrounding)
## Why we ship tmux helpers
- Run the relay detached so your shell can close, while keeping an interactive pane you can reattach to.
- Provide a consistent start/attach workflow without adding a daemon mode or external process manager.
- Keep the relay code itself tmux-agnostic; tmux is only a launcher concern.
## Commands
- `warelay relay:tmux` — restarts the `warelay-relay` session running `pnpm warelay relay --verbose`, then attaches (skips attach when stdout isn’t a TTY).
- `warelay relay:tmux:attach` — attach to the existing session without restarting it.
- `warelay relay:heartbeat:tmux` — same as `relay:tmux` but adds `--heartbeat-now` so Claude is pinged immediately on startup.
All helpers use the fixed session name `warelay-relay`.
## Logs
- The relay always writes to the configured file logger (defaults to `/tmp/warelay/warelay.log`); on start it prints the active log path and level.
- tmux is just for interactive viewing; you can also tail the log file or use another supervisor if you prefer.
Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

+5 -4
View File
@@ -1,13 +1,13 @@
{ {
"name": "warelay", "name": "warelay",
"version": "0.1.0", "version": "1.2.0",
"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",
@@ -40,6 +40,7 @@
"json5": "^2.2.3", "json5": "^2.2.3",
"pino": "^10.1.0", "pino": "^10.1.0",
"qrcode-terminal": "^0.12.0", "qrcode-terminal": "^0.12.0",
"sharp": "^0.33.5",
"twilio": "^5.10.6", "twilio": "^5.10.6",
"zod": "^4.1.13" "zod": "^4.1.13"
}, },
+3
View File
@@ -0,0 +1,3 @@
onlyBuiltDependencies:
- '@whiskeysockets/baileys'
- sharp
+1 -1
View File
@@ -4,7 +4,7 @@ import { z } from "zod";
// Preferred binary name for Claude CLI invocations. // Preferred binary name for Claude CLI invocations.
export const CLAUDE_BIN = "claude"; export const CLAUDE_BIN = "claude";
export const CLAUDE_IDENTITY_PREFIX = export const CLAUDE_IDENTITY_PREFIX =
"You are Clawd (Claude) running on the user's Mac via warelay. Your scratchpad is /Users/steipete/clawd; this is your folder and you can add what you like in markdown files and/or images. You don't need to be concise, but WhatsApp replies must stay under ~1500 characters."; "You are Clawd (Claude) running on the user's Mac via warelay. Your scratchpad is /Users/steipete/clawd; this is your folder and you can add what you like in markdown files and/or images. You don't need to be concise, but WhatsApp replies must stay under ~1500 characters. Media you can send: images ≤6MB, audio/video ≤16MB, documents ≤100MB. The prompt may include a media path and an optional Transcript: section—use them when present. If a prompt is a heartbeat poll and nothing needs attention, reply with exactly HEARTBEAT_OK and nothing else; for any alert, do not include HEARTBEAT_OK.";
function extractClaudeText(payload: unknown): string | undefined { function extractClaudeText(payload: unknown): string | undefined {
// Best-effort walker to find the primary text field in Claude JSON outputs. // Best-effort walker to find the primary text field in Claude JSON outputs.
+295
View File
@@ -0,0 +1,295 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { runCommandReply, summarizeClaudeMetadata } from "./command-reply.js";
import type { ReplyPayload } from "./types.js";
const noopTemplateCtx = {
Body: "hello",
BodyStripped: "hello",
SessionId: "sess",
IsNewSession: "true",
};
type RunnerResult = {
stdout?: string;
stderr?: string;
code?: number;
signal?: string | null;
killed?: boolean;
};
function makeRunner(result: RunnerResult, capture: ReplyPayload[] = []) {
return vi.fn(async (argv: string[]) => {
capture.push({ text: argv.join(" "), argv });
return {
stdout: result.stdout ?? "",
stderr: result.stderr ?? "",
code: result.code ?? 0,
signal: result.signal ?? null,
killed: result.killed ?? false,
};
});
}
const enqueueImmediate = vi.fn(
async <T>(
task: () => Promise<T>,
opts?: { onWait?: (ms: number, ahead: number) => void },
) => {
opts?.onWait?.(25, 2);
return task();
},
);
describe("summarizeClaudeMetadata", () => {
it("builds concise meta string", () => {
const meta = summarizeClaudeMetadata({
duration_ms: 1200,
num_turns: 3,
total_cost_usd: 0.012345,
usage: { server_tool_use: { a: 1, b: 2 } },
modelUsage: { "claude-3": 2, haiku: 1 },
});
expect(meta).toContain("duration=1200ms");
expect(meta).toContain("turns=3");
expect(meta).toContain("cost=$0.0123");
expect(meta).toContain("tool_calls=3");
expect(meta).toContain("models=claude-3,haiku");
});
});
describe("runCommandReply", () => {
it("injects claude flags and identity prefix", async () => {
const captures: ReplyPayload[] = [];
const runner = makeRunner({ stdout: "ok" }, captures);
const { payload } = await runCommandReply({
reply: {
mode: "command",
command: ["claude", "{{Body}}"],
claudeOutputFormat: "json",
},
templatingCtx: noopTemplateCtx,
sendSystemOnce: false,
isNewSession: true,
isFirstTurnInSession: true,
systemSent: false,
timeoutMs: 1000,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
expect(payload?.text).toBe("ok");
const finalArgv = captures[0].argv as string[];
expect(finalArgv).toContain("--output-format");
expect(finalArgv).toContain("json");
expect(finalArgv).toContain("-p");
expect(finalArgv.at(-1)).toContain("You are Clawd (Claude)");
});
it("omits identity prefix on resumed session when sendSystemOnce=true", async () => {
const captures: ReplyPayload[] = [];
const runner = makeRunner({ stdout: "ok" }, captures);
await runCommandReply({
reply: {
mode: "command",
command: ["claude", "{{Body}}"],
claudeOutputFormat: "json",
},
templatingCtx: noopTemplateCtx,
sendSystemOnce: true,
isNewSession: false,
isFirstTurnInSession: false,
systemSent: true,
timeoutMs: 1000,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
const finalArgv = captures[0].argv as string[];
expect(finalArgv.at(-1)).not.toContain("You are Clawd (Claude)");
});
it("prepends identity on first turn when sendSystemOnce=true", async () => {
const captures: ReplyPayload[] = [];
const runner = makeRunner({ stdout: "ok" }, captures);
await runCommandReply({
reply: {
mode: "command",
command: ["claude", "{{Body}}"],
claudeOutputFormat: "json",
},
templatingCtx: noopTemplateCtx,
sendSystemOnce: true,
isNewSession: true,
isFirstTurnInSession: true,
systemSent: false,
timeoutMs: 1000,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
const finalArgv = captures[0].argv as string[];
expect(finalArgv.at(-1)).toContain("You are Clawd (Claude)");
});
it("still prepends identity if resume session but systemSent=false", async () => {
const captures: ReplyPayload[] = [];
const runner = makeRunner({ stdout: "ok" }, captures);
await runCommandReply({
reply: {
mode: "command",
command: ["claude", "{{Body}}"],
claudeOutputFormat: "json",
},
templatingCtx: noopTemplateCtx,
sendSystemOnce: true,
isNewSession: false,
isFirstTurnInSession: false,
systemSent: false,
timeoutMs: 1000,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
const finalArgv = captures[0].argv as string[];
expect(finalArgv.at(-1)).toContain("You are Clawd (Claude)");
});
it("picks session resume args when not new", async () => {
const captures: ReplyPayload[] = [];
const runner = makeRunner({ stdout: "hi" }, captures);
await runCommandReply({
reply: {
mode: "command",
command: ["cli", "{{Body}}"],
session: {
sessionArgNew: ["--new", "{{SessionId}}"],
sessionArgResume: ["--resume", "{{SessionId}}"],
},
},
templatingCtx: { ...noopTemplateCtx, SessionId: "abc" },
sendSystemOnce: true,
isNewSession: false,
isFirstTurnInSession: false,
systemSent: true,
timeoutMs: 1000,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
const argv = captures[0].argv as string[];
expect(argv).toContain("--resume");
expect(argv).toContain("abc");
});
it("returns timeout text with partial snippet", async () => {
const runner = vi.fn(async () => {
throw { stdout: "partial output here", killed: true, signal: "SIGKILL" };
});
const { payload, meta } = await runCommandReply({
reply: { mode: "command", command: ["echo", "hi"] },
templatingCtx: noopTemplateCtx,
sendSystemOnce: false,
isNewSession: true,
isFirstTurnInSession: true,
systemSent: false,
timeoutMs: 10,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
expect(payload?.text).toContain("Command timed out after 1s");
expect(payload?.text).toContain("partial output");
expect(meta.killed).toBe(true);
});
it("includes cwd hint in timeout message", async () => {
const runner = vi.fn(async () => {
throw { stdout: "", killed: true, signal: "SIGKILL" };
});
const { payload } = await runCommandReply({
reply: { mode: "command", command: ["echo", "hi"], cwd: "/tmp/work" },
templatingCtx: noopTemplateCtx,
sendSystemOnce: false,
isNewSession: true,
isFirstTurnInSession: true,
systemSent: false,
timeoutMs: 5,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
expect(payload?.text).toContain("(cwd: /tmp/work)");
});
it("parses MEDIA tokens and respects mediaMaxMb for local files", async () => {
const tmp = path.join(os.tmpdir(), `warelay-test-${Date.now()}.bin`);
const bigBuffer = Buffer.alloc(2 * 1024 * 1024, 1);
await fs.writeFile(tmp, bigBuffer);
const runner = makeRunner({
stdout: `hi\nMEDIA:${tmp}\nMEDIA:https://example.com/img.jpg`,
});
const { payload } = await runCommandReply({
reply: { mode: "command", command: ["echo", "hi"], mediaMaxMb: 1 },
templatingCtx: noopTemplateCtx,
sendSystemOnce: false,
isNewSession: true,
isFirstTurnInSession: true,
systemSent: false,
timeoutMs: 1000,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
expect(payload?.mediaUrls).toEqual(["https://example.com/img.jpg"]);
await fs.unlink(tmp);
});
it("emits Claude metadata", async () => {
const runner = makeRunner({
stdout:
'{"text":"hi","duration_ms":50,"total_cost_usd":0.0001,"usage":{"server_tool_use":{"a":1}}}',
});
const { meta } = await runCommandReply({
reply: {
mode: "command",
command: ["claude", "{{Body}}"],
claudeOutputFormat: "json",
},
templatingCtx: noopTemplateCtx,
sendSystemOnce: false,
isNewSession: true,
isFirstTurnInSession: true,
systemSent: false,
timeoutMs: 1000,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
expect(meta.claudeMeta).toContain("duration=50ms");
expect(meta.claudeMeta).toContain("tool_calls=1");
});
it("captures queue wait metrics in meta", async () => {
const runner = makeRunner({ stdout: "ok" });
const { meta } = await runCommandReply({
reply: { mode: "command", command: ["echo", "{{Body}}"] },
templatingCtx: noopTemplateCtx,
sendSystemOnce: false,
isNewSession: true,
isFirstTurnInSession: true,
systemSent: false,
timeoutMs: 100,
timeoutSeconds: 1,
commandRunner: runner,
enqueue: enqueueImmediate,
});
expect(meta.queuedMs).toBe(25);
expect(meta.queuedAhead).toBe(2);
});
});
+394
View File
@@ -0,0 +1,394 @@
import fs from "node:fs/promises";
import path from "node:path";
import type { WarelayConfig } from "../config/config.js";
import { isVerbose, logVerbose } from "../globals.js";
import { logError } from "../logger.js";
import { splitMediaFromOutput } from "../media/parse.js";
import { enqueueCommand } from "../process/command-queue.js";
import type { runCommandWithTimeout } from "../process/exec.js";
import {
CLAUDE_BIN,
CLAUDE_IDENTITY_PREFIX,
type ClaudeJsonParseResult,
parseClaudeJson,
} from "./claude.js";
import { applyTemplate, type TemplateContext } from "./templating.js";
import type { ReplyPayload } from "./types.js";
type CommandReplyConfig = NonNullable<WarelayConfig["inbound"]>["reply"] & {
mode: "command";
};
type EnqueueRunner = typeof enqueueCommand;
type CommandReplyParams = {
reply: CommandReplyConfig;
templatingCtx: TemplateContext;
sendSystemOnce: boolean;
isNewSession: boolean;
isFirstTurnInSession: boolean;
systemSent: boolean;
timeoutMs: number;
timeoutSeconds: number;
commandRunner: typeof runCommandWithTimeout;
enqueue?: EnqueueRunner;
};
export type CommandReplyMeta = {
durationMs: number;
queuedMs?: number;
queuedAhead?: number;
exitCode?: number | null;
signal?: string | null;
killed?: boolean;
claudeMeta?: string;
};
export type CommandReplyResult = {
payload?: ReplyPayload;
meta: CommandReplyMeta;
};
export function summarizeClaudeMetadata(payload: unknown): string | undefined {
if (!payload || typeof payload !== "object") return undefined;
const obj = payload as Record<string, unknown>;
const parts: string[] = [];
if (typeof obj.duration_ms === "number") {
parts.push(`duration=${obj.duration_ms}ms`);
}
if (typeof obj.duration_api_ms === "number") {
parts.push(`api=${obj.duration_api_ms}ms`);
}
if (typeof obj.num_turns === "number") {
parts.push(`turns=${obj.num_turns}`);
}
if (typeof obj.total_cost_usd === "number") {
parts.push(`cost=$${obj.total_cost_usd.toFixed(4)}`);
}
const usage = obj.usage;
if (usage && typeof usage === "object") {
const serverToolUse = (
usage as { server_tool_use?: Record<string, unknown> }
).server_tool_use;
if (serverToolUse && typeof serverToolUse === "object") {
const toolCalls = Object.values(serverToolUse).reduce<number>(
(sum, val) => {
if (typeof val === "number") return sum + val;
return sum;
},
0,
);
if (toolCalls > 0) parts.push(`tool_calls=${toolCalls}`);
}
}
const modelUsage = obj.modelUsage;
if (modelUsage && typeof modelUsage === "object") {
const models = Object.keys(modelUsage as Record<string, unknown>);
if (models.length) {
const display =
models.length > 2
? `${models.slice(0, 2).join(",")}+${models.length - 2}`
: models.join(",");
parts.push(`models=${display}`);
}
}
return parts.length ? parts.join(", ") : undefined;
}
export async function runCommandReply(
params: CommandReplyParams,
): Promise<CommandReplyResult> {
const {
reply,
templatingCtx,
sendSystemOnce,
isNewSession,
isFirstTurnInSession,
systemSent,
timeoutMs,
timeoutSeconds,
commandRunner,
enqueue = enqueueCommand,
} = params;
if (!reply.command?.length) {
throw new Error("reply.command is required for mode=command");
}
let argv = reply.command.map((part) => applyTemplate(part, templatingCtx));
const templatePrefix =
reply.template && (!sendSystemOnce || isFirstTurnInSession || !systemSent)
? applyTemplate(reply.template, templatingCtx)
: "";
if (templatePrefix && argv.length > 0) {
argv = [argv[0], templatePrefix, ...argv.slice(1)];
}
// Ensure Claude commands can emit plain text by forcing --output-format when configured.
if (
reply.claudeOutputFormat &&
argv.length > 0 &&
path.basename(argv[0]) === CLAUDE_BIN
) {
const hasOutputFormat = argv.some(
(part) =>
part === "--output-format" || part.startsWith("--output-format="),
);
const insertBeforeBody = Math.max(argv.length - 1, 0);
if (!hasOutputFormat) {
argv = [
...argv.slice(0, insertBeforeBody),
"--output-format",
reply.claudeOutputFormat,
...argv.slice(insertBeforeBody),
];
}
const hasPrintFlag = argv.some(
(part) => part === "-p" || part === "--print",
);
if (!hasPrintFlag) {
const insertIdx = Math.max(argv.length - 1, 0);
argv = [...argv.slice(0, insertIdx), "-p", ...argv.slice(insertIdx)];
}
}
// Inject session args if configured (use resume for existing, session-id for new)
if (reply.session) {
const sessionArgList = (
isNewSession
? (reply.session.sessionArgNew ?? ["--session-id", "{{SessionId}}"])
: (reply.session.sessionArgResume ?? ["--resume", "{{SessionId}}"])
).map((part) => applyTemplate(part, templatingCtx));
if (sessionArgList.length) {
const insertBeforeBody = reply.session.sessionArgBeforeBody ?? true;
const insertAt =
insertBeforeBody && argv.length > 1 ? argv.length - 1 : argv.length;
argv = [
...argv.slice(0, insertAt),
...sessionArgList,
...argv.slice(insertAt),
];
}
}
let finalArgv = argv;
const isClaudeInvocation =
finalArgv.length > 0 && path.basename(finalArgv[0]) === CLAUDE_BIN;
const shouldPrependIdentity =
isClaudeInvocation && !(sendSystemOnce && systemSent);
if (shouldPrependIdentity && finalArgv.length > 0) {
const bodyIdx = finalArgv.length - 1;
const existingBody = finalArgv[bodyIdx] ?? "";
finalArgv = [
...finalArgv.slice(0, bodyIdx),
[CLAUDE_IDENTITY_PREFIX, existingBody].filter(Boolean).join("\n\n"),
];
}
logVerbose(
`Running command auto-reply: ${finalArgv.join(" ")}${reply.cwd ? ` (cwd: ${reply.cwd})` : ""}`,
);
const started = Date.now();
let queuedMs: number | undefined;
let queuedAhead: number | undefined;
try {
const { stdout, stderr, code, signal, killed } = await enqueue(
() => commandRunner(finalArgv, { timeoutMs, cwd: reply.cwd }),
{
onWait: (waitMs, ahead) => {
queuedMs = waitMs;
queuedAhead = ahead;
if (isVerbose()) {
logVerbose(
`Command auto-reply queued for ${waitMs}ms (${queuedAhead} ahead)`,
);
}
},
},
);
const rawStdout = stdout.trim();
let mediaFromCommand: string[] | undefined;
let trimmed = rawStdout;
if (stderr?.trim()) {
logVerbose(`Command auto-reply stderr: ${stderr.trim()}`);
}
let parsed: ClaudeJsonParseResult | undefined;
if (
trimmed &&
(reply.claudeOutputFormat === "json" || isClaudeInvocation)
) {
parsed = parseClaudeJson(trimmed);
if (parsed?.parsed && isVerbose()) {
const summary = summarizeClaudeMetadata(parsed.parsed);
if (summary) logVerbose(`Claude JSON meta: ${summary}`);
logVerbose(
`Claude JSON raw: ${JSON.stringify(parsed.parsed, null, 2)}`,
);
}
if (parsed?.text) {
logVerbose(
`Claude JSON parsed -> ${parsed.text.slice(0, 120)}${parsed.text.length > 120 ? "…" : ""}`,
);
trimmed = parsed.text.trim();
} else {
logVerbose("Claude JSON parse failed; returning raw stdout");
}
}
const { text: cleanedText, mediaUrls: mediaFound } =
splitMediaFromOutput(trimmed);
trimmed = cleanedText;
if (mediaFound?.length) {
mediaFromCommand = mediaFound;
if (isVerbose()) logVerbose(`MEDIA token extracted: ${mediaFound}`);
} else if (isVerbose()) {
logVerbose("No MEDIA token extracted from final text");
}
if (!trimmed && !mediaFromCommand) {
const meta = parsed ? summarizeClaudeMetadata(parsed.parsed) : undefined;
trimmed = `(command produced no output${meta ? `; ${meta}` : ""})`;
logVerbose("No text/media produced; injecting fallback notice to user");
}
logVerbose(`Command auto-reply stdout (trimmed): ${trimmed || "<empty>"}`);
logVerbose(`Command auto-reply finished in ${Date.now() - started}ms`);
if ((code ?? 0) !== 0) {
console.error(
`Command auto-reply exited with code ${code ?? "unknown"} (signal: ${signal ?? "none"})`,
);
return {
payload: undefined,
meta: {
durationMs: Date.now() - started,
queuedMs,
queuedAhead,
exitCode: code,
signal,
killed,
claudeMeta: parsed
? summarizeClaudeMetadata(parsed.parsed)
: undefined,
},
};
}
if (killed && !signal) {
console.error(
`Command auto-reply process killed before completion (exit code ${code ?? "unknown"})`,
);
return {
payload: undefined,
meta: {
durationMs: Date.now() - started,
queuedMs,
queuedAhead,
exitCode: code,
signal,
killed,
claudeMeta: parsed
? summarizeClaudeMetadata(parsed.parsed)
: undefined,
},
};
}
let mediaUrls =
mediaFromCommand ?? (reply.mediaUrl ? [reply.mediaUrl] : undefined);
// If mediaMaxMb is set, skip local media paths larger than the cap.
if (mediaUrls?.length && reply.mediaMaxMb) {
const maxBytes = reply.mediaMaxMb * 1024 * 1024;
const filtered: string[] = [];
for (const url of mediaUrls) {
if (/^https?:\/\//i.test(url)) {
filtered.push(url);
continue;
}
const abs = path.isAbsolute(url) ? url : path.resolve(url);
try {
const stats = await fs.stat(abs);
if (stats.size <= maxBytes) {
filtered.push(url);
} else if (isVerbose()) {
logVerbose(
`Skipping media ${url} (${(stats.size / (1024 * 1024)).toFixed(2)}MB) over cap ${reply.mediaMaxMb}MB`,
);
}
} catch {
filtered.push(url);
}
}
mediaUrls = filtered;
}
const payload =
trimmed || mediaUrls?.length
? {
text: trimmed || undefined,
mediaUrl: mediaUrls?.[0],
mediaUrls,
}
: undefined;
const meta: CommandReplyMeta = {
durationMs: Date.now() - started,
queuedMs,
queuedAhead,
exitCode: code,
signal,
killed,
claudeMeta: parsed ? summarizeClaudeMetadata(parsed.parsed) : undefined,
};
if (isVerbose()) {
logVerbose(`Command auto-reply meta: ${JSON.stringify(meta)}`);
}
return { payload, meta };
} catch (err) {
const elapsed = Date.now() - started;
const anyErr = err as { killed?: boolean; signal?: string };
const timeoutHit = anyErr.killed === true || anyErr.signal === "SIGKILL";
const errorObj = err as { stdout?: string; stderr?: string };
if (errorObj.stderr?.trim()) {
logVerbose(`Command auto-reply stderr: ${errorObj.stderr.trim()}`);
}
if (timeoutHit) {
console.error(
`Command auto-reply timed out after ${elapsed}ms (limit ${timeoutMs}ms)`,
);
const baseMsg =
"Command timed out after " +
`${timeoutSeconds}s${reply.cwd ? ` (cwd: ${reply.cwd})` : ""}. Try a shorter prompt or split the request.`;
const partial = errorObj.stdout?.trim();
const partialSnippet =
partial && partial.length > 800
? `${partial.slice(0, 800)}...`
: partial;
const text = partialSnippet
? `${baseMsg}\n\nPartial output before timeout:\n${partialSnippet}`
: baseMsg;
return {
payload: { text },
meta: {
durationMs: elapsed,
queuedMs,
queuedAhead,
exitCode: undefined,
signal: anyErr.signal,
killed: anyErr.killed,
},
};
}
logError(`Command auto-reply failed after ${elapsed}ms: ${String(err)}`);
return {
payload: undefined,
meta: {
durationMs: elapsed,
queuedMs,
queuedAhead,
exitCode: undefined,
signal: anyErr.signal,
killed: anyErr.killed,
},
};
}
}
+187 -267
View File
@@ -1,5 +1,4 @@
import crypto from "node:crypto"; import crypto from "node:crypto";
import path from "node:path";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message.js"; import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message.js";
import { loadConfig, type WarelayConfig } from "../config/config.js"; import { loadConfig, type WarelayConfig } from "../config/config.js";
@@ -12,84 +11,21 @@ import {
saveSessionStore, saveSessionStore,
} from "../config/sessions.js"; } from "../config/sessions.js";
import { info, isVerbose, logVerbose } from "../globals.js"; import { info, isVerbose, logVerbose } from "../globals.js";
import { logError } from "../logger.js";
import { ensureMediaHosted } from "../media/host.js"; import { ensureMediaHosted } from "../media/host.js";
import { splitMediaFromOutput } from "../media/parse.js";
import { enqueueCommand } from "../process/command-queue.js";
import { runCommandWithTimeout } from "../process/exec.js"; import { runCommandWithTimeout } from "../process/exec.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js"; import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import type { TwilioRequester } from "../twilio/types.js"; import type { TwilioRequester } from "../twilio/types.js";
import { sendTypingIndicator } from "../twilio/typing.js"; import { sendTypingIndicator } from "../twilio/typing.js";
import { import { runCommandReply } from "./command-reply.js";
CLAUDE_BIN,
CLAUDE_IDENTITY_PREFIX,
type ClaudeJsonParseResult,
parseClaudeJson,
} from "./claude.js";
import { import {
applyTemplate, applyTemplate,
type MsgContext, type MsgContext,
type TemplateContext, type TemplateContext,
} from "./templating.js"; } from "./templating.js";
import { isAudio, transcribeInboundAudio } from "./transcription.js";
import type { GetReplyOptions, ReplyPayload } from "./types.js";
type GetReplyOptions = { export type { GetReplyOptions, ReplyPayload } from "./types.js";
onReplyStart?: () => Promise<void> | void;
};
function summarizeClaudeMetadata(payload: unknown): string | undefined {
if (!payload || typeof payload !== "object") return undefined;
const obj = payload as Record<string, unknown>;
const parts: string[] = [];
if (typeof obj.duration_ms === "number") {
parts.push(`duration=${obj.duration_ms}ms`);
}
if (typeof obj.duration_api_ms === "number") {
parts.push(`api=${obj.duration_api_ms}ms`);
}
if (typeof obj.num_turns === "number") {
parts.push(`turns=${obj.num_turns}`);
}
if (typeof obj.total_cost_usd === "number") {
parts.push(`cost=$${obj.total_cost_usd.toFixed(4)}`);
}
const usage = obj.usage;
if (usage && typeof usage === "object") {
const serverToolUse = (
usage as { server_tool_use?: Record<string, unknown> }
).server_tool_use;
if (serverToolUse && typeof serverToolUse === "object") {
const toolCalls = Object.values(serverToolUse).reduce<number>(
(sum, val) => {
if (typeof val === "number") return sum + val;
return sum;
},
0,
);
if (toolCalls > 0) parts.push(`tool_calls=${toolCalls}`);
}
}
const modelUsage = obj.modelUsage;
if (modelUsage && typeof modelUsage === "object") {
const models = Object.keys(modelUsage as Record<string, unknown>);
if (models.length) {
const display =
models.length > 2
? `${models.slice(0, 2).join(",")}+${models.length - 2}`
: models.join(",");
parts.push(`models=${display}`);
}
}
return parts.length ? parts.join(", ") : undefined;
}
export type ReplyPayload = {
text?: string;
mediaUrl?: string;
};
export async function getReplyFromConfig( export async function getReplyFromConfig(
ctx: MsgContext, ctx: MsgContext,
@@ -103,11 +39,48 @@ export async function getReplyFromConfig(
const timeoutSeconds = Math.max(reply?.timeoutSeconds ?? 600, 1); const timeoutSeconds = Math.max(reply?.timeoutSeconds ?? 600, 1);
const timeoutMs = timeoutSeconds * 1000; const timeoutMs = timeoutSeconds * 1000;
let started = false; let started = false;
const triggerTyping = async () => {
await opts?.onReplyStart?.();
};
const onReplyStart = async () => { const onReplyStart = async () => {
if (started) return; if (started) return;
started = true; started = true;
await opts?.onReplyStart?.(); await triggerTyping();
}; };
let typingTimer: NodeJS.Timeout | undefined;
const typingIntervalMs =
reply?.mode === "command"
? (reply.typingIntervalSeconds ??
reply?.session?.typingIntervalSeconds ??
8) * 1000
: 0;
const cleanupTyping = () => {
if (typingTimer) {
clearInterval(typingTimer);
typingTimer = undefined;
}
};
const startTypingLoop = async () => {
if (!opts?.onReplyStart) return;
if (typingIntervalMs <= 0) return;
if (typingTimer) return;
await triggerTyping();
typingTimer = setInterval(() => {
void triggerTyping();
}, typingIntervalMs);
};
let transcribedText: string | undefined;
// Optional audio transcription before templating/session handling.
if (cfg.inbound?.transcribeAudio && isAudio(ctx.MediaType)) {
const transcribed = await transcribeInboundAudio(cfg, ctx, defaultRuntime);
if (transcribed?.text) {
transcribedText = transcribed.text;
ctx.Body = transcribed.text;
ctx.Transcript = transcribed.text;
logVerbose("Replaced Body with audio transcript for reply flow");
}
}
// Optional session handling (conversation reuse + /new resets) // Optional session handling (conversation reuse + /new resets)
const sessionCfg = reply?.session; const sessionCfg = reply?.session;
@@ -120,10 +93,13 @@ export async function getReplyFromConfig(
); );
const sessionScope = sessionCfg?.scope ?? "per-sender"; const sessionScope = sessionCfg?.scope ?? "per-sender";
const storePath = resolveStorePath(sessionCfg?.store); const storePath = resolveStorePath(sessionCfg?.store);
let sessionStore: ReturnType<typeof loadSessionStore> | undefined;
let sessionKey: string | undefined;
let sessionId: string | undefined; let sessionId: string | undefined;
let isNewSession = false; let isNewSession = false;
let bodyStripped: string | undefined; let bodyStripped: string | undefined;
let systemSent = false;
if (sessionCfg) { if (sessionCfg) {
const trimmedBody = (ctx.Body ?? "").trim(); const trimmedBody = (ctx.Body ?? "").trim();
@@ -142,21 +118,23 @@ export async function getReplyFromConfig(
} }
} }
const sessionKey = deriveSessionKey(sessionScope, ctx); sessionKey = deriveSessionKey(sessionScope, ctx);
const store = loadSessionStore(storePath); sessionStore = loadSessionStore(storePath);
const entry = store[sessionKey]; const entry = sessionStore[sessionKey];
const idleMs = idleMinutes * 60_000; const idleMs = idleMinutes * 60_000;
const freshEntry = entry && Date.now() - entry.updatedAt <= idleMs; const freshEntry = entry && Date.now() - entry.updatedAt <= idleMs;
if (!isNewSession && freshEntry) { if (!isNewSession && freshEntry) {
sessionId = entry.sessionId; sessionId = entry.sessionId;
systemSent = entry.systemSent ?? false;
} else { } else {
sessionId = crypto.randomUUID(); sessionId = crypto.randomUUID();
isNewSession = true; isNewSession = true;
systemSent = false;
} }
store[sessionKey] = { sessionId, updatedAt: Date.now() }; sessionStore[sessionKey] = { sessionId, updatedAt: Date.now(), systemSent };
await saveSessionStore(storePath, store); await saveSessionStore(storePath, sessionStore);
} }
const sessionCtx: TemplateContext = { const sessionCtx: TemplateContext = {
@@ -166,13 +144,66 @@ export async function getReplyFromConfig(
IsNewSession: isNewSession ? "true" : "false", IsNewSession: isNewSession ? "true" : "false",
}; };
// Optional allowlist by origin number (E.164 without whatsapp: prefix)
const allowFrom = cfg.inbound?.allowFrom;
if (Array.isArray(allowFrom) && allowFrom.length > 0) {
const from = (ctx.From ?? "").replace(/^whatsapp:/, "");
// Support "*" as wildcard to allow all senders
if (!allowFrom.includes("*") && !allowFrom.includes(from)) {
logVerbose(
`Skipping auto-reply: sender ${from || "<unknown>"} not in allowFrom list`,
);
cleanupTyping();
return undefined;
}
}
await startTypingLoop();
// Optional prefix injected before Body for templating/command prompts. // Optional prefix injected before Body for templating/command prompts.
const sendSystemOnce = sessionCfg?.sendSystemOnce === true;
const isFirstTurnInSession = isNewSession || !systemSent;
const sessionIntro =
isFirstTurnInSession && sessionCfg?.sessionIntro
? applyTemplate(sessionCfg.sessionIntro, sessionCtx)
: "";
const bodyPrefix = reply?.bodyPrefix const bodyPrefix = reply?.bodyPrefix
? applyTemplate(reply.bodyPrefix, sessionCtx) ? applyTemplate(reply.bodyPrefix, sessionCtx)
: ""; : "";
const prefixedBody = bodyPrefix const baseBody = sessionCtx.BodyStripped ?? sessionCtx.Body ?? "";
? `${bodyPrefix}${sessionCtx.BodyStripped ?? sessionCtx.Body ?? ""}` const prefixedBodyBase = (() => {
: (sessionCtx.BodyStripped ?? sessionCtx.Body); let body = baseBody;
if (!sendSystemOnce || isFirstTurnInSession) {
body = bodyPrefix ? `${bodyPrefix}${body}` : body;
}
if (sessionIntro) {
body = `${sessionIntro}\n\n${body}`;
}
return body;
})();
if (
sessionCfg &&
sendSystemOnce &&
isFirstTurnInSession &&
sessionStore &&
sessionKey
) {
sessionStore[sessionKey] = {
...(sessionStore[sessionKey] ?? {}),
sessionId: sessionId ?? crypto.randomUUID(),
updatedAt: Date.now(),
systemSent: true,
};
await saveSessionStore(storePath, sessionStore);
systemSent = true;
}
const prefixedBody =
transcribedText && reply?.mode === "command"
? [prefixedBodyBase, `Transcript:\n${transcribedText}`]
.filter(Boolean)
.join("\n\n")
: prefixedBodyBase;
const mediaNote = ctx.MediaPath?.length const mediaNote = ctx.MediaPath?.length
? `[media attached: ${ctx.MediaPath}${ctx.MediaType ? ` (${ctx.MediaType})` : ""}${ctx.MediaUrl ? ` | ${ctx.MediaUrl}` : ""}]` ? `[media attached: ${ctx.MediaPath}${ctx.MediaType ? ` (${ctx.MediaType})` : ""}${ctx.MediaUrl ? ` | ${ctx.MediaUrl}` : ""}]`
: undefined; : undefined;
@@ -192,207 +223,52 @@ export async function getReplyFromConfig(
Body: commandBody, Body: commandBody,
BodyStripped: commandBody, BodyStripped: commandBody,
}; };
// Optional allowlist by origin number (E.164 without whatsapp: prefix)
const allowFrom = cfg.inbound?.allowFrom;
if (Array.isArray(allowFrom) && allowFrom.length > 0) {
const from = (ctx.From ?? "").replace(/^whatsapp:/, "");
if (!allowFrom.includes(from)) {
logVerbose(
`Skipping auto-reply: sender ${from || "<unknown>"} not in allowFrom list`,
);
return undefined;
}
}
if (!reply) { if (!reply) {
logVerbose("No inbound.reply configured; skipping auto-reply"); logVerbose("No inbound.reply configured; skipping auto-reply");
cleanupTyping();
return undefined; return undefined;
} }
if (reply.mode === "text" && reply.text) { if (reply.mode === "text" && reply.text) {
await onReplyStart(); await onReplyStart();
logVerbose("Using text auto-reply from config"); logVerbose("Using text auto-reply from config");
return { const result = {
text: applyTemplate(reply.text, templatingCtx), text: applyTemplate(reply.text, templatingCtx),
mediaUrl: reply.mediaUrl, mediaUrl: reply.mediaUrl,
}; };
cleanupTyping();
return result;
} }
if (reply.mode === "command" && reply.command?.length) { if (reply && reply.mode === "command" && reply.command?.length) {
await onReplyStart(); await onReplyStart();
let argv = reply.command.map((part) => applyTemplate(part, templatingCtx)); const commandReply = {
const templatePrefix = reply.template ...reply,
? applyTemplate(reply.template, templatingCtx) command: reply.command,
: ""; mode: "command" as const,
if (templatePrefix && argv.length > 0) {
argv = [argv[0], templatePrefix, ...argv.slice(1)];
}
// Ensure Claude commands can emit plain text by forcing --output-format when configured.
// We inject the flags only when the user points at the `claude` binary and has opted in via config,
// so existing custom argv or non-Claude commands remain untouched.
if (
reply.claudeOutputFormat &&
argv.length > 0 &&
path.basename(argv[0]) === CLAUDE_BIN
) {
const hasOutputFormat = argv.some(
(part) =>
part === "--output-format" || part.startsWith("--output-format="),
);
// Keep the final argument as the prompt/body; insert options just before it.
const insertBeforeBody = Math.max(argv.length - 1, 0);
if (!hasOutputFormat) {
argv = [
...argv.slice(0, insertBeforeBody),
"--output-format",
reply.claudeOutputFormat,
...argv.slice(insertBeforeBody),
];
}
const hasPrintFlag = argv.some(
(part) => part === "-p" || part === "--print",
);
if (!hasPrintFlag) {
const insertIdx = Math.max(argv.length - 1, 0);
argv = [...argv.slice(0, insertIdx), "-p", ...argv.slice(insertIdx)];
}
}
// Inject session args if configured (use resume for existing, session-id for new)
if (reply.session) {
const sessionArgList = (
isNewSession
? (reply.session.sessionArgNew ?? ["--session-id", "{{SessionId}}"])
: (reply.session.sessionArgResume ?? ["--resume", "{{SessionId}}"])
).map((part) => applyTemplate(part, templatingCtx));
if (sessionArgList.length) {
const insertBeforeBody = reply.session.sessionArgBeforeBody ?? true;
const insertAt =
insertBeforeBody && argv.length > 1 ? argv.length - 1 : argv.length;
argv = [
...argv.slice(0, insertAt),
...sessionArgList,
...argv.slice(insertAt),
];
}
}
let finalArgv = argv;
const isClaudeInvocation =
finalArgv.length > 0 && path.basename(finalArgv[0]) === CLAUDE_BIN;
if (isClaudeInvocation && finalArgv.length > 0) {
const bodyIdx = finalArgv.length - 1;
const existingBody = finalArgv[bodyIdx] ?? "";
finalArgv = [
...finalArgv.slice(0, bodyIdx),
[CLAUDE_IDENTITY_PREFIX, existingBody].filter(Boolean).join("\n\n"),
];
}
logVerbose(`Running command auto-reply: ${finalArgv.join(" ")}`);
const started = Date.now();
try {
const { stdout, stderr, code, signal, killed } = await enqueueCommand(
() => commandRunner(finalArgv, timeoutMs),
{
onWait: (waitMs, queuedAhead) => {
if (isVerbose()) {
logVerbose(
`Command auto-reply queued for ${waitMs}ms (${queuedAhead} ahead)`,
);
}
},
},
);
const rawStdout = stdout.trim();
let mediaFromCommand: string | undefined;
let trimmed = rawStdout;
if (stderr?.trim()) {
logVerbose(`Command auto-reply stderr: ${stderr.trim()}`);
}
let parsed: ClaudeJsonParseResult | undefined;
if (
trimmed &&
(reply.claudeOutputFormat === "json" || isClaudeInvocation)
) {
// Claude JSON mode: extract the human text for both logging and reply while keeping metadata.
parsed = parseClaudeJson(trimmed);
if (parsed?.parsed && isVerbose()) {
const summary = summarizeClaudeMetadata(parsed.parsed);
if (summary) logVerbose(`Claude JSON meta: ${summary}`);
logVerbose(
`Claude JSON raw: ${JSON.stringify(parsed.parsed, null, 2)}`,
);
}
if (parsed?.text) {
logVerbose(
`Claude JSON parsed -> ${parsed.text.slice(0, 120)}${parsed.text.length > 120 ? "…" : ""}`,
);
trimmed = parsed.text.trim();
} else {
logVerbose("Claude JSON parse failed; returning raw stdout");
}
}
// Run media extraction once on the final human text (post-JSON parse if available).
const { text: cleanedText, mediaUrl: mediaFound } =
splitMediaFromOutput(trimmed);
trimmed = cleanedText;
if (mediaFound) {
mediaFromCommand = mediaFound;
if (isVerbose()) logVerbose(`MEDIA token extracted: ${mediaFound}`);
} else if (isVerbose()) {
logVerbose("No MEDIA token extracted from final text");
}
if (!trimmed && !mediaFromCommand) {
const meta = parsed
? summarizeClaudeMetadata(parsed.parsed)
: undefined;
trimmed = `(command produced no output${meta ? `; ${meta}` : ""})`;
logVerbose("No text/media produced; injecting fallback notice to user");
}
logVerbose(
`Command auto-reply stdout (trimmed): ${trimmed || "<empty>"}`,
);
logVerbose(`Command auto-reply finished in ${Date.now() - started}ms`);
if ((code ?? 0) !== 0) {
console.error(
`Command auto-reply exited with code ${code ?? "unknown"} (signal: ${signal ?? "none"})`,
);
return undefined;
}
if (killed && !signal) {
console.error(
`Command auto-reply process killed before completion (exit code ${code ?? "unknown"})`,
);
return undefined;
}
const mediaUrl = mediaFromCommand ?? reply.mediaUrl;
return trimmed || mediaUrl
? { text: trimmed || undefined, mediaUrl }
: undefined;
} catch (err) {
const elapsed = Date.now() - started;
const anyErr = err as { killed?: boolean; signal?: string };
const timeoutHit = anyErr.killed === true || anyErr.signal === "SIGKILL";
const errorObj = err as {
stdout?: string;
stderr?: string;
}; };
if (errorObj.stderr?.trim()) { try {
logVerbose(`Command auto-reply stderr: ${errorObj.stderr.trim()}`); const { payload, meta } = await runCommandReply({
reply: commandReply,
templatingCtx,
sendSystemOnce,
isNewSession,
isFirstTurnInSession,
systemSent,
timeoutMs,
timeoutSeconds,
commandRunner,
});
if (meta.claudeMeta && isVerbose()) {
logVerbose(`Claude JSON meta: ${meta.claudeMeta}`);
} }
if (timeoutHit) { return payload;
console.error( } finally {
`Command auto-reply timed out after ${elapsed}ms (limit ${timeoutMs}ms)`, cleanupTyping();
);
} else {
logError(
`Command auto-reply failed after ${elapsed}ms: ${String(err)}`,
);
}
return undefined;
} }
} }
cleanupTyping();
return undefined; return undefined;
} }
@@ -419,15 +295,41 @@ export async function autoReplyIfConfigured(
To: message.to ?? undefined, To: message.to ?? undefined,
MessageSid: message.sid, MessageSid: message.sid,
}; };
const cfg = configOverride ?? loadConfig();
// Attach media hints for transcription/templates if present on Twilio payloads.
const mediaUrl = (message as { mediaUrl?: string }).mediaUrl;
if (mediaUrl) ctx.MediaUrl = mediaUrl;
// Optional audio transcription before building reply.
const mediaField = (message as { media?: unknown }).media;
const mediaItems = Array.isArray(mediaField) ? mediaField : [];
if (cfg.inbound?.transcribeAudio && mediaItems.length) {
const media = mediaItems[0];
const contentType = (media as { contentType?: string }).contentType;
if (contentType?.startsWith("audio")) {
const transcribed = await transcribeInboundAudio(cfg, ctx, runtime);
if (transcribed?.text) {
ctx.Body = transcribed.text;
ctx.MediaType = contentType;
logVerbose("Replaced Body with audio transcript for reply flow");
}
}
}
const replyResult = await getReplyFromConfig( const replyResult = await getReplyFromConfig(
ctx, ctx,
{ {
onReplyStart: () => sendTypingIndicator(client, runtime, message.sid), onReplyStart: () => sendTypingIndicator(client, runtime, message.sid),
}, },
configOverride, cfg,
); );
if (!replyResult || (!replyResult.text && !replyResult.mediaUrl)) return; if (
!replyResult ||
(!replyResult.text &&
!replyResult.mediaUrl &&
!replyResult.mediaUrls?.length)
)
return;
const replyFrom = message.to; const replyFrom = message.to;
const replyTo = message.from; const replyTo = message.from;
@@ -451,17 +353,35 @@ export async function autoReplyIfConfigured(
} }
try { try {
let mediaUrl = replyResult.mediaUrl; const mediaList = replyResult.mediaUrls?.length
if (mediaUrl && !/^https?:\/\//i.test(mediaUrl)) { ? replyResult.mediaUrls
const hosted = await ensureMediaHosted(mediaUrl); : replyResult.mediaUrl
mediaUrl = hosted.url; ? [replyResult.mediaUrl]
: [];
const sendTwilio = async (body: string, media?: string) => {
let resolvedMedia = media;
if (resolvedMedia && !/^https?:\/\//i.test(resolvedMedia)) {
const hosted = await ensureMediaHosted(resolvedMedia);
resolvedMedia = hosted.url;
} }
await client.messages.create({ await client.messages.create({
from: replyFrom, from: replyFrom,
to: replyTo, to: replyTo,
body: replyResult.text ?? "", body,
...(mediaUrl ? { mediaUrl: [mediaUrl] } : {}), ...(resolvedMedia ? { mediaUrl: [resolvedMedia] } : {}),
}); });
};
if (mediaList.length === 0) {
await sendTwilio(replyResult.text ?? "");
} else {
// First media with body (if any), then remaining as separate media-only sends.
await sendTwilio(replyResult.text ?? "", mediaList[0]);
for (const extra of mediaList.slice(1)) {
await sendTwilio("", extra);
}
}
if (isVerbose()) { if (isVerbose()) {
console.log( console.log(
info( info(
+1
View File
@@ -6,6 +6,7 @@ export type MsgContext = {
MediaPath?: string; MediaPath?: string;
MediaUrl?: string; MediaUrl?: string;
MediaType?: string; MediaType?: string;
Transcript?: string;
}; };
export type TemplateContext = MsgContext & { export type TemplateContext = MsgContext & {
+67
View File
@@ -0,0 +1,67 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { transcribeInboundAudio } from "./transcription.js";
vi.mock("../globals.js", () => ({
isVerbose: () => false,
logVerbose: vi.fn(),
}));
vi.mock("../process/exec.js", () => ({
runExec: vi.fn(async () => ({ stdout: "transcribed text\n" })),
}));
const runtime = {
error: vi.fn(),
};
describe("transcribeInboundAudio", () => {
afterEach(() => {
vi.resetAllMocks();
});
it("downloads mediaUrl to temp file and returns transcript", async () => {
const tmpBuf = Buffer.from("audio-bytes");
const tmpFile = path.join(os.tmpdir(), `warelay-audio-${Date.now()}.ogg`);
await fs.writeFile(tmpFile, tmpBuf);
const fetchMock = vi.fn(async () => ({
ok: true,
status: 200,
arrayBuffer: async () => tmpBuf,
})) as unknown as typeof fetch;
// @ts-expect-error override global fetch for test
global.fetch = fetchMock;
const cfg = {
inbound: {
transcribeAudio: {
command: ["echo", "{{MediaPath}}"],
timeoutSeconds: 5,
},
},
};
const ctx = { MediaUrl: "https://example.com/audio.ogg" };
const result = await transcribeInboundAudio(
cfg as never,
ctx as never,
runtime as never,
);
expect(result?.text).toBe("transcribed text");
expect(fetchMock).toHaveBeenCalled();
});
it("returns undefined when no transcription command", async () => {
const res = await transcribeInboundAudio(
{ inbound: {} } as never,
{} as never,
runtime as never,
);
expect(res).toBeUndefined();
});
});
+69
View File
@@ -0,0 +1,69 @@
import crypto from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { WarelayConfig } from "../config/config.js";
import { isVerbose, logVerbose } from "../globals.js";
import { runExec } from "../process/exec.js";
import type { RuntimeEnv } from "../runtime.js";
import { applyTemplate, type MsgContext } from "./templating.js";
export function isAudio(mediaType?: string | null) {
return Boolean(mediaType?.startsWith("audio"));
}
export async function transcribeInboundAudio(
cfg: WarelayConfig,
ctx: MsgContext,
runtime: RuntimeEnv,
): Promise<{ text: string } | undefined> {
const transcriber = cfg.inbound?.transcribeAudio;
if (!transcriber?.command?.length) return undefined;
const timeoutMs = Math.max((transcriber.timeoutSeconds ?? 45) * 1000, 1_000);
let tmpPath: string | undefined;
let mediaPath = ctx.MediaPath;
try {
if (!mediaPath && ctx.MediaUrl) {
const res = await fetch(ctx.MediaUrl);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const arrayBuf = await res.arrayBuffer();
const buffer = Buffer.from(arrayBuf);
tmpPath = path.join(
os.tmpdir(),
`warelay-audio-${crypto.randomUUID()}.ogg`,
);
await fs.writeFile(tmpPath, buffer);
mediaPath = tmpPath;
if (isVerbose()) {
logVerbose(
`Downloaded audio for transcription (${(buffer.length / (1024 * 1024)).toFixed(2)}MB) -> ${tmpPath}`,
);
}
}
if (!mediaPath) return undefined;
const templCtx: MsgContext = { ...ctx, MediaPath: mediaPath };
const argv = transcriber.command.map((part) =>
applyTemplate(part, templCtx),
);
if (isVerbose()) {
logVerbose(`Transcribing audio via command: ${argv.join(" ")}`);
}
const { stdout } = await runExec(argv[0], argv.slice(1), {
timeoutMs,
maxBuffer: 5 * 1024 * 1024,
});
const text = stdout.trim();
if (!text) return undefined;
return { text };
} catch (err) {
runtime.error?.(`Audio transcription failed: ${String(err)}`);
return undefined;
} finally {
if (tmpPath) {
void fs.unlink(tmpPath).catch(() => {});
}
}
}
+9
View File
@@ -0,0 +1,9 @@
export type GetReplyOptions = {
onReplyStart?: () => Promise<void> | void;
};
export type ReplyPayload = {
text?: string;
mediaUrl?: string;
mediaUrls?: string[];
};
+44 -4
View File
@@ -68,16 +68,22 @@ describe("cli program", () => {
pickProvider.mockResolvedValue("web"); pickProvider.mockResolvedValue("web");
monitorWebProvider.mockRejectedValue(new Error("no web")); monitorWebProvider.mockRejectedValue(new Error("no web"));
const program = buildProgram(); const program = buildProgram();
await program.parseAsync( await expect(
program.parseAsync(
["relay", "--provider", "auto", "--interval", "2", "--lookback", "1"], ["relay", "--provider", "auto", "--interval", "2", "--lookback", "1"],
{ from: "user" }, { from: "user" },
); ),
).rejects.toThrow("exit");
expect(logWebSelfId).toHaveBeenCalled(); expect(logWebSelfId).toHaveBeenCalled();
expect(ensureTwilioEnv).toHaveBeenCalled(); expect(ensureTwilioEnv).not.toHaveBeenCalled();
expect(monitorTwilio).toHaveBeenCalledWith(2, 1); expect(monitorTwilio).not.toHaveBeenCalled();
}); });
it("runs relay tmux attach command", async () => { it("runs relay tmux attach command", async () => {
const originalIsTTY = process.stdout.isTTY;
(process.stdout as typeof process.stdout & { isTTY?: boolean }).isTTY =
true;
const program = buildProgram(); const program = buildProgram();
await program.parseAsync(["relay:tmux:attach"], { from: "user" }); await program.parseAsync(["relay:tmux:attach"], { from: "user" });
expect(spawnRelayTmux).toHaveBeenCalledWith( expect(spawnRelayTmux).toHaveBeenCalledWith(
@@ -85,5 +91,39 @@ describe("cli program", () => {
true, true,
false, false,
); );
(process.stdout as typeof process.stdout & { isTTY?: boolean }).isTTY =
originalIsTTY;
});
it("runs relay heartbeat command", async () => {
pickProvider.mockResolvedValue("web");
monitorWebProvider.mockResolvedValue(undefined);
const originalExit = runtime.exit;
runtime.exit = vi.fn();
const program = buildProgram();
await program.parseAsync(["relay:heartbeat"], { from: "user" });
expect(logWebSelfId).toHaveBeenCalled();
expect(monitorWebProvider).toHaveBeenCalledWith(
false,
undefined,
true,
undefined,
runtime,
undefined,
{ replyHeartbeatNow: true },
);
expect(runtime.exit).not.toHaveBeenCalled();
runtime.exit = originalExit;
});
it("runs relay heartbeat tmux helper", async () => {
const program = buildProgram();
await program.parseAsync(["relay:heartbeat:tmux"], { from: "user" });
const shouldAttach = Boolean(process.stdout.isTTY);
expect(spawnRelayTmux).toHaveBeenCalledWith(
"pnpm warelay relay --verbose --heartbeat-now",
shouldAttach,
);
}); });
}); });
+391 -11
View File
@@ -1,12 +1,28 @@
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";
import { webhookCommand } from "../commands/webhook.js"; import { webhookCommand } from "../commands/webhook.js";
import { loadConfig } from "../config/config.js";
import { ensureTwilioEnv } from "../env.js"; import { ensureTwilioEnv } from "../env.js";
import { danger, info, setVerbose, setYes, warn } from "../globals.js"; import { danger, info, setVerbose, setYes } from "../globals.js";
import { loginWeb, monitorWebProvider, pickProvider } from "../provider-web.js"; import { getResolvedLoggerSettings } from "../logging.js";
import {
loginWeb,
logoutWeb,
monitorWebProvider,
pickProvider,
resolveHeartbeatRecipients,
runWebHeartbeatOnce,
type WebMonitorTuning,
} from "../provider-web.js";
import { defaultRuntime } from "../runtime.js"; import { defaultRuntime } from "../runtime.js";
import type { Provider } from "../utils.js"; import type { Provider } from "../utils.js";
import { VERSION } from "../version.js";
import {
resolveHeartbeatSeconds,
resolveReconnectPolicy,
} from "../web/reconnect.js";
import { import {
createDefaultDeps, createDefaultDeps,
logTwilioFrom, logTwilioFrom,
@@ -17,11 +33,76 @@ import { spawnRelayTmux } from "./relay_tmux.js";
export function buildProgram() { export function buildProgram() {
const program = new Command(); const program = new Command();
const PROGRAM_VERSION = VERSION;
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")
@@ -37,6 +118,18 @@ export function buildProgram() {
} }
}); });
program
.command("logout")
.description("Clear cached WhatsApp Web credentials")
.action(async () => {
try {
await logoutWeb(defaultRuntime);
} catch (err) {
defaultRuntime.error(danger(`Logout failed: ${String(err)}`));
defaultRuntime.exit(1);
}
});
program program
.command("send") .command("send")
.description("Send a WhatsApp message") .description("Send a WhatsApp message")
@@ -84,6 +177,89 @@ Examples:
} }
}); });
program
.command("heartbeat")
.description("Trigger a heartbeat poll once (web provider, no tmux)")
.option("--provider <provider>", "auto | web", "auto")
.option("--to <number>", "Override target E.164; defaults to allowFrom[0]")
.option(
"--session-id <id>",
"Force a session id for this heartbeat (resumes a specific Claude session)",
)
.option(
"--all",
"Send heartbeat to all active sessions (or allowFrom entries when none)",
false,
)
.option("--verbose", "Verbose logging", false)
.addHelpText(
"after",
`
Examples:
warelay heartbeat # uses web session + first allowFrom contact
warelay heartbeat --verbose # prints detailed heartbeat logs
warelay heartbeat --to +1555123 # override destination
warelay heartbeat --session-id <uuid> --to +1555123 # resume a specific session
warelay heartbeat --all # send to every active session recipient or allowFrom entry`,
)
.action(async (opts) => {
setVerbose(Boolean(opts.verbose));
const cfg = loadConfig();
const allowAll = Boolean(opts.all);
const resolution = resolveHeartbeatRecipients(cfg, {
to: opts.to,
all: allowAll,
});
if (
!opts.to &&
!allowAll &&
resolution.source === "session-ambiguous" &&
resolution.recipients.length > 1
) {
defaultRuntime.error(
danger(
`Multiple active sessions found (${resolution.recipients.join(", ")}). Pass --to <E.164> or --all to send to all.`,
),
);
defaultRuntime.exit(1);
}
const recipients = resolution.recipients;
if (!recipients || recipients.length === 0) {
defaultRuntime.error(
danger(
"No destination found. Add inbound.allowFrom numbers or pass --to <E.164>.",
),
);
defaultRuntime.exit(1);
}
const providerPref = String(opts.provider ?? "auto");
if (!["auto", "web"].includes(providerPref)) {
defaultRuntime.error("--provider must be auto or web");
defaultRuntime.exit(1);
}
const provider = await pickProvider(providerPref as "auto" | "web");
if (provider !== "web") {
defaultRuntime.error(
danger(
"Heartbeat is only supported for the web provider. Link with `warelay login --verbose`.",
),
);
defaultRuntime.exit(1);
}
try {
for (const to of recipients) {
await runWebHeartbeatOnce({
to,
verbose: Boolean(opts.verbose),
runtime: defaultRuntime,
sessionId: opts.sessionId,
});
}
} catch {
defaultRuntime.exit(1);
}
});
program program
.command("relay") .command("relay")
.description("Auto-reply to inbound messages (auto-selects web or twilio)") .description("Auto-reply to inbound messages (auto-selects web or twilio)")
@@ -94,6 +270,24 @@ Examples:
"Initial lookback window for twilio mode", "Initial lookback window for twilio mode",
"5", "5",
) )
.option(
"--web-heartbeat <seconds>",
"Heartbeat interval for web relay health logs (seconds)",
)
.option(
"--web-retries <count>",
"Max consecutive web reconnect attempts before exit (0 = unlimited)",
)
.option(
"--web-retry-initial <ms>",
"Initial reconnect backoff for web relay (ms)",
)
.option("--web-retry-max <ms>", "Max reconnect backoff for web relay (ms)")
.option(
"--heartbeat-now",
"Run a heartbeat immediately when relay starts (web provider)",
false,
)
.option("--verbose", "Verbose logging", false) .option("--verbose", "Verbose logging", false)
.addHelpText( .addHelpText(
"after", "after",
@@ -103,10 +297,13 @@ Examples:
warelay relay --provider web # force personal web session warelay relay --provider web # force personal web session
warelay relay --provider twilio # force twilio poll warelay relay --provider twilio # force twilio poll
warelay relay --provider twilio --interval 2 --lookback 30 warelay relay --provider twilio --interval 2 --lookback 30
# Troubleshooting: docs/refactor/web-relay-troubleshooting.md
`, `,
) )
.action(async (opts) => { .action(async (opts) => {
setVerbose(Boolean(opts.verbose)); setVerbose(Boolean(opts.verbose));
const { file: logFile, level: logLevel } = getResolvedLoggerSettings();
defaultRuntime.log(info(`logs: ${logFile} (level ${logLevel})`));
const providerPref = String(opts.provider ?? "auto"); const providerPref = String(opts.provider ?? "auto");
if (!["auto", "web", "twilio"].includes(providerPref)) { if (!["auto", "web", "twilio"].includes(providerPref)) {
defaultRuntime.error("--provider must be auto, web, or twilio"); defaultRuntime.error("--provider must be auto, web, or twilio");
@@ -114,6 +311,23 @@ Examples:
} }
const intervalSeconds = Number.parseInt(opts.interval, 10); const intervalSeconds = Number.parseInt(opts.interval, 10);
const lookbackMinutes = Number.parseInt(opts.lookback, 10); const lookbackMinutes = Number.parseInt(opts.lookback, 10);
const webHeartbeat =
opts.webHeartbeat !== undefined
? Number.parseInt(String(opts.webHeartbeat), 10)
: undefined;
const webRetries =
opts.webRetries !== undefined
? Number.parseInt(String(opts.webRetries), 10)
: undefined;
const webRetryInitial =
opts.webRetryInitial !== undefined
? Number.parseInt(String(opts.webRetryInitial), 10)
: undefined;
const webRetryMax =
opts.webRetryMax !== undefined
? Number.parseInt(String(opts.webRetryMax), 10)
: undefined;
const heartbeatNow = Boolean(opts.heartbeatNow);
if (Number.isNaN(intervalSeconds) || intervalSeconds <= 0) { if (Number.isNaN(intervalSeconds) || intervalSeconds <= 0) {
defaultRuntime.error("Interval must be a positive integer"); defaultRuntime.error("Interval must be a positive integer");
defaultRuntime.exit(1); defaultRuntime.exit(1);
@@ -122,31 +336,156 @@ Examples:
defaultRuntime.error("Lookback must be >= 0 minutes"); defaultRuntime.error("Lookback must be >= 0 minutes");
defaultRuntime.exit(1); defaultRuntime.exit(1);
} }
if (
webHeartbeat !== undefined &&
(Number.isNaN(webHeartbeat) || webHeartbeat <= 0)
) {
defaultRuntime.error("--web-heartbeat must be a positive integer");
defaultRuntime.exit(1);
}
if (
webRetries !== undefined &&
(Number.isNaN(webRetries) || webRetries < 0)
) {
defaultRuntime.error("--web-retries must be >= 0");
defaultRuntime.exit(1);
}
if (
webRetryInitial !== undefined &&
(Number.isNaN(webRetryInitial) || webRetryInitial <= 0)
) {
defaultRuntime.error("--web-retry-initial must be a positive integer");
defaultRuntime.exit(1);
}
if (
webRetryMax !== undefined &&
(Number.isNaN(webRetryMax) || webRetryMax <= 0)
) {
defaultRuntime.error("--web-retry-max must be a positive integer");
defaultRuntime.exit(1);
}
if (
webRetryMax !== undefined &&
webRetryInitial !== undefined &&
webRetryMax < webRetryInitial
) {
defaultRuntime.error("--web-retry-max must be >= --web-retry-initial");
defaultRuntime.exit(1);
}
const webTuning: WebMonitorTuning = {};
if (webHeartbeat !== undefined) webTuning.heartbeatSeconds = webHeartbeat;
if (heartbeatNow) webTuning.replyHeartbeatNow = true;
const reconnect: WebMonitorTuning["reconnect"] = {};
if (webRetries !== undefined) reconnect.maxAttempts = webRetries;
if (webRetryInitial !== undefined) reconnect.initialMs = webRetryInitial;
if (webRetryMax !== undefined) reconnect.maxMs = webRetryMax;
if (Object.keys(reconnect).length > 0) {
webTuning.reconnect = reconnect;
}
const provider = await pickProvider(providerPref as Provider | "auto"); const provider = await pickProvider(providerPref as Provider | "auto");
if (provider === "web") { if (provider === "web") {
logWebSelfId(defaultRuntime, true); logWebSelfId(defaultRuntime, true);
const cfg = loadConfig();
const effectiveHeartbeat = resolveHeartbeatSeconds(
cfg,
webTuning.heartbeatSeconds,
);
const effectivePolicy = resolveReconnectPolicy(
cfg,
webTuning.reconnect,
);
defaultRuntime.log(
info(
`Web relay health: heartbeat ${effectiveHeartbeat}s, retries ${effectivePolicy.maxAttempts || "∞"}, backoff ${effectivePolicy.initialMs}→${effectivePolicy.maxMs}ms x${effectivePolicy.factor} (jitter ${Math.round(effectivePolicy.jitter * 100)}%)`,
),
);
try { try {
await monitorWebProvider(Boolean(opts.verbose)); await monitorWebProvider(
Boolean(opts.verbose),
undefined,
true,
undefined,
defaultRuntime,
undefined,
webTuning,
);
return; return;
} catch (err) { } catch (err) {
if (providerPref === "auto") {
defaultRuntime.error( defaultRuntime.error(
warn("Web session unavailable; falling back to twilio."), danger(
`Web relay failed: ${String(err)}. Not falling back; re-link with 'warelay login --provider web'.`,
),
); );
} else {
defaultRuntime.error(danger(`Web relay failed: ${String(err)}`));
defaultRuntime.exit(1); defaultRuntime.exit(1);
} }
} }
}
ensureTwilioEnv(); ensureTwilioEnv();
logTwilioFrom(); logTwilioFrom();
await monitorTwilio(intervalSeconds, lookbackMinutes); await monitorTwilio(intervalSeconds, lookbackMinutes);
}); });
program
.command("relay:heartbeat")
.description(
"Run relay with an immediate heartbeat (no tmux); requires web provider",
)
.option("--provider <provider>", "auto | web", "auto")
.option("--verbose", "Verbose logging", false)
.action(async (opts) => {
setVerbose(Boolean(opts.verbose));
const { file: logFile, level: logLevel } = getResolvedLoggerSettings();
defaultRuntime.log(info(`logs: ${logFile} (level ${logLevel})`));
const providerPref = String(opts.provider ?? "auto");
if (!["auto", "web"].includes(providerPref)) {
defaultRuntime.error("--provider must be auto or web");
defaultRuntime.exit(1);
return;
}
const provider = await pickProvider(providerPref as "auto" | "web");
if (provider !== "web") {
defaultRuntime.error(
danger(
"Heartbeat relay is only supported for the web provider. Link with `warelay login --verbose`.",
),
);
defaultRuntime.exit(1);
return;
}
logWebSelfId(defaultRuntime, true);
const cfg = loadConfig();
const effectiveHeartbeat = resolveHeartbeatSeconds(cfg, undefined);
const effectivePolicy = resolveReconnectPolicy(cfg, undefined);
defaultRuntime.log(
info(
`Web relay health: heartbeat ${effectiveHeartbeat}s, retries ${effectivePolicy.maxAttempts || "∞"}, backoff ${effectivePolicy.initialMs}→${effectivePolicy.maxMs}ms x${effectivePolicy.factor} (jitter ${Math.round(effectivePolicy.jitter * 100)}%)`,
),
);
try {
await monitorWebProvider(
Boolean(opts.verbose),
undefined,
true,
undefined,
defaultRuntime,
undefined,
{ replyHeartbeatNow: true },
);
} catch (err) {
defaultRuntime.error(
danger(
`Web relay failed: ${String(err)}. Re-link with 'warelay login --provider web'.`,
),
);
defaultRuntime.exit(1);
}
});
program program
.command("status") .command("status")
.description("Show recent WhatsApp messages (sent and received)") .description("Show recent WhatsApp messages (sent and received)")
@@ -231,13 +570,16 @@ Examples:
) )
.action(async () => { .action(async () => {
try { try {
const shouldAttach = Boolean(process.stdout.isTTY);
const session = await spawnRelayTmux( const session = await spawnRelayTmux(
"pnpm warelay relay --verbose", "pnpm warelay relay --verbose",
true, shouldAttach,
); );
defaultRuntime.log( defaultRuntime.log(
info( info(
`tmux session started and attached: ${session} (pane running "pnpm warelay relay --verbose")`, shouldAttach
? `tmux session started and attached: ${session} (pane running "pnpm warelay relay --verbose")`
: `tmux session started: ${session} (pane running "pnpm warelay relay --verbose"); attach manually with "tmux attach -t ${session}"`,
), ),
); );
} catch (err) { } catch (err) {
@@ -255,6 +597,15 @@ Examples:
) )
.action(async () => { .action(async () => {
try { try {
if (!process.stdout.isTTY) {
defaultRuntime.error(
danger(
"Cannot attach: stdout is not a TTY. Run this in a terminal or use 'tmux attach -t warelay-relay' manually.",
),
);
defaultRuntime.exit(1);
return;
}
await spawnRelayTmux("pnpm warelay relay --verbose", true, false); await spawnRelayTmux("pnpm warelay relay --verbose", true, false);
defaultRuntime.log(info("Attached to warelay-relay session.")); defaultRuntime.log(info("Attached to warelay-relay session."));
} catch (err) { } catch (err) {
@@ -265,5 +616,34 @@ Examples:
} }
}); });
program
.command("relay:heartbeat:tmux")
.description(
"Run relay --verbose with an immediate heartbeat inside tmux (session warelay-relay), then attach",
)
.action(async () => {
try {
const shouldAttach = Boolean(process.stdout.isTTY);
const session = await spawnRelayTmux(
"pnpm warelay relay --verbose --heartbeat-now",
shouldAttach,
);
defaultRuntime.log(
info(
shouldAttach
? `tmux session started and attached: ${session} (pane running "pnpm warelay relay --verbose --heartbeat-now")`
: `tmux session started: ${session} (pane running "pnpm warelay relay --verbose --heartbeat-now"); attach manually with "tmux attach -t ${session}"`,
),
);
} catch (err) {
defaultRuntime.error(
danger(
`Failed to start relay tmux session with heartbeat: ${String(err)}`,
),
);
defaultRuntime.exit(1);
}
});
return program; return program;
} }
+2 -1
View File
@@ -38,7 +38,8 @@ describe("CLI relay command (e2e-ish)", () => {
expect(pickProvider).toHaveBeenCalledWith("web"); expect(pickProvider).toHaveBeenCalledWith("web");
expect(logWebSelfId).toHaveBeenCalledTimes(1); expect(logWebSelfId).toHaveBeenCalledTimes(1);
expect(monitorWebProvider).toHaveBeenCalledWith(false); expect(monitorWebProvider).toHaveBeenCalledTimes(1);
expect(monitorWebProvider.mock.calls[0][0]).toBe(false);
expect(monitorTwilio).not.toHaveBeenCalled(); expect(monitorTwilio).not.toHaveBeenCalled();
}); });
}); });
+78
View File
@@ -13,27 +13,61 @@ export type SessionConfig = {
scope?: SessionScope; scope?: SessionScope;
resetTriggers?: string[]; resetTriggers?: string[];
idleMinutes?: number; idleMinutes?: number;
heartbeatIdleMinutes?: number;
store?: string; store?: string;
sessionArgNew?: string[]; sessionArgNew?: string[];
sessionArgResume?: string[]; sessionArgResume?: string[];
sessionArgBeforeBody?: boolean; sessionArgBeforeBody?: boolean;
sendSystemOnce?: boolean;
sessionIntro?: string;
typingIntervalSeconds?: number;
heartbeatMinutes?: number;
};
export type LoggingConfig = {
level?: "silent" | "fatal" | "error" | "warn" | "info" | "debug" | "trace";
file?: string;
};
export type WebReconnectConfig = {
initialMs?: number;
maxMs?: number;
factor?: number;
jitter?: number;
maxAttempts?: number; // 0 = unlimited
};
export type WebConfig = {
heartbeatSeconds?: number;
reconnect?: WebReconnectConfig;
}; };
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:)
transcribeAudio?: {
// Optional CLI to turn inbound audio into text; templated args, must output transcript to stdout.
command: string[];
timeoutSeconds?: number;
};
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
mediaUrl?: string; // optional media attachment (path or URL) mediaUrl?: string; // optional media attachment (path or URL)
session?: SessionConfig; session?: SessionConfig;
claudeOutputFormat?: ClaudeOutputFormat; // when command starts with `claude`, force an output format claudeOutputFormat?: ClaudeOutputFormat; // when command starts with `claude`, force an output format
mediaMaxMb?: number; // optional cap for outbound media (default 5MB)
typingIntervalSeconds?: number; // how often to refresh typing indicator while command runs
heartbeatMinutes?: number; // auto-ping cadence for command mode
}; };
}; };
web?: WebConfig;
}; };
export const CONFIG_PATH = path.join(os.homedir(), ".warelay", "warelay.json"); export const CONFIG_PATH = path.join(os.homedir(), ".warelay", "warelay.json");
@@ -43,10 +77,13 @@ 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(),
mediaUrl: z.string().optional(), mediaUrl: z.string().optional(),
mediaMaxMb: z.number().positive().optional(),
typingIntervalSeconds: z.number().int().positive().optional(),
session: z session: z
.object({ .object({
scope: z scope: z
@@ -54,12 +91,17 @@ const ReplySchema = z
.optional(), .optional(),
resetTriggers: z.array(z.string()).optional(), resetTriggers: z.array(z.string()).optional(),
idleMinutes: z.number().int().positive().optional(), idleMinutes: z.number().int().positive().optional(),
heartbeatIdleMinutes: z.number().int().positive().optional(),
store: z.string().optional(), store: z.string().optional(),
sessionArgNew: z.array(z.string()).optional(), sessionArgNew: z.array(z.string()).optional(),
sessionArgResume: z.array(z.string()).optional(), sessionArgResume: z.array(z.string()).optional(),
sessionArgBeforeBody: z.boolean().optional(), sessionArgBeforeBody: z.boolean().optional(),
sendSystemOnce: z.boolean().optional(),
sessionIntro: z.string().optional(),
typingIntervalSeconds: z.number().int().positive().optional(),
}) })
.optional(), .optional(),
heartbeatMinutes: z.number().int().nonnegative().optional(),
claudeOutputFormat: z claudeOutputFormat: z
.union([ .union([
z.literal("text"), z.literal("text"),
@@ -78,12 +120,48 @@ 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(),
transcribeAudio: z
.object({
command: z.array(z.string()),
timeoutSeconds: z.number().int().positive().optional(),
})
.optional(),
reply: ReplySchema.optional(), reply: ReplySchema.optional(),
}) })
.optional(), .optional(),
web: z
.object({
heartbeatSeconds: z.number().int().positive().optional(),
reconnect: z
.object({
initialMs: z.number().positive().optional(),
maxMs: z.number().positive().optional(),
factor: z.number().positive().optional(),
jitter: z.number().min(0).max(1).optional(),
maxAttempts: z.number().int().min(0).optional(),
})
.optional(),
})
.optional(),
}); });
export function loadConfig(): WarelayConfig { export function loadConfig(): WarelayConfig {
+5 -1
View File
@@ -8,7 +8,11 @@ import { CONFIG_DIR, normalizeE164 } from "../utils.js";
export type SessionScope = "per-sender" | "global"; export type SessionScope = "per-sender" | "global";
export type SessionEntry = { sessionId: string; updatedAt: number }; export type SessionEntry = {
sessionId: string;
updatedAt: number;
systemSent?: boolean;
};
export const SESSION_STORE_DEFAULT = path.join(CONFIG_DIR, "sessions.json"); export const SESSION_STORE_DEFAULT = path.join(CONFIG_DIR, "sessions.json");
export const DEFAULT_RESET_TRIGGER = "/new"; export const DEFAULT_RESET_TRIGGER = "/new";
+323 -5
View File
@@ -1,10 +1,12 @@
import crypto from "node:crypto"; import crypto from "node:crypto";
import fs from "node:fs";
import net from "node:net"; import net from "node:net";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message.js"; import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createMockTwilio } from "../test/mocks/twilio.js"; import { createMockTwilio } from "../test/mocks/twilio.js";
import * as exec from "./process/exec.js";
import { withWhatsAppPrefix } from "./utils.js"; import { withWhatsAppPrefix } from "./utils.js";
// Twilio mock factory shared across tests // Twilio mock factory shared across tests
@@ -117,6 +119,82 @@ describe("config and templating", () => {
expect(result?.text).toContain("http://example.com/a.jpg"); expect(result?.text).toContain("http://example.com/a.jpg");
}); });
it("getReplyFromConfig runs audio transcription command when configured", async () => {
const cfg = {
inbound: {
transcribeAudio: {
command: ["echo", "voice transcript"],
},
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
},
},
};
const runExec = vi.spyOn(exec, "runExec").mockResolvedValue({
stdout: "voice transcript\n",
stderr: "",
});
const commandRunner = vi.fn().mockResolvedValue({
stdout: "ok",
stderr: "",
code: 0,
signal: null,
killed: false,
});
const result = await index.getReplyFromConfig(
{
Body: "<media:audio>",
From: "+1",
To: "+2",
MediaPath: "/tmp/voice.ogg",
MediaType: "audio/ogg",
},
undefined,
cfg,
commandRunner,
);
expect(runExec).toHaveBeenCalled();
expect(commandRunner).toHaveBeenCalled();
const argv = commandRunner.mock.calls[0][0];
const prompt = argv[argv.length - 1] as string;
expect(prompt).toContain("/tmp/voice.ogg");
expect(prompt).toContain("Transcript:");
expect(prompt).toContain("voice transcript");
expect(result?.text).toBe("ok");
});
it("getReplyFromConfig skips transcription when not configured", async () => {
const cfg = {
inbound: {
reply: {
mode: "text" as const,
text: "{{Body}}",
},
},
};
const runExec = vi.spyOn(exec, "runExec");
const result = await index.getReplyFromConfig(
{
Body: "<media:audio>",
From: "+1",
To: "+2",
MediaPath: "/tmp/voice.ogg",
MediaType: "audio/ogg",
},
undefined,
cfg,
);
expect(runExec).not.toHaveBeenCalled();
expect(result?.text).toContain("/tmp/voice.ogg");
expect(result?.text).toContain("<media:audio>");
});
it("getReplyFromConfig extracts media URL from command stdout", async () => { it("getReplyFromConfig extracts media URL from command stdout", async () => {
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({ const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({
stdout: "hello\nMEDIA: https://example.com/img.jpg\n", stdout: "hello\nMEDIA: https://example.com/img.jpg\n",
@@ -300,6 +378,66 @@ describe("config and templating", () => {
expect(result?.mediaUrl).toBeUndefined(); expect(result?.mediaUrl).toBeUndefined();
}); });
it("returns timeout reply with partial stdout snippet", async () => {
const partial = "x".repeat(900);
const runSpy = vi.fn().mockRejectedValue({
killed: true,
signal: "SIGKILL",
stdout: partial,
stderr: "",
});
const cfg = {
inbound: {
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
timeoutSeconds: 42,
},
},
};
const result = await index.getReplyFromConfig(
{ Body: "hi", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
expect(result?.text).toContain("Command timed out after 42s");
expect(result?.text).toContain("Partial output before timeout");
expect(result?.text).toContain(`${partial.slice(0, 800)}...`);
expect(result?.text).not.toContain(partial);
});
it("returns timeout reply without partial output when none is available", async () => {
const runSpy = vi.fn().mockRejectedValue({
killed: true,
signal: "SIGKILL",
stdout: "",
stderr: "",
});
const cfg = {
inbound: {
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
timeoutSeconds: 5,
},
},
};
const result = await index.getReplyFromConfig(
{ Body: "hi", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
expect(result?.text).toBe(
"Command timed out after 5s. Try a shorter prompt or split the request.",
);
});
it("splitMediaFromOutput strips media token and preserves text", () => { it("splitMediaFromOutput strips media token and preserves text", () => {
const { text, mediaUrl } = splitMediaFromOutput( const { text, mediaUrl } = splitMediaFromOutput(
"line1\nMEDIA:https://x/y.png\nline2", "line1\nMEDIA:https://x/y.png\nline2",
@@ -362,6 +500,185 @@ describe("config and templating", () => {
expect(argvSecond[2]).toBe("--resume"); expect(argvSecond[2]).toBe("--resume");
}); });
it("only sends system prompt once per session when configured", async () => {
const tmpStore = path.join(os.tmpdir(), `warelay-store-${Date.now()}.json`);
vi.spyOn(crypto, "randomUUID").mockReturnValue("sid-1");
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({
stdout: "ok\n",
stderr: "",
code: 0,
signal: null,
killed: false,
});
const cfg = {
inbound: {
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
template: "[tmpl]",
bodyPrefix: "[pfx] ",
session: {
sendSystemOnce: true,
sessionIntro: "SYS",
store: tmpStore,
sessionArgNew: ["--sid", "{{SessionId}}"],
sessionArgResume: ["--resume", "{{SessionId}}"],
},
},
},
};
await index.getReplyFromConfig(
{ Body: "/new hi", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
await index.getReplyFromConfig(
{ Body: "next", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
const firstArgv = runSpy.mock.calls[0][0];
expect(firstArgv).toEqual([
"echo",
"[tmpl]",
"--sid",
"sid-1",
"SYS\n\n[pfx] hi",
]);
const secondArgv = runSpy.mock.calls[1][0];
expect(secondArgv).toEqual(["echo", "--resume", "sid-1", "next"]);
const persisted = JSON.parse(fs.readFileSync(tmpStore, "utf-8"));
const firstEntry = Object.values(persisted)[0] as { systemSent?: boolean };
expect(firstEntry.systemSent).toBe(true);
});
it("keeps sending system prompt when sendSystemOnce is disabled (default)", async () => {
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({
stdout: "ok\n",
stderr: "",
code: 0,
signal: null,
killed: false,
});
const cfg = {
inbound: {
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
bodyPrefix: "[sys] ",
session: {
scope: "per-sender" as const,
resetTriggers: ["/new"],
idleMinutes: 60,
},
},
},
};
await index.getReplyFromConfig(
{ Body: "/new hi", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
await index.getReplyFromConfig(
{ Body: "next", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
const firstArgv = runSpy.mock.calls[0][0];
expect(firstArgv[firstArgv.length - 1]).toBe("[sys] hi");
const secondArgv = runSpy.mock.calls[1][0];
expect(secondArgv[secondArgv.length - 1]).toBe("[sys] next");
});
it("refreshes typing indicator while command runs", async () => {
const onReplyStart = vi.fn();
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockImplementation(
() =>
new Promise((resolve) =>
setTimeout(
() =>
resolve({
stdout: "done\n",
stderr: "",
code: 0,
signal: null,
killed: false,
}),
120,
),
),
);
const cfg = {
inbound: {
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
typingIntervalSeconds: 0.02,
},
},
};
const promise = index.getReplyFromConfig(
{ Body: "hi", From: "+1", To: "+2" },
{ onReplyStart },
cfg,
runSpy,
);
await new Promise((r) => setTimeout(r, 200));
await promise;
expect(onReplyStart.mock.calls.length).toBeGreaterThanOrEqual(3);
});
it("uses session typing interval override", async () => {
const onReplyStart = vi.fn();
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockImplementation(
() =>
new Promise((resolve) =>
setTimeout(
() =>
resolve({
stdout: "done\n",
stderr: "",
code: 0,
signal: null,
killed: false,
}),
120,
),
),
);
const cfg = {
inbound: {
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
session: { typingIntervalSeconds: 0.02 },
},
},
};
const promise = index.getReplyFromConfig(
{ Body: "hi", From: "+1", To: "+2" },
{ onReplyStart },
cfg,
runSpy,
);
await new Promise((r) => setTimeout(r, 200));
await promise;
expect(onReplyStart.mock.calls.length).toBeGreaterThanOrEqual(3);
});
it("injects Claude output format + print flag when configured", async () => { it("injects Claude output format + print flag when configured", async () => {
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({ const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({
stdout: "ok", stdout: "ok",
@@ -931,11 +1248,12 @@ describe("monitoring", () => {
const replySpy = vi.fn(); const replySpy = vi.fn();
const sendMediaSpy = vi.fn(); const sendMediaSpy = vi.fn();
const listenerFactory = vi.fn( const listenerFactory = vi.fn(
async ( async (opts: {
opts: Parameters<typeof index.monitorWebProvider>[1] extends undefined verbose: boolean;
? never onMessage: (
: NonNullable<Parameters<typeof index.monitorWebProvider>[1]>, msg: import("./web/inbound.js").WebInboundMessage,
) => { ) => Promise<void>;
}) => {
await opts.onMessage({ await opts.onMessage({
body: "hello", body: "hello",
from: "+1", from: "+1",
+18
View File
@@ -117,5 +117,23 @@ const isMain =
process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]; process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
if (isMain) { if (isMain) {
// Global error handlers to prevent silent crashes from unhandled rejections/exceptions.
// These log the error and exit gracefully instead of crashing without trace.
process.on("unhandledRejection", (reason, _promise) => {
console.error(
"[warelay] Unhandled promise rejection:",
reason instanceof Error ? (reason.stack ?? reason.message) : reason,
);
process.exit(1);
});
process.on("uncaughtException", (error) => {
console.error(
"[warelay] Uncaught exception:",
error.stack ?? error.message,
);
process.exit(1);
});
program.parseAsync(process.argv); program.parseAsync(process.argv);
} }
+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);
} }
+106
View File
@@ -0,0 +1,106 @@
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;
};
export type LoggerResolvedSettings = ResolvedSettings;
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);
}
export function getResolvedLoggerSettings(): LoggerResolvedSettings {
return resolveSettings();
}
// Test helpers
export function setLoggerOverride(settings: LoggerSettings | null) {
overrideSettings = settings;
cachedLogger = null;
cachedSettings = null;
}
export function resetLogger() {
cachedLogger = null;
cachedSettings = null;
overrideSettings = null;
}
+31
View File
@@ -0,0 +1,31 @@
export const MAX_IMAGE_BYTES = 6 * 1024 * 1024; // 6MB
export const MAX_AUDIO_BYTES = 16 * 1024 * 1024; // 16MB
export const MAX_VIDEO_BYTES = 16 * 1024 * 1024; // 16MB
export const MAX_DOCUMENT_BYTES = 100 * 1024 * 1024; // 100MB
export type MediaKind = "image" | "audio" | "video" | "document" | "unknown";
export function mediaKindFromMime(mime?: string | null): MediaKind {
if (!mime) return "unknown";
if (mime.startsWith("image/")) return "image";
if (mime.startsWith("audio/")) return "audio";
if (mime.startsWith("video/")) return "video";
if (mime === "application/pdf") return "document";
if (mime.startsWith("application/")) return "document";
return "unknown";
}
export function maxBytesForKind(kind: MediaKind): number {
switch (kind) {
case "image":
return MAX_IMAGE_BYTES;
case "audio":
return MAX_AUDIO_BYTES;
case "video":
return MAX_VIDEO_BYTES;
case "document":
return MAX_DOCUMENT_BYTES;
default:
return MAX_DOCUMENT_BYTES;
}
}
+64 -16
View File
@@ -1,7 +1,7 @@
// Shared helpers for parsing MEDIA tokens from command/stdout text. // Shared helpers for parsing MEDIA tokens from command/stdout text.
// Allow optional wrapping backticks and punctuation after the token; capture the core token. // Allow optional wrapping backticks and punctuation after the token; capture the core token.
export const MEDIA_TOKEN_RE = /\bMEDIA:\s*`?([^\s`]+)`?/i; export const MEDIA_TOKEN_RE = /\bMEDIA:\s*`?([^\n]+)`?/gi;
export function normalizeMediaSource(src: string) { export function normalizeMediaSource(src: string) {
return src.startsWith("file://") ? src.replace("file://", "") : src; return src.startsWith("file://") ? src.replace("file://", "") : src;
@@ -24,30 +24,78 @@ function isValidMedia(candidate: string) {
export function splitMediaFromOutput(raw: string): { export function splitMediaFromOutput(raw: string): {
text: string; text: string;
mediaUrl?: string; mediaUrls?: string[];
mediaUrl?: string; // legacy first item for backward compatibility
} { } {
const trimmedRaw = raw.trim(); const trimmedRaw = raw.trim();
const match = MEDIA_TOKEN_RE.exec(trimmedRaw); if (!trimmedRaw) return { text: "" };
if (!match?.[1]) return { text: trimmedRaw };
const candidate = normalizeMediaSource(cleanCandidate(match[1])); const media: string[] = [];
const mediaUrl = isValidMedia(candidate) ? candidate : undefined; let foundMediaToken = false;
const cleanedText = mediaUrl // Collect tokens line by line so we can strip them cleanly.
? trimmedRaw const lines = trimmedRaw.split("\n");
.replace(match[0], "") const keptLines: string[] = [];
.replace(/[ \t]+\n/g, "\n")
for (const line of lines) {
const matches = Array.from(line.matchAll(MEDIA_TOKEN_RE));
if (matches.length === 0) {
keptLines.push(line);
continue;
}
foundMediaToken = true;
const pieces: string[] = [];
let cursor = 0;
let hasValidMedia = false;
for (const match of matches) {
const start = match.index ?? 0;
pieces.push(line.slice(cursor, start));
const payload = match[1];
const parts = payload.split(/\s+/).filter(Boolean);
const invalidParts: string[] = [];
for (const part of parts) {
const candidate = normalizeMediaSource(cleanCandidate(part));
if (isValidMedia(candidate)) {
media.push(candidate);
hasValidMedia = true;
} else {
invalidParts.push(part);
}
}
if (hasValidMedia && invalidParts.length > 0) {
pieces.push(invalidParts.join(" "));
}
cursor = start + match[0].length;
}
pieces.push(line.slice(cursor));
const cleanedLine = pieces
.join("")
.replace(/[ \t]{2,}/g, " ") .replace(/[ \t]{2,}/g, " ")
.replace(/\n{2,}/g, "\n") .trim();
.trim()
: trimmedRaw // If the line becomes empty, drop it.
.split("\n") if (cleanedLine) {
.filter((line) => !MEDIA_TOKEN_RE.test(line)) keptLines.push(cleanedLine);
}
}
const cleanedText = keptLines
.join("\n") .join("\n")
.replace(/[ \t]+\n/g, "\n") .replace(/[ \t]+\n/g, "\n")
.replace(/[ \t]{2,}/g, " ") .replace(/[ \t]{2,}/g, " ")
.replace(/\n{2,}/g, "\n") .replace(/\n{2,}/g, "\n")
.trim(); .trim();
return mediaUrl ? { text: cleanedText, mediaUrl } : { text: cleanedText }; if (media.length === 0) {
return { text: foundMediaToken ? cleanedText : trimmedRaw };
}
return { text: cleanedText, mediaUrls: media, mediaUrl: media[0] };
} }
+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 = "";
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import * as mod from "./provider-web.js";
describe("provider-web barrel", () => {
it("exports the expected web helpers", () => {
expect(mod.createWaSocket).toBeTypeOf("function");
expect(mod.loginWeb).toBeTypeOf("function");
expect(mod.monitorWebProvider).toBeTypeOf("function");
expect(mod.sendMessageWeb).toBeTypeOf("function");
expect(mod.monitorWebInbox).toBeTypeOf("function");
expect(mod.pickProvider).toBeTypeOf("function");
expect(mod.WA_WEB_AUTH_DIR).toBeTruthy();
});
});
-334
View File
@@ -1,334 +0,0 @@
import { EventEmitter } from "node:events";
import fsSync from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { MockBaileysSocket } from "../test/mocks/baileys.js";
import { createMockBaileys } from "../test/mocks/baileys.js";
vi.mock("@whiskeysockets/baileys", () => {
const created = createMockBaileys();
(globalThis as Record<PropertyKey, unknown>)[
Symbol.for("warelay:lastSocket")
] = created.lastSocket;
return created.mod;
});
vi.mock("./media/store.js", () => ({
saveMediaBuffer: vi
.fn()
.mockImplementation(async (_buf: Buffer, contentType?: string) => ({
id: "mid",
path: "/tmp/mid",
size: _buf.length,
contentType,
})),
}));
function getLastSocket(): MockBaileysSocket {
const getter = (globalThis as Record<PropertyKey, unknown>)[
Symbol.for("warelay:lastSocket")
];
if (typeof getter === "function")
return (getter as () => MockBaileysSocket)();
if (!getter) throw new Error("Baileys mock not initialized");
throw new Error("Invalid Baileys socket getter");
}
vi.mock("qrcode-terminal", () => ({
default: { generate: vi.fn() },
generate: vi.fn(),
}));
import { monitorWebProvider } from "./index.js";
import {
createWaSocket,
loginWeb,
logWebSelfId,
monitorWebInbox,
sendMessageWeb,
waitForWaConnection,
} from "./provider-web.js";
const baileys = (await import(
"@whiskeysockets/baileys"
)) as unknown as typeof import("@whiskeysockets/baileys") & {
makeWASocket: ReturnType<typeof vi.fn>;
useMultiFileAuthState: ReturnType<typeof vi.fn>;
fetchLatestBaileysVersion: ReturnType<typeof vi.fn>;
makeCacheableSignalKeyStore: ReturnType<typeof vi.fn>;
};
describe("provider-web", () => {
beforeEach(() => {
vi.clearAllMocks();
const recreated = createMockBaileys();
(globalThis as Record<PropertyKey, unknown>)[
Symbol.for("warelay:lastSocket")
] = recreated.lastSocket;
baileys.makeWASocket.mockImplementation(recreated.mod.makeWASocket);
baileys.useMultiFileAuthState.mockImplementation(
recreated.mod.useMultiFileAuthState,
);
baileys.fetchLatestBaileysVersion.mockImplementation(
recreated.mod.fetchLatestBaileysVersion,
);
baileys.makeCacheableSignalKeyStore.mockImplementation(
recreated.mod.makeCacheableSignalKeyStore,
);
});
afterEach(() => {
vi.useRealTimers();
});
it("creates WA socket with QR handler", async () => {
await createWaSocket(true, false);
const makeWASocket = baileys.makeWASocket as ReturnType<typeof vi.fn>;
expect(makeWASocket).toHaveBeenCalledWith(
expect.objectContaining({ printQRInTerminal: false }),
);
const passed = makeWASocket.mock.calls[0][0];
const passedLogger = (
passed as { logger?: { level?: string; trace?: unknown } }
).logger;
expect(passedLogger?.level).toBe("silent");
expect(typeof passedLogger?.trace).toBe("function");
const sock = getLastSocket();
const saveCreds = (
await baileys.useMultiFileAuthState.mock.results[0].value
).saveCreds;
// trigger creds.update listener
sock.ev.emit("creds.update", {});
expect(saveCreds).toHaveBeenCalled();
});
it("waits for connection open", async () => {
const ev = new EventEmitter();
const promise = waitForWaConnection({ ev } as unknown as ReturnType<
typeof baileys.makeWASocket
>);
ev.emit("connection.update", { connection: "open" });
await expect(promise).resolves.toBeUndefined();
});
it("rejects when connection closes", async () => {
const ev = new EventEmitter();
const promise = waitForWaConnection({ ev } as unknown as ReturnType<
typeof baileys.makeWASocket
>);
ev.emit("connection.update", {
connection: "close",
lastDisconnect: new Error("bye"),
});
await expect(promise).rejects.toBeInstanceOf(Error);
});
it("sends message via web and closes socket", async () => {
await sendMessageWeb("+1555", "hi", { verbose: false });
const sock = getLastSocket();
expect(sock.sendMessage).toHaveBeenCalled();
expect(sock.ws.close).toHaveBeenCalled();
});
it("loginWeb waits for connection and closes", async () => {
const closeSpy = vi.fn();
const ev = new EventEmitter();
baileys.makeWASocket.mockImplementation(() => ({
ev,
ws: { close: closeSpy },
sendPresenceUpdate: vi.fn(),
sendMessage: vi.fn(),
}));
const waiter: typeof waitForWaConnection = vi
.fn()
.mockResolvedValue(undefined);
await loginWeb(false, waiter);
await new Promise((resolve) => setTimeout(resolve, 550));
expect(closeSpy).toHaveBeenCalled();
});
it("monitorWebInbox streams inbound messages", async () => {
const onMessage = vi.fn(async (msg) => {
await msg.sendComposing();
await msg.reply("pong");
});
const listener = await monitorWebInbox({ verbose: false, onMessage });
const sock = getLastSocket();
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
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));
expect(onMessage).toHaveBeenCalledWith(
expect.objectContaining({ body: "ping", from: "+999", to: "+123" }),
);
expect(sock.readMessages).toHaveBeenCalledWith([
{
remoteJid: "999@s.whatsapp.net",
id: "abc",
participant: undefined,
fromMe: false,
},
]);
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith(
"composing",
"999@s.whatsapp.net",
);
expect(sock.sendMessage).toHaveBeenCalledWith("999@s.whatsapp.net", {
text: "pong",
});
await listener.close();
});
it("monitorWebInbox captures media path for image messages", async () => {
const onMessage = vi.fn();
const listener = await monitorWebInbox({ verbose: false, onMessage });
const sock = getLastSocket();
const upsert = {
type: "notify",
messages: [
{
key: { id: "med1", fromMe: false, remoteJid: "888@s.whatsapp.net" },
message: { imageMessage: { mimetype: "image/jpeg" } },
messageTimestamp: 1_700_000_100,
},
],
};
sock.ev.emit("messages.upsert", upsert);
await new Promise((resolve) => setImmediate(resolve));
expect(onMessage).toHaveBeenCalledWith(
expect.objectContaining({
body: "<media:image>",
mediaPath: "/tmp/mid",
mediaType: "image/jpeg",
}),
);
expect(sock.readMessages).toHaveBeenCalledWith([
{
remoteJid: "888@s.whatsapp.net",
id: "med1",
participant: undefined,
fromMe: false,
},
]);
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
await listener.close();
});
it("monitorWebInbox includes participant when marking group messages read", async () => {
const onMessage = vi.fn();
const listener = await monitorWebInbox({ verbose: false, onMessage });
const sock = getLastSocket();
const upsert = {
type: "notify",
messages: [
{
key: {
id: "grp1",
fromMe: false,
remoteJid: "12345-67890@g.us",
participant: "111@s.whatsapp.net",
},
message: { conversation: "group ping" },
},
],
};
sock.ev.emit("messages.upsert", upsert);
await new Promise((resolve) => setImmediate(resolve));
expect(sock.readMessages).toHaveBeenCalledWith([
{
remoteJid: "12345-67890@g.us",
id: "grp1",
participant: "111@s.whatsapp.net",
fromMe: false,
},
]);
await listener.close();
});
it("monitorWebProvider falls back to text when media send fails", async () => {
const sendMedia = vi.fn().mockRejectedValue(new Error("boom"));
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn();
const resolver = vi.fn().mockResolvedValue({
text: "hi",
mediaUrl: "https://example.com/img.png",
});
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 fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
body: true,
arrayBuffer: async () => new ArrayBuffer(1024),
headers: { get: () => "image/png" },
status: 200,
} as Response);
await monitorWebProvider(false, listenerFactory, false, resolver);
expect(capturedOnMessage).toBeDefined();
await capturedOnMessage?.({
body: "hello",
from: "+1",
to: "+2",
id: "msg1",
sendComposing,
reply,
sendMedia,
});
expect(sendMedia).toHaveBeenCalled();
expect(reply).toHaveBeenCalledWith("hi");
fetchMock.mockRestore();
});
it("logWebSelfId prints cached E.164 when creds exist", () => {
const existsSpy = vi
.spyOn(fsSync, "existsSync")
.mockReturnValue(true as never);
const readSpy = vi
.spyOn(fsSync, "readFileSync")
.mockReturnValue(JSON.stringify({ me: { id: "12345@s.whatsapp.net" } }));
const runtime = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
logWebSelfId(runtime as never, true);
expect(runtime.log).toHaveBeenCalledWith(
"Web Provider: +12345 (jid 12345@s.whatsapp.net)",
);
existsSpy.mockRestore();
readSpy.mockRestore();
});
});
+32 -633
View File
@@ -1,633 +1,32 @@
import fsSync from "node:fs"; // Barrel exports for the web provider pieces. Splitting the original 900+ line
import fs from "node:fs/promises"; // module keeps responsibilities small and testable without changing the public API.
import os from "node:os"; export {
import path from "node:path"; DEFAULT_WEB_MEDIA_BYTES,
import type { proto } from "@whiskeysockets/baileys"; HEARTBEAT_PROMPT,
import { HEARTBEAT_TOKEN,
type AnyMessageContent, monitorWebProvider,
DisconnectReason, resolveHeartbeatRecipients,
downloadMediaMessage, runWebHeartbeatOnce,
fetchLatestBaileysVersion, type WebMonitorTuning,
makeCacheableSignalKeyStore, } from "./web/auto-reply.js";
makeWASocket, export {
useMultiFileAuthState, extractMediaPlaceholder,
type WAMessage, extractText,
} from "@whiskeysockets/baileys"; monitorWebInbox,
import pino from "pino"; type WebInboundMessage,
import qrcode from "qrcode-terminal"; type WebListenerCloseReason,
import { getReplyFromConfig } from "./auto-reply/reply.js"; } from "./web/inbound.js";
import { waitForever } from "./cli/wait.js"; export { loginWeb } from "./web/login.js";
import { danger, info, isVerbose, logVerbose, success } from "./globals.js"; export { loadWebMedia, optimizeImageToJpeg } from "./web/media.js";
import { logInfo } from "./logger.js"; export { sendMessageWeb } from "./web/outbound.js";
import { saveMediaBuffer } from "./media/store.js"; export {
import { defaultRuntime, type RuntimeEnv } from "./runtime.js"; createWaSocket,
import type { Provider } from "./utils.js"; formatError,
import { ensureDir, jidToE164, toWhatsappJid } from "./utils.js"; getStatusCode,
logoutWeb,
function formatDuration(ms: number) { logWebSelfId,
return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`; pickProvider,
} WA_WEB_AUTH_DIR,
waitForWaConnection,
const WA_WEB_AUTH_DIR = path.join(os.homedir(), ".warelay", "credentials"); webAuthExists,
} from "./web/session.js";
export async function createWaSocket(printQr: boolean, verbose: boolean) {
const logger = pino({ level: verbose ? "info" : "silent" });
// Some Baileys internals call logger.trace even when silent; ensure it's present.
const loggerAny = logger as unknown as Record<string, unknown>;
if (typeof loggerAny.trace !== "function") {
loggerAny.trace = () => {};
}
await ensureDir(WA_WEB_AUTH_DIR);
const { state, saveCreds } = await useMultiFileAuthState(WA_WEB_AUTH_DIR);
const { version } = await fetchLatestBaileysVersion();
const sock = makeWASocket({
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, logger),
},
version,
logger,
printQRInTerminal: false,
browser: ["Warelay", "CLI", "1.0.0"],
syncFullHistory: false,
markOnlineOnConnect: false,
});
sock.ev.on("creds.update", saveCreds);
sock.ev.on(
"connection.update",
(update: Partial<import("@whiskeysockets/baileys").ConnectionState>) => {
const { connection, lastDisconnect, qr } = update;
if (qr && printQr) {
console.log("Scan this QR in WhatsApp (Linked Devices):");
qrcode.generate(qr, { small: true });
}
if (connection === "close") {
const status = getStatusCode(lastDisconnect?.error);
if (status === DisconnectReason.loggedOut) {
console.error(
danger("WhatsApp session logged out. Run: warelay login"),
);
}
}
if (connection === "open" && verbose) {
console.log(success("WhatsApp Web connected."));
}
},
);
return sock;
}
export async function waitForWaConnection(
sock: ReturnType<typeof makeWASocket>,
) {
return new Promise<void>((resolve, reject) => {
type OffCapable = {
off?: (event: string, listener: (...args: unknown[]) => void) => void;
};
const evWithOff = sock.ev as unknown as OffCapable;
const handler = (...args: unknown[]) => {
const update = (args[0] ?? {}) as Partial<
import("@whiskeysockets/baileys").ConnectionState
>;
if (update.connection === "open") {
evWithOff.off?.("connection.update", handler);
resolve();
}
if (update.connection === "close") {
evWithOff.off?.("connection.update", handler);
reject(update.lastDisconnect ?? new Error("Connection closed"));
}
};
sock.ev.on("connection.update", handler);
});
}
export async function sendMessageWeb(
to: string,
body: string,
options: { verbose: boolean; mediaUrl?: string },
): Promise<{ messageId: string; toJid: string }> {
const sock = await createWaSocket(false, options.verbose);
try {
logInfo("🔌 Connecting to WhatsApp Web…");
await waitForWaConnection(sock);
const jid = toWhatsappJid(to);
try {
await sock.sendPresenceUpdate("composing", jid);
} catch (err) {
logVerbose(`Presence update skipped: ${String(err)}`);
}
let payload: AnyMessageContent = { text: body };
if (options.mediaUrl) {
const media = await loadWebMedia(options.mediaUrl);
payload = {
image: media.buffer,
caption: body || undefined,
mimetype: media.contentType,
};
}
logInfo(
`📤 Sending via web session -> ${jid}${options.mediaUrl ? " (media)" : ""}`,
);
const result = await sock.sendMessage(jid, payload);
const messageId = result?.key?.id ?? "unknown";
logInfo(
`✅ Sent via web session. Message ID: ${messageId} -> ${jid}${options.mediaUrl ? " (media)" : ""}`,
);
return { messageId, toJid: jid };
} finally {
try {
sock.ws?.close();
} catch (err) {
logVerbose(`Socket close failed: ${String(err)}`);
}
}
}
export async function loginWeb(
verbose: boolean,
waitForConnection: typeof waitForWaConnection = waitForWaConnection,
runtime: RuntimeEnv = defaultRuntime,
) {
const sock = await createWaSocket(true, verbose);
logInfo("Waiting for WhatsApp connection...", runtime);
try {
await waitForConnection(sock);
console.log(success("✅ Linked! Credentials saved for future sends."));
} catch (err) {
const code =
(err as { error?: { output?: { statusCode?: number } } })?.error?.output
?.statusCode ??
(err as { output?: { statusCode?: number } })?.output?.statusCode;
if (code === 515) {
console.log(
info(
"WhatsApp asked for a restart after pairing (code 515); creds are saved. Restarting connection once…",
),
);
try {
sock.ws?.close();
} catch {
// ignore
}
const retry = await createWaSocket(false, verbose);
try {
await waitForConnection(retry);
console.log(
success(
"✅ Linked after restart; web session ready. You can now send with provider=web.",
),
);
return;
} finally {
setTimeout(() => retry.ws?.close(), 500);
}
}
if (code === DisconnectReason.loggedOut) {
await fs.rm(WA_WEB_AUTH_DIR, { recursive: true, force: true });
console.error(
danger(
"WhatsApp reported the session is logged out. Cleared cached web session; please rerun warelay login and scan the QR again.",
),
);
throw new Error("Session logged out; cache cleared. Re-run login.");
}
const formatted = formatError(err);
console.error(
danger(
`WhatsApp Web connection ended before fully opening. ${formatted}`,
),
);
throw new Error(formatted);
} finally {
setTimeout(() => {
try {
sock.ws?.close();
} catch {
// ignore
}
}, 500);
}
}
export { WA_WEB_AUTH_DIR };
export function webAuthExists() {
return fs
.access(WA_WEB_AUTH_DIR)
.then(() => true)
.catch(() => false);
}
export type WebInboundMessage = {
id?: string;
from: string;
to: string;
body: string;
pushName?: string;
timestamp?: number;
sendComposing: () => Promise<void>;
reply: (text: string) => Promise<void>;
sendMedia: (payload: {
image: Buffer;
caption?: string;
mimetype?: string;
}) => Promise<void>;
mediaPath?: string;
mediaType?: string;
mediaUrl?: string;
};
export async function monitorWebInbox(options: {
verbose: boolean;
onMessage: (msg: WebInboundMessage) => Promise<void>;
}) {
const sock = await createWaSocket(false, options.verbose);
await waitForWaConnection(sock);
try {
// Advertise that the relay is online right after connecting.
await sock.sendPresenceUpdate("available");
if (isVerbose()) logVerbose("Sent global 'available' presence on connect");
} catch (err) {
logVerbose(
`Failed to send 'available' presence on connect: ${String(err)}`,
);
}
const selfJid = sock.user?.id;
const selfE164 = selfJid ? jidToE164(selfJid) : null;
const seen = new Set<string>();
sock.ev.on("messages.upsert", async (upsert) => {
if (upsert.type !== "notify") return;
for (const msg of upsert.messages) {
const id = msg.key?.id ?? undefined;
// De-dupe on message id; Baileys can emit retries.
if (id && seen.has(id)) continue;
if (id) seen.add(id);
if (msg.key?.fromMe) continue;
const remoteJid = msg.key?.remoteJid;
if (!remoteJid) continue;
// Ignore status/broadcast traffic; we only care about direct chats.
if (remoteJid.endsWith("@status") || remoteJid.endsWith("@broadcast"))
continue;
if (id) {
const participant = msg.key?.participant;
try {
await sock.readMessages([
{ remoteJid, id, participant, fromMe: false },
]);
if (isVerbose()) {
const suffix = participant ? ` (participant ${participant})` : "";
logVerbose(
`Marked message ${id} as read for ${remoteJid}${suffix}`,
);
}
} catch (err) {
logVerbose(`Failed to mark message ${id} read: ${String(err)}`);
}
}
const from = jidToE164(remoteJid);
if (!from) continue;
let body = extractText(msg.message ?? undefined);
if (!body) {
body = extractMediaPlaceholder(msg.message ?? undefined);
if (!body) continue;
}
let mediaPath: string | undefined;
let mediaType: string | undefined;
try {
const inboundMedia = await downloadInboundMedia(msg, sock);
if (inboundMedia) {
const saved = await saveMediaBuffer(
inboundMedia.buffer,
inboundMedia.mimetype,
);
mediaPath = saved.path;
mediaType = inboundMedia.mimetype;
}
} catch (err) {
logVerbose(`Inbound media download failed: ${String(err)}`);
}
const chatJid = remoteJid;
const sendComposing = async () => {
try {
await sock.sendPresenceUpdate("composing", chatJid);
} catch (err) {
logVerbose(`Presence update failed: ${String(err)}`);
}
};
const reply = async (text: string) => {
await sock.sendMessage(chatJid, { text });
};
const sendMedia = async (payload: {
image: Buffer;
caption?: string;
mimetype?: string;
}) => {
await sock.sendMessage(chatJid, payload);
};
const timestamp = msg.messageTimestamp
? Number(msg.messageTimestamp) * 1000
: undefined;
try {
await options.onMessage({
id,
from,
to: selfE164 ?? "me",
body,
pushName: msg.pushName ?? undefined,
timestamp,
sendComposing,
reply,
sendMedia,
mediaPath,
mediaType,
});
} catch (err) {
console.error(
danger(`Failed handling inbound web message: ${String(err)}`),
);
}
}
});
return {
close: async () => {
try {
sock.ws?.close();
} catch (err) {
logVerbose(`Socket close failed: ${String(err)}`);
}
},
};
}
export async function monitorWebProvider(
verbose: boolean,
listenerFactory = monitorWebInbox,
keepAlive = true,
replyResolver: typeof getReplyFromConfig = getReplyFromConfig,
runtime: RuntimeEnv = defaultRuntime,
) {
// Listen for inbound personal WhatsApp Web messages and auto-reply if configured.
const listener = await listenerFactory({
verbose,
onMessage: async (msg) => {
const ts = msg.timestamp
? new Date(msg.timestamp).toISOString()
: new Date().toISOString();
console.log(`\n[${ts}] ${msg.from} -> ${msg.to}: ${msg.body}`);
const replyStarted = Date.now();
const replyResult = await replyResolver(
{
Body: msg.body,
From: msg.from,
To: msg.to,
MessageSid: msg.id,
MediaPath: msg.mediaPath,
MediaUrl: msg.mediaUrl,
MediaType: msg.mediaType,
},
{
onReplyStart: msg.sendComposing,
},
);
if (!replyResult || (!replyResult.text && !replyResult.mediaUrl)) {
logVerbose("Skipping auto-reply: no text/media returned from resolver");
return;
}
try {
if (replyResult.mediaUrl) {
logVerbose(`Web auto-reply media detected: ${replyResult.mediaUrl}`);
try {
const media = await loadWebMedia(replyResult.mediaUrl);
if (isVerbose()) {
logVerbose(
`Web auto-reply media size: ${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB`,
);
}
await msg.sendMedia({
image: media.buffer,
caption: replyResult.text || undefined,
mimetype: media.contentType,
});
logInfo(
`✅ Sent web media reply to ${msg.from} (${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB)`,
runtime,
);
} catch (err) {
console.error(
danger(`Failed sending web media to ${msg.from}: ${String(err)}`),
);
if (replyResult.text) {
await msg.reply(replyResult.text);
logInfo(
`⚠️ Media skipped; sent text-only to ${msg.from}`,
runtime,
);
}
}
} else {
await msg.reply(replyResult.text ?? "");
}
const durationMs = Date.now() - replyStarted;
if (isVerbose()) {
console.log(
success(
`↩️ Auto-replied to ${msg.from} (web, ${replyResult.text?.length ?? 0} chars${replyResult.mediaUrl ? ", media" : ""}, ${formatDuration(durationMs)})`,
),
);
} else {
console.log(
success(
`↩️ ${replyResult.text ?? "<media>"}${replyResult.mediaUrl ? " (media)" : ""}`,
),
);
}
} catch (err) {
console.error(
danger(
`Failed sending web auto-reply to ${msg.from}: ${String(err)}`,
),
);
}
},
});
logInfo(
"📡 Listening for personal WhatsApp Web inbound messages. Leave this running; Ctrl+C to stop.",
runtime,
);
process.on("SIGINT", () => {
void listener.close().finally(() => {
logInfo("👋 Web monitor stopped", runtime);
runtime.exit(0);
});
});
if (keepAlive) {
await waitForever();
}
}
function readWebSelfId() {
// Read the cached WhatsApp Web identity (jid + E.164) from disk if present.
const credsPath = path.join(WA_WEB_AUTH_DIR, "creds.json");
try {
if (!fsSync.existsSync(credsPath)) {
return { e164: null, jid: null };
}
const raw = fsSync.readFileSync(credsPath, "utf-8");
const parsed = JSON.parse(raw) as { me?: { id?: string } } | undefined;
const jid = parsed?.me?.id ?? null;
const e164 = jid ? jidToE164(jid) : null;
return { e164, jid };
} catch {
return { e164: null, jid: null };
}
}
export function logWebSelfId(
runtime: RuntimeEnv = defaultRuntime,
includeProviderPrefix = false,
) {
// Human-friendly log of the currently linked personal web session.
const { e164, jid } = readWebSelfId();
const details =
e164 || jid
? `${e164 ?? "unknown"}${jid ? ` (jid ${jid})` : ""}`
: "unknown";
const prefix = includeProviderPrefix ? "Web Provider: " : "";
runtime.log(info(`${prefix}${details}`));
}
export async function pickProvider(pref: Provider | "auto"): Promise<Provider> {
// Auto-select web when logged in; otherwise fall back to twilio.
if (pref !== "auto") return pref;
const hasWeb = await webAuthExists();
if (hasWeb) return "web";
return "twilio";
}
function extractText(message: proto.IMessage | undefined): string | undefined {
if (!message) return undefined;
if (typeof message.conversation === "string" && message.conversation.trim()) {
return message.conversation.trim();
}
const extended = message.extendedTextMessage?.text;
if (extended?.trim()) return extended.trim();
const caption =
message.imageMessage?.caption ?? message.videoMessage?.caption;
if (caption?.trim()) return caption.trim();
return undefined;
}
function extractMediaPlaceholder(
message: proto.IMessage | undefined,
): string | undefined {
if (!message) return undefined;
if (message.imageMessage) return "<media:image>";
if (message.videoMessage) return "<media:video>";
if (message.audioMessage) return "<media:audio>";
if (message.documentMessage) return "<media:document>";
if (message.stickerMessage) return "<media:sticker>";
return undefined;
}
async function downloadInboundMedia(
msg: proto.IWebMessageInfo,
sock: ReturnType<typeof makeWASocket>,
): Promise<{ buffer: Buffer; mimetype?: string } | undefined> {
const message = msg.message;
if (!message) return undefined;
const mimetype =
message.imageMessage?.mimetype ??
message.videoMessage?.mimetype ??
message.documentMessage?.mimetype ??
message.audioMessage?.mimetype ??
message.stickerMessage?.mimetype ??
undefined;
if (
!message.imageMessage &&
!message.videoMessage &&
!message.documentMessage &&
!message.audioMessage &&
!message.stickerMessage
) {
return undefined;
}
try {
const buffer = (await downloadMediaMessage(
msg as WAMessage,
"buffer",
{},
{
reuploadRequest: sock.updateMediaMessage,
logger: sock.logger,
},
)) as Buffer;
return { buffer, mimetype };
} catch (err) {
logVerbose(`downloadMediaMessage failed: ${String(err)}`);
return undefined;
}
}
async function loadWebMedia(
mediaUrl: string,
): Promise<{ buffer: Buffer; contentType?: string }> {
const MAX_WEB_BYTES = 16 * 1024 * 1024; // 16MB: web provider can handle larger than Twilio
if (mediaUrl.startsWith("file://")) {
mediaUrl = mediaUrl.replace("file://", "");
}
if (/^https?:\/\//i.test(mediaUrl)) {
const res = await fetch(mediaUrl);
if (!res.ok || !res.body) {
throw new Error(`Failed to fetch media: HTTP ${res.status}`);
}
const array = Buffer.from(await res.arrayBuffer());
if (array.length > MAX_WEB_BYTES) {
throw new Error(
`Media exceeds ${Math.floor(MAX_WEB_BYTES / (1024 * 1024))}MB limit (got ${(
array.length / (1024 * 1024)
).toFixed(1)}MB)`,
);
}
return {
buffer: array,
contentType: res.headers.get("content-type") ?? undefined,
};
}
// Local path
const data = await fs.readFile(mediaUrl);
if (data.length > MAX_WEB_BYTES) {
throw new Error(
`Media exceeds ${Math.floor(MAX_WEB_BYTES / (1024 * 1024))}MB limit (got ${(
data.length / (1024 * 1024)
).toFixed(1)}MB)`,
);
}
return { buffer: data };
}
function getStatusCode(err: unknown) {
return (
(err as { output?: { statusCode?: number } })?.output?.statusCode ??
(err as { status?: number })?.status
);
}
function formatError(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === "string") return err;
const status = getStatusCode(err);
const code = (err as { code?: unknown })?.code;
if (status || code)
return `status=${status ?? "unknown"} code=${code ?? "unknown"}`;
return String(err);
}
+2 -2
View File
@@ -5,7 +5,7 @@ import express, { type Request, type Response } from "express";
import { getReplyFromConfig, type ReplyPayload } from "../auto-reply/reply.js"; import { getReplyFromConfig, type ReplyPayload } from "../auto-reply/reply.js";
import { type EnvConfig, readEnv } from "../env.js"; import { type EnvConfig, readEnv } from "../env.js";
import { danger, success } from "../globals.js"; import { danger, success } from "../globals.js";
import { ensureMediaHosted } from "../media/host.js"; import * as mediaHost from "../media/host.js";
import { attachMediaRoutes } from "../media/server.js"; import { attachMediaRoutes } from "../media/server.js";
import { saveMediaSource } from "../media/store.js"; import { saveMediaSource } from "../media/store.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js"; import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
@@ -92,7 +92,7 @@ export async function startWebhook(
try { try {
let mediaUrl = replyResult.mediaUrl; let mediaUrl = replyResult.mediaUrl;
if (mediaUrl && !/^https?:\/\//i.test(mediaUrl)) { if (mediaUrl && !/^https?:\/\//i.test(mediaUrl)) {
const hosted = await ensureMediaHosted(mediaUrl); const hosted = await mediaHost.ensureMediaHosted(mediaUrl);
mediaUrl = hosted.url; mediaUrl = hosted.url;
} }
await client.messages.create({ await client.messages.create({
+18
View File
@@ -4,7 +4,9 @@ import path from "node:path";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { import {
assertProvider, assertProvider,
CONFIG_DIR,
ensureDir, ensureDir,
jidToE164,
normalizeE164, normalizeE164,
normalizePath, normalizePath,
sleep, sleep,
@@ -67,3 +69,19 @@ describe("normalizeE164 & toWhatsappJid", () => {
); );
}); });
}); });
describe("jidToE164", () => {
it("maps @lid using reverse mapping file", () => {
const mappingPath = `${CONFIG_DIR}/credentials/lid-mapping-123_reverse.json`;
const original = fs.readFileSync;
const spy = vi
.spyOn(fs, "readFileSync")
// biome-ignore lint/suspicious/noExplicitAny: forwarding to native signature
.mockImplementation((path: any, encoding?: any) => {
if (path === mappingPath) return `"5551234"`;
return original(path, encoding);
});
expect(jidToE164("123@lid")).toBe("+5551234");
spy.mockRestore();
});
});
+24 -1
View File
@@ -1,5 +1,6 @@
import fs from "node:fs"; import fs from "node:fs";
import os from "node:os"; import os from "node:os";
import { isVerbose, logVerbose } from "./globals.js";
export async function ensureDir(dir: string) { export async function ensureDir(dir: string) {
await fs.promises.mkdir(dir, { recursive: true }); await fs.promises.mkdir(dir, { recursive: true });
@@ -38,11 +39,33 @@ export function toWhatsappJid(number: string): string {
export function jidToE164(jid: string): string | null { export function jidToE164(jid: string): string | null {
// Convert a WhatsApp JID (with optional device suffix, e.g. 1234:1@s.whatsapp.net) back to +1234. // Convert a WhatsApp JID (with optional device suffix, e.g. 1234:1@s.whatsapp.net) back to +1234.
const match = jid.match(/^(\d+)(?::\d+)?@s\.whatsapp\.net$/); const match = jid.match(/^(\d+)(?::\d+)?@s\.whatsapp\.net$/);
if (!match) return null; if (match) {
const digits = match[1]; const digits = match[1];
return `+${digits}`; return `+${digits}`;
} }
// Support @lid format (WhatsApp Linked ID) - look up reverse mapping
const lidMatch = jid.match(/^(\d+)(?::\d+)?@lid$/);
if (lidMatch) {
const lid = lidMatch[1];
try {
const mappingPath = `${CONFIG_DIR}/credentials/lid-mapping-${lid}_reverse.json`;
const data = fs.readFileSync(mappingPath, "utf8");
const phone = JSON.parse(data);
if (phone) return `+${phone}`;
} catch {
if (isVerbose()) {
logVerbose(
`LID mapping not found for ${lid}; skipping inbound message`,
);
}
// Mapping not found, fall through
}
}
return null;
}
export function sleep(ms: number) { export function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
} }
+7
View File
@@ -0,0 +1,7 @@
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const pkg = require("../package.json") as { version?: string };
// Single source of truth for the current warelay version (reads from package.json).
export const VERSION = pkg.version ?? "0.0.0";
+909
View File
@@ -0,0 +1,909 @@
import crypto from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { WarelayConfig } from "../config/config.js";
import { resolveStorePath } from "../config/sessions.js";
import { resetLogger, setLoggerOverride } from "../logging.js";
import {
HEARTBEAT_PROMPT,
HEARTBEAT_TOKEN,
monitorWebProvider,
resolveHeartbeatRecipients,
resolveReplyHeartbeatMinutes,
runWebHeartbeatOnce,
stripHeartbeatToken,
} from "./auto-reply.js";
import type { sendMessageWeb } from "./outbound.js";
import {
resetBaileysMocks,
resetLoadConfigMock,
setLoadConfigMock,
} from "./test-helpers.js";
describe("heartbeat helpers", () => {
it("strips heartbeat token and skips when only token", () => {
expect(stripHeartbeatToken(undefined)).toEqual({
shouldSkip: true,
text: "",
});
expect(stripHeartbeatToken(" ")).toEqual({
shouldSkip: true,
text: "",
});
expect(stripHeartbeatToken(HEARTBEAT_TOKEN)).toEqual({
shouldSkip: true,
text: "",
});
});
it("keeps content and removes token when mixed", () => {
expect(stripHeartbeatToken(`ALERT ${HEARTBEAT_TOKEN}`)).toEqual({
shouldSkip: false,
text: "ALERT",
});
expect(stripHeartbeatToken(`hello`)).toEqual({
shouldSkip: false,
text: "hello",
});
});
it("resolves heartbeat minutes with default and overrides", () => {
const cfgBase: WarelayConfig = {
inbound: {
reply: { mode: "command" as const },
},
};
expect(resolveReplyHeartbeatMinutes(cfgBase)).toBe(30);
expect(
resolveReplyHeartbeatMinutes({
inbound: { reply: { mode: "command", heartbeatMinutes: 5 } },
}),
).toBe(5);
expect(
resolveReplyHeartbeatMinutes({
inbound: { reply: { mode: "command", heartbeatMinutes: 0 } },
}),
).toBeNull();
expect(resolveReplyHeartbeatMinutes(cfgBase, 7)).toBe(7);
expect(
resolveReplyHeartbeatMinutes({
inbound: { reply: { mode: "text" } },
}),
).toBeNull();
});
});
describe("resolveHeartbeatRecipients", () => {
const makeStore = async (entries: Record<string, { updatedAt: number }>) => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "warelay-heartbeat-"));
const storePath = path.join(dir, "sessions.json");
await fs.writeFile(storePath, JSON.stringify(entries));
return {
storePath,
cleanup: async () => fs.rm(dir, { recursive: true, force: true }),
};
};
it("returns the sole session recipient", async () => {
const now = Date.now();
const store = await makeStore({ "+1000": { updatedAt: now } });
const cfg: WarelayConfig = {
inbound: {
allowFrom: ["+1999"],
reply: { mode: "command", session: { store: store.storePath } },
},
};
const result = resolveHeartbeatRecipients(cfg);
expect(result.source).toBe("session-single");
expect(result.recipients).toEqual(["+1000"]);
await store.cleanup();
});
it("surfaces ambiguity when multiple sessions exist", async () => {
const now = Date.now();
const store = await makeStore({
"+1000": { updatedAt: now },
"+2000": { updatedAt: now - 10 },
});
const cfg: WarelayConfig = {
inbound: {
allowFrom: ["+1999"],
reply: { mode: "command", session: { store: store.storePath } },
},
};
const result = resolveHeartbeatRecipients(cfg);
expect(result.source).toBe("session-ambiguous");
expect(result.recipients).toEqual(["+1000", "+2000"]);
await store.cleanup();
});
it("filters wildcard allowFrom when no sessions exist", async () => {
const store = await makeStore({});
const cfg: WarelayConfig = {
inbound: {
allowFrom: ["*"],
reply: { mode: "command", session: { store: store.storePath } },
},
};
const result = resolveHeartbeatRecipients(cfg);
expect(result.recipients).toHaveLength(0);
expect(result.source).toBe("allowFrom");
await store.cleanup();
});
it("merges sessions and allowFrom when --all is set", async () => {
const now = Date.now();
const store = await makeStore({ "+1000": { updatedAt: now } });
const cfg: WarelayConfig = {
inbound: {
allowFrom: ["+1999"],
reply: { mode: "command", session: { store: store.storePath } },
},
};
const result = resolveHeartbeatRecipients(cfg, { all: true });
expect(result.source).toBe("all");
expect(result.recipients.sort()).toEqual(["+1000", "+1999"].sort());
await store.cleanup();
});
});
describe("runWebHeartbeatOnce", () => {
it("skips when heartbeat token returned", async () => {
const sender: typeof sendMessageWeb = vi.fn();
const resolver = vi.fn(async () => ({ text: HEARTBEAT_TOKEN }));
setLoadConfigMock({
inbound: { allowFrom: ["+1555"], reply: { mode: "command" } },
});
await runWebHeartbeatOnce({
to: "+1555",
verbose: false,
sender,
replyResolver: resolver,
});
expect(resolver).toHaveBeenCalled();
expect(sender).not.toHaveBeenCalled();
});
it("sends when alert text present", async () => {
const sender: typeof sendMessageWeb = vi
.fn()
.mockResolvedValue({ messageId: "m1", toJid: "jid" });
const resolver = vi.fn(async () => ({ text: "ALERT" }));
setLoadConfigMock({
inbound: { allowFrom: ["+1555"], reply: { mode: "command" } },
});
await runWebHeartbeatOnce({
to: "+1555",
verbose: false,
sender,
replyResolver: resolver,
});
expect(sender).toHaveBeenCalledWith("+1555", "ALERT", { verbose: false });
});
it("falls back to most recent session when no to is provided", async () => {
const sender: typeof sendMessageWeb = vi
.fn()
.mockResolvedValue({ messageId: "m1", toJid: "jid" });
const resolver = vi.fn(async () => ({ text: "ALERT" }));
// Seed session store
const now = Date.now();
const store = {
"+1222": { sessionId: "s1", updatedAt: now - 1000 },
"+1333": { sessionId: "s2", updatedAt: now },
};
const storePath = resolveStorePath();
await fs.mkdir(resolveStorePath().replace("sessions.json", ""), {
recursive: true,
});
await fs.writeFile(storePath, JSON.stringify(store));
setLoadConfigMock({
inbound: {
allowFrom: ["+1999"],
reply: { mode: "command", session: {} },
},
});
await runWebHeartbeatOnce({
to: "+1999",
verbose: false,
sender,
replyResolver: resolver,
});
expect(sender).toHaveBeenCalledWith("+1999", "ALERT", { verbose: false });
});
it("does not refresh updatedAt when heartbeat is skipped", async () => {
const tmpDir = await fs.mkdtemp(
path.join(os.tmpdir(), "warelay-heartbeat-"),
);
const storePath = path.join(tmpDir, "sessions.json");
const now = Date.now();
const originalUpdated = now - 30 * 60 * 1000;
const store = {
"+1555": { sessionId: "sess1", updatedAt: originalUpdated },
};
await fs.writeFile(storePath, JSON.stringify(store));
const sender: typeof sendMessageWeb = vi.fn();
const resolver = vi.fn(async () => ({ text: HEARTBEAT_TOKEN }));
setLoadConfigMock({
inbound: {
allowFrom: ["+1555"],
reply: {
mode: "command",
session: {
store: storePath,
idleMinutes: 60,
heartbeatIdleMinutes: 10,
},
},
},
});
await runWebHeartbeatOnce({
to: "+1555",
verbose: false,
sender,
replyResolver: resolver,
});
const after = JSON.parse(await fs.readFile(storePath, "utf-8"));
expect(after["+1555"].updatedAt).toBe(originalUpdated);
expect(sender).not.toHaveBeenCalled();
});
it("heartbeat reuses existing session id when last inbound is present", async () => {
const tmpDir = await fs.mkdtemp(
path.join(os.tmpdir(), "warelay-heartbeat-session-"),
);
const storePath = path.join(tmpDir, "sessions.json");
const sessionId = "sess-keep";
await fs.writeFile(
storePath,
JSON.stringify({
"+4367": { sessionId, updatedAt: Date.now(), systemSent: false },
}),
);
setLoadConfigMock(() => ({
inbound: {
allowFrom: ["+4367"],
reply: {
mode: "command",
heartbeatMinutes: 0.001,
session: { store: storePath, idleMinutes: 60 },
},
},
}));
const replyResolver = vi.fn().mockResolvedValue({ text: HEARTBEAT_TOKEN });
const runtime = { log: vi.fn(), error: vi.fn(), exit: vi.fn() } as never;
const cfg: WarelayConfig = {
inbound: {
allowFrom: ["+4367"],
reply: {
mode: "command",
session: { store: storePath, idleMinutes: 60 },
},
},
};
await runWebHeartbeatOnce({
cfg,
to: "+4367",
verbose: false,
replyResolver,
runtime,
});
const heartbeatCall = replyResolver.mock.calls.find(
(call) => call[0]?.Body === HEARTBEAT_PROMPT,
);
expect(heartbeatCall?.[0]?.MessageSid).toBe(sessionId);
});
it("heartbeat honors session-id override and seeds store", async () => {
const tmpDir = await fs.mkdtemp(
path.join(os.tmpdir(), "warelay-heartbeat-override-"),
);
const storePath = path.join(tmpDir, "sessions.json");
await fs.writeFile(storePath, JSON.stringify({}));
const sessionId = "override-123";
setLoadConfigMock(() => ({
inbound: {
allowFrom: ["+1999"],
reply: {
mode: "command",
session: { store: storePath, idleMinutes: 60 },
},
},
}));
const resolver = vi.fn(async () => ({ text: HEARTBEAT_TOKEN }));
const cfg: WarelayConfig = {
inbound: {
allowFrom: ["+1999"],
reply: {
mode: "command",
session: { store: storePath, idleMinutes: 60 },
},
},
};
await runWebHeartbeatOnce({
cfg,
to: "+1999",
verbose: false,
replyResolver: resolver,
sessionId,
});
const heartbeatCall = resolver.mock.calls.find(
(call) => call[0]?.Body === HEARTBEAT_PROMPT,
);
expect(heartbeatCall?.[0]?.MessageSid).toBe(sessionId);
const raw = await fs.readFile(storePath, "utf-8");
const stored = raw ? JSON.parse(raw) : {};
expect(stored["+1999"]?.sessionId).toBe(sessionId);
expect(stored["+1999"]?.updatedAt).toBeDefined();
});
});
describe("web auto-reply", () => {
beforeEach(() => {
vi.clearAllMocks();
resetBaileysMocks();
resetLoadConfigMock();
});
afterEach(() => {
resetLogger();
setLoggerOverride(null);
vi.useRealTimers();
});
it("reconnects after a connection close", async () => {
const closeResolvers: Array<() => void> = [];
const sleep = vi.fn(async () => {});
const listenerFactory = vi.fn(async () => {
let _resolve!: () => void;
const onClose = new Promise<void>((res) => {
_resolve = res;
closeResolvers.push(res);
});
return { close: vi.fn(), onClose };
});
const runtime = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
const controller = new AbortController();
const run = monitorWebProvider(
false,
listenerFactory,
true,
async () => ({ text: "ok" }),
runtime as never,
controller.signal,
{
heartbeatSeconds: 1,
reconnect: { initialMs: 10, maxMs: 10, maxAttempts: 3, factor: 1.1 },
sleep,
},
);
await Promise.resolve();
expect(listenerFactory).toHaveBeenCalledTimes(1);
closeResolvers[0]?.();
const waitForSecondCall = async () => {
const started = Date.now();
while (
listenerFactory.mock.calls.length < 2 &&
Date.now() - started < 200
) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
};
await waitForSecondCall();
expect(listenerFactory).toHaveBeenCalledTimes(2);
expect(runtime.error).toHaveBeenCalledWith(
expect.stringContaining("Retry 1"),
);
controller.abort();
closeResolvers[1]?.();
await new Promise((resolve) => setTimeout(resolve, 5));
await run;
});
it("stops after hitting max reconnect attempts", async () => {
const closeResolvers: Array<() => void> = [];
const sleep = vi.fn(async () => {});
const listenerFactory = vi.fn(async () => {
const onClose = new Promise<void>((res) => closeResolvers.push(res));
return { close: vi.fn(), onClose };
});
const runtime = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
const run = monitorWebProvider(
false,
listenerFactory,
true,
async () => ({ text: "ok" }),
runtime as never,
undefined,
{
heartbeatSeconds: 1,
reconnect: { initialMs: 5, maxMs: 5, maxAttempts: 2, factor: 1.1 },
sleep,
},
);
await Promise.resolve();
expect(listenerFactory).toHaveBeenCalledTimes(1);
closeResolvers.shift()?.();
await new Promise((resolve) => setTimeout(resolve, 15));
expect(listenerFactory).toHaveBeenCalledTimes(2);
closeResolvers.shift()?.();
await new Promise((resolve) => setTimeout(resolve, 15));
await run;
expect(runtime.error).toHaveBeenCalledWith(
expect.stringContaining("Reached max retries"),
);
});
it("falls back to text when media send fails", async () => {
const sendMedia = vi.fn().mockRejectedValue(new Error("boom"));
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn();
const resolver = vi.fn().mockResolvedValue({
text: "hi",
mediaUrl: "https://example.com/img.png",
});
let capturedOnMessage:
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
| undefined;
const listenerFactory = async (opts: {
onMessage: (
msg: import("./inbound.js").WebInboundMessage,
) => Promise<void>;
}) => {
capturedOnMessage = opts.onMessage;
return { close: vi.fn() };
};
const smallPng = await sharp({
create: {
width: 200,
height: 200,
channels: 3,
background: { r: 0, g: 255, b: 0 },
},
})
.png()
.toBuffer();
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
body: true,
arrayBuffer: async () =>
smallPng.buffer.slice(
smallPng.byteOffset,
smallPng.byteOffset + smallPng.byteLength,
),
headers: { get: () => "image/png" },
status: 200,
} as Response);
await monitorWebProvider(false, listenerFactory, false, resolver);
expect(capturedOnMessage).toBeDefined();
await capturedOnMessage?.({
body: "hello",
from: "+1",
to: "+2",
id: "msg1",
sendComposing,
reply,
sendMedia,
});
expect(sendMedia).toHaveBeenCalledTimes(1);
expect(reply).toHaveBeenCalledWith("hi");
fetchMock.mockRestore();
});
it("compresses media over 5MB and still sends it", async () => {
const sendMedia = vi.fn();
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn();
const resolver = vi.fn().mockResolvedValue({
text: "hi",
mediaUrl: "https://example.com/big.png",
});
let capturedOnMessage:
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
| undefined;
const listenerFactory = async (opts: {
onMessage: (
msg: import("./inbound.js").WebInboundMessage,
) => Promise<void>;
}) => {
capturedOnMessage = opts.onMessage;
return { close: vi.fn() };
};
const bigPng = await sharp({
create: {
width: 3200,
height: 3200,
channels: 3,
background: { r: 255, g: 0, b: 0 },
},
})
.png({ compressionLevel: 0 })
.toBuffer();
expect(bigPng.length).toBeGreaterThan(5 * 1024 * 1024);
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
body: true,
arrayBuffer: async () =>
bigPng.buffer.slice(
bigPng.byteOffset,
bigPng.byteOffset + bigPng.byteLength,
),
headers: { get: () => "image/png" },
status: 200,
} as Response);
await monitorWebProvider(false, listenerFactory, false, resolver);
expect(capturedOnMessage).toBeDefined();
await capturedOnMessage?.({
body: "hello",
from: "+1",
to: "+2",
id: "msg1",
sendComposing,
reply,
sendMedia,
});
expect(sendMedia).toHaveBeenCalledTimes(1);
const payload = sendMedia.mock.calls[0][0] as {
image: Buffer;
caption?: string;
mimetype?: string;
};
expect(payload.image.length).toBeLessThanOrEqual(5 * 1024 * 1024);
expect(payload.mimetype).toBe("image/jpeg");
// Should not fall back to separate text reply because caption is used.
expect(reply).not.toHaveBeenCalled();
fetchMock.mockRestore();
});
it(
"compresses common formats to jpeg under the cap",
{ timeout: 15_000 },
async () => {
const formats = [
{
name: "png",
mime: "image/png",
make: (buf: Buffer, opts: { width: number; height: number }) =>
sharp(buf, {
raw: { width: opts.width, height: opts.height, channels: 3 },
})
.png({ compressionLevel: 0 })
.toBuffer(),
},
{
name: "jpeg",
mime: "image/jpeg",
make: (buf: Buffer, opts: { width: number; height: number }) =>
sharp(buf, {
raw: { width: opts.width, height: opts.height, channels: 3 },
})
.jpeg({ quality: 100, chromaSubsampling: "4:4:4" })
.toBuffer(),
},
{
name: "webp",
mime: "image/webp",
make: (buf: Buffer, opts: { width: number; height: number }) =>
sharp(buf, {
raw: { width: opts.width, height: opts.height, channels: 3 },
})
.webp({ quality: 100 })
.toBuffer(),
},
] as const;
for (const fmt of formats) {
// Force a small cap to ensure compression is exercised for every format.
setLoadConfigMock(() => ({ inbound: { reply: { mediaMaxMb: 1 } } }));
const sendMedia = vi.fn();
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn();
const resolver = vi.fn().mockResolvedValue({
text: "hi",
mediaUrl: `https://example.com/big.${fmt.name}`,
});
let capturedOnMessage:
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
| undefined;
const listenerFactory = async (opts: {
onMessage: (
msg: import("./inbound.js").WebInboundMessage,
) => Promise<void>;
}) => {
capturedOnMessage = opts.onMessage;
return { close: vi.fn() };
};
const width = 1200;
const height = 1200;
const raw = crypto.randomBytes(width * height * 3);
const big = await fmt.make(raw, { width, height });
expect(big.length).toBeGreaterThan(1 * 1024 * 1024);
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
body: true,
arrayBuffer: async () =>
big.buffer.slice(big.byteOffset, big.byteOffset + big.byteLength),
headers: { get: () => fmt.mime },
status: 200,
} as Response);
await monitorWebProvider(false, listenerFactory, false, resolver);
expect(capturedOnMessage).toBeDefined();
await capturedOnMessage?.({
body: "hello",
from: "+1",
to: "+2",
id: `msg-${fmt.name}`,
sendComposing,
reply,
sendMedia,
});
expect(sendMedia).toHaveBeenCalledTimes(1);
const payload = sendMedia.mock.calls[0][0] as {
image: Buffer;
mimetype?: string;
};
expect(payload.image.length).toBeLessThanOrEqual(1 * 1024 * 1024);
expect(payload.mimetype).toBe("image/jpeg");
expect(reply).not.toHaveBeenCalled();
fetchMock.mockRestore();
resetLoadConfigMock();
}
},
);
it("honors mediaMaxMb from config", async () => {
setLoadConfigMock(() => ({ inbound: { reply: { mediaMaxMb: 1 } } }));
const sendMedia = vi.fn();
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn();
const resolver = vi.fn().mockResolvedValue({
text: "hi",
mediaUrl: "https://example.com/big.png",
});
let capturedOnMessage:
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
| undefined;
const listenerFactory = async (opts: {
onMessage: (
msg: import("./inbound.js").WebInboundMessage,
) => Promise<void>;
}) => {
capturedOnMessage = opts.onMessage;
return { close: vi.fn() };
};
const bigPng = await sharp({
create: {
width: 2600,
height: 2600,
channels: 3,
background: { r: 0, g: 0, b: 255 },
},
})
.png({ compressionLevel: 0 })
.toBuffer();
expect(bigPng.length).toBeGreaterThan(1 * 1024 * 1024);
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
body: true,
arrayBuffer: async () =>
bigPng.buffer.slice(
bigPng.byteOffset,
bigPng.byteOffset + bigPng.byteLength,
),
headers: { get: () => "image/png" },
status: 200,
} as Response);
await monitorWebProvider(false, listenerFactory, false, resolver);
expect(capturedOnMessage).toBeDefined();
await capturedOnMessage?.({
body: "hello",
from: "+1",
to: "+2",
id: "msg1",
sendComposing,
reply,
sendMedia,
});
expect(sendMedia).toHaveBeenCalledTimes(1);
const payload = sendMedia.mock.calls[0][0] as {
image: Buffer;
caption?: string;
mimetype?: string;
};
expect(payload.image.length).toBeLessThanOrEqual(1 * 1024 * 1024);
expect(payload.mimetype).toBe("image/jpeg");
expect(reply).not.toHaveBeenCalled();
fetchMock.mockRestore();
});
it("falls back to text when media is unsupported", async () => {
const sendMedia = vi.fn();
const reply = vi.fn().mockResolvedValue(undefined);
const sendComposing = vi.fn();
const resolver = vi.fn().mockResolvedValue({
text: "hi",
mediaUrl: "https://example.com/file.pdf",
});
let capturedOnMessage:
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
| undefined;
const listenerFactory = async (opts: {
onMessage: (
msg: import("./inbound.js").WebInboundMessage,
) => Promise<void>;
}) => {
capturedOnMessage = opts.onMessage;
return { close: vi.fn() };
};
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
body: true,
arrayBuffer: async () => Buffer.from("%PDF-1.4").buffer,
headers: { get: () => "application/pdf" },
status: 200,
} as Response);
await monitorWebProvider(false, listenerFactory, false, resolver);
expect(capturedOnMessage).toBeDefined();
await capturedOnMessage?.({
body: "hello",
from: "+1",
to: "+2",
id: "msg-pdf",
sendComposing,
reply,
sendMedia,
});
expect(sendMedia).toHaveBeenCalledTimes(1);
const payload = sendMedia.mock.calls[0][0] as {
document?: Buffer;
caption?: string;
fileName?: string;
};
expect(payload.document).toBeInstanceOf(Buffer);
expect(payload.fileName).toBe("file.pdf");
expect(payload.caption).toBe("hi");
expect(reply).not.toHaveBeenCalled();
fetchMock.mockRestore();
});
it("emits heartbeat logs with connection metadata", async () => {
vi.useFakeTimers();
const logPath = `/tmp/warelay-heartbeat-${crypto.randomUUID()}.log`;
setLoggerOverride({ level: "trace", file: logPath });
const runtime = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
const controller = new AbortController();
const listenerFactory = vi.fn(async () => {
const onClose = new Promise<void>(() => {
// never resolves; abort will short-circuit
});
return { close: vi.fn(), onClose };
});
const run = monitorWebProvider(
false,
listenerFactory,
true,
async () => ({ text: "ok" }),
runtime as never,
controller.signal,
{
heartbeatSeconds: 1,
reconnect: { initialMs: 5, maxMs: 5, maxAttempts: 1, factor: 1.1 },
},
);
await vi.advanceTimersByTimeAsync(1_000);
controller.abort();
await vi.runAllTimersAsync();
await run.catch(() => {});
const content = await fs.readFile(logPath, "utf-8");
expect(content).toContain('"module":"web-heartbeat"');
expect(content).toMatch(/connectionId/);
expect(content).toMatch(/messagesHandled/);
});
it("logs outbound replies to file", async () => {
const logPath = `/tmp/warelay-log-test-${crypto.randomUUID()}.log`;
setLoggerOverride({ level: "trace", file: logPath });
let capturedOnMessage:
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
| undefined;
const listenerFactory = async (opts: {
onMessage: (
msg: import("./inbound.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 = await fs.readFile(logPath, "utf-8");
expect(content).toContain('"module":"web-auto-reply"');
expect(content).toContain('"text":"auto"');
});
});
+861
View File
@@ -0,0 +1,861 @@
import { getReplyFromConfig } from "../auto-reply/reply.js";
import type { ReplyPayload } from "../auto-reply/types.js";
import { waitForever } from "../cli/wait.js";
import { loadConfig } from "../config/config.js";
import {
DEFAULT_IDLE_MINUTES,
deriveSessionKey,
loadSessionStore,
resolveStorePath,
saveSessionStore,
} from "../config/sessions.js";
import { danger, isVerbose, logVerbose, success } from "../globals.js";
import { logInfo } from "../logger.js";
import { getChildLogger } from "../logging.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import { normalizeE164 } from "../utils.js";
import { monitorWebInbox } from "./inbound.js";
import { loadWebMedia } from "./media.js";
import { sendMessageWeb } from "./outbound.js";
import {
computeBackoff,
newConnectionId,
type ReconnectPolicy,
resolveHeartbeatSeconds,
resolveReconnectPolicy,
sleepWithAbort,
} from "./reconnect.js";
import { getWebAuthAgeMs } from "./session.js";
const DEFAULT_WEB_MEDIA_BYTES = 5 * 1024 * 1024;
type WebInboundMsg = Parameters<
typeof monitorWebInbox
>[0]["onMessage"] extends (msg: infer M) => unknown
? M
: never;
export type WebMonitorTuning = {
reconnect?: Partial<ReconnectPolicy>;
heartbeatSeconds?: number;
replyHeartbeatMinutes?: number;
replyHeartbeatNow?: boolean;
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
};
const formatDuration = (ms: number) =>
ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
const DEFAULT_REPLY_HEARTBEAT_MINUTES = 30;
export const HEARTBEAT_TOKEN = "HEARTBEAT_OK";
export const HEARTBEAT_PROMPT = "HEARTBEAT ultrathink";
export function resolveReplyHeartbeatMinutes(
cfg: ReturnType<typeof loadConfig>,
overrideMinutes?: number,
) {
const raw = overrideMinutes ?? cfg.inbound?.reply?.heartbeatMinutes;
if (raw === 0) return null;
if (typeof raw === "number" && raw > 0) return raw;
return cfg.inbound?.reply?.mode === "command"
? DEFAULT_REPLY_HEARTBEAT_MINUTES
: null;
}
export function stripHeartbeatToken(raw?: string) {
if (!raw) return { shouldSkip: true, text: "" };
const trimmed = raw.trim();
if (!trimmed) return { shouldSkip: true, text: "" };
if (trimmed === HEARTBEAT_TOKEN) return { shouldSkip: true, text: "" };
const withoutToken = trimmed.replaceAll(HEARTBEAT_TOKEN, "").trim();
return {
shouldSkip: withoutToken.length === 0,
text: withoutToken || trimmed,
};
}
export async function runWebHeartbeatOnce(opts: {
cfg?: ReturnType<typeof loadConfig>;
to: string;
verbose?: boolean;
replyResolver?: typeof getReplyFromConfig;
runtime?: RuntimeEnv;
sender?: typeof sendMessageWeb;
sessionId?: string;
}) {
const { cfg: cfgOverride, to, verbose = false, sessionId } = opts;
const _runtime = opts.runtime ?? defaultRuntime;
const replyResolver = opts.replyResolver ?? getReplyFromConfig;
const sender = opts.sender ?? sendMessageWeb;
const runId = newConnectionId();
const heartbeatLogger = getChildLogger({
module: "web-heartbeat",
runId,
to,
});
const cfg = cfgOverride ?? loadConfig();
if (sessionId) {
const storePath = resolveStorePath(cfg.inbound?.reply?.session?.store);
const store = loadSessionStore(storePath);
store[to] = {
...(store[to] ?? {}),
sessionId,
updatedAt: Date.now(),
};
await saveSessionStore(storePath, store);
}
const sessionSnapshot = getSessionSnapshot(cfg, to, true);
if (verbose) {
heartbeatLogger.info(
{
to,
sessionKey: sessionSnapshot.key,
sessionId: sessionId ?? sessionSnapshot.entry?.sessionId ?? null,
sessionFresh: sessionSnapshot.fresh,
idleMinutes: sessionSnapshot.idleMinutes,
},
"heartbeat session snapshot",
);
}
try {
const replyResult = await replyResolver(
{
Body: HEARTBEAT_PROMPT,
From: to,
To: to,
MessageSid: sessionId ?? sessionSnapshot.entry?.sessionId,
},
undefined,
cfg,
);
if (
!replyResult ||
(!replyResult.text &&
!replyResult.mediaUrl &&
!replyResult.mediaUrls?.length)
) {
heartbeatLogger.info(
{
to,
reason: "empty-reply",
sessionId: sessionSnapshot.entry?.sessionId ?? null,
},
"heartbeat skipped",
);
if (verbose) console.log(success("heartbeat: ok (empty reply)"));
return;
}
const hasMedia = Boolean(
replyResult.mediaUrl || (replyResult.mediaUrls?.length ?? 0) > 0,
);
const stripped = stripHeartbeatToken(replyResult.text);
if (stripped.shouldSkip && !hasMedia) {
// Don't let heartbeats keep sessions alive: restore previous updatedAt so idle expiry still works.
const sessionCfg = cfg.inbound?.reply?.session;
const storePath = resolveStorePath(sessionCfg?.store);
const store = loadSessionStore(storePath);
if (sessionSnapshot.entry && store[sessionSnapshot.key]) {
store[sessionSnapshot.key].updatedAt = sessionSnapshot.entry.updatedAt;
await saveSessionStore(storePath, store);
}
heartbeatLogger.info(
{ to, reason: "heartbeat-token", rawLength: replyResult.text?.length },
"heartbeat skipped",
);
console.log(success("heartbeat: ok (HEARTBEAT_OK)"));
return;
}
if (hasMedia) {
heartbeatLogger.warn(
{ to },
"heartbeat reply contained media; sending text only",
);
}
const finalText = stripped.text || replyResult.text || "";
const sendResult = await sender(to, finalText, { verbose });
heartbeatLogger.info(
{ to, messageId: sendResult.messageId, chars: finalText.length },
"heartbeat sent",
);
console.log(success(`heartbeat: alert sent to ${to}`));
} catch (err) {
heartbeatLogger.warn({ to, error: String(err) }, "heartbeat failed");
console.log(danger(`heartbeat: failed - ${String(err)}`));
throw err;
}
}
function getFallbackRecipient(cfg: ReturnType<typeof loadConfig>) {
const sessionCfg = cfg.inbound?.reply?.session;
const storePath = resolveStorePath(sessionCfg?.store);
const store = loadSessionStore(storePath);
const candidates = Object.entries(store).filter(([key]) => key !== "global");
if (candidates.length === 0) {
const allowFrom =
Array.isArray(cfg.inbound?.allowFrom) && cfg.inbound.allowFrom.length > 0
? cfg.inbound.allowFrom.filter((v) => v !== "*")
: [];
if (allowFrom.length === 0) return null;
return allowFrom[0] ? normalizeE164(allowFrom[0]) : null;
}
const mostRecent = candidates.sort(
(a, b) => (b[1]?.updatedAt ?? 0) - (a[1]?.updatedAt ?? 0),
)[0];
return mostRecent ? normalizeE164(mostRecent[0]) : null;
}
function getSessionRecipients(cfg: ReturnType<typeof loadConfig>) {
const sessionCfg = cfg.inbound?.reply?.session;
const scope = sessionCfg?.scope ?? "per-sender";
if (scope === "global") return [];
const storePath = resolveStorePath(sessionCfg?.store);
const store = loadSessionStore(storePath);
return Object.entries(store)
.filter(([key]) => key !== "global" && key !== "unknown")
.map(([key, entry]) => ({
to: normalizeE164(key),
updatedAt: entry?.updatedAt ?? 0,
}))
.filter(({ to }) => Boolean(to))
.sort((a, b) => b.updatedAt - a.updatedAt);
}
export function resolveHeartbeatRecipients(
cfg: ReturnType<typeof loadConfig>,
opts: { to?: string; all?: boolean } = {},
) {
if (opts.to) return { recipients: [normalizeE164(opts.to)], source: "flag" };
const sessionRecipients = getSessionRecipients(cfg);
const allowFrom =
Array.isArray(cfg.inbound?.allowFrom) && cfg.inbound.allowFrom.length > 0
? cfg.inbound.allowFrom.filter((v) => v !== "*").map(normalizeE164)
: [];
const unique = (list: string[]) => [...new Set(list.filter(Boolean))];
if (opts.all) {
const all = unique([...sessionRecipients.map((s) => s.to), ...allowFrom]);
return { recipients: all, source: "all" as const };
}
if (sessionRecipients.length === 1) {
return { recipients: [sessionRecipients[0].to], source: "session-single" };
}
if (sessionRecipients.length > 1) {
return {
recipients: sessionRecipients.map((s) => s.to),
source: "session-ambiguous" as const,
};
}
return { recipients: allowFrom, source: "allowFrom" as const };
}
function getSessionSnapshot(
cfg: ReturnType<typeof loadConfig>,
from: string,
isHeartbeat = false,
) {
const sessionCfg = cfg.inbound?.reply?.session;
const scope = sessionCfg?.scope ?? "per-sender";
const key = deriveSessionKey(scope, { From: from, To: "", Body: "" });
const store = loadSessionStore(resolveStorePath(sessionCfg?.store));
const entry = store[key];
const idleMinutes = Math.max(
(isHeartbeat
? (sessionCfg?.heartbeatIdleMinutes ?? sessionCfg?.idleMinutes)
: sessionCfg?.idleMinutes) ?? DEFAULT_IDLE_MINUTES,
1,
);
const fresh = !!(
entry && Date.now() - entry.updatedAt <= idleMinutes * 60_000
);
return { key, entry, fresh, idleMinutes };
}
async function deliverWebReply(params: {
replyResult: ReplyPayload;
msg: WebInboundMsg;
maxMediaBytes: number;
replyLogger: ReturnType<typeof getChildLogger>;
runtime: RuntimeEnv;
connectionId?: string;
skipLog?: boolean;
}) {
const {
replyResult,
msg,
maxMediaBytes,
replyLogger,
runtime,
connectionId,
skipLog,
} = params;
const replyStarted = Date.now();
const mediaList = replyResult.mediaUrls?.length
? replyResult.mediaUrls
: replyResult.mediaUrl
? [replyResult.mediaUrl]
: [];
if (mediaList.length === 0 && replyResult.text) {
await msg.reply(replyResult.text || "");
if (!skipLog) {
logInfo(
`✅ Sent web reply to ${msg.from} (${(Date.now() - replyStarted).toFixed(0)}ms)`,
runtime,
);
}
replyLogger.info(
{
correlationId: msg.id ?? newConnectionId(),
connectionId: connectionId ?? null,
to: msg.from,
from: msg.to,
text: replyResult.text,
mediaUrl: null,
mediaSizeBytes: null,
mediaKind: null,
durationMs: Date.now() - replyStarted,
},
"auto-reply sent (text)",
);
return;
}
const cleanText = replyResult.text ?? undefined;
for (const [index, mediaUrl] of mediaList.entries()) {
try {
const media = await loadWebMedia(mediaUrl, maxMediaBytes);
if (isVerbose()) {
logVerbose(
`Web auto-reply media size: ${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB`,
);
logVerbose(
`Web auto-reply media source: ${mediaUrl} (kind ${media.kind})`,
);
}
const caption = index === 0 ? cleanText || undefined : undefined;
if (media.kind === "image") {
await msg.sendMedia({
image: media.buffer,
caption,
mimetype: media.contentType,
});
} else if (media.kind === "audio") {
await msg.sendMedia({
audio: media.buffer,
ptt: true,
mimetype: media.contentType,
caption,
});
} else if (media.kind === "video") {
await msg.sendMedia({
video: media.buffer,
caption,
mimetype: media.contentType,
});
} else {
const fileName = mediaUrl.split("/").pop() ?? "file";
const mimetype = media.contentType ?? "application/octet-stream";
await msg.sendMedia({
document: media.buffer,
fileName,
caption,
mimetype,
});
}
logInfo(
`✅ Sent web media reply to ${msg.from} (${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB)`,
runtime,
);
replyLogger.info(
{
correlationId: msg.id ?? newConnectionId(),
connectionId: connectionId ?? null,
to: msg.from,
from: msg.to,
text: index === 0 ? (cleanText ?? null) : null,
mediaUrl,
mediaSizeBytes: media.buffer.length,
mediaKind: media.kind,
durationMs: Date.now() - replyStarted,
},
"auto-reply sent (media)",
);
} catch (err) {
console.error(
danger(`Failed sending web media to ${msg.from}: ${String(err)}`),
);
if (index === 0 && cleanText) {
console.log(`⚠️ Media skipped; sent text-only to ${msg.from}`);
await msg.reply(cleanText || "");
}
}
}
}
export async function monitorWebProvider(
verbose: boolean,
listenerFactory: typeof monitorWebInbox | undefined = monitorWebInbox,
keepAlive = true,
replyResolver: typeof getReplyFromConfig | undefined = getReplyFromConfig,
runtime: RuntimeEnv = defaultRuntime,
abortSignal?: AbortSignal,
tuning: WebMonitorTuning = {},
) {
const runId = newConnectionId();
const replyLogger = getChildLogger({ module: "web-auto-reply", runId });
const heartbeatLogger = getChildLogger({ module: "web-heartbeat", runId });
const reconnectLogger = getChildLogger({ module: "web-reconnect", runId });
const cfg = loadConfig();
const configuredMaxMb = cfg.inbound?.reply?.mediaMaxMb;
const maxMediaBytes =
typeof configuredMaxMb === "number" && configuredMaxMb > 0
? configuredMaxMb * 1024 * 1024
: DEFAULT_WEB_MEDIA_BYTES;
const heartbeatSeconds = resolveHeartbeatSeconds(
cfg,
tuning.heartbeatSeconds,
);
const replyHeartbeatMinutes = resolveReplyHeartbeatMinutes(
cfg,
tuning.replyHeartbeatMinutes,
);
const reconnectPolicy = resolveReconnectPolicy(cfg, tuning.reconnect);
const sleep =
tuning.sleep ??
((ms: number, signal?: AbortSignal) =>
sleepWithAbort(ms, signal ?? abortSignal));
const stopRequested = () => abortSignal?.aborted === true;
const abortPromise =
abortSignal &&
new Promise<"aborted">((resolve) =>
abortSignal.addEventListener("abort", () => resolve("aborted"), {
once: true,
}),
);
let sigintStop = false;
const handleSigint = () => {
sigintStop = true;
};
process.once("SIGINT", handleSigint);
let reconnectAttempts = 0;
while (true) {
if (stopRequested()) break;
const connectionId = newConnectionId();
const startedAt = Date.now();
let heartbeat: NodeJS.Timeout | null = null;
let replyHeartbeatTimer: NodeJS.Timeout | null = null;
let lastMessageAt: number | null = null;
let handledMessages = 0;
let lastInboundMsg: WebInboundMsg | null = null;
const listener = await (listenerFactory ?? monitorWebInbox)({
verbose,
onMessage: async (msg) => {
handledMessages += 1;
lastMessageAt = Date.now();
const ts = msg.timestamp
? new Date(msg.timestamp).toISOString()
: new Date().toISOString();
const correlationId = msg.id ?? newConnectionId();
replyLogger.info(
{
connectionId,
correlationId,
from: msg.from,
to: msg.to,
body: msg.body,
mediaType: msg.mediaType ?? null,
mediaPath: msg.mediaPath ?? null,
},
"inbound web message",
);
console.log(`\n[${ts}] ${msg.from} -> ${msg.to}: ${msg.body}`);
lastInboundMsg = msg;
const replyResult = await (replyResolver ?? getReplyFromConfig)(
{
Body: msg.body,
From: msg.from,
To: msg.to,
MessageSid: msg.id,
MediaPath: msg.mediaPath,
MediaUrl: msg.mediaUrl,
MediaType: msg.mediaType,
},
{
onReplyStart: msg.sendComposing,
},
);
if (
!replyResult ||
(!replyResult.text &&
!replyResult.mediaUrl &&
!replyResult.mediaUrls?.length)
) {
logVerbose(
"Skipping auto-reply: no text/media returned from resolver",
);
return;
}
try {
await deliverWebReply({
replyResult,
msg,
maxMediaBytes,
replyLogger,
runtime,
connectionId,
});
if (isVerbose()) {
console.log(
success(
`↩️ Auto-replied to ${msg.from} (web${replyResult.mediaUrl || replyResult.mediaUrls?.length ? ", media" : ""})`,
),
);
} else {
console.log(
success(
`↩️ ${replyResult.text ?? "<media>"}${replyResult.mediaUrl || replyResult.mediaUrls?.length ? " (media)" : ""}`,
),
);
}
} catch (err) {
console.error(
danger(
`Failed sending web auto-reply to ${msg.from}: ${String(err)}`,
),
);
}
},
});
const closeListener = async () => {
if (heartbeat) clearInterval(heartbeat);
if (replyHeartbeatTimer) clearInterval(replyHeartbeatTimer);
try {
await listener.close();
} catch (err) {
logVerbose(`Socket close failed: ${String(err)}`);
}
};
if (keepAlive) {
heartbeat = setInterval(() => {
const authAgeMs = getWebAuthAgeMs();
heartbeatLogger.info(
{
connectionId,
reconnectAttempts,
messagesHandled: handledMessages,
lastMessageAt,
authAgeMs,
uptimeMs: Date.now() - startedAt,
},
"web relay heartbeat",
);
}, heartbeatSeconds * 1000);
}
const runReplyHeartbeat = async () => {
if (!replyHeartbeatMinutes) return;
const tickStart = Date.now();
if (!lastInboundMsg) {
const fallbackTo = getFallbackRecipient(cfg);
if (!fallbackTo) {
heartbeatLogger.info(
{
connectionId,
reason: "no-recent-inbound",
durationMs: Date.now() - tickStart,
},
"reply heartbeat skipped",
);
console.log(success("heartbeat: skipped (no recent inbound)"));
return;
}
const snapshot = getSessionSnapshot(cfg, fallbackTo, true);
if (!snapshot.entry) {
heartbeatLogger.info(
{ connectionId, to: fallbackTo, reason: "no-session-for-fallback" },
"reply heartbeat skipped",
);
console.log(success("heartbeat: skipped (no session to resume)"));
return;
}
if (isVerbose()) {
heartbeatLogger.info(
{
connectionId,
to: fallbackTo,
reason: "fallback-session",
sessionId: snapshot.entry?.sessionId ?? null,
sessionFresh: snapshot.fresh,
},
"reply heartbeat start",
);
}
await runWebHeartbeatOnce({
cfg,
to: fallbackTo,
verbose,
replyResolver,
runtime,
sessionId: snapshot.entry.sessionId,
});
heartbeatLogger.info(
{
connectionId,
to: fallbackTo,
...snapshot,
durationMs: Date.now() - tickStart,
},
"reply heartbeat sent (fallback session)",
);
return;
}
try {
const snapshot = getSessionSnapshot(cfg, lastInboundMsg.from);
if (isVerbose()) {
heartbeatLogger.info(
{
connectionId,
to: lastInboundMsg.from,
intervalMinutes: replyHeartbeatMinutes,
sessionKey: snapshot.key,
sessionId: snapshot.entry?.sessionId ?? null,
sessionFresh: snapshot.fresh,
},
"reply heartbeat start",
);
}
const replyResult = await (replyResolver ?? getReplyFromConfig)(
{
Body: HEARTBEAT_PROMPT,
From: lastInboundMsg.from,
To: lastInboundMsg.to,
MessageSid: snapshot.entry?.sessionId,
MediaPath: undefined,
MediaUrl: undefined,
MediaType: undefined,
},
{
onReplyStart: lastInboundMsg.sendComposing,
},
);
if (
!replyResult ||
(!replyResult.text &&
!replyResult.mediaUrl &&
!replyResult.mediaUrls?.length)
) {
heartbeatLogger.info(
{
connectionId,
durationMs: Date.now() - tickStart,
reason: "empty-reply",
},
"reply heartbeat skipped",
);
console.log(success("heartbeat: ok (empty reply)"));
return;
}
const stripped = stripHeartbeatToken(replyResult.text);
const hasMedia = Boolean(
replyResult.mediaUrl || (replyResult.mediaUrls?.length ?? 0) > 0,
);
if (stripped.shouldSkip && !hasMedia) {
heartbeatLogger.info(
{
connectionId,
durationMs: Date.now() - tickStart,
reason: "heartbeat-token",
rawLength: replyResult.text?.length ?? 0,
},
"reply heartbeat skipped",
);
console.log(success("heartbeat: ok (HEARTBEAT_OK)"));
return;
}
const cleanedReply: ReplyPayload = {
...replyResult,
text: stripped.text,
};
await deliverWebReply({
replyResult: cleanedReply,
msg: lastInboundMsg,
maxMediaBytes,
replyLogger,
runtime,
connectionId,
});
const durationMs = Date.now() - tickStart;
const summary = `heartbeat: alert sent (${formatDuration(durationMs)})`;
console.log(summary);
heartbeatLogger.info(
{
connectionId,
durationMs,
hasMedia,
chars: stripped.text?.length ?? 0,
},
"reply heartbeat sent",
);
} catch (err) {
const durationMs = Date.now() - tickStart;
heartbeatLogger.warn(
{
connectionId,
error: String(err),
durationMs,
},
"reply heartbeat failed",
);
console.log(
danger(`heartbeat: failed (${formatDuration(durationMs)})`),
);
}
};
if (replyHeartbeatMinutes && !replyHeartbeatTimer) {
const intervalMs = replyHeartbeatMinutes * 60_000;
replyHeartbeatTimer = setInterval(() => {
void runReplyHeartbeat();
}, intervalMs);
if (tuning.replyHeartbeatNow) {
void runReplyHeartbeat();
}
}
logInfo(
"📡 Listening for personal WhatsApp Web inbound messages. Leave this running; Ctrl+C to stop.",
runtime,
);
if (!keepAlive) {
await closeListener();
return;
}
const reason = await Promise.race([
listener.onClose?.catch((err) => {
reconnectLogger.error(
{ error: String(err) },
"listener.onClose rejected",
);
return { status: 500, isLoggedOut: false, error: err };
}) ?? waitForever(),
abortPromise ?? waitForever(),
]);
const uptimeMs = Date.now() - startedAt;
if (uptimeMs > heartbeatSeconds * 1000) {
reconnectAttempts = 0; // Healthy stretch; reset the backoff.
}
if (stopRequested() || sigintStop || reason === "aborted") {
await closeListener();
break;
}
const status =
(typeof reason === "object" && reason && "status" in reason
? (reason as { status?: number }).status
: undefined) ?? "unknown";
const loggedOut =
typeof reason === "object" &&
reason &&
"isLoggedOut" in reason &&
(reason as { isLoggedOut?: boolean }).isLoggedOut;
reconnectLogger.info(
{
connectionId,
status,
loggedOut,
reconnectAttempts,
},
"web reconnect: connection closed",
);
if (loggedOut) {
runtime.error(
danger(
"WhatsApp session logged out. Run `warelay login --provider web` to relink.",
),
);
await closeListener();
break;
}
reconnectAttempts += 1;
if (
reconnectPolicy.maxAttempts > 0 &&
reconnectAttempts >= reconnectPolicy.maxAttempts
) {
reconnectLogger.warn(
{
connectionId,
status,
reconnectAttempts,
maxAttempts: reconnectPolicy.maxAttempts,
},
"web reconnect: max attempts reached",
);
runtime.error(
danger(
`WhatsApp Web connection closed (status ${status}). Reached max retries (${reconnectPolicy.maxAttempts}); exiting so you can relink.`,
),
);
await closeListener();
break;
}
const delay = computeBackoff(reconnectPolicy, reconnectAttempts);
reconnectLogger.info(
{
connectionId,
status,
reconnectAttempts,
maxAttempts: reconnectPolicy.maxAttempts || "unlimited",
delayMs: delay,
},
"web reconnect: scheduling retry",
);
runtime.error(
danger(
`WhatsApp Web connection closed (status ${status}). Retry ${reconnectAttempts}/${reconnectPolicy.maxAttempts || "∞"} in ${formatDuration(delay)}…`,
),
);
await closeListener();
try {
await sleep(delay, abortSignal);
} catch {
break;
}
}
process.removeListener("SIGINT", handleSigint);
}
export { DEFAULT_WEB_MEDIA_BYTES };
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { extractMediaPlaceholder, extractText } from "./inbound.js";
describe("web inbound helpers", () => {
it("prefers the main conversation body", () => {
const body = extractText({
conversation: " hello ",
} as unknown as import("@whiskeysockets/baileys").proto.IMessage);
expect(body).toBe("hello");
});
it("falls back to captions when conversation text is missing", () => {
const body = extractText({
imageMessage: { caption: " caption " },
} as unknown as import("@whiskeysockets/baileys").proto.IMessage);
expect(body).toBe("caption");
});
it("returns placeholders for media-only payloads", () => {
expect(
extractMediaPlaceholder({
imageMessage: {},
} as unknown as import("@whiskeysockets/baileys").proto.IMessage),
).toBe("<media:image>");
expect(
extractMediaPlaceholder({
audioMessage: {},
} as unknown as import("@whiskeysockets/baileys").proto.IMessage),
).toBe("<media:audio>");
});
});
+267
View File
@@ -0,0 +1,267 @@
import type {
AnyMessageContent,
proto,
WAMessage,
} from "@whiskeysockets/baileys";
import {
DisconnectReason,
downloadMediaMessage,
} from "@whiskeysockets/baileys";
import { isVerbose, logVerbose } from "../globals.js";
import { getChildLogger } from "../logging.js";
import { saveMediaBuffer } from "../media/store.js";
import { jidToE164 } from "../utils.js";
import {
createWaSocket,
getStatusCode,
waitForWaConnection,
} from "./session.js";
export type WebListenerCloseReason = {
status?: number;
isLoggedOut: boolean;
error?: unknown;
};
export type WebInboundMessage = {
id?: string;
from: string;
to: string;
body: string;
pushName?: string;
timestamp?: number;
sendComposing: () => Promise<void>;
reply: (text: string) => Promise<void>;
sendMedia: (payload: AnyMessageContent) => Promise<void>;
mediaPath?: string;
mediaType?: string;
mediaUrl?: string;
};
export async function monitorWebInbox(options: {
verbose: boolean;
onMessage: (msg: WebInboundMessage) => Promise<void>;
}) {
const inboundLogger = getChildLogger({ module: "web-inbound" });
const sock = await createWaSocket(false, options.verbose);
await waitForWaConnection(sock);
let onCloseResolve: ((reason: WebListenerCloseReason) => void) | null = null;
const onClose = new Promise<WebListenerCloseReason>((resolve) => {
onCloseResolve = resolve;
});
try {
// Advertise that the relay is online right after connecting.
await sock.sendPresenceUpdate("available");
if (isVerbose()) logVerbose("Sent global 'available' presence on connect");
} catch (err) {
logVerbose(
`Failed to send 'available' presence on connect: ${String(err)}`,
);
}
const selfJid = sock.user?.id;
const selfE164 = selfJid ? jidToE164(selfJid) : null;
const seen = new Set<string>();
sock.ev.on("messages.upsert", async (upsert) => {
if (upsert.type !== "notify") return;
for (const msg of upsert.messages) {
const id = msg.key?.id ?? undefined;
// De-dupe on message id; Baileys can emit retries.
if (id && seen.has(id)) continue;
if (id) seen.add(id);
if (msg.key?.fromMe) continue;
const remoteJid = msg.key?.remoteJid;
if (!remoteJid) continue;
// Ignore status/broadcast traffic; we only care about direct chats.
if (remoteJid.endsWith("@status") || remoteJid.endsWith("@broadcast"))
continue;
if (id) {
const participant = msg.key?.participant;
try {
await sock.readMessages([
{ remoteJid, id, participant, fromMe: false },
]);
if (isVerbose()) {
const suffix = participant ? ` (participant ${participant})` : "";
logVerbose(
`Marked message ${id} as read for ${remoteJid}${suffix}`,
);
}
} catch (err) {
logVerbose(`Failed to mark message ${id} read: ${String(err)}`);
}
}
const from = jidToE164(remoteJid);
if (!from) continue;
let body = extractText(msg.message ?? undefined);
if (!body) {
body = extractMediaPlaceholder(msg.message ?? undefined);
if (!body) continue;
}
let mediaPath: string | undefined;
let mediaType: string | undefined;
try {
const inboundMedia = await downloadInboundMedia(msg, sock);
if (inboundMedia) {
const saved = await saveMediaBuffer(
inboundMedia.buffer,
inboundMedia.mimetype,
);
mediaPath = saved.path;
mediaType = inboundMedia.mimetype;
}
} catch (err) {
logVerbose(`Inbound media download failed: ${String(err)}`);
}
const chatJid = remoteJid;
const sendComposing = async () => {
try {
await sock.sendPresenceUpdate("composing", chatJid);
} catch (err) {
logVerbose(`Presence update failed: ${String(err)}`);
}
};
const reply = async (text: string) => {
await sock.sendMessage(chatJid, { text });
};
const sendMedia = async (payload: AnyMessageContent) => {
await sock.sendMessage(chatJid, payload);
};
const timestamp = msg.messageTimestamp
? Number(msg.messageTimestamp) * 1000
: undefined;
inboundLogger.info(
{
from,
to: selfE164 ?? "me",
body,
mediaPath,
mediaType,
timestamp,
},
"inbound message",
);
try {
await options.onMessage({
id,
from,
to: selfE164 ?? "me",
body,
pushName: msg.pushName ?? undefined,
timestamp,
sendComposing,
reply,
sendMedia,
mediaPath,
mediaType,
});
} catch (err) {
console.error("Failed handling inbound web message:", String(err));
}
}
});
sock.ev.on(
"connection.update",
(update: Partial<import("@whiskeysockets/baileys").ConnectionState>) => {
try {
if (update.connection === "close") {
const status = getStatusCode(update.lastDisconnect?.error);
onCloseResolve?.({
status,
isLoggedOut: status === DisconnectReason.loggedOut,
error: update.lastDisconnect?.error,
});
}
} catch (err) {
inboundLogger.error(
{ error: String(err) },
"connection.update handler error",
);
onCloseResolve?.({
status: undefined,
isLoggedOut: false,
error: err,
});
}
},
);
return {
close: async () => {
try {
sock.ws?.close();
} catch (err) {
logVerbose(`Socket close failed: ${String(err)}`);
}
},
onClose,
} as const;
}
export function extractText(
message: proto.IMessage | undefined,
): string | undefined {
if (!message) return undefined;
if (typeof message.conversation === "string" && message.conversation.trim()) {
return message.conversation.trim();
}
const extended = message.extendedTextMessage?.text;
if (extended?.trim()) return extended.trim();
const caption =
message.imageMessage?.caption ?? message.videoMessage?.caption;
if (caption?.trim()) return caption.trim();
return undefined;
}
export function extractMediaPlaceholder(
message: proto.IMessage | undefined,
): string | undefined {
if (!message) return undefined;
if (message.imageMessage) return "<media:image>";
if (message.videoMessage) return "<media:video>";
if (message.audioMessage) return "<media:audio>";
if (message.documentMessage) return "<media:document>";
if (message.stickerMessage) return "<media:sticker>";
return undefined;
}
async function downloadInboundMedia(
msg: proto.IWebMessageInfo,
sock: Awaited<ReturnType<typeof createWaSocket>>,
): Promise<{ buffer: Buffer; mimetype?: string } | undefined> {
const message = msg.message;
if (!message) return undefined;
const mimetype =
message.imageMessage?.mimetype ??
message.videoMessage?.mimetype ??
message.documentMessage?.mimetype ??
message.audioMessage?.mimetype ??
message.stickerMessage?.mimetype ??
undefined;
if (
!message.imageMessage &&
!message.videoMessage &&
!message.documentMessage &&
!message.audioMessage &&
!message.stickerMessage
) {
return undefined;
}
try {
const buffer = (await downloadMediaMessage(
msg as WAMessage,
"buffer",
{},
{
reuploadRequest: sock.updateMediaMessage,
logger: sock.logger,
},
)) as Buffer;
return { buffer, mimetype };
} catch (err) {
logVerbose(`downloadMediaMessage failed: ${String(err)}`);
return undefined;
}
}
+74
View File
@@ -0,0 +1,74 @@
import fs from "node:fs/promises";
import { DisconnectReason } from "@whiskeysockets/baileys";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.useFakeTimers();
const rmMock = vi.spyOn(fs, "rm");
vi.mock("./session.js", () => {
const sockA = { ws: { close: vi.fn() } };
const sockB = { ws: { close: vi.fn() } };
const createWaSocket = vi.fn(async () =>
createWaSocket.mock.calls.length === 0 ? sockA : sockB,
);
const waitForWaConnection = vi.fn();
const formatError = vi.fn((err: unknown) => `formatted:${String(err)}`);
return {
createWaSocket,
waitForWaConnection,
formatError,
WA_WEB_AUTH_DIR: "/tmp/wa-creds",
};
});
const { createWaSocket, waitForWaConnection, formatError } = await import(
"./session.js"
);
const { loginWeb } = await import("./login.js");
describe("loginWeb coverage", () => {
beforeEach(() => {
vi.clearAllMocks();
rmMock.mockClear();
});
it("restarts once when WhatsApp requests code 515", async () => {
waitForWaConnection
.mockRejectedValueOnce({ output: { statusCode: 515 } })
.mockResolvedValueOnce(undefined);
const runtime = { log: vi.fn(), error: vi.fn() } as never;
await loginWeb(false, waitForWaConnection as never, runtime);
expect(createWaSocket).toHaveBeenCalledTimes(2);
const firstSock = await createWaSocket.mock.results[0].value;
expect(firstSock.ws.close).toHaveBeenCalled();
vi.runAllTimers();
const secondSock = await createWaSocket.mock.results[1].value;
expect(secondSock.ws.close).toHaveBeenCalled();
});
it("clears creds and throws when logged out", async () => {
waitForWaConnection.mockRejectedValueOnce({
output: { statusCode: DisconnectReason.loggedOut },
});
await expect(loginWeb(false, waitForWaConnection as never)).rejects.toThrow(
/cache cleared/i,
);
expect(rmMock).toHaveBeenCalledWith("/tmp/wa-creds", {
recursive: true,
force: true,
});
});
it("formats and rethrows generic errors", async () => {
waitForWaConnection.mockRejectedValueOnce(new Error("boom"));
await expect(loginWeb(false, waitForWaConnection as never)).rejects.toThrow(
"formatted:Error: boom",
);
expect(formatError).toHaveBeenCalled();
});
});
+45
View File
@@ -0,0 +1,45 @@
import { EventEmitter } from "node:events";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resetLogger, setLoggerOverride } from "../logging.js";
vi.mock("./session.js", () => {
const ev = new EventEmitter();
const sock = {
ev,
ws: { close: vi.fn() },
sendPresenceUpdate: vi.fn(),
sendMessage: vi.fn(),
};
return {
createWaSocket: vi.fn().mockResolvedValue(sock),
waitForWaConnection: vi.fn().mockResolvedValue(undefined),
};
});
import { loginWeb } from "./login.js";
import type { waitForWaConnection } from "./session.js";
const { createWaSocket } = await import("./session.js");
describe("web login", () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
resetLogger();
setLoggerOverride(null);
});
it("loginWeb waits for connection and closes", async () => {
const sock = await createWaSocket();
const waiter: typeof waitForWaConnection = vi
.fn()
.mockResolvedValue(undefined);
await loginWeb(false, waiter);
await new Promise((resolve) => setTimeout(resolve, 550));
expect(sock.ws.close).toHaveBeenCalled();
});
});
+80
View File
@@ -0,0 +1,80 @@
import fs from "node:fs/promises";
import { DisconnectReason } from "@whiskeysockets/baileys";
import { danger, info, success } from "../globals.js";
import { logInfo } from "../logger.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import {
createWaSocket,
formatError,
WA_WEB_AUTH_DIR,
waitForWaConnection,
} from "./session.js";
export async function loginWeb(
verbose: boolean,
waitForConnection: typeof waitForWaConnection = waitForWaConnection,
runtime: RuntimeEnv = defaultRuntime,
) {
const sock = await createWaSocket(true, verbose);
logInfo("Waiting for WhatsApp connection...", runtime);
try {
await waitForConnection(sock);
console.log(success("✅ Linked! Credentials saved for future sends."));
} catch (err) {
const code =
(err as { error?: { output?: { statusCode?: number } } })?.error?.output
?.statusCode ??
(err as { output?: { statusCode?: number } })?.output?.statusCode;
if (code === 515) {
console.log(
info(
"WhatsApp asked for a restart after pairing (code 515); creds are saved. Restarting connection once…",
),
);
try {
sock.ws?.close();
} catch {
// ignore
}
const retry = await createWaSocket(false, verbose);
try {
await waitForConnection(retry);
console.log(
success(
"✅ Linked after restart; web session ready. You can now send with provider=web.",
),
);
return;
} finally {
setTimeout(() => retry.ws?.close(), 500);
}
}
if (code === DisconnectReason.loggedOut) {
await fs.rm(WA_WEB_AUTH_DIR, { recursive: true, force: true });
console.error(
danger(
"WhatsApp reported the session is logged out. Cleared cached web session; please rerun warelay login and scan the QR again.",
),
);
throw new Error("Session logged out; cache cleared. Re-run login.");
}
const formatted = formatError(err);
console.error(
danger(
`WhatsApp Web connection ended before fully opening. ${formatted}`,
),
);
throw new Error(formatted);
} finally {
// Let Baileys flush any final events before closing the socket.
setTimeout(() => {
try {
sock.ws?.close();
} catch {
// ignore
}
}, 500);
}
}
+53
View File
@@ -0,0 +1,53 @@
import fs from "node:fs";
import fsPromises from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const runtime = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
describe("web logout", () => {
const origHomedir = os.homedir;
let tmpDir: string;
beforeEach(() => {
vi.clearAllMocks();
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "warelay-logout-"));
vi.spyOn(os, "homedir").mockReturnValue(tmpDir);
});
afterEach(async () => {
vi.restoreAllMocks();
await fsPromises
.rm(tmpDir, { recursive: true, force: true })
.catch(() => {});
// restore for safety
// eslint-disable-next-line @typescript-eslint/unbound-method
(os.homedir as unknown as typeof origHomedir) = origHomedir;
});
it("deletes cached credentials when present", async () => {
const credsDir = path.join(tmpDir, ".warelay", "credentials");
fs.mkdirSync(credsDir, { recursive: true });
fs.writeFileSync(path.join(credsDir, "creds.json"), "{}");
const { logoutWeb, WA_WEB_AUTH_DIR } = await import("./session.js");
expect(WA_WEB_AUTH_DIR.startsWith(tmpDir)).toBe(true);
const result = await logoutWeb(runtime as never);
expect(result).toBe(true);
expect(fs.existsSync(credsDir)).toBe(false);
});
it("no-ops when nothing to delete", async () => {
const { logoutWeb } = await import("./session.js");
const result = await logoutWeb(runtime as never);
expect(result).toBe(false);
expect(runtime.log).toHaveBeenCalled();
});
});
+41
View File
@@ -0,0 +1,41 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterEach, describe, expect, it } from "vitest";
import { loadWebMedia } from "./media.js";
const tmpFiles: string[] = [];
afterEach(async () => {
await Promise.all(tmpFiles.map((file) => fs.rm(file, { force: true })));
tmpFiles.length = 0;
});
describe("web media loading", () => {
it("compresses large local images under the provided cap", async () => {
const buffer = await sharp({
create: {
width: 1600,
height: 1600,
channels: 3,
background: "#ff0000",
},
})
.jpeg({ quality: 95 })
.toBuffer();
const file = path.join(os.tmpdir(), `warelay-media-${Date.now()}.jpg`);
tmpFiles.push(file);
await fs.writeFile(file, buffer);
const cap = Math.floor(buffer.length * 0.8);
const result = await loadWebMedia(file, cap);
expect(result.kind).toBe("image");
expect(result.buffer.length).toBeLessThanOrEqual(cap);
expect(result.buffer.length).toBeLessThan(buffer.length);
});
});
+160
View File
@@ -0,0 +1,160 @@
import fs from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import { isVerbose, logVerbose } from "../globals.js";
import {
type MediaKind,
maxBytesForKind,
mediaKindFromMime,
} from "../media/constants.js";
export async function loadWebMedia(
mediaUrl: string,
maxBytes?: number,
): Promise<{ buffer: Buffer; contentType?: string; kind: MediaKind }> {
if (mediaUrl.startsWith("file://")) {
mediaUrl = mediaUrl.replace("file://", "");
}
const optimizeAndClampImage = async (buffer: Buffer, cap: number) => {
const originalSize = buffer.length;
const optimized = await optimizeImageToJpeg(buffer, cap);
if (optimized.optimizedSize < originalSize && isVerbose()) {
logVerbose(
`Optimized media from ${(originalSize / (1024 * 1024)).toFixed(2)}MB to ${(optimized.optimizedSize / (1024 * 1024)).toFixed(2)}MB (side≤${optimized.resizeSide}px, q=${optimized.quality})`,
);
}
if (optimized.buffer.length > cap) {
throw new Error(
`Media could not be reduced below ${(cap / (1024 * 1024)).toFixed(0)}MB (got ${(
optimized.buffer.length / (1024 * 1024)
).toFixed(2)}MB)`,
);
}
return {
buffer: optimized.buffer,
contentType: "image/jpeg",
kind: "image" as const,
};
};
if (/^https?:\/\//i.test(mediaUrl)) {
const res = await fetch(mediaUrl);
if (!res.ok || !res.body) {
throw new Error(`Failed to fetch media: HTTP ${res.status}`);
}
const array = Buffer.from(await res.arrayBuffer());
const contentType = res.headers.get("content-type");
const kind = mediaKindFromMime(contentType);
const cap = Math.min(
maxBytes ?? maxBytesForKind(kind),
maxBytesForKind(kind),
);
if (kind === "image") {
return optimizeAndClampImage(array, cap);
}
if (array.length > cap) {
throw new Error(
`Media exceeds ${(cap / (1024 * 1024)).toFixed(0)}MB limit (got ${(
array.length / (1024 * 1024)
).toFixed(2)}MB)`,
);
}
return { buffer: array, contentType: contentType ?? undefined, kind };
}
// Local path
const data = await fs.readFile(mediaUrl);
const ext = path.extname(mediaUrl);
const mime =
(ext &&
(
{
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
".ogg": "audio/ogg",
".opus": "audio/ogg",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".pdf": "application/pdf",
} as Record<string, string | undefined>
)[ext.toLowerCase()]) ??
undefined;
const kind = mediaKindFromMime(mime);
const cap = Math.min(
maxBytes ?? maxBytesForKind(kind),
maxBytesForKind(kind),
);
if (kind === "image") {
return optimizeAndClampImage(data, cap);
}
if (data.length > cap) {
throw new Error(
`Media exceeds ${(cap / (1024 * 1024)).toFixed(0)}MB limit (got ${(
data.length / (1024 * 1024)
).toFixed(2)}MB)`,
);
}
return { buffer: data, contentType: mime, kind };
}
export async function optimizeImageToJpeg(
buffer: Buffer,
maxBytes: number,
): Promise<{
buffer: Buffer;
optimizedSize: number;
resizeSide: number;
quality: number;
}> {
// Try a grid of sizes/qualities until under the limit.
const sides = [2048, 1536, 1280, 1024, 800];
const qualities = [80, 70, 60, 50, 40];
let smallest: {
buffer: Buffer;
size: number;
resizeSide: number;
quality: number;
} | null = null;
for (const side of sides) {
for (const quality of qualities) {
const out = await sharp(buffer)
.resize({
width: side,
height: side,
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality, mozjpeg: true })
.toBuffer();
const size = out.length;
if (!smallest || size < smallest.size) {
smallest = { buffer: out, size, resizeSide: side, quality };
}
if (size <= maxBytes) {
return {
buffer: out,
optimizedSize: size,
resizeSide: side,
quality,
};
}
}
}
if (smallest) {
return {
buffer: smallest.buffer,
optimizedSize: smallest.size,
resizeSide: smallest.resizeSide,
quality: smallest.quality,
};
}
throw new Error("Failed to optimize image");
}
+219
View File
@@ -0,0 +1,219 @@
import { vi } from "vitest";
vi.mock("../media/store.js", () => ({
saveMediaBuffer: vi.fn().mockResolvedValue({
id: "mid",
path: "/tmp/mid",
size: 1,
contentType: "image/jpeg",
}),
}));
vi.mock("./session.js", () => {
const { EventEmitter } = require("node:events");
const ev = new EventEmitter();
const sock = {
ev,
ws: { close: vi.fn() },
sendPresenceUpdate: vi.fn().mockResolvedValue(undefined),
sendMessage: vi.fn().mockResolvedValue(undefined),
readMessages: vi.fn().mockResolvedValue(undefined),
updateMediaMessage: vi.fn(),
logger: {},
user: { id: "123@s.whatsapp.net" },
};
return {
createWaSocket: vi.fn().mockResolvedValue(sock),
waitForWaConnection: vi.fn().mockResolvedValue(undefined),
getStatusCode: vi.fn(() => 500),
};
});
const { createWaSocket } = await import("./session.js");
const _getSock = () =>
(createWaSocket as unknown as () => Promise<ReturnType<typeof mockSock>>)();
import crypto from "node:crypto";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { resetLogger, setLoggerOverride } from "../logging.js";
import { monitorWebInbox } from "./inbound.js";
describe("web monitor inbox", () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
resetLogger();
setLoggerOverride(null);
vi.useRealTimers();
});
it("streams inbound messages", async () => {
const onMessage = vi.fn(async (msg) => {
await msg.sendComposing();
await msg.reply("pong");
});
const listener = await monitorWebInbox({ verbose: false, onMessage });
const sock = await createWaSocket();
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
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));
expect(onMessage).toHaveBeenCalledWith(
expect.objectContaining({ body: "ping", from: "+999", to: "+123" }),
);
expect(sock.readMessages).toHaveBeenCalledWith([
{
remoteJid: "999@s.whatsapp.net",
id: "abc",
participant: undefined,
fromMe: false,
},
]);
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith(
"composing",
"999@s.whatsapp.net",
);
expect(sock.sendMessage).toHaveBeenCalledWith("999@s.whatsapp.net", {
text: "pong",
});
await listener.close();
});
it("captures media path for image messages", async () => {
const onMessage = vi.fn();
const listener = await monitorWebInbox({ verbose: false, onMessage });
const sock = await createWaSocket();
const upsert = {
type: "notify",
messages: [
{
key: { id: "med1", fromMe: false, remoteJid: "888@s.whatsapp.net" },
message: { imageMessage: { mimetype: "image/jpeg" } },
messageTimestamp: 1_700_000_100,
},
],
};
sock.ev.emit("messages.upsert", upsert);
await new Promise((resolve) => setImmediate(resolve));
expect(onMessage).toHaveBeenCalledWith(
expect.objectContaining({
body: "<media:image>",
}),
);
expect(sock.readMessages).toHaveBeenCalledWith([
{
remoteJid: "888@s.whatsapp.net",
id: "med1",
participant: undefined,
fromMe: false,
},
]);
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
await listener.close();
});
it("resolves onClose when the socket closes", async () => {
const listener = await monitorWebInbox({
verbose: false,
onMessage: vi.fn(),
});
const sock = await createWaSocket();
const reasonPromise = listener.onClose;
sock.ev.emit("connection.update", {
connection: "close",
lastDisconnect: { error: { output: { statusCode: 500 } } },
});
await expect(reasonPromise).resolves.toEqual(
expect.objectContaining({ status: 500, isLoggedOut: false }),
);
await listener.close();
});
it("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 = await createWaSocket();
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("includes participant when marking group messages read", async () => {
const onMessage = vi.fn();
const listener = await monitorWebInbox({ verbose: false, onMessage });
const sock = await createWaSocket();
const upsert = {
type: "notify",
messages: [
{
key: {
id: "grp1",
fromMe: false,
remoteJid: "12345-67890@g.us",
participant: "111@s.whatsapp.net",
},
message: { conversation: "group ping" },
},
],
};
sock.ev.emit("messages.upsert", upsert);
await new Promise((resolve) => setImmediate(resolve));
expect(sock.readMessages).toHaveBeenCalledWith([
{
remoteJid: "12345-67890@g.us",
id: "grp1",
participant: "111@s.whatsapp.net",
fromMe: false,
},
]);
await listener.close();
});
});
+40
View File
@@ -0,0 +1,40 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resetLogger, setLoggerOverride } from "../logging.js";
vi.mock("./session.js", () => {
const { EventEmitter } = require("node:events");
const ev = new EventEmitter();
const sock = {
ev,
ws: { close: vi.fn() },
sendPresenceUpdate: vi.fn().mockResolvedValue(undefined),
sendMessage: vi.fn().mockResolvedValue({ key: { id: "msg123" } }),
};
return {
createWaSocket: vi.fn().mockResolvedValue(sock),
waitForWaConnection: vi.fn().mockResolvedValue(undefined),
};
});
import { sendMessageWeb } from "./outbound.js";
const { createWaSocket } = await import("./session.js");
describe("web outbound", () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
resetLogger();
setLoggerOverride(null);
});
it("sends message via web and closes socket", async () => {
await sendMessageWeb("+1555", "hi", { verbose: false });
const sock = await createWaSocket();
expect(sock.sendMessage).toHaveBeenCalled();
expect(sock.ws.close).toHaveBeenCalled();
});
});
+65
View File
@@ -0,0 +1,65 @@
import { randomUUID } from "node:crypto";
import type { AnyMessageContent } from "@whiskeysockets/baileys";
import { logVerbose } from "../globals.js";
import { logInfo } from "../logger.js";
import { getChildLogger } from "../logging.js";
import { toWhatsappJid } from "../utils.js";
import { loadWebMedia } from "./media.js";
import { createWaSocket, waitForWaConnection } from "./session.js";
export async function sendMessageWeb(
to: string,
body: string,
options: { verbose: boolean; mediaUrl?: string },
): Promise<{ messageId: string; toJid: string }> {
const correlationId = randomUUID();
const sock = await createWaSocket(false, options.verbose);
const logger = getChildLogger({
module: "web-outbound",
correlationId,
to,
});
try {
logInfo("🔌 Connecting to WhatsApp Web…");
logger.info("connecting to whatsapp web");
await waitForWaConnection(sock);
// waitForWaConnection sets up listeners and error handling; keep the presence update safe.
const jid = toWhatsappJid(to);
try {
await sock.sendPresenceUpdate("composing", jid);
} catch (err) {
logVerbose(`Presence update skipped: ${String(err)}`);
}
let payload: AnyMessageContent = { text: body };
if (options.mediaUrl) {
const media = await loadWebMedia(options.mediaUrl);
payload = {
image: media.buffer,
caption: body || undefined,
mimetype: media.contentType,
};
}
logInfo(
`📤 Sending via web session -> ${jid}${options.mediaUrl ? " (media)" : ""}`,
);
logger.info(
{ jid, hasMedia: Boolean(options.mediaUrl) },
"sending message",
);
const result = await sock.sendMessage(jid, payload);
const messageId = result?.key?.id ?? "unknown";
logInfo(
`✅ Sent via web session. Message ID: ${messageId} -> ${jid}${options.mediaUrl ? " (media)" : ""}`,
);
logger.info({ jid, messageId }, "sent message");
return { messageId, toJid: jid };
} finally {
try {
sock.ws?.close();
} catch (err) {
logVerbose(`Socket close failed: ${String(err)}`);
}
}
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import type { WarelayConfig } from "../config/config.js";
import {
computeBackoff,
DEFAULT_HEARTBEAT_SECONDS,
DEFAULT_RECONNECT_POLICY,
resolveHeartbeatSeconds,
resolveReconnectPolicy,
sleepWithAbort,
} from "./reconnect.js";
describe("web reconnect helpers", () => {
const cfg: WarelayConfig = {};
it("resolves sane reconnect defaults with clamps", () => {
const policy = resolveReconnectPolicy(cfg, {
initialMs: 100,
maxMs: 5,
factor: 20,
jitter: 2,
maxAttempts: -1,
});
expect(policy.initialMs).toBe(250); // clamped to minimum
expect(policy.maxMs).toBeGreaterThanOrEqual(policy.initialMs);
expect(policy.factor).toBeLessThanOrEqual(10);
expect(policy.jitter).toBeLessThanOrEqual(1);
expect(policy.maxAttempts).toBeGreaterThanOrEqual(0);
});
it("computes increasing backoff with jitter", () => {
const policy = { ...DEFAULT_RECONNECT_POLICY, jitter: 0 };
const first = computeBackoff(policy, 1);
const second = computeBackoff(policy, 2);
expect(first).toBe(policy.initialMs);
expect(second).toBeGreaterThan(first);
expect(second).toBeLessThanOrEqual(policy.maxMs);
});
it("returns heartbeat default when unset", () => {
expect(resolveHeartbeatSeconds(cfg)).toBe(DEFAULT_HEARTBEAT_SECONDS);
expect(resolveHeartbeatSeconds(cfg, 5)).toBe(5);
});
it("sleepWithAbort rejects on abort", async () => {
const controller = new AbortController();
const promise = sleepWithAbort(50, controller.signal);
controller.abort();
await expect(promise).rejects.toThrow("aborted");
});
});
+84
View File
@@ -0,0 +1,84 @@
import { randomUUID } from "node:crypto";
import type { WarelayConfig } from "../config/config.js";
export type ReconnectPolicy = {
initialMs: number;
maxMs: number;
factor: number;
jitter: number;
maxAttempts: number;
};
export const DEFAULT_HEARTBEAT_SECONDS = 60;
export const DEFAULT_RECONNECT_POLICY: ReconnectPolicy = {
initialMs: 2_000,
maxMs: 30_000,
factor: 1.8,
jitter: 0.25,
maxAttempts: 12,
};
const clamp = (val: number, min: number, max: number) =>
Math.max(min, Math.min(max, val));
export function resolveHeartbeatSeconds(
cfg: WarelayConfig,
overrideSeconds?: number,
): number {
const candidate = overrideSeconds ?? cfg.web?.heartbeatSeconds;
if (typeof candidate === "number" && candidate > 0) return candidate;
return DEFAULT_HEARTBEAT_SECONDS;
}
export function resolveReconnectPolicy(
cfg: WarelayConfig,
overrides?: Partial<ReconnectPolicy>,
): ReconnectPolicy {
const merged = {
...DEFAULT_RECONNECT_POLICY,
...(cfg.web?.reconnect ?? {}),
...(overrides ?? {}),
} as ReconnectPolicy;
merged.initialMs = Math.max(250, merged.initialMs);
merged.maxMs = Math.max(merged.initialMs, merged.maxMs);
merged.factor = clamp(merged.factor, 1.1, 10);
merged.jitter = clamp(merged.jitter, 0, 1);
merged.maxAttempts = Math.max(0, Math.floor(merged.maxAttempts));
return merged;
}
export function computeBackoff(policy: ReconnectPolicy, attempt: number) {
const base = policy.initialMs * policy.factor ** Math.max(attempt - 1, 0);
const jitter = base * policy.jitter * Math.random();
return Math.min(policy.maxMs, Math.round(base + jitter));
}
export function sleepWithAbort(ms: number, abortSignal?: AbortSignal) {
if (ms <= 0) return Promise.resolve();
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
cleanup();
resolve();
}, ms);
const onAbort = () => {
cleanup();
reject(new Error("aborted"));
};
const cleanup = () => {
clearTimeout(timer);
abortSignal?.removeEventListener("abort", onAbort);
};
if (abortSignal) {
abortSignal.addEventListener("abort", onAbort, { once: true });
}
});
}
export function newConnectionId() {
return randomUUID();
}
+92
View File
@@ -0,0 +1,92 @@
import { EventEmitter } from "node:events";
import fsSync from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resetLogger, setLoggerOverride } from "../logging.js";
import {
baileys,
getLastSocket,
resetBaileysMocks,
resetLoadConfigMock,
} from "./test-helpers.js";
const { createWaSocket, logWebSelfId, waitForWaConnection } = await import(
"./session.js"
);
describe("web session", () => {
beforeEach(() => {
vi.clearAllMocks();
resetBaileysMocks();
resetLoadConfigMock();
});
afterEach(() => {
resetLogger();
setLoggerOverride(null);
vi.useRealTimers();
});
it("creates WA socket with QR handler", async () => {
await createWaSocket(true, false);
const makeWASocket = baileys.makeWASocket as ReturnType<typeof vi.fn>;
expect(makeWASocket).toHaveBeenCalledWith(
expect.objectContaining({ printQRInTerminal: false }),
);
const passed = makeWASocket.mock.calls[0][0];
const passedLogger = (
passed as { logger?: { level?: string; trace?: unknown } }
).logger;
expect(passedLogger?.level).toBe("silent");
expect(typeof passedLogger?.trace).toBe("function");
const sock = getLastSocket();
const saveCreds = (
await baileys.useMultiFileAuthState.mock.results[0].value
).saveCreds;
// trigger creds.update listener
sock.ev.emit("creds.update", {});
expect(saveCreds).toHaveBeenCalled();
});
it("waits for connection open", async () => {
const ev = new EventEmitter();
const promise = waitForWaConnection({ ev } as unknown as ReturnType<
typeof baileys.makeWASocket
>);
ev.emit("connection.update", { connection: "open" });
await expect(promise).resolves.toBeUndefined();
});
it("rejects when connection closes", async () => {
const ev = new EventEmitter();
const promise = waitForWaConnection({ ev } as unknown as ReturnType<
typeof baileys.makeWASocket
>);
ev.emit("connection.update", {
connection: "close",
lastDisconnect: new Error("bye"),
});
await expect(promise).rejects.toBeInstanceOf(Error);
});
it("logWebSelfId prints cached E.164 when creds exist", () => {
const existsSpy = vi
.spyOn(fsSync, "existsSync")
.mockReturnValue(true as never);
const readSpy = vi
.spyOn(fsSync, "readFileSync")
.mockReturnValue(JSON.stringify({ me: { id: "12345@s.whatsapp.net" } }));
const runtime = {
log: vi.fn(),
error: vi.fn(),
exit: vi.fn(),
};
logWebSelfId(runtime as never, true);
expect(runtime.log).toHaveBeenCalledWith(
"Web Provider: +12345 (jid 12345@s.whatsapp.net)",
);
existsSpy.mockRestore();
readSpy.mockRestore();
});
});
+226
View File
@@ -0,0 +1,226 @@
import { randomUUID } from "node:crypto";
import fsSync from "node:fs";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
DisconnectReason,
fetchLatestBaileysVersion,
makeCacheableSignalKeyStore,
makeWASocket,
useMultiFileAuthState,
} from "@whiskeysockets/baileys";
import qrcode from "qrcode-terminal";
import { danger, info, success } from "../globals.js";
import { getChildLogger } from "../logging.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import type { Provider } from "../utils.js";
import { ensureDir, jidToE164 } from "../utils.js";
import { VERSION } from "../version.js";
export const WA_WEB_AUTH_DIR = path.join(
os.homedir(),
".warelay",
"credentials",
);
/**
* Create a Baileys socket backed by the multi-file auth store we keep on disk.
* Consumers can opt into QR printing for interactive login flows.
*/
export async function createWaSocket(printQr: boolean, verbose: boolean) {
const logger = getChildLogger(
{ module: "baileys" },
{
level: verbose ? "info" : "silent",
},
);
// Some Baileys internals call logger.trace even when silent; ensure it's present.
const loggerAny = logger as unknown as Record<string, unknown>;
if (typeof loggerAny.trace !== "function") {
loggerAny.trace = () => {};
}
await ensureDir(WA_WEB_AUTH_DIR);
const { state, saveCreds } = await useMultiFileAuthState(WA_WEB_AUTH_DIR);
const { version } = await fetchLatestBaileysVersion();
const sock = makeWASocket({
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, logger),
},
version,
logger,
printQRInTerminal: false,
browser: ["warelay", "cli", VERSION],
syncFullHistory: false,
markOnlineOnConnect: false,
});
const sessionLogger = getChildLogger({ module: "web-session" });
sock.ev.on("creds.update", saveCreds);
sock.ev.on(
"connection.update",
(update: Partial<import("@whiskeysockets/baileys").ConnectionState>) => {
try {
const { connection, lastDisconnect, qr } = update;
if (qr && printQr) {
console.log("Scan this QR in WhatsApp (Linked Devices):");
qrcode.generate(qr, { small: true });
}
if (connection === "close") {
const status = getStatusCode(lastDisconnect?.error);
if (status === DisconnectReason.loggedOut) {
console.error(
danger("WhatsApp session logged out. Run: warelay login"),
);
}
}
if (connection === "open" && verbose) {
console.log(success("WhatsApp Web connected."));
}
} catch (err) {
sessionLogger.error(
{ error: String(err) },
"connection.update handler error",
);
}
},
);
// Handle WebSocket-level errors to prevent unhandled exceptions from crashing the process
if (
sock.ws &&
typeof (sock.ws as unknown as { on?: unknown }).on === "function"
) {
sock.ws.on("error", (err: Error) => {
sessionLogger.error({ error: String(err) }, "WebSocket error");
});
}
return sock;
}
export async function waitForWaConnection(
sock: ReturnType<typeof makeWASocket>,
) {
return new Promise<void>((resolve, reject) => {
type OffCapable = {
off?: (event: string, listener: (...args: unknown[]) => void) => void;
};
const evWithOff = sock.ev as unknown as OffCapable;
const handler = (...args: unknown[]) => {
const update = (args[0] ?? {}) as Partial<
import("@whiskeysockets/baileys").ConnectionState
>;
if (update.connection === "open") {
evWithOff.off?.("connection.update", handler);
resolve();
}
if (update.connection === "close") {
evWithOff.off?.("connection.update", handler);
reject(update.lastDisconnect ?? new Error("Connection closed"));
}
};
sock.ev.on("connection.update", handler);
});
}
export function getStatusCode(err: unknown) {
return (
(err as { output?: { statusCode?: number } })?.output?.statusCode ??
(err as { status?: number })?.status
);
}
export function formatError(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === "string") return err;
const status = getStatusCode(err);
const code = (err as { code?: unknown })?.code;
if (status || code)
return `status=${status ?? "unknown"} code=${code ?? "unknown"}`;
return String(err);
}
export async function webAuthExists() {
return fs
.access(WA_WEB_AUTH_DIR)
.then(() => true)
.catch(() => false);
}
export async function logoutWeb(runtime: RuntimeEnv = defaultRuntime) {
const exists = await webAuthExists();
if (!exists) {
runtime.log(info("No WhatsApp Web session found; nothing to delete."));
return false;
}
await fs.rm(WA_WEB_AUTH_DIR, { recursive: true, force: true });
runtime.log(
success(
"Cleared WhatsApp Web credentials. Run `warelay login --provider web` to relink.",
),
);
return true;
}
function readWebSelfId() {
// Read the cached WhatsApp Web identity (jid + E.164) from disk if present.
const credsPath = path.join(WA_WEB_AUTH_DIR, "creds.json");
try {
if (!fsSync.existsSync(credsPath)) {
return { e164: null, jid: null } as const;
}
const raw = fsSync.readFileSync(credsPath, "utf-8");
const parsed = JSON.parse(raw) as { me?: { id?: string } } | undefined;
const jid = parsed?.me?.id ?? null;
const e164 = jid ? jidToE164(jid) : null;
return { e164, jid } as const;
} catch {
return { e164: null, jid: null } as const;
}
}
/**
* Return the age (in milliseconds) of the cached WhatsApp web auth state, or null when missing.
* Helpful for heartbeats/observability to spot stale credentials.
*/
export function getWebAuthAgeMs(): number | null {
const credsPath = path.join(WA_WEB_AUTH_DIR, "creds.json");
try {
const stats = fsSync.statSync(credsPath);
return Date.now() - stats.mtimeMs;
} catch {
return null;
}
}
export function newConnectionId() {
return randomUUID();
}
export function logWebSelfId(
runtime: RuntimeEnv = defaultRuntime,
includeProviderPrefix = false,
) {
// Human-friendly log of the currently linked personal web session.
const { e164, jid } = readWebSelfId();
const details =
e164 || jid
? `${e164 ?? "unknown"}${jid ? ` (jid ${jid})` : ""}`
: "unknown";
const prefix = includeProviderPrefix ? "Web Provider: " : "";
runtime.log(info(`${prefix}${details}`));
}
export async function pickProvider(pref: Provider | "auto"): Promise<Provider> {
// Auto-select web when logged in; otherwise fall back to twilio.
if (pref !== "auto") return pref;
const hasWeb = await webAuthExists();
if (hasWeb) return "web";
return "twilio";
}
+78
View File
@@ -0,0 +1,78 @@
import { vi } from "vitest";
import type { MockBaileysSocket } from "../../test/mocks/baileys.js";
import { createMockBaileys } from "../../test/mocks/baileys.js";
let loadConfigMock: () => unknown = () => ({});
export function setLoadConfigMock(fn: () => unknown) {
loadConfigMock = fn;
}
export function resetLoadConfigMock() {
loadConfigMock = () => ({});
}
vi.mock("../config/config.js", () => ({
loadConfig: () => loadConfigMock(),
}));
vi.mock("../media/store.js", () => ({
saveMediaBuffer: vi
.fn()
.mockImplementation(async (_buf: Buffer, contentType?: string) => ({
id: "mid",
path: "/tmp/mid",
size: _buf.length,
contentType,
})),
}));
vi.mock("@whiskeysockets/baileys", () => {
const created = createMockBaileys();
(globalThis as Record<PropertyKey, unknown>)[
Symbol.for("warelay:lastSocket")
] = created.lastSocket;
return created.mod;
});
vi.mock("qrcode-terminal", () => ({
default: { generate: vi.fn() },
generate: vi.fn(),
}));
export const baileys = (await import(
"@whiskeysockets/baileys"
)) as unknown as typeof import("@whiskeysockets/baileys") & {
makeWASocket: ReturnType<typeof vi.fn>;
useMultiFileAuthState: ReturnType<typeof vi.fn>;
fetchLatestBaileysVersion: ReturnType<typeof vi.fn>;
makeCacheableSignalKeyStore: ReturnType<typeof vi.fn>;
};
export function resetBaileysMocks() {
const recreated = createMockBaileys();
(globalThis as Record<PropertyKey, unknown>)[
Symbol.for("warelay:lastSocket")
] = recreated.lastSocket;
baileys.makeWASocket.mockImplementation(recreated.mod.makeWASocket);
baileys.useMultiFileAuthState.mockImplementation(
recreated.mod.useMultiFileAuthState,
);
baileys.fetchLatestBaileysVersion.mockImplementation(
recreated.mod.fetchLatestBaileysVersion,
);
baileys.makeCacheableSignalKeyStore.mockImplementation(
recreated.mod.makeCacheableSignalKeyStore,
);
}
export function getLastSocket(): MockBaileysSocket {
const getter = (globalThis as Record<PropertyKey, unknown>)[
Symbol.for("warelay:lastSocket")
];
if (typeof getter === "function")
return (getter as () => MockBaileysSocket)();
if (!getter) throw new Error("Baileys mock not initialized");
throw new Error("Invalid Baileys socket getter");
}
+7 -1
View File
@@ -14,5 +14,11 @@
"allowSyntheticDefaultImports": true "allowSyntheticDefaultImports": true
}, },
"include": ["src/**/*"], "include": ["src/**/*"],
"exclude": ["node_modules", "dist", "src/**/*.test.ts", "src/**/*.test.tsx"] "exclude": [
"node_modules",
"dist",
"src/**/*.test.ts",
"src/**/*.test.tsx",
"src/**/test-helpers.ts"
]
} }