Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(whatsapp): backend supervises edgymeow binary; session DB lives under server/data/whatsapp
trohitg3a97aa8c8c10
diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.mdindex be55d245..5130999b 100644--- a/docs-internal/SCRIPTS.md+++ b/docs-internal/SCRIPTS.md@@ -54,11 +54,6 @@ Run with `npm run <script>` from the project root.|--------|---------|-------------|| `client:start` | `cd client && npm run start` | Start React frontend (Vite) || `python:start` | `cd server && uv run uvicorn main:app ...` | Start Python backend |-| `whatsapp:api` | `cd server/whatsapp-rpc && npm run api` | Start WhatsApp API server |-| `whatsapp:start` | `cd server/whatsapp-rpc && npm start` | Start WhatsApp connection |-| `whatsapp:stop` | `cd server/whatsapp-rpc && npm stop` | Stop WhatsApp service |-| `whatsapp:status` | `cd server/whatsapp-rpc && npm run status` | Check WhatsApp status |-| `whatsapp:build` | `cd server/whatsapp-rpc && npm run build` | Build WhatsApp Go binary || `temporal:start` | `temporal-server api` | Start Temporal server (foreground) || `temporal:stop` | `temporal-server stop` | Stop Temporal server || `temporal:status` | `temporal-server status` | Check Temporal server status |@@ -107,8 +102,7 @@ Cross-platform start script that runs all services concurrently.4. Frees configured app ports (client, backend, WhatsApp, Node.js executor)5. Starts services via `concurrently` with `--kill-others`:- Static client server (`serve-client.js`)- - Python backend (uvicorn)- - WhatsApp API server (unless `--skip-whatsapp`)+ - Python backend (uvicorn) -- supervises the edgymeow Go binary lazily via [server/nodes/whatsapp/_runtime.py](../server/nodes/whatsapp/_runtime.py)- Temporal server via `npm:temporal:start` (unless already running)**Temporal handling:** If `temporal-server status` reports the server is already running, Temporal is skipped in the concurrently service list. This prevents `temporal-server api` from exiting immediately with "Already running", which would trigger `--kill-others` and cascade-kill all services.@@ -178,9 +172,7 @@ Removes build artifacts and dependencies.- `client/.vite/` - Vite cache- `server/.venv/` - Python virtual environment- `server/data/` - Server data-- `server/whatsapp-rpc/node_modules/` - WhatsApp dependencies-- `server/whatsapp-rpc/bin/` - WhatsApp Go binary-- `server/whatsapp-rpc/data/` - WhatsApp data+- `server/data/whatsapp/` - WhatsApp session DB + edgymeow logs (managed by [server/nodes/whatsapp/_runtime.py](../server/nodes/whatsapp/_runtime.py))---diff --git a/package.json b/package.jsonindex b58645f0..7a3b4ce2 100644--- a/package.json+++ b/package.json@@ -70,11 +70,6 @@"temporal:stop": "temporal stop","temporal:status": "temporal status","temporal:worker": "cd server && uv run python -m services.temporal.worker",- "whatsapp:start": "edgymeow start",- "whatsapp:stop": "edgymeow stop",- "whatsapp:status": "edgymeow status",- "whatsapp:api": "edgymeow api --foreground",- "whatsapp:build": "edgymeow build","build": "node scripts/build.js","clean": "node scripts/clean.js","stop": "node scripts/stop.js",@@ -104,7 +99,7 @@"rimraf": "^6.0.1","temporal-server": "^0.0.10","agent-browser": "latest",- "edgymeow": "0.0.18"+ "edgymeow": "0.0.20"},"pnpm": {"peerDependencyRules": {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 46b616a6..a30a225a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -18,8 +18,8 @@ importers:specifier: ^7.0.3version: 7.0.3edgymeow:- specifier: 0.0.18- version: 0.0.18+ specifier: 0.0.20+ version: 0.0.20rimraf:specifier: ^6.0.1version: 6.1.2@@ -3548,8 +3548,8 @@ packages:resolution: {integrity: sha512-wG99Zcfcys9fZux7Cft8BAX/YrOJLJSZ3jyYPfhZHqN2E+Ffx+QXBDsv3gubEgPtV6dTzJMSQUwk1H98/t/0wQ==}engines: {bun: '>=1', deno: '>=2', node: '>=16'}- resolution: {integrity: sha512-+iWozBpK7zOdOqvlFK9AaWKENzcaLdMzSOnivKIg5ynCIBMxUlUoTnGlwt6m8HpG4d30iI3OWA9jtyO4lBlS/A==}+ resolution: {integrity: sha512-c/3VgIzWAvZa0ffBFdKDwmM0w3zCyGSHILiXDnW6XELWtxFJ/aONAN+xoDzS38hTRKDGTZ1cDRt29Wyi4Vqv5A==}engines: {node: '>=18.0.0'}hasBin: true@@ -10347,7 +10347,7 @@ snapshots:'@noble/curves': 1.9.7'@noble/hashes': 1.8.0dependencies:chalk: 5.6.2commander: 11.1.0diff --git a/scripts/build.js b/scripts/build.jsindex 61bc0f57..ed4a1f43 100755--- a/scripts/build.js+++ b/scripts/build.js@@ -192,12 +192,16 @@ try {console.log(' Warning: Playwright browser install failed. JS-rendered web scraping will be unavailable.');}- // Step 5: Verify WhatsApp RPC package (non-fatal)- console.log('[5/5] Verifying WhatsApp RPC...');- try {- run('edgymeow status', ROOT);- } catch {- console.log(' Warning: edgymeow not available. Use --skip-whatsapp when starting.');+ // Step 5: Verify edgymeow Go binary is installed (non-fatal). The Python+ // backend supervises it lazily via nodes/whatsapp/_runtime.py, so we just+ // confirm pnpm fetched the package.+ console.log('[5/5] Verifying edgymeow binary...');+ const edgymeowBin = resolve(ROOT, 'node_modules', 'edgymeow', 'bin',+ process.platform === 'win32' ? 'edgymeow-server.exe' : 'edgymeow-server');+ if (existsSync(edgymeowBin)) {+ console.log(` Binary present: ${edgymeowBin}`);+ } else {+ console.log(' Warning: edgymeow binary not found. Set WHATSAPP_RUNTIME_ENABLED=false to disable.');}console.log('\nBuild complete.');diff --git a/scripts/dev.js b/scripts/dev.jsindex 54c8254f..71762e7e 100644--- a/scripts/dev.js+++ b/scripts/dev.js@@ -2,7 +2,10 @@/*** Development server for MachinaOS.* Vite HMR, uvicorn hot-reload, full log output.- * Usage: machina dev [--daemon] [--skip-whatsapp]+ * Usage: machina dev [--daemon]+ *+ * WhatsApp's edgymeow Go binary is supervised by the Python backend+ * (see server/nodes/whatsapp/_runtime.py) — no separate npm script.*/import { spawn } from 'child_process';import { existsSync, rmSync } from 'fs';@@ -29,7 +32,6 @@ installPerfMeasureLogger(log);// Parse command line argumentsconst args = process.argv.slice(2);const isDaemonMode = args.includes('--daemon');-const skipWhatsApp = args.includes('--skip-whatsapp');async function main() {// Check if build has been run@@ -48,7 +50,6 @@ async function main() {log(`Mode: ${isDaemonMode ? 'Daemon (uvicorn)' : 'Development (uvicorn)'}`);log(`Ports: ${config.allPorts.join(', ')}`);log(`Temporal: enabled`);- log(`WhatsApp: ${skipWhatsApp ? 'skipped' : 'enabled'}`);// Create .env if not existsif (ensureEnvFile()) {@@ -93,7 +94,6 @@ async function main() {services.push('"pnpm run client:start"');}services.push(isDaemonMode ? '"pnpm run python:daemon"' : '"pnpm run python:start"');- if (!skipWhatsApp) services.push('"pnpm run whatsapp:api"');services.push('"pnpm run temporal:start"');// Worker runs embedded in the backend (main.py TemporalWorkerManager)@@ -118,9 +118,6 @@ async function main() {{ name: 'Client', port: config.clientPort },{ name: 'Backend', port: config.backendPort },];- if (!skipWhatsApp) {- readyTargets.push({ name: 'WhatsApp', port: config.ports.whatsapp });- }readyTargets.push({ name: 'Temporal', port: config.ports.temporal });Promise.all(diff --git a/scripts/start.js b/scripts/start.jsindex c414d4a0..dd38d8d7 100755--- a/scripts/start.js+++ b/scripts/start.js@@ -2,7 +2,10 @@/*** Production start script for MachinaOS.* Clean output by default, --verbose for full logs.- * Usage: machina start [--verbose|-v] [--skip-whatsapp]+ * Usage: machina start [--verbose|-v]+ *+ * WhatsApp's edgymeow Go binary is supervised by the Python backend+ * (see server/nodes/whatsapp/_runtime.py) — no separate npm script.*/import { spawn, execSync } from 'child_process';import { existsSync, readFileSync } from 'fs';@@ -29,7 +32,6 @@ installPerfMeasureLogger(log);const args = process.argv.slice(2);const isVerbose = args.includes('--verbose') || args.includes('-v');-const skipWhatsApp = args.includes('--skip-whatsapp');function getVersion() {try {@@ -107,11 +109,13 @@ async function main() {}log('Ports ready');- // Services: static client, backend (uvicorn), whatsapp, temporal+ // Services: static client, backend (uvicorn), temporal.+ // WhatsApp's edgymeow Go binary is spawned lazily by the Python backend+ // (see server/nodes/whatsapp/_runtime.py) so the session DB lives under+ // data_dir. Disable via WHATSAPP_RUNTIME_ENABLED=false in .env.const services = [];services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);services.push((isWindows || isWSL) ? '"pnpm run python:start"' : '"pnpm run python:daemon"');- if (!skipWhatsApp) services.push('"pnpm run whatsapp:api"');if (!temporalRunning) services.push('"pnpm run temporal:start"');// Worker runs embedded in the backend (main.py TemporalWorkerManager)@@ -123,9 +127,6 @@ async function main() {{ name: 'Client', port: config.clientPort },{ name: 'Backend', port: config.backendPort },];- if (!skipWhatsApp) {- readyTargets.push({ name: 'WhatsApp', port: config.ports.whatsapp });- }if (!temporalRunning) {readyTargets.push({ name: 'Temporal', port: config.ports.temporal });}@@ -172,7 +173,6 @@ async function main() {console.log(` Use --verbose for full logs\n`);const serviceNames = ['client', 'server'];- if (!skipWhatsApp) serviceNames.push('whatsapp');if (!temporalRunning) serviceNames.push('temporal');const proc = spawn('pnpm', [diff --git a/server/core/config.py b/server/core/config.pyindex 3be10076..97699460 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -133,6 +133,16 @@ class Settings(BaseSettings):# Workspace base -- relative to data_dir unless absoluteworkspace_base_dir: str = Field(default="workspaces", env="WORKSPACE_BASE_DIR")+ # WhatsApp runtime (edgymeow Go binary supervised by the backend so the+ # session DB lives under data_dir, surviving pnpm install / version bumps)+ whatsapp_runtime_enabled: bool = Field(default=True, env="WHATSAPP_RUNTIME_ENABLED")+ whatsapp_data_subdir: str = Field(default="whatsapp", env="WHATSAPP_DATA_SUBDIR")+ whatsapp_port: int = Field(default=9400, env="WHATSAPP_RPC_PORT", ge=1024, le=65535)+ whatsapp_binary_path: Optional[str] = Field(default=None, env="WHATSAPP_BINARY_PATH")+ # `localhost` is the only bind that Windows Firewall's loopback exception+ # silently allows. Override to "0.0.0.0" for container deployments.+ whatsapp_bind_host: str = Field(default="localhost", env="WHATSAPP_BIND_HOST")+# Compaction Configurationcompaction_enabled: bool = Field(default=True, env="COMPACTION_ENABLED")compaction_threshold: int = Field(default=100000, env="COMPACTION_THRESHOLD", ge=10000)diff --git a/server/main.py b/server/main.pyindex 64d70a59..980eb8d4 100644--- a/server/main.py+++ b/server/main.py@@ -345,6 +345,12 @@ async def lifespan(app: FastAPI):from services.process_service import shutdown_process_serviceawait shutdown_process_service()+ # Stop every plugin supervisor that registered itself via+ # services._supervisor.register_supervisor() (currently: WhatsApp;+ # other plugins migrate in PR 2).+ from services._supervisor import shutdown_all_supervisors+ await shutdown_all_supervisors()+# Stop cleanup serviceif cleanup_service is not None:await cleanup_service.stop()diff --git a/server/nodes/whatsapp/__init__.py b/server/nodes/whatsapp/__init__.pyindex 201cdf1b..db64d555 100644--- a/server/nodes/whatsapp/__init__.py+++ b/server/nodes/whatsapp/__init__.py@@ -1 +1,24 @@-"""Plugins for the 'whatsapp' palette group. See ../__init__.py for the package layout."""+"""Plugins for the 'whatsapp' palette group.++Public surface:+ WhatsAppRuntime - edgymeow Go binary supervisor+ get_whatsapp_runtime() - singleton accessor (lazy-init via classmethod)++The runtime self-registers with ``services._supervisor.registry`` on+package import, so ``services._supervisor.shutdown_all_supervisors()``+called from the FastAPI lifespan will tear it down with all other+plugin supervisors. No per-plugin lifespan hooks needed.+"""++from services._supervisor import register_supervisor++from ._runtime import WhatsAppRuntime, get_whatsapp_runtime++# Self-registration: ensures shutdown_all_supervisors() reaches us.+# get_instance() constructs the singleton once (lazy in spawn, not here).+register_supervisor(WhatsAppRuntime.get_instance())++__all__ = [+ "WhatsAppRuntime",+ "get_whatsapp_runtime",+]diff --git a/server/nodes/whatsapp/_runtime.py b/server/nodes/whatsapp/_runtime.pynew file mode 100644index 00000000..a3322938--- /dev/null+++ b/server/nodes/whatsapp/_runtime.py@@ -0,0 +1,116 @@+"""WhatsApp runtime — supervises the edgymeow Go binary.++Spawns the binary with cwd inside the project (``<data_dir>/whatsapp``)+so the SQLite session DB lives next to ``credentials.db`` and survives+``pnpm install``, version bumps, and worktree switches. Lazy-init from+``services.whatsapp_service.get_client()``; teardown from FastAPI lifespan.++Subclasses :class:`BaseProcessSupervisor` for spawning, tree-kill, status+snapshots, restart policy, and the singleton ``get_instance()`` accessor.+Plugin-specific surface here is just binary discovery + config patching.+"""++from __future__ import annotations++import os+import sys+from pathlib import Path++import yaml++from services._supervisor import BaseProcessSupervisor++_PROJECT_ROOT = Path(__file__).resolve().parents[3]+++class WhatsAppRuntime(BaseProcessSupervisor):+ name = "WhatsApp"++ # Inherit stdio so logrus output (with colors) lands directly in the+ # backend console — no custom forwarder needed.+ pipe_streams = False+ terminate_grace_seconds = 5.0+ graceful_shutdown = False++ def __init__(self, settings=None) -> None:+ super().__init__()+ if settings is None:+ from core.config import Settings+ settings = Settings()+ self.settings = settings++ # ---- public read-only properties -------------------------------------++ @property+ def data_root(self) -> Path:+ sub = getattr(self.settings, "whatsapp_data_subdir", "whatsapp")+ base = Path(self.settings.data_dir)+ if not base.is_absolute():+ base = _PROJECT_ROOT / "server" / base+ return (base / sub).resolve()++ @property+ def port(self) -> int:+ return int(getattr(self.settings, "whatsapp_port", 9400))++ @property+ def bind_host(self) -> str:+ # `localhost` is the only bind that Windows Firewall's loopback+ # exception silently allows; 127.0.0.1 / 0.0.0.0 trigger Defender+ # prompts and TLS interception that surfaces as a misleading+ # `Client outdated (405)`. See aarol.dev/posts/go-windows-firewall.+ return getattr(self.settings, "whatsapp_bind_host", "localhost")++ @property+ def _package_dir(self) -> Path:+ return (_PROJECT_ROOT / "node_modules" / "edgymeow").resolve()++ # ---- BaseProcessSupervisor overrides ---------------------------------++ def binary_path(self) -> Path:+ override = getattr(self.settings, "whatsapp_binary_path", None)+ if override:+ return Path(override).resolve()+ name = "edgymeow-server.exe" if sys.platform == "win32" else "edgymeow-server"+ # pnpm symlinks node_modules/edgymeow -> .pnpm/edgymeow@<v>/.../edgymeow+ return self._package_dir / "bin" / name++ def argv(self) -> list[str]:+ return [str(self.binary_path())]++ def cwd(self) -> Path:+ return self.data_root++ def env(self) -> dict[str, str]:+ return {**os.environ, "WA_SERVER_PORT": str(self.port)}++ async def _pre_spawn(self) -> None:+ if not getattr(self.settings, "whatsapp_runtime_enabled", True):+ raise RuntimeError("WhatsApp runtime disabled via WHATSAPP_RUNTIME_ENABLED")+ self._write_config()++ def _extra_status(self) -> dict:+ base = super()._extra_status()+ return {**base, "port": self.port, "data_root": str(self.data_root)}++ # ---- private helpers -------------------------------------------------++ def _write_config(self) -> None:+ for sub in ("configs", "data"):+ (self.data_root / sub).mkdir(parents=True, exist_ok=True)+ # Read the package's bundled config and patch only the fields we+ # need to override. Keeps Python free of any YAML structure that+ # could drift from upstream.+ bundled = self._package_dir / "configs" / "config.yaml"+ config = yaml.safe_load(bundled.read_text(encoding="utf-8")) or {}+ config.setdefault("server", {})+ config["server"]["port"] = self.port+ config["server"]["host"] = self.bind_host+ (self.data_root / "configs" / "config.yaml").write_text(+ yaml.safe_dump(config, sort_keys=False), encoding="utf-8",+ )+++def get_whatsapp_runtime() -> WhatsAppRuntime:+ """Return the WhatsApp runtime singleton."""+ return WhatsAppRuntime.get_instance()diff --git a/server/services/whatsapp_service.py b/server/services/whatsapp_service.pyindex cedcefaf..95928987 100644--- a/server/services/whatsapp_service.py+++ b/server/services/whatsapp_service.py@@ -301,6 +301,17 @@ async def reset_client():async def get_client(force_reconnect: bool = False) -> RPCClient:"""Get or create RPC client. Use force_reconnect=True to ensure fresh connection."""global _client+ # Lazy-spawn the edgymeow binary on first use so its session DB lives+ # under <data_dir>/whatsapp/ instead of the pnpm package directory.+ # Idempotent: no-op if already running or disabled via settings.+ from nodes.whatsapp import get_whatsapp_runtime+ try:+ # `start()` is idempotent (BaseSupervisor takes a lock and no-ops+ # if already running) so calling it from every get_client() is safe.+ await get_whatsapp_runtime().start()+ except Exception as e:+ logger.warning(f"[WhatsApp RPC] Runtime start failed (will try connecting anyway): {e}")+async with _lock:# Force reconnect if requested or if client is staleif force_reconnect and _client: