Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c194247dab | ||
|
|
a48420d85f | ||
|
|
5c66e8273b | ||
|
|
5992e629c3 | ||
|
|
765d67cd18 | ||
|
|
baf20af17f | ||
|
|
e482e7768b | ||
|
|
8682352edb | ||
|
|
ef1222ff31 | ||
|
|
0145f3a585 | ||
|
|
4a8bb56a1e | ||
|
|
ce5b02a9ad | ||
|
|
5c8ce41e12 | ||
|
|
a2586b8b06 | ||
|
|
1fd4485716 | ||
|
|
b029ab933e | ||
|
|
e0b28b6718 | ||
|
|
4dd2f3b7f7 | ||
|
|
e5f677803f | ||
|
|
a67f4db5e2 | ||
|
|
8a01dc7f4c | ||
|
|
e107f115e2 | ||
|
|
af8af4881b | ||
|
|
d871dad85f | ||
|
|
5b83d30887 | ||
|
|
2e3b8a03aa | ||
|
|
d924b7d283 | ||
|
|
e0425ad3e1 | ||
|
|
5dced02a20 | ||
|
|
e642f128ae | ||
|
|
7d0ae151e8 | ||
|
|
f945e284e1 | ||
|
|
7166efef08 | ||
|
|
a81689e902 | ||
|
|
0a0418b973 | ||
|
|
f81f432af5 | ||
|
|
dda017df23 | ||
|
|
46be5eac7d | ||
|
|
e4076d14c0 | ||
|
|
20fc412765 | ||
|
|
c251681a40 | ||
|
|
9c25e15e92 | ||
|
|
bcbf0de240 | ||
|
|
1ef7f4dbad | ||
|
|
9db969e94e | ||
|
|
4f27f4cf79 | ||
|
|
b7c46909cd | ||
|
|
953f9af419 | ||
|
|
6ea32873df |
No files matched your search
+35
-5
@@ -1,5 +1,40 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 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
|
## 0.1.1 — 2025-11-25
|
||||||
|
|
||||||
### CLI polish
|
### CLI polish
|
||||||
@@ -8,11 +43,6 @@
|
|||||||
- `send` and `status` gained a `--verbose` flag for consistent noisy output when debugging.
|
- `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`.
|
- Lowercased branding in docs/UA; web provider UA is `warelay/cli/0.1.1`.
|
||||||
|
|
||||||
## 0.1.2 — 2025-11-25
|
|
||||||
|
|
||||||
### CI/build fix
|
|
||||||
- Fixed commander help configuration (`subcommandTerm`) so TypeScript builds pass in CI.
|
|
||||||
- Bumped version/UA to 0.1.2; no functional changes beyond the CI fix.
|
|
||||||
|
|
||||||
## 0.1.0 — 2025-11-25
|
## 0.1.0 — 2025-11-25
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
@@ -1,7 +1,14 @@
|
|||||||
# 📡 warelay — Send, receive, and auto-reply on WhatsApp—Twilio-backed or QR-linked.
|
# 📡 warelay — Send, receive, and auto-reply on WhatsApp.
|
||||||
[](https://github.com/steipete/warelay/actions/workflows/ci.yml)
|
|
||||||
[](https://www.npmjs.com/package/warelay)
|
<p align="center">
|
||||||
[](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).
|
||||||
|
|
||||||
@@ -11,7 +18,7 @@ Install from npm (global): `npm install -g warelay` (Node 22+). Then choose **on
|
|||||||
**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`).
|
||||||
@@ -39,15 +46,41 @@ Install from npm (global): `npm install -g warelay` (Node 22+). Then choose **on
|
|||||||
| `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.
|
||||||
|
|
||||||
@@ -84,10 +117,23 @@ Best practice: use a dedicated WhatsApp account (separate SIM/eSIM or business a
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Logging (optional)
|
||||||
|
- File logs are written to `/tmp/warelay/warelay.log` by default. Levels: `silent | fatal | error | warn | info | debug | trace` (CLI `--verbose` forces `debug`). Web-provider inbound/outbound entries include message bodies and auto-reply text for easier auditing.
|
||||||
|
- Override in `~/.warelay/warelay.json`:
|
||||||
|
|
||||||
|
```json5
|
||||||
|
{
|
||||||
|
logging: {
|
||||||
|
level: "warn",
|
||||||
|
file: "/tmp/warelay/custom.log"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Claude CLI setup (how we run it)
|
### Claude CLI setup (how we run it)
|
||||||
1) Install the official Claude CLI (e.g., `brew install anthropic-ai/cli/claude` or follow the Anthropic docs) and run `claude login` so it can read your API key.
|
1) Install the official Claude CLI (e.g., `brew install anthropic-ai/cli/claude` or follow the Anthropic docs) and run `claude login` so it can read your API key.
|
||||||
2) In `warelay.json`, set `reply.mode` to `"command"` and point `command[0]` to `"claude"`; set `claudeOutputFormat` to `"text"` (or `"json"`/`"stream-json"` if you want warelay to parse and trim the JSON output).
|
2) In `warelay.json`, set `reply.mode` to `"command"` and point `command[0]` to `"claude"`; set `claudeOutputFormat` to `"text"` (or `"json"`/`"stream-json"` if you want warelay to parse and trim the JSON output).
|
||||||
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)
|
||||||
@@ -105,6 +151,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 +171,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.
|
||||||
|
|||||||
+2
-1
@@ -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
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -21,6 +21,8 @@ warelay reads `~/.warelay/warelay.json` (JSON5 accepted). Add a command-mode rep
|
|||||||
allowFrom: ["+15551234567"],
|
allowFrom: ["+15551234567"],
|
||||||
reply: {
|
reply: {
|
||||||
mode: "command",
|
mode: "command",
|
||||||
|
// Working directory for command execution (useful for Claude Code project context).
|
||||||
|
cwd: "/Users/you/Projects/my-project",
|
||||||
// Prepended before the inbound body; good for system prompts.
|
// Prepended before the inbound body; good for system prompts.
|
||||||
bodyPrefix: "You are a concise WhatsApp assistant. Keep replies under 1500 characters.\n\n",
|
bodyPrefix: "You are a concise WhatsApp assistant. Keep replies under 1500 characters.\n\n",
|
||||||
// Claude CLI argv; the final element is the prompt/body provided by warelay.
|
// Claude CLI argv; the final element is the prompt/body provided by warelay.
|
||||||
@@ -38,6 +40,7 @@ warelay reads `~/.warelay/warelay.json` (JSON5 accepted). Add a command-mode rep
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes on this configuration:
|
Notes on this configuration:
|
||||||
|
- `cwd` sets the working directory where the command runs. This is essential for Claude Code to have the right project context—Claude will see the project's `CLAUDE.md`, have access to project files, and understand the codebase structure.
|
||||||
- warelay automatically injects a Claude identity prefix and the correct `--output-format`/`-p` flags when `command[0]` is `claude` and `claudeOutputFormat` is set.
|
- warelay automatically injects a Claude identity prefix and the correct `--output-format`/`-p` flags when `command[0]` is `claude` and `claudeOutputFormat` is set.
|
||||||
- Sessions are stored in `~/.warelay/sessions.json`; `scope: per-sender` keeps separate threads for each contact.
|
- Sessions are stored in `~/.warelay/sessions.json`; `scope: per-sender` keeps separate threads for each contact.
|
||||||
- `bodyPrefix` is added before the inbound message body that reaches Claude. The string above mirrors the built-in 1500-character WhatsApp guardrail.
|
- `bodyPrefix` is added before the inbound message body that reaches Claude. The string above mirrors the built-in 1500-character WhatsApp guardrail.
|
||||||
@@ -56,6 +59,10 @@ Notes on this configuration:
|
|||||||
- Host local paths for Twilio using the media server/Tailscale Funnel.
|
- Host local paths for Twilio using the media server/Tailscale Funnel.
|
||||||
- Send buffers directly for the Web provider.
|
- Send buffers directly for the Web provider.
|
||||||
- Inbound media is downloaded (≤5 MB) and exposed to your templates as `{{MediaPath}}`, `{{MediaUrl}}`, and `{{MediaType}}`. You can mention this in your prompt if you want Claude to reason about the attachment.
|
- Inbound media is downloaded (≤5 MB) and exposed to your templates as `{{MediaPath}}`, `{{MediaUrl}}`, and `{{MediaType}}`. You can mention this in your prompt if you want Claude to reason about the attachment.
|
||||||
|
- Outbound media from Claude (via `MEDIA:`) follows provider caps: Web resizes images to the configured target (`inbound.reply.mediaMaxMb`, default 5 MB) within hard limits of 6 MB (image), 16 MB (audio/video voice notes), and 100 MB (documents); Twilio still uses the Funnel host with a 5 MB guard.
|
||||||
|
- Voice notes: set `inbound.transcribeAudio.command` to run a CLI that emits the transcript to stdout (e.g., OpenAI Whisper: `openai api audio.transcriptions.create -m whisper-1 -f {{MediaPath}} --response-format text`). If it succeeds, warelay replaces `Body` with the transcript and adds the original media path plus a `Transcript:` block into the prompt before invoking Claude.
|
||||||
|
- To avoid re-sending long system prompts every turn, set `inbound.reply.session.sendSystemOnce: true` and keep your prompt in `bodyPrefix` or `sessionIntro`; they are sent only on the first message of each session (resets on `/new` or idle expiry).
|
||||||
|
- Typing indicators: for long-running Claude/command replies, `inbound.reply.typingIntervalSeconds` (or the session-level equivalent) refreshes the “composing” indicator periodically (default 8 s for command replies).
|
||||||
|
|
||||||
## Testing the setup
|
## Testing the setup
|
||||||
1. Start a relay (auto-selects Web when logged in, otherwise Twilio polling):
|
1. Start a relay (auto-selects Web when logged in, otherwise Twilio polling):
|
||||||
|
|||||||
+10
-5
@@ -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.
|
||||||
+2
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "warelay",
|
"name": "warelay",
|
||||||
"version": "0.1.2",
|
"version": "1.1.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",
|
||||||
@@ -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"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
onlyBuiltDependencies:
|
||||||
|
- '@whiskeysockets/baileys'
|
||||||
|
- sharp
|
||||||
@@ -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.";
|
||||||
|
|
||||||
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.
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
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("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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
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;
|
||||||
|
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(" ")}${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,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+186
-267
@@ -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,65 @@ 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:/, "");
|
||||||
|
if (!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 +222,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 +294,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 +352,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(
|
||||||
|
|||||||
@@ -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 & {
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
export type GetReplyOptions = {
|
||||||
|
onReplyStart?: () => Promise<void> | void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ReplyPayload = {
|
||||||
|
text?: string;
|
||||||
|
mediaUrl?: string;
|
||||||
|
mediaUrls?: string[];
|
||||||
|
};
|
||||||
@@ -68,13 +68,15 @@ 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 () => {
|
||||||
|
|||||||
+129
-9
@@ -3,11 +3,23 @@ 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 {
|
||||||
|
loginWeb,
|
||||||
|
logoutWeb,
|
||||||
|
monitorWebProvider,
|
||||||
|
pickProvider,
|
||||||
|
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,
|
||||||
@@ -18,7 +30,7 @@ import { spawnRelayTmux } from "./relay_tmux.js";
|
|||||||
|
|
||||||
export function buildProgram() {
|
export function buildProgram() {
|
||||||
const program = new Command();
|
const program = new Command();
|
||||||
const PROGRAM_VERSION = "0.1.2";
|
const PROGRAM_VERSION = VERSION;
|
||||||
const TAGLINE =
|
const TAGLINE =
|
||||||
"Send, receive, and auto-reply on WhatsApp—Twilio-backed or QR-linked.";
|
"Send, receive, and auto-reply on WhatsApp—Twilio-backed or QR-linked.";
|
||||||
|
|
||||||
@@ -103,6 +115,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")
|
||||||
@@ -160,6 +184,19 @@ 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("--verbose", "Verbose logging", false)
|
.option("--verbose", "Verbose logging", false)
|
||||||
.addHelpText(
|
.addHelpText(
|
||||||
"after",
|
"after",
|
||||||
@@ -169,6 +206,7 @@ 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) => {
|
||||||
@@ -180,6 +218,22 @@ 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;
|
||||||
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);
|
||||||
@@ -188,25 +242,91 @@ 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;
|
||||||
|
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();
|
||||||
|
|||||||
@@ -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();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -17,23 +17,54 @@ export type SessionConfig = {
|
|||||||
sessionArgNew?: string[];
|
sessionArgNew?: string[];
|
||||||
sessionArgResume?: string[];
|
sessionArgResume?: string[];
|
||||||
sessionArgBeforeBody?: boolean;
|
sessionArgBeforeBody?: boolean;
|
||||||
|
sendSystemOnce?: boolean;
|
||||||
|
sessionIntro?: string;
|
||||||
|
typingIntervalSeconds?: 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
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
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 +74,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
|
||||||
@@ -58,6 +92,9 @@ const ReplySchema = z
|
|||||||
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(),
|
||||||
claudeOutputFormat: z
|
claudeOutputFormat: z
|
||||||
@@ -78,12 +115,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 {
|
||||||
|
|||||||
@@ -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
@@ -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",
|
||||||
|
|||||||
+49
-1
@@ -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
@@ -6,14 +6,17 @@ import {
|
|||||||
success,
|
success,
|
||||||
warn,
|
warn,
|
||||||
} from "./globals.js";
|
} from "./globals.js";
|
||||||
|
import { getLogger } from "./logging.js";
|
||||||
import { defaultRuntime, type RuntimeEnv } from "./runtime.js";
|
import { defaultRuntime, type RuntimeEnv } from "./runtime.js";
|
||||||
|
|
||||||
export function logInfo(message: string, runtime: RuntimeEnv = defaultRuntime) {
|
export function logInfo(message: string, runtime: RuntimeEnv = defaultRuntime) {
|
||||||
runtime.log(info(message));
|
runtime.log(info(message));
|
||||||
|
getLogger().info(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logWarn(message: string, runtime: RuntimeEnv = defaultRuntime) {
|
export function logWarn(message: string, runtime: RuntimeEnv = defaultRuntime) {
|
||||||
runtime.log(warn(message));
|
runtime.log(warn(message));
|
||||||
|
getLogger().warn(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logSuccess(
|
export function logSuccess(
|
||||||
@@ -21,6 +24,7 @@ export function logSuccess(
|
|||||||
runtime: RuntimeEnv = defaultRuntime,
|
runtime: RuntimeEnv = defaultRuntime,
|
||||||
) {
|
) {
|
||||||
runtime.log(success(message));
|
runtime.log(success(message));
|
||||||
|
getLogger().info(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logError(
|
export function logError(
|
||||||
@@ -28,9 +32,11 @@ export function logError(
|
|||||||
runtime: RuntimeEnv = defaultRuntime,
|
runtime: RuntimeEnv = defaultRuntime,
|
||||||
) {
|
) {
|
||||||
runtime.error(danger(message));
|
runtime.error(danger(message));
|
||||||
|
getLogger().error(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logDebug(message: string) {
|
export function logDebug(message: string) {
|
||||||
// Verbose helper that respects global verbosity flag.
|
// Always emit to file logger (level-filtered); console only when verbose.
|
||||||
|
getLogger().debug(message);
|
||||||
if (isVerbose()) logVerbose(message);
|
if (isVerbose()) logVerbose(message);
|
||||||
}
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import pino, { type Bindings, type LevelWithSilent, type Logger } from "pino";
|
||||||
|
import { loadConfig, type WarelayConfig } from "./config/config.js";
|
||||||
|
import { isVerbose } from "./globals.js";
|
||||||
|
|
||||||
|
const DEFAULT_LOG_DIR = path.join(os.tmpdir(), "warelay");
|
||||||
|
export const DEFAULT_LOG_FILE = path.join(DEFAULT_LOG_DIR, "warelay.log");
|
||||||
|
|
||||||
|
const ALLOWED_LEVELS: readonly LevelWithSilent[] = [
|
||||||
|
"silent",
|
||||||
|
"fatal",
|
||||||
|
"error",
|
||||||
|
"warn",
|
||||||
|
"info",
|
||||||
|
"debug",
|
||||||
|
"trace",
|
||||||
|
];
|
||||||
|
|
||||||
|
export type LoggerSettings = {
|
||||||
|
level?: LevelWithSilent;
|
||||||
|
file?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ResolvedSettings = {
|
||||||
|
level: LevelWithSilent;
|
||||||
|
file: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
let cachedLogger: Logger | null = null;
|
||||||
|
let cachedSettings: ResolvedSettings | null = null;
|
||||||
|
let overrideSettings: LoggerSettings | null = null;
|
||||||
|
|
||||||
|
function normalizeLevel(level?: string): LevelWithSilent {
|
||||||
|
if (isVerbose()) return "debug";
|
||||||
|
const candidate = level ?? "info";
|
||||||
|
return ALLOWED_LEVELS.includes(candidate as LevelWithSilent)
|
||||||
|
? (candidate as LevelWithSilent)
|
||||||
|
: "info";
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveSettings(): ResolvedSettings {
|
||||||
|
const cfg: WarelayConfig["logging"] | undefined =
|
||||||
|
overrideSettings ?? loadConfig().logging;
|
||||||
|
const level = normalizeLevel(cfg?.level);
|
||||||
|
const file = cfg?.file ?? DEFAULT_LOG_FILE;
|
||||||
|
return { level, file };
|
||||||
|
}
|
||||||
|
|
||||||
|
function settingsChanged(a: ResolvedSettings | null, b: ResolvedSettings) {
|
||||||
|
if (!a) return true;
|
||||||
|
return a.level !== b.level || a.file !== b.file;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLogger(settings: ResolvedSettings): Logger {
|
||||||
|
fs.mkdirSync(path.dirname(settings.file), { recursive: true });
|
||||||
|
const destination = pino.destination({
|
||||||
|
dest: settings.file,
|
||||||
|
mkdir: true,
|
||||||
|
sync: true, // deterministic for tests; log volume is modest.
|
||||||
|
});
|
||||||
|
return pino(
|
||||||
|
{
|
||||||
|
level: settings.level,
|
||||||
|
base: undefined,
|
||||||
|
timestamp: pino.stdTimeFunctions.isoTime,
|
||||||
|
},
|
||||||
|
destination,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLogger(): Logger {
|
||||||
|
const settings = resolveSettings();
|
||||||
|
if (!cachedLogger || settingsChanged(cachedSettings, settings)) {
|
||||||
|
cachedLogger = buildLogger(settings);
|
||||||
|
cachedSettings = settings;
|
||||||
|
}
|
||||||
|
return cachedLogger;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getChildLogger(
|
||||||
|
bindings?: Bindings,
|
||||||
|
opts?: { level?: LevelWithSilent },
|
||||||
|
): Logger {
|
||||||
|
return getLogger().child(bindings ?? {}, opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test helpers
|
||||||
|
export function setLoggerOverride(settings: LoggerSettings | null) {
|
||||||
|
overrideSettings = settings;
|
||||||
|
cachedLogger = null;
|
||||||
|
cachedSettings = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resetLogger() {
|
||||||
|
cachedLogger = null;
|
||||||
|
cachedSettings = null;
|
||||||
|
overrideSettings = null;
|
||||||
|
}
|
||||||
@@ -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
@@ -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
@@ -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 = "";
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+28
-633
@@ -1,633 +1,28 @@
|
|||||||
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";
|
monitorWebProvider,
|
||||||
import {
|
type WebMonitorTuning,
|
||||||
type AnyMessageContent,
|
} from "./web/auto-reply.js";
|
||||||
DisconnectReason,
|
export {
|
||||||
downloadMediaMessage,
|
extractMediaPlaceholder,
|
||||||
fetchLatestBaileysVersion,
|
extractText,
|
||||||
makeCacheableSignalKeyStore,
|
monitorWebInbox,
|
||||||
makeWASocket,
|
type WebInboundMessage,
|
||||||
useMultiFileAuthState,
|
type WebListenerCloseReason,
|
||||||
type WAMessage,
|
} from "./web/inbound.js";
|
||||||
} from "@whiskeysockets/baileys";
|
export { loginWeb } from "./web/login.js";
|
||||||
import pino from "pino";
|
export { loadWebMedia, optimizeImageToJpeg } from "./web/media.js";
|
||||||
import qrcode from "qrcode-terminal";
|
export { sendMessageWeb } from "./web/outbound.js";
|
||||||
import { getReplyFromConfig } from "./auto-reply/reply.js";
|
export {
|
||||||
import { waitForever } from "./cli/wait.js";
|
createWaSocket,
|
||||||
import { danger, info, isVerbose, logVerbose, success } from "./globals.js";
|
formatError,
|
||||||
import { logInfo } from "./logger.js";
|
getStatusCode,
|
||||||
import { saveMediaBuffer } from "./media/store.js";
|
logoutWeb,
|
||||||
import { defaultRuntime, type RuntimeEnv } from "./runtime.js";
|
logWebSelfId,
|
||||||
import type { Provider } from "./utils.js";
|
pickProvider,
|
||||||
import { ensureDir, jidToE164, toWhatsappJid } from "./utils.js";
|
WA_WEB_AUTH_DIR,
|
||||||
|
waitForWaConnection,
|
||||||
function formatDuration(ms: number) {
|
webAuthExists,
|
||||||
return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
|
} from "./web/session.js";
|
||||||
}
|
|
||||||
|
|
||||||
const WA_WEB_AUTH_DIR = path.join(os.homedir(), ".warelay", "credentials");
|
|
||||||
|
|
||||||
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", "0.1.2"],
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
@@ -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";
|
||||||
@@ -0,0 +1,567 @@
|
|||||||
|
import crypto from "node:crypto";
|
||||||
|
import fs from "node:fs/promises";
|
||||||
|
import sharp from "sharp";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { resetLogger, setLoggerOverride } from "../logging.js";
|
||||||
|
import { monitorWebProvider } from "./auto-reply.js";
|
||||||
|
import {
|
||||||
|
resetBaileysMocks,
|
||||||
|
resetLoadConfigMock,
|
||||||
|
setLoadConfigMock,
|
||||||
|
} from "./test-helpers.js";
|
||||||
|
|
||||||
|
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"');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
import { getReplyFromConfig } from "../auto-reply/reply.js";
|
||||||
|
import { waitForever } from "../cli/wait.js";
|
||||||
|
import { loadConfig } from "../config/config.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 { monitorWebInbox } from "./inbound.js";
|
||||||
|
import { loadWebMedia } from "./media.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;
|
||||||
|
|
||||||
|
export type WebMonitorTuning = {
|
||||||
|
reconnect?: Partial<ReconnectPolicy>;
|
||||||
|
heartbeatSeconds?: number;
|
||||||
|
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDuration = (ms: number) =>
|
||||||
|
ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
|
||||||
|
|
||||||
|
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 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 lastMessageAt: number | null = null;
|
||||||
|
let handledMessages = 0;
|
||||||
|
|
||||||
|
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}`);
|
||||||
|
|
||||||
|
const replyStarted = Date.now();
|
||||||
|
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 {
|
||||||
|
const mediaList = replyResult.mediaUrls?.length
|
||||||
|
? replyResult.mediaUrls
|
||||||
|
: replyResult.mediaUrl
|
||||||
|
? [replyResult.mediaUrl]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
if (mediaList.length > 0) {
|
||||||
|
logVerbose(
|
||||||
|
`Web auto-reply media detected: ${mediaList.filter(Boolean).join(", ")}`,
|
||||||
|
);
|
||||||
|
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 ? replyResult.text || 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(
|
||||||
|
{
|
||||||
|
connectionId,
|
||||||
|
correlationId,
|
||||||
|
to: msg.from,
|
||||||
|
from: msg.to,
|
||||||
|
text: index === 0 ? (replyResult.text ?? 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 && replyResult.text) {
|
||||||
|
console.log(
|
||||||
|
`⚠️ Media skipped; sent text-only to ${msg.from}`,
|
||||||
|
);
|
||||||
|
await msg.reply(replyResult.text || "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (replyResult.text) {
|
||||||
|
await msg.reply(replyResult.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
const durationMs = Date.now() - replyStarted;
|
||||||
|
const hasMedia = mediaList.length > 0;
|
||||||
|
if (isVerbose()) {
|
||||||
|
console.log(
|
||||||
|
success(
|
||||||
|
`↩️ Auto-replied to ${msg.from} (web, ${replyResult.text?.length ?? 0} chars${hasMedia ? ", media" : ""}, ${formatDuration(durationMs)})`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.log(
|
||||||
|
success(
|
||||||
|
`↩️ ${replyResult.text ?? "<media>"}${hasMedia ? " (media)" : ""}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
replyLogger.info(
|
||||||
|
{
|
||||||
|
connectionId,
|
||||||
|
correlationId,
|
||||||
|
to: msg.from,
|
||||||
|
from: msg.to,
|
||||||
|
text: replyResult.text ?? null,
|
||||||
|
mediaUrl: mediaList[0] ?? null,
|
||||||
|
durationMs,
|
||||||
|
},
|
||||||
|
"auto-reply sent",
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(
|
||||||
|
danger(
|
||||||
|
`Failed sending web auto-reply to ${msg.from}: ${String(err)}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const closeListener = async () => {
|
||||||
|
if (heartbeat) clearInterval(heartbeat);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 ?? 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 };
|
||||||
@@ -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>");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
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>) => {
|
||||||
|
if (update.connection === "close") {
|
||||||
|
const status = getStatusCode(update.lastDisconnect?.error);
|
||||||
|
onCloseResolve?.({
|
||||||
|
status,
|
||||||
|
isLoggedOut: status === DisconnectReason.loggedOut,
|
||||||
|
error: update.lastDisconnect?.error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
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,
|
||||||
|
});
|
||||||
|
|
||||||
|
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 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";
|
||||||
|
}
|
||||||
@@ -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
@@ -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"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user