Skip to content

t1385.3: WhatsApp bot subagent doc (Baileys)#2761

Closed
marcusquinn wants to merge 2 commits intomainfrom
chore/t1385.3-whatsapp-agent
Closed

t1385.3: WhatsApp bot subagent doc (Baileys)#2761
marcusquinn wants to merge 2 commits intomainfrom
chore/t1385.3-whatsapp-agent

Conversation

@marcusquinn
Copy link
Owner

@marcusquinn marcusquinn commented Mar 3, 2026

Summary

  • Add .agents/services/communications/whatsapp.md — comprehensive subagent doc for WhatsApp bot integration using the Baileys library (TypeScript, MIT, unofficial WhatsApp Web API)
  • Covers QR linking, multi-device support, full messaging features (text, media, reactions, polls, status broadcasts), group management, access control patterns, and connection management
  • Includes thorough privacy/security assessment: Signal Protocol E2E encryption for message content, but extensive Meta metadata harvesting (contact graph, usage patterns, device info, ad targeting), ToS violation risks with mitigation strategies
  • Documents aidevops runner dispatch integration with command router pattern and Matterbridge bridging via whatsmeow

Closes #2750

Summary by CodeRabbit

  • Documentation
    • Added a comprehensive WhatsApp bot integration guide: architecture and session management, installation and auth options (QR and pairing), message types and group features, multi-device & multi-bot patterns, connection management and health monitoring, admin controls, rate limiting, privacy/security assessment, external dispatcher integration, and bridging considerations for production deployments.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 3, 2026

Walkthrough

Adds a new comprehensive documentation file describing a Baileys-based WhatsApp bot implementation (TypeScript/Node.js), covering architecture, authentication (QR/pairing), session and multi-device management, messaging features, group management, privacy/security considerations, runner-dispatch integration, and Matterbridge bridging options.

Changes

Cohort / File(s) Summary
WhatsApp Bot Documentation
.agents/services/communications/whatsapp.md
Add new ~963-line guide covering Baileys-based WhatsApp bot: architecture (Baileys client, auth/session persistence), QR & pairing-code auth flows, multi-device sessions, reconnection/health strategies, messaging features (text, media, reactions, polls, receipts, presence), group management, JID formats, access control & rate limiting, privacy/security assessment (Signal E2EE vs metadata risks), runner-dispatch integration (command router, secure shell dispatch), and Matterbridge comparison (whatsmeow notes).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

documentation

Poem

🐚 Baileys hums, QR lights the way,
TypeScript threads messages into day,
Sessions cling as devices align,
Encryption sings while metadata signs,
Docs now guide the bot’s bright play.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly references the task ID (t1385.3) and clearly identifies the main change as a WhatsApp bot subagent documentation using Baileys library.
Linked Issues check ✅ Passed The PR comprehensively addresses all coding-related requirements from issue #2750: Baileys documentation, authentication flows, messaging features, group management, access control patterns, runner dispatch integration, Matterbridge bridging, and privacy/security assessment.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the whatsapp.md documentation file required by issue #2750; no extraneous modifications to unrelated files or objectives detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/t1385.3-whatsapp-agent

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link

github-actions bot commented Mar 3, 2026

🔍 Code Quality Report

�[0;35m[MONITOR]�[0m Code Review Monitoring Report

�[0;34m[INFO]�[0m Latest Quality Status:
SonarCloud: 0 bugs, 0 vulnerabilities, 113 code smells

�[0;34m[INFO]�[0m Recent monitoring activity:
Tue Mar 3 04:43:47 UTC 2026: Code review monitoring started
Tue Mar 3 04:43:47 UTC 2026: SonarCloud - Bugs: 0, Vulnerabilities: 0, Code Smells: 113

📈 Current Quality Metrics

  • BUGS: 0
  • CODE SMELLS: 113
  • VULNERABILITIES: 0

Generated on: Tue Mar 3 04:43:50 UTC 2026


Generated by AI DevOps Framework Code Review Monitoring

@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request adds a new subagent documentation file for WhatsApp bot integration using the Baileys library. It provides detailed instructions on setting up and using Baileys, along with a comprehensive overview of its features, security considerations, and integration possibilities with other tools.

Highlights

  • New Subagent Documentation: This PR introduces comprehensive documentation for integrating WhatsApp bots using the Baileys library, covering setup, features, security, and integration with aidevops runners and Matterbridge.
  • WhatsApp Bot Integration via Baileys: The documentation details how to use Baileys, a TypeScript library, to connect to WhatsApp as a linked device, enabling full messaging capabilities without the WhatsApp Business API.
  • Privacy and Security Assessment: The documentation includes a thorough assessment of the privacy and security implications of using WhatsApp bots, highlighting the metadata collection by Meta and the ToS violation risks associated with Baileys.
Changelog
  • .agents/services/communications/whatsapp.md
    • Added comprehensive documentation for WhatsApp bot integration using the Baileys library.
Activity
  • No reviewer activity detected.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds a comprehensive documentation file for WhatsApp bot integration using the Baileys library. The document is well-structured and covers a wide range of topics from setup to advanced features and security considerations. My review focuses on improving the correctness, robustness, and security of the code examples provided within the documentation to ensure users who copy them have a safe and stable starting point. I've identified a few areas for improvement, including a potential security vulnerability in input sanitization (with a reference to repository guidelines on safe command construction), risky recursive function calls for reconnection logic, and best practices for dependency management.

Note: Security Review has been skipped due to the limited scope of the PR.

): Promise<string> {
try {
// Sanitize input — treat all inbound messages as untrusted
const sanitized = prompt.replace(/[`$\\]/g, "")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The input sanitization is insufficient and poses a security risk. It only removes backticks, dollar signs, and backslashes, but misses other critical shell metacharacters like ;, |, &, (, ), <, and >. If the downstream runner-helper.sh script is not written to handle arbitrary arguments safely (e.g., if it uses eval), this could lead to a command injection vulnerability. The sanitization should be made more robust by removing all potentially dangerous characters. As per repository guidelines, to avoid command injection vulnerabilities when constructing shell commands dynamically, it is recommended to avoid eval and instead use a bash array to build the command and its arguments safely.

Suggested change
const sanitized = prompt.replace(/[`$\\]/g, "")
const sanitized = prompt.replace(/[`$\\;|()<>!]/g, "")
References
  1. To avoid command injection vulnerabilities when constructing shell commands dynamically, do not use eval. Instead, use a bash array to build the command and its arguments safely.

const shouldReconnect = reason !== DisconnectReason.loggedOut
console.log(`Connection closed: ${reason}. Reconnect: ${shouldReconnect}`)
if (shouldReconnect) {
startBot() // Recursive reconnect

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The recursive call startBot() for reconnection can lead to a stack overflow if connection failures occur in quick succession. It's safer to use setTimeout to schedule the reconnection, which avoids increasing the call stack depth. This also makes the example consistent with the more robust reconnection strategy shown later in this document.

Suggested change
startBot() // Recursive reconnect
setTimeout(startBot, 5000) // Reconnect after a delay


// Request pairing code for a phone number
if (!sock.authState.creds.registered) {
const code = await sock.requestPairingCode("+1234567890")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The example phone number +1234567890 includes a + prefix. According to the Baileys documentation and this document's "JID Format" section (line 519), phone numbers should be provided without the + prefix. This example is incorrect and could cause errors.

Suggested change
const code = await sock.requestPairingCode("+1234567890")
const code = await sock.requestPairingCode("1234567890")

Comment on lines +833 to +836
go install -tags whatsappmulti github.com/42wim/matterbridge@master

# Without MS Teams (saves ~2.5GB RAM during build) + with WhatsApp
go install -tags nomsteams,whatsappmulti github.com/42wim/matterbridge@master

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using @master to install the Matterbridge binary is not recommended for stable setups as it can pull in breaking changes unexpectedly. For reproducible builds, it is a best practice to pin to a specific version tag (e.g., @v1.20.0). Please update the command to use the latest stable release tag instead of @master.

break
case DisconnectReason.restartRequired:
// Normal restart — reconnect immediately
startBot()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This direct recursive call to startBot() can lead to stack depth issues on repeated restarts, which is a robustness concern. For consistency with the other reconnection cases and to prevent potential stack overflows, it's safer to use setTimeout to schedule the restart, even with a short delay.

Suggested change
startBot()
setTimeout(() => startBot(), 1000)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
.agents/services/communications/whatsapp.md (1)

175-182: Consider adding backoff delay for reconnection.

The immediate recursive reconnection on line 180 could cause rapid connection attempts if the server is temporarily unavailable. While the shouldReconnect guard is good, adding a brief delay would be more resilient.

⏱️ Proposed fix with connection backoff
     if (connection === "close") {
       const reason = (lastDisconnect?.error as Boom)?.output?.statusCode
       const shouldReconnect = reason !== DisconnectReason.loggedOut
       console.log(`Connection closed: ${reason}. Reconnect: ${shouldReconnect}`)
       if (shouldReconnect) {
-        startBot() // Recursive reconnect
+        setTimeout(() => startBot(), 3000) // Reconnect with 3s delay
       }
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.agents/services/communications/whatsapp.md around lines 175 - 182, The
reconnect path currently calls startBot() immediately when connection ===
"close" and shouldReconnect is true; add a backoff delay before calling
startBot() to avoid rapid retries (e.g., use a setTimeout or an exponential
backoff helper with an increasing delay and jitter) and ensure the logic uses
the same lastDisconnect/DisconnectReason.loggedOut check so you only schedule
reconnection when appropriate; update the block that checks shouldReconnect to
schedule startBot() after the computed delay and reset/backoff counters on
successful connection.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.agents/services/communications/whatsapp.md:
- Around line 787-796: Update the security guidance to recommend the secure
implementation patterns instead of weak sanitization: replace any suggestion to
sanitize strings inline for runner dispatch with explicit guidance to use
execFileSync (or equivalent) with argument arrays and avoid shell interpolation,
or to use JSON-based IPC for passing messages to runners; reference the
prompt-injection scan step (`prompt-guard-helper.sh scan "$message"`) as a
pre-dispatch check but state it does not replace safe execution models; call out
credential isolation and leak detection remain required (see
`tools/credentials/gopass.md`) and link to
`tools/security/prompt-injection-defender.md` for examples of using
execFileSync/JSON IPC in the runner dispatch flow.
- Around line 755-784: The dispatchToRunner function currently builds a shell
command string and uses execSync with a lightly "sanitized" prompt, which allows
shell injection; replace this by calling a non-shell API (e.g.,
child_process.execFile or spawnSync) to run runner-helper.sh with an argument
array instead of a single interpolated string (pass ["dispatch", runner, prompt]
or similar), remove the unsafe string interpolation and the fragile regex
sanitization (or, if you must restrict input, validate prompt/runner against a
strict whitelist/regex before calling), ensure environment variables
(DISPATCH_SENDER, DISPATCH_CHANNEL) are still passed, and update the error
handling message to mention secure dispatch failure; target the dispatchToRunner
function and the execSync invocation to make this change.
- Around line 22-29: Update the Baileys entry to reflect current requirements:
change the runtime requirement text from "Node.js 18+" to "Node.js 20+"; update
the npm package name from "`@whiskeysockets/baileys`" to the unscoped
"`baileys`"; and change the "Session store" line to state that Baileys only
provides a file-based example (useMultiFileAuthState) for non-production use and
that SQLite/Redis/PostgreSQL require custom implementations rather than being
built-in pluggable options.

---

Nitpick comments:
In @.agents/services/communications/whatsapp.md:
- Around line 175-182: The reconnect path currently calls startBot() immediately
when connection === "close" and shouldReconnect is true; add a backoff delay
before calling startBot() to avoid rapid retries (e.g., use a setTimeout or an
exponential backoff helper with an increasing delay and jitter) and ensure the
logic uses the same lastDisconnect/DisconnectReason.loggedOut check so you only
schedule reconnection when appropriate; update the block that checks
shouldReconnect to schedule startBot() after the computed delay and
reset/backoff counters on successful connection.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac2beaf and e7676532fa2a7d1f57cf698bb6bd3f098d4a8a2a.

📒 Files selected for processing (1)
  • .agents/services/communications/whatsapp.md

Create .agents/services/communications/whatsapp.md covering:
- Baileys library (TypeScript, MIT, unofficial WhatsApp Web API)
- QR code linking and pairing code authentication
- Multi-device support and session persistence
- Full messaging features (text, media, reactions, polls, status)
- Group management and JID format reference
- Access control patterns (allowlist, rate limiting, permission levels)
- Privacy/security assessment: Signal Protocol E2E for content but
  extensive Meta metadata harvesting, ToS violation risks, account
  ban mitigation strategies
- aidevops runner dispatch integration with command router pattern
- Matterbridge bridging via whatsmeow (native WhatsApp support)
- Connection management and health monitoring
- Comparison tables vs SimpleX, Matrix, XMTP, WhatsApp Business API

Closes #2750
@github-actions
Copy link

github-actions bot commented Mar 3, 2026

🔍 Code Quality Report

�[0;35m[MONITOR]�[0m Code Review Monitoring Report

�[0;34m[INFO]�[0m Latest Quality Status:
SonarCloud: 0 bugs, 0 vulnerabilities, 113 code smells

�[0;34m[INFO]�[0m Recent monitoring activity:
Tue Mar 3 04:59:16 UTC 2026: Code review monitoring started
Tue Mar 3 04:59:16 UTC 2026: SonarCloud - Bugs: 0, Vulnerabilities: 0, Code Smells: 113

📈 Current Quality Metrics

  • BUGS: 0
  • CODE SMELLS: 113
  • VULNERABILITIES: 0

Generated on: Tue Mar 3 04:59:19 UTC 2026


Generated by AI DevOps Framework Code Review Monitoring

@sonarqubecloud
Copy link

sonarqubecloud bot commented Mar 3, 2026

- Replace execSync with execFileSync + argument array to eliminate shell
  injection vulnerability (critical security fix)
- Add setTimeout backoff delays to all reconnect paths to prevent stack
  overflow on rapid connection failures
- Update package name from @whiskeysockets/baileys to baileys (official
  unscoped package) and Node.js requirement from 18+ to 20+
- Clarify session store as non-production example, not pluggable built-in
- Update security guidance to recommend execFileSync and JSON IPC patterns
- Fix pairing code example to omit + prefix per JID format spec
- Pin matterbridge install to @latest instead of @master for stability
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
.agents/services/communications/whatsapp.md (1)

139-215: Consider adding a note about production-ready patterns.

The minimal setup example is clear and functional, but developers might benefit from a brief callout that this is an illustrative starting point. Production deployments would typically add:

  • Structured logging with correlation IDs
  • Metrics/telemetry for message throughput and latency
  • Persistent message queuing for reliability
  • Database-backed auth state instead of file-based

This doesn't require code changes — just a short note like "This minimal example is suitable for development and testing. See production deployment patterns for scaling considerations."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.agents/services/communications/whatsapp.md around lines 139 - 215, Add a
short production-readiness note to the README or the top of the example file
explaining that startBot() and the file-based auth from
useMultiFileAuthState("./auth_info") are for development only and listing
recommended production practices (structured logging with correlation IDs,
metrics/telemetry, durable message queuing, and storing auth state in a DB or
secure store); place the note near the example invocation of startBot() or above
the WASocket setup so readers see that sock.ev event handling and simple echo
logic are illustrative, and link to a longer "production deployment patterns"
doc if available.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In @.agents/services/communications/whatsapp.md:
- Around line 139-215: Add a short production-readiness note to the README or
the top of the example file explaining that startBot() and the file-based auth
from useMultiFileAuthState("./auth_info") are for development only and listing
recommended production practices (structured logging with correlation IDs,
metrics/telemetry, durable message queuing, and storing auth state in a DB or
secure store); place the note near the example invocation of startBot() or above
the WASocket setup so readers see that sock.ev event handling and simple echo
logic are illustrative, and link to a longer "production deployment patterns"
doc if available.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e7676532fa2a7d1f57cf698bb6bd3f098d4a8a2a and fb5f161.

📒 Files selected for processing (1)
  • .agents/services/communications/whatsapp.md

@alex-solovyev
Copy link
Collaborator

This PR was superseded by the batch merge in PR #2771 (feat: t1385 — add 11 chat platform integration agents), which merged all the content from this branch. Closing as the content is already in main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

t1385.3: WhatsApp bot agent

2 participants