Skip to content

Personal AI, On Personal Devices

Python

feat: merge channel gateway from PR #78 — ChannelBridge, webhooks, sessions, auth

Jon Saad-Falcon17de84b9e6ea
diff --git a/pyproject.toml b/pyproject.toml
index 67e820eb..bc51a610 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -82,6 +82,7 @@ channel-rocketchat = ["rocketchat-API>=1.30"]
channel-zulip = ["zulip>=0.9"]
channel-twitch = ["twitchio>=2.6"]
channel-nostr = ["pynostr>=0.6"]
+channel-twilio = ["twilio>=9.0"]
browser = ["playwright>=1.40"]
media = ["openai>=1.30"]
pdf = ["pdfplumber>=0.10"]
diff --git a/src/openjarvis/channels/__init__.py b/src/openjarvis/channels/__init__.py
index df908166..fb52ce90 100644
--- a/src/openjarvis/channels/__init__.py
+++ b/src/openjarvis/channels/__init__.py
@@ -38,6 +38,7 @@ _CHANNEL_MODULES = [
"zulip_channel",
"twitch_channel",
"nostr_channel",
+ "twilio_sms",
]
for _mod in _CHANNEL_MODULES:
diff --git a/src/openjarvis/channels/twilio_sms.py b/src/openjarvis/channels/twilio_sms.py
new file mode 100644
index 00000000..97281573
--- /dev/null
+++ b/src/openjarvis/channels/twilio_sms.py
@@ -0,0 +1,150 @@
+"""Twilio SMS channel for sending and receiving text messages."""
+
+from __future__ import annotations
+
+import logging
+import os
+from typing import Any, Dict, List, Optional
+
+from openjarvis.channels._stubs import (
+ BaseChannel,
+ ChannelHandler,
+ ChannelMessage,
+ ChannelStatus,
+)
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.core.registry import ChannelRegistry
+
+logger = logging.getLogger(__name__)
+
+
+def _create_twilio_client( # noqa: ANN201
+ account_sid: str, auth_token: str
+):
+ from twilio.rest import Client
+
+ return Client(account_sid, auth_token)
+
+
+class TwilioSMSChannel(BaseChannel):
+ """Send and receive SMS via Twilio.
+
+ Sending uses the Twilio REST API. Receiving is handled by
+ the ``/webhooks/twilio`` FastAPI endpoint which calls
+ registered handlers.
+ """
+
+ channel_id = "twilio"
+
+ def __init__(
+ self,
+ *,
+ account_sid: str = "",
+ auth_token: str = "",
+ phone_number: str = "",
+ bus: Optional[EventBus] = None,
+ ) -> None:
+ self._account_sid = account_sid or os.environ.get(
+ "TWILIO_ACCOUNT_SID", ""
+ )
+ self._auth_token = auth_token or os.environ.get(
+ "TWILIO_AUTH_TOKEN", ""
+ )
+ self._phone_number = phone_number or os.environ.get(
+ "TWILIO_PHONE_NUMBER", ""
+ )
+ self._bus = bus
+ self._client: Any = None
+ self._handlers: List[ChannelHandler] = []
+ self._status = ChannelStatus.DISCONNECTED
+
+ def connect(self) -> None:
+ try:
+ self._client = _create_twilio_client(
+ self._account_sid, self._auth_token
+ )
+ self._status = ChannelStatus.CONNECTED
+ except Exception:
+ logger.exception("Failed to create Twilio client")
+ self._status = ChannelStatus.ERROR
+
+ def disconnect(self) -> None:
+ self._client = None
+ self._status = ChannelStatus.DISCONNECTED
+
+ def send(
+ self,
+ channel: str,
+ content: str,
+ *,
+ conversation_id: str = "",
+ metadata: Dict[str, Any] | None = None,
+ ) -> bool:
+ if not self._client:
+ logger.error("Twilio client not connected")
+ return False
+ try:
+ self._client.messages.create(
+ body=content,
+ from_=self._phone_number,
+ to=channel,
+ )
+ self._publish_sent(channel, content, conversation_id)
+ return True
+ except Exception:
+ logger.exception(
+ "Failed to send SMS to %s", channel
+ )
+ return False
+
+ def status(self) -> ChannelStatus:
+ return self._status
+
+ def list_channels(self) -> List[str]:
+ return ["twilio"]
+
+ def on_message(self, handler: ChannelHandler) -> None:
+ self._handlers.append(handler)
+
+ def handle_webhook(
+ self,
+ from_number: str,
+ body: str,
+ message_sid: str = "",
+ ) -> None:
+ """Called by the webhook route for incoming SMS."""
+ msg = ChannelMessage(
+ channel="twilio",
+ sender=from_number,
+ content=body,
+ message_id=message_sid,
+ )
+ for handler in self._handlers:
+ handler(msg)
+ if self._bus:
+ self._bus.publish(
+ EventType.CHANNEL_MESSAGE_RECEIVED,
+ {
+ "channel": "twilio",
+ "sender": from_number,
+ "content": body,
+ "message_id": message_sid,
+ },
+ )
+
+ def _publish_sent(
+ self,
+ channel: str,
+ content: str,
+ conversation_id: str,
+ ) -> None:
+ if self._bus:
+ self._bus.publish(
+ EventType.CHANNEL_MESSAGE_SENT,
+ {
+ "channel": "twilio",
+ "content": content,
+ "conversation_id": conversation_id,
+ },
+ )
diff --git a/src/openjarvis/cli/__init__.py b/src/openjarvis/cli/__init__.py
index 419e45e3..df3e7be2 100644
--- a/src/openjarvis/cli/__init__.py
+++ b/src/openjarvis/cli/__init__.py
@@ -95,6 +95,21 @@ cli.add_command(connect, "connect")
cli.add_command(deep_research_setup, "deep-research-setup")
cli.add_command(deep_research_setup, "research")
+# Gateway CLI commands (lazy import to avoid pulling starlette)
+try:
+ from openjarvis.cli.auth_cmd import auth
+
+ cli.add_command(auth, "auth")
+except ImportError:
+ pass
+
+try:
+ from openjarvis.cli.tunnel_cmd import tunnel
+
+ cli.add_command(tunnel, "tunnel")
+except ImportError:
+ pass
+
def main() -> None:
"""Entry point registered as ``jarvis`` console script."""
diff --git a/src/openjarvis/cli/auth_cmd.py b/src/openjarvis/cli/auth_cmd.py
new file mode 100644
index 00000000..c4a5e5ea
--- /dev/null
+++ b/src/openjarvis/cli/auth_cmd.py
@@ -0,0 +1,78 @@
+"""CLI commands for API key management."""
+
+from __future__ import annotations
+
+import os
+import re
+import stat
+
+import click
+
+from openjarvis.core.config import (
+ DEFAULT_CONFIG_DIR,
+ DEFAULT_CONFIG_PATH,
+)
+from openjarvis.server.auth_middleware import generate_api_key
+
+
+def auth() -> None:
+ """Manage API authentication keys."""
+
+
[email protected]("create-key")
+def create_key() -> None:
+ """Generate a new API key and store it in config."""
+ key = generate_api_key()
+ config_path = DEFAULT_CONFIG_PATH
+
+ # Ensure config directory exists
+ DEFAULT_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
+
+ # Read existing config or start fresh
+ if config_path.exists():
+ content = config_path.read_text()
+ else:
+ content = ""
+
+ # Update or add [server.auth] section
+ if "[server.auth]" in content:
+ content = re.sub(
+ r'(api_key\s*=\s*)"[^"]*"',
+ f'\\1"{key}"',
+ content,
+ )
+ else:
+ content += f'\n[server.auth]\napi_key = "{key}"\n'
+
+ config_path.write_text(content)
+ os.chmod(
+ config_path, stat.S_IRUSR | stat.S_IWUSR
+ ) # 0600
+
+ click.echo(f"API key generated: {key}")
+ click.echo(f"Stored in: {config_path}")
+ click.echo(
+ "File permissions set to 0600 "
+ "(user-only read/write)."
+ )
+
+
[email protected]("revoke-key")
+def revoke_key() -> None:
+ """Revoke the current API key."""
+ config_path = DEFAULT_CONFIG_PATH
+ if not config_path.exists():
+ click.echo("No config file found.")
+ return
+
+ content = config_path.read_text()
+ if "api_key" not in content:
+ click.echo("No API key found in config.")
+ return
+
+ content = re.sub(
+ r'api_key\s*=\s*"[^"]*"', 'api_key = ""', content
+ )
+ config_path.write_text(content)
+ click.echo("API key revoked.")
diff --git a/src/openjarvis/cli/serve.py b/src/openjarvis/cli/serve.py
index bfd819a6..9952dfdd 100644
--- a/src/openjarvis/cli/serve.py
+++ b/src/openjarvis/cli/serve.py
@@ -316,6 +316,68 @@ def serve(
except Exception as exc:
logger.debug("Memory backend init failed: %s", exc)
+ # --- Channel Gateway: API key, sessions, ChannelBridge ---
+ import os as _os
+
+ api_key = _os.environ.get("OPENJARVIS_API_KEY", "")
+ if not api_key:
+ try:
+ import tomllib
+ _cfg_path = str(
+ __import__("pathlib").Path.home()
+ / ".openjarvis" / "config.toml"
+ )
+ with open(_cfg_path, "rb") as _f:
+ _raw = tomllib.load(_f)
+ api_key = (
+ _raw.get("server", {})
+ .get("auth", {})
+ .get("api_key", "")
+ )
+ except (FileNotFoundError, ImportError):
+ pass
+
+ webhook_config = {
+ "twilio_auth_token": _os.environ.get(
+ "TWILIO_AUTH_TOKEN", ""
+ ),
+ "bluebubbles_password": _os.environ.get(
+ "BLUEBUBBLES_PASSWORD", ""
+ ),
+ "whatsapp_verify_token": _os.environ.get(
+ "WHATSAPP_VERIFY_TOKEN", ""
+ ),
+ "whatsapp_app_secret": _os.environ.get(
+ "WHATSAPP_APP_SECRET", ""
+ ),
+ }
+
+ # Wrap existing channel in ChannelBridge orchestrator
+ if channel_bridge is not None:
+ try:
+ from openjarvis.server.channel_bridge import (
+ ChannelBridge,
+ )
+ from openjarvis.server.session_store import (
+ SessionStore,
+ )
+
+ session_store = SessionStore()
+ channels = {
+ channel_bridge.channel_id: channel_bridge
+ }
+ channel_bridge = ChannelBridge(
+ channels=channels,
+ session_store=session_store,
+ bus=bus,
+ system=None,
+ agent_manager=agent_manager,
+ )
+ except Exception as exc:
+ logger.debug(
+ "ChannelBridge init skipped: %s", exc
+ )
+
app = create_app(
engine, model_name, agent=agent, bus=bus,
engine_name=engine_name, agent_name=agent_key or "",
@@ -324,6 +386,8 @@ def serve(
speech_backend=speech_backend,
agent_manager=agent_manager,
agent_scheduler=agent_scheduler,
+ api_key=api_key,
+ webhook_config=webhook_config,
)
console.print(
diff --git a/src/openjarvis/cli/tunnel_cmd.py b/src/openjarvis/cli/tunnel_cmd.py
new file mode 100644
index 00000000..a3047283
--- /dev/null
+++ b/src/openjarvis/cli/tunnel_cmd.py
@@ -0,0 +1,79 @@
+"""CLI commands for Cloudflare Tunnel management."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+
+import click
+
+from openjarvis.core.config import DEFAULT_CONFIG_PATH
+
+
[email protected]("tunnel", invoke_without_command=True)
+ "--port", default=8000, help="Local port to tunnel."
+)
+def tunnel(ctx: click.Context, port: int) -> None:
+ """Start a Cloudflare tunnel or manage config."""
+ if ctx.invoked_subcommand is not None:
+ return
+ # Default behavior: start the tunnel
+ if not shutil.which("cloudflared"):
+ click.echo("Error: cloudflared is not installed.")
+ click.echo(
+ "Install it from: "
+ "https://developers.cloudflare.com/"
+ "cloudflare-one/connections/"
+ "connect-networks/downloads/"
+ )
+ sys.exit(1)
+
+ click.echo(
+ f"Starting Cloudflare tunnel "
+ f"to localhost:{port}..."
+ )
+ click.echo("Press Ctrl+C to stop.\n")
+
+ try:
+ subprocess.run(
+ [
+ "cloudflared",
+ "tunnel",
+ "--url",
+ f"http://localhost:{port}",
+ ],
+ check=True,
+ )
+ except KeyboardInterrupt:
+ click.echo("\nTunnel stopped.")
+ except subprocess.CalledProcessError as e:
+ click.echo(f"Tunnel failed: {e}")
+ sys.exit(1)
+
+
+def status() -> None:
+ """Show current tunnel configuration."""
+ config_path = DEFAULT_CONFIG_PATH
+ if not config_path.exists():
+ click.echo("No config file found.")
+ return
+
+ content = config_path.read_text()
+ if "public_url" in content:
+ for line in content.splitlines():
+ if "public_url" in line:
+ click.echo(
+ "Configured tunnel URL: "
+ f"{line.split('=', 1)[1].strip()}"
+ )
+ return
+ click.echo("No tunnel URL configured.")
+
+ if shutil.which("cloudflared"):
+ click.echo("cloudflared: installed")
+ else:
+ click.echo("cloudflared: not installed")
diff --git a/src/openjarvis/server/app.py b/src/openjarvis/server/app.py
index 467ed354..7ee7a20a 100644
--- a/src/openjarvis/server/app.py
+++ b/src/openjarvis/server/app.py
@@ -61,6 +61,8 @@ def create_app(
speech_backend=None,
agent_manager=None,
agent_scheduler=None,
+ api_key: str = "",
+ webhook_config: dict | None = None,
) -> FastAPI:
"""Create and configure the FastAPI application.
@@ -139,6 +141,43 @@ def create_app(
except Exception as exc:
logger.debug("Security middleware init skipped: %s", exc)
+ # API key authentication middleware
+ if api_key:
+ try:
+ from openjarvis.server.auth_middleware import AuthMiddleware
+
+ app.add_middleware(AuthMiddleware, api_key=api_key)
+ except Exception as exc:
+ logger.debug("Auth middleware init skipped: %s", exc)
+
+ # Mount webhook routes if bridge and config provided
+ if channel_bridge and webhook_config:
+ try:
+ from openjarvis.server.webhook_routes import (
+ create_webhook_router,
+ )
+
+ webhook_router = create_webhook_router(
+ bridge=channel_bridge,
+ twilio_auth_token=webhook_config.get(
+ "twilio_auth_token", ""
+ ),
+ bluebubbles_password=webhook_config.get(
+ "bluebubbles_password", ""
+ ),
+ whatsapp_verify_token=webhook_config.get(
+ "whatsapp_verify_token", ""
+ ),
+ whatsapp_app_secret=webhook_config.get(
+ "whatsapp_app_secret", ""
+ ),
+ )
+ app.include_router(webhook_router)
+ except Exception as exc:
+ logger.debug(
+ "Webhook routes init skipped: %s", exc
+ )
+
# Serve static frontend assets if the static/ directory exists
static_dir = pathlib.Path(__file__).parent / "static"
if static_dir.is_dir():
diff --git a/src/openjarvis/server/auth_middleware.py b/src/openjarvis/server/auth_middleware.py
new file mode 100644
index 00000000..d004c293
--- /dev/null
+++ b/src/openjarvis/server/auth_middleware.py
@@ -0,0 +1,65 @@
+"""API key authentication middleware for the OpenJarvis server."""
+
+from __future__ import annotations
+
+import logging
+import os
+import secrets
+
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.requests import Request
+from starlette.responses import JSONResponse
+
+logger = logging.getLogger(__name__)
+
+# Paths exempt from API key auth
+_EXEMPT_PREFIXES = (
+ "/health",
+ "/webhooks/",
+ "/docs",
+ "/openapi.json",
+)
+
+
+class AuthMiddleware(BaseHTTPMiddleware):
+ """Validates ``Authorization: Bearer <key>`` on ``/v1/*`` routes.
+
+ Webhook routes and health checks are exempt — they use
+ per-channel signature verification instead.
+ """
+
+ def __init__(self, app, api_key: str = "") -> None: # noqa: ANN001
+ super().__init__(app)
+ self._api_key = api_key or os.environ.get(
+ "OPENJARVIS_API_KEY", ""
+ )
+
+ async def dispatch(self, request: Request, call_next): # noqa: ANN001
+ if self._api_key and not self._is_exempt(
+ request.url.path
+ ):
+ auth = request.headers.get("Authorization", "")
+ if not auth:
+ return JSONResponse(
+ {"detail": "Missing Authorization header"},
+ status_code=401,
+ )
+ scheme, _, token = auth.partition(" ")
+ if (
+ scheme.lower() != "bearer"
+ or token != self._api_key
+ ):
+ return JSONResponse(
+ {"detail": "Invalid API key"},
+ status_code=401,
+ )
+ return await call_next(request)
+
+ @staticmethod
+ def _is_exempt(path: str) -> bool:
+ return any(path.startswith(p) for p in _EXEMPT_PREFIXES)
+
+
+def generate_api_key() -> str:
+ """Generate a new API key with ``oj_sk_`` prefix."""
+ return f"oj_sk_{secrets.token_urlsafe(32)}"
diff --git a/src/openjarvis/server/channel_bridge.py b/src/openjarvis/server/channel_bridge.py
new file mode 100644
index 00000000..735018db
--- /dev/null
+++ b/src/openjarvis/server/channel_bridge.py
@@ -0,0 +1,399 @@
+"""ChannelBridge — unified orchestrator for multi-channel messaging."""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any, Dict, List, Optional
+
+from openjarvis.channels._stubs import BaseChannel, ChannelStatus
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.server.session_store import SessionStore
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_MAX_LENGTH = 4000
+_SMS_MAX_LENGTH = 1600
+
+_HELP_TEXT = """\
+Available commands:
+/agents — list running agents
+/agent <id> status — agent state and current task
+/agent <id> <message> — send a message to an agent
+/agent <id> pause — pause an agent
+/agent <id> resume — resume an agent
+/notify <channel> — set where to receive notifications
+/sessions — list your active sessions
+/more — get the rest of a truncated response
+/help — show this message\
+"""
+
+# Events the bridge subscribes to for notifications
+_NOTIFICATION_EVENTS = [
+ EventType.AGENT_TICK_END,
+ EventType.AGENT_TICK_ERROR,
+ EventType.AGENT_BUDGET_EXCEEDED,
+ EventType.SCHEDULER_TASK_END,
+]
+
+
+class ChannelBridge:
+ """Orchestrates incoming messages across multiple channel adapters.
+
+ Provides backward-compatible ``send()``/``status()``/``list_channels()``
+ so it can replace the old single-channel bridge in ``app.state``.
+ """
+
+ def __init__(
+ self,
+ channels: Dict[str, BaseChannel],
+ session_store: SessionStore,
+ bus: EventBus,
+ system: Any = None,
+ agent_manager: Any = None,
+ ) -> None:
+ self._channels = channels
+ self._session_store = session_store
+ self._bus = bus
+ self._system = system
+ self._agent_manager = agent_manager
+ self._notification_timestamps: Dict[str, float] = {}
+ self._subscribe_notifications()
+
+ # --------------------------------------------------------------
+ # Backward-compatible BaseChannel interface
+ # --------------------------------------------------------------
+
+ def connect(self) -> None:
+ for ch in self._channels.values():
+ ch.connect()
+
+ def disconnect(self) -> None:
+ for ch in self._channels.values():
+ ch.disconnect()
+
+ def list_channels(self) -> List[str]:
+ result: List[str] = []
+ for ch in self._channels.values():
+ result.extend(ch.list_channels())
+ return result
+
+ def status(self) -> ChannelStatus:
+ statuses = [ch.status() for ch in self._channels.values()]
+ if not statuses:
+ return ChannelStatus.DISCONNECTED
+ if any(s == ChannelStatus.CONNECTED for s in statuses):
+ return ChannelStatus.CONNECTED
+ if all(s == ChannelStatus.ERROR for s in statuses):
+ return ChannelStatus.ERROR
+ return ChannelStatus.DISCONNECTED
+
+ def send(
+ self,
+ channel: str,
+ content: str,
+ *,
+ conversation_id: str = "",
+ metadata: Dict[str, Any] | None = None,
+ ) -> bool:
+ for ch in self._channels.values():
+ if channel in ch.list_channels():
+ return ch.send(
+ channel,
+ content,
+ conversation_id=conversation_id,
+ metadata=metadata,
+ )
+ logger.warning("No adapter found for channel %s", channel)
+ return False
+
+ # --------------------------------------------------------------
+ # Incoming message handling
+ # --------------------------------------------------------------
+
+ def handle_incoming(
+ self,
+ sender_id: str,
+ content: str,
+ channel_type: str,
+ metadata: Optional[Dict[str, Any]] = None,
+ max_length: int = _DEFAULT_MAX_LENGTH,
+ ) -> str:
+ self._session_store.get_or_create(sender_id, channel_type)
+
+ # Command routing
+ stripped = content.strip()
+ if stripped.startswith("/"):
+ result = self._handle_command(
+ sender_id, stripped, channel_type
+ )
+ if result is not None:
+ return result
+
+ # Regular chat — route to JarvisSystem.ask()
+ return self._handle_chat(
+ sender_id, stripped, channel_type, max_length
+ )
+
+ # --------------------------------------------------------------
+ # Command parsing
+ # --------------------------------------------------------------
+
+ def _handle_command(
+ self,
+ sender_id: str,
+ content: str,
+ channel_type: str,
+ ) -> Optional[str]:
+ parts = content.split(None, 2)
+ cmd = parts[0].lower()
+
+ if cmd == "/help":
+ return _HELP_TEXT
+
+ if cmd == "/more":
+ return self._handle_more(sender_id, channel_type)
+
+ if cmd == "/notify" and len(parts) >= 2:
+ pref = parts[1]
+ self._session_store.set_notification_preference(
+ sender_id, channel_type, pref
+ )
+ return f"Notifications will be sent to {pref}."
+
+ if cmd == "/sessions":
+ return self._handle_sessions(sender_id)
+
+ if cmd == "/agents":
+ return self._handle_agents_list()
+
+ if cmd == "/agent" and len(parts) >= 2:
+ agent_id = parts[1]
+ rest = parts[2] if len(parts) > 2 else "status"
+ return self._handle_agent_command(agent_id, rest)
+
+ # Unknown command — fall through to chat
+ return None
+
+ def _handle_more(
+ self, sender_id: str, channel_type: str
+ ) -> str:
+ session = self._session_store.get_or_create(
+ sender_id, channel_type
+ )
+ pending = session.get("pending_response")
+ if pending:
+ self._session_store.clear_pending_response(
+ sender_id, channel_type
+ )
+ return pending
+ return "No pending response."
+
+ def _handle_agents_list(self) -> str:
+ if not self._agent_manager:
+ return "No agent manager configured."
+ agents = self._agent_manager.list_agents()
+ if not agents:
+ return "No agents currently running."
+ lines = []
+ for a in agents:
+ name = a.get("name", a.get("agent_id", "unknown"))
+ status = a.get("status", "unknown")
+ lines.append(f" {name} — {status}")
+ return "Running agents:\n" + "\n".join(lines)
+
+ def _handle_agent_command(
+ self, agent_id: str, action: str
+ ) -> str:
+ if not self._agent_manager:
+ return "No agent manager configured."
+ action_lower = action.strip().lower()
+ if action_lower == "status":
+ state = self._agent_manager.get_agent(agent_id)
+ if state is None:
+ return f"Agent '{agent_id}' not found."
+ name = state.get("name", agent_id)
+ status = state.get("status", "unknown")
+ return f"Agent '{name}': {status}"
+ if action_lower == "pause":
+ self._agent_manager.pause_agent(agent_id)
+ return f"Agent '{agent_id}' paused."
+ if action_lower == "resume":
+ self._agent_manager.resume_agent(agent_id)
+ return f"Agent '{agent_id}' resumed."
+ # Treat as a message to the agent
+ result = self._agent_manager.send_message(agent_id, action)
+ return (
+ str(result)
+ if result
+ else f"Message sent to agent '{agent_id}'."
+ )
+
+ # --------------------------------------------------------------
+ # Chat handling
+ # --------------------------------------------------------------
+
+ def _handle_sessions(self, sender_id: str) -> str:
+ targets = self._session_store.get_notification_targets()
+ user_sessions = [
+ t for t in targets if t["sender_id"] == sender_id
+ ]
+ if not user_sessions:
+ return "No active sessions with notification preferences."
+ lines = []
+ for s in user_sessions:
+ lines.append(
+ f" {s['channel_type']} -> "
+ f"notifications: {s['preferred_notification_channel']}"
+ )
+ return "Your sessions:\n" + "\n".join(lines)
+
+ def _handle_chat(
+ self,
+ sender_id: str,
+ content: str,
+ channel_type: str,
+ max_length: int,
+ ) -> str:
+ self._session_store.append_message(
+ sender_id, channel_type, "user", content
+ )
+
+ # Build context from conversation history
+ session = self._session_store.get_or_create(
+ sender_id, channel_type
+ )
+ history = session.get("conversation_history", [])
+ context_lines = []
+ for msg in history[:-1]: # exclude the message we just appended
+ context_lines.append(
+ f"{msg['role']}: {msg['content']}"
+ )
+ context_str = "\n".join(context_lines)
+
+ query = content
+ if context_str:
+ query = (
+ f"Previous conversation:\n{context_str}\n\n"
+ f"Current message: {content}"
+ )
+
+ try:
+ result = self._system.ask(query)
+ response_text = result.get("content", str(result))
+ except Exception:
+ logger.exception("Error in JarvisSystem.ask()")
+ error_msg = (
+ "Sorry, I couldn't process that right now. "
+ "Try again in a moment."
+ )
+ self._session_store.append_message(
+ sender_id, channel_type, "assistant", error_msg
+ )
+ return error_msg
+
+ # Format and possibly truncate
+ formatted = self._format_response(
+ sender_id, channel_type, response_text, max_length
+ )
+ self._session_store.append_message(
+ sender_id, channel_type, "assistant", response_text
+ )
+ return formatted
+
+ def _format_response(
+ self,
+ sender_id: str,
+ channel_type: str,
+ response: str,
+ max_length: int,
+ ) -> str:
+ if len(response) <= max_length:
+ return response
+ # Truncate and store full response for /more retrieval
+ truncation_notice = (
+ "\n\n... (reply /more for full response)"
+ )
+ cut_at = max_length - len(truncation_notice)
+ truncated = response[:cut_at] + truncation_notice
+ self._session_store.set_pending_response(
+ sender_id, channel_type, response
+ )
+ return truncated
+
+ # --------------------------------------------------------------
+ # Notifications
+ # --------------------------------------------------------------
+
+ def _subscribe_notifications(self) -> None:
+ for event_type in _NOTIFICATION_EVENTS:
+ self._bus.subscribe(
+ event_type, self._on_notification_event
+ )
+
+ def _on_notification_event(self, event) -> None: # noqa: ANN001
+ event_key = str(event.event_type)
+ now = time.time()
+
+ # Rate limit: max 1 per event type per 5 minutes
+ last = self._notification_timestamps.get(event_key, 0)
+ if now - last < 300:
+ return
+ self._notification_timestamps[event_key] = now
+
+ message = self._format_notification(event)
+ if not message:
+ return
+
+ targets = self._session_store.get_notification_targets()
+ for target in targets:
+ pref_channel = target["preferred_notification_channel"]
+ sender_id = target["sender_id"]
+ self._send_notification(
+ pref_channel, sender_id, message
+ )
+
+ def _format_notification( # noqa: ANN201
+ self, event # noqa: ANN001
+ ) -> Optional[str]:
+ data = event.data or {}
+ name = data.get("agent_name", data.get("name", "unknown"))
+
+ if event.event_type == EventType.AGENT_TICK_END:
+ summary = data.get("summary", data.get("result", ""))
+ return (
+ f"Agent '{name}' finished: {summary}"
+ if summary
+ else None
+ )
+ if event.event_type == EventType.AGENT_TICK_ERROR:
+ error = data.get("error", "unknown error")
+ return f"Agent '{name}' error: {error}"
+ if event.event_type == EventType.AGENT_BUDGET_EXCEEDED:
+ return f"Agent '{name}' hit budget limit."
+ if event.event_type == EventType.SCHEDULER_TASK_END:
+ if data.get("success", True):
+ return f"Scheduled task '{name}' completed."
+ error = data.get("error", "unknown error")
+ return f"Scheduled task '{name}' failed: {error}"
+ return None
+
+ def _send_notification(
+ self,
+ channel_type: str,
+ sender_id: str,
+ message: str,
+ ) -> None:
+ ch = self._channels.get(channel_type)
+ if ch is None:
+ logger.warning(
+ "No adapter for notification channel %s",
+ channel_type,
+ )
+ return
+ try:
+ ch.send(sender_id, message)
+ except Exception:
+ logger.exception(
+ "Failed to send notification to %s", channel_type
+ )
diff --git a/src/openjarvis/server/session_store.py b/src/openjarvis/server/session_store.py
new file mode 100644
index 00000000..627e2345
--- /dev/null
+++ b/src/openjarvis/server/session_store.py
@@ -0,0 +1,189 @@
+"""SQLite-backed session store for channel conversations."""
+
+from __future__ import annotations
+
+import json
+import logging
+import sqlite3
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+logger = logging.getLogger(__name__)
+
+_MAX_HISTORY_TURNS = 20
+
+
+class SessionStore:
+ """Manages per-sender, per-channel conversation sessions.
+
+ Each session tracks conversation history, notification preferences,
+ and pending long responses for the ``/more`` command.
+ """
+
+ def __init__(self, db_path: str = "") -> None:
+ if not db_path:
+ db_path = str(Path.home() / ".openjarvis" / "sessions.db")
+ Path(db_path).parent.mkdir(parents=True, exist_ok=True)
+ self._db = sqlite3.connect(db_path, check_same_thread=False)
+ self._db.row_factory = sqlite3.Row
+ self._create_tables()
+
+ # ------------------------------------------------------------------
+ # Schema
+ # ------------------------------------------------------------------
+
+ def _create_tables(self) -> None:
+ self._db.executescript(
+ """\
+ CREATE TABLE IF NOT EXISTS channel_sessions (
+ sender_id TEXT NOT NULL,
+ channel_type TEXT NOT NULL,
+ conversation_history TEXT NOT NULL DEFAULT '[]',
+ preferred_notification_channel TEXT,
+ pending_response TEXT,
+ created_at TIMESTAMP DEFAULT (datetime('now')),
+ updated_at TIMESTAMP DEFAULT (datetime('now')),
+ PRIMARY KEY (sender_id, channel_type)
+ );
+ CREATE INDEX IF NOT EXISTS idx_sessions_updated_at
+ ON channel_sessions (updated_at);
+ """
+ )
+ self._db.commit()
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+
+ def get_or_create(
+ self, sender_id: str, channel_type: str
+ ) -> Dict[str, Any]:
+ row = self._db.execute(
+ "SELECT * FROM channel_sessions "
+ "WHERE sender_id = ? AND channel_type = ?",
+ (sender_id, channel_type),
+ ).fetchone()
+ if row is None:
+ self._db.execute(
+ "INSERT INTO channel_sessions "
+ "(sender_id, channel_type) VALUES (?, ?)",
+ (sender_id, channel_type),
+ )
+ self._db.commit()
+ return {
+ "sender_id": sender_id,
+ "channel_type": channel_type,
+ "conversation_history": [],
+ "preferred_notification_channel": None,
+ "pending_response": None,
+ }
+ return {
+ "sender_id": row["sender_id"],
+ "channel_type": row["channel_type"],
+ "conversation_history": json.loads(
+ row["conversation_history"]
+ ),
+ "preferred_notification_channel": row[
+ "preferred_notification_channel"
+ ],
+ "pending_response": row["pending_response"],
+ }
+
+ def append_message(
+ self,
+ sender_id: str,
+ channel_type: str,
+ role: str,
+ content: str,
+ ) -> None:
+ row = self._db.execute(
+ "SELECT conversation_history FROM channel_sessions "
+ "WHERE sender_id = ? AND channel_type = ?",
+ (sender_id, channel_type),
+ ).fetchone()
+ if row is None:
+ return
+ history: List[Dict[str, str]] = json.loads(
+ row["conversation_history"]
+ )
+ history.append({"role": role, "content": content})
+ if len(history) > _MAX_HISTORY_TURNS:
+ history = history[-_MAX_HISTORY_TURNS:]
+ self._db.execute(
+ "UPDATE channel_sessions "
+ "SET conversation_history = ?, "
+ "updated_at = datetime('now') "
+ "WHERE sender_id = ? AND channel_type = ?",
+ (json.dumps(history), sender_id, channel_type),
+ )
+ self._db.commit()
+
+ def set_notification_preference(
+ self,
+ sender_id: str,
+ channel_type: str,
+ preferred: str,
+ ) -> None:
+ self._db.execute(
+ "UPDATE channel_sessions "
+ "SET preferred_notification_channel = ?, "
+ "updated_at = datetime('now') "
+ "WHERE sender_id = ? AND channel_type = ?",
+ (preferred, sender_id, channel_type),
+ )
+ self._db.commit()
+
+ def set_pending_response(
+ self,
+ sender_id: str,
+ channel_type: str,
+ response: str,
+ ) -> None:
+ self._db.execute(
+ "UPDATE channel_sessions "
+ "SET pending_response = ?, "
+ "updated_at = datetime('now') "
+ "WHERE sender_id = ? AND channel_type = ?",
+ (response, sender_id, channel_type),
+ )
+ self._db.commit()
+
+ def clear_pending_response(
+ self, sender_id: str, channel_type: str
+ ) -> None:
+ self.set_pending_response(sender_id, channel_type, None)
+
+ def expire_sessions(self, max_age_hours: int = 24) -> int:
+ cur = self._db.execute(
+ "UPDATE channel_sessions "
+ "SET conversation_history = '[]', "
+ "pending_response = NULL "
+ "WHERE updated_at < datetime('now', ? || ' hours')",
+ (f"-{max_age_hours}",),
+ )
+ self._db.commit()
+ return cur.rowcount
+
+ def get_last_active_channel(
+ self, sender_id: str
+ ) -> Optional[str]:
+ row = self._db.execute(
+ "SELECT channel_type FROM channel_sessions "
+ "WHERE sender_id = ? "
+ "ORDER BY updated_at DESC LIMIT 1",
+ (sender_id,),
+ ).fetchone()
+ return row["channel_type"] if row else None
+
+ def get_notification_targets(self) -> List[Dict[str, str]]:
+ """Return all senders with a notification channel."""
+ rows = self._db.execute(
+ "SELECT sender_id, channel_type, "
+ "preferred_notification_channel "
+ "FROM channel_sessions "
+ "WHERE preferred_notification_channel IS NOT NULL"
+ ).fetchall()
+ return [dict(r) for r in rows]
+
+ def close(self) -> None:
+ self._db.close()
diff --git a/src/openjarvis/server/webhook_routes.py b/src/openjarvis/server/webhook_routes.py
new file mode 100644
index 00000000..ba869d1a
--- /dev/null
+++ b/src/openjarvis/server/webhook_routes.py
@@ -0,0 +1,212 @@
+"""Webhook endpoints for receiving messages from external platforms."""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import hmac
+import json
+import logging
+from typing import Any
+
+from fastapi import APIRouter, Request, Response
+from starlette.responses import PlainTextResponse
+
+logger = logging.getLogger(__name__)
+
+
+def _log_task_exception(task: asyncio.Task) -> None:
+ """Log exceptions from background message handling tasks."""
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ logger.error(
+ "Background message handling failed: %s",
+ exc,
+ exc_info=exc,
+ )
+
+
+def _validate_twilio_signature(
+ auth_token: str,
+ url: str,
+ params: dict,
+ signature: str,
+) -> bool:
+ """Validate Twilio webhook signature using the SDK."""
+ try:
+ from twilio.request_validator import RequestValidator
+
+ validator = RequestValidator(auth_token)
+ return validator.validate(url, params, signature)
+ except ImportError:
+ logger.warning(
+ "twilio SDK not installed — skipping signature validation"
+ )
+ return True
+
+
+def create_webhook_router(
+ bridge: Any,
+ twilio_auth_token: str = "",
+ bluebubbles_password: str = "",
+ whatsapp_verify_token: str = "",
+ whatsapp_app_secret: str = "",
+) -> APIRouter:
+ """Create a FastAPI router with webhook endpoints.
+
+ Args:
+ bridge: ChannelBridge instance for routing messages.
+ twilio_auth_token: Twilio auth token for signatures.
+ bluebubbles_password: BlueBubbles server password.
+ whatsapp_verify_token: WhatsApp verification token.
+ whatsapp_app_secret: WhatsApp app secret for HMAC.
+ """
+ router = APIRouter(
+ prefix="/webhooks", tags=["webhooks"]
+ )
+
+ # ----------------------------------------------------------
+ # Twilio SMS
+ # ----------------------------------------------------------
+
+ @router.post("/twilio")
+ async def twilio_incoming(request: Request) -> Response:
+ form = await request.form()
+ params = dict(form)
+ signature = request.headers.get(
+ "X-Twilio-Signature", ""
+ )
+ url = str(request.url)
+
+ if twilio_auth_token and not _validate_twilio_signature(
+ twilio_auth_token, url, params, signature
+ ):
+ return Response("Invalid signature", status_code=403)
+
+ from_number = params.get("From", "")
+ body = params.get("Body", "")
+
+ # Dispatch to background — return TwiML immediately
+ task = asyncio.create_task(
+ asyncio.to_thread(
+ bridge.handle_incoming,
+ from_number,
+ body,
+ "twilio",
+ max_length=1600,
+ )
+ )
+ task.add_done_callback(_log_task_exception)
+
+ return Response(
+ content="<Response></Response>",
+ media_type="application/xml",
+ )
+
+ # ----------------------------------------------------------
+ # BlueBubbles (iMessage)
+ # ----------------------------------------------------------
+
+ @router.post("/bluebubbles")
+ async def bluebubbles_incoming(
+ request: Request,
+ ) -> Response:
+ auth = request.headers.get("Authorization", "")
+ if bluebubbles_password and auth != bluebubbles_password:
+ return Response(
+ "Invalid password", status_code=403
+ )
+
+ payload = await request.json()
+ msg_type = payload.get("type", "")
+ if msg_type != "new-message":
+ return Response("OK", status_code=200)
+
+ data = payload.get("data", {})
+ handle = data.get("handle", {})
+ sender = handle.get("address", "")
+ text = data.get("text", "")
+
+ task = asyncio.create_task(
+ asyncio.to_thread(
+ bridge.handle_incoming,
+ sender,
+ text,
+ "bluebubbles",
+ )
+ )
+ task.add_done_callback(_log_task_exception)
+
+ return Response("OK", status_code=200)
+
+ # ----------------------------------------------------------
+ # WhatsApp Cloud API
+ # ----------------------------------------------------------
+
+ @router.get("/whatsapp")
+ async def whatsapp_verify(request: Request) -> Response:
+ mode = request.query_params.get("hub.mode", "")
+ token = request.query_params.get(
+ "hub.verify_token", ""
+ )
+ challenge = request.query_params.get(
+ "hub.challenge", ""
+ )
+
+ if mode == "subscribe" and token == whatsapp_verify_token:
+ return PlainTextResponse(challenge)
+ return Response("Forbidden", status_code=403)
+
+ @router.post("/whatsapp")
+ async def whatsapp_incoming(
+ request: Request,
+ ) -> Response:
+ body_bytes = await request.body()
+
+ # Verify signature
+ if whatsapp_app_secret:
+ signature = request.headers.get(
+ "X-Hub-Signature-256", ""
+ )
+ expected = (
+ "sha256="
+ + hmac.new(
+ whatsapp_app_secret.encode(),
+ body_bytes,
+ hashlib.sha256,
+ ).hexdigest()
+ )
+ if not hmac.compare_digest(signature, expected):
+ return Response(
+ "Invalid signature", status_code=403
+ )
+
+ payload = json.loads(body_bytes)
+ for entry in payload.get("entry", []):
+ for change in entry.get("changes", []):
+ value = change.get("value", {})
+ for message in value.get("messages", []):
+ if message.get("type") != "text":
+ continue
+ sender = message.get("from", "")
+ text = message.get("text", {}).get(
+ "body", ""
+ )
+
+ task = asyncio.create_task(
+ asyncio.to_thread(
+ bridge.handle_incoming,
+ sender,
+ text,
+ "whatsapp",
+ )
+ )
+ task.add_done_callback(
+ _log_task_exception
+ )
+
+ return Response("OK", status_code=200)
+
+ return router
diff --git a/tests/channels/test_twilio_sms.py b/tests/channels/test_twilio_sms.py
new file mode 100644
index 00000000..e5b58ccb
--- /dev/null
+++ b/tests/channels/test_twilio_sms.py
@@ -0,0 +1,182 @@
+"""Tests for Twilio SMS channel."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.channels._stubs import ChannelStatus
+from openjarvis.core.events import EventBus, EventType
+from openjarvis.core.registry import ChannelRegistry
+
+
[email protected](autouse=True)
+def _register_twilio():
+ if not ChannelRegistry.contains("twilio"):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ ChannelRegistry.register_value(
+ "twilio", TwilioSMSChannel
+ )
+
+
+class TestRegistration:
+ def test_registered(self):
+ assert ChannelRegistry.contains("twilio")
+
+
+class TestInit:
+ def test_from_params(self):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ ch = TwilioSMSChannel(
+ account_sid="AC_test",
+ auth_token="token_test",
+ phone_number="+15551234567",
+ )
+ assert ch.channel_id == "twilio"
+ assert ch.status() == ChannelStatus.DISCONNECTED
+
+ def test_from_env_vars(self, monkeypatch):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ monkeypatch.setenv("TWILIO_ACCOUNT_SID", "AC_env")
+ monkeypatch.setenv("TWILIO_AUTH_TOKEN", "token_env")
+ monkeypatch.setenv(
+ "TWILIO_PHONE_NUMBER", "+15559876543"
+ )
+ ch = TwilioSMSChannel()
+ assert ch._account_sid == "AC_env"
+
+
+class TestSend:
+ def test_send_success(self):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ ch = TwilioSMSChannel(
+ account_sid="AC_test",
+ auth_token="token_test",
+ phone_number="+15551234567",
+ )
+ ch.connect()
+
+ mock_client = MagicMock()
+ mock_client.messages.create.return_value = MagicMock(
+ sid="SM_test"
+ )
+ ch._client = mock_client
+
+ result = ch.send("+15559999999", "Hello via SMS!")
+ assert result is True
+ mock_client.messages.create.assert_called_once_with(
+ body="Hello via SMS!",
+ from_="+15551234567",
+ to="+15559999999",
+ )
+
+ def test_send_failure(self):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ ch = TwilioSMSChannel(
+ account_sid="AC_test",
+ auth_token="token_test",
+ phone_number="+15551234567",
+ )
+ ch.connect()
+
+ mock_client = MagicMock()
+ mock_client.messages.create.side_effect = Exception(
+ "API error"
+ )
+ ch._client = mock_client
+
+ result = ch.send("+15559999999", "Hello!")
+ assert result is False
+
+ def test_send_publishes_event(self):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ bus = EventBus(record_history=True)
+ ch = TwilioSMSChannel(
+ account_sid="AC_test",
+ auth_token="token_test",
+ phone_number="+15551234567",
+ bus=bus,
+ )
+ ch.connect()
+
+ mock_client = MagicMock()
+ mock_client.messages.create.return_value = MagicMock(
+ sid="SM_test"
+ )
+ ch._client = mock_client
+
+ ch.send("+15559999999", "Hello!")
+ event_types = [e.event_type for e in bus.history]
+ assert EventType.CHANNEL_MESSAGE_SENT in event_types
+
+
+class TestStatus:
+ def test_connected_after_connect(self):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ ch = TwilioSMSChannel(
+ account_sid="AC_test",
+ auth_token="token_test",
+ phone_number="+15551234567",
+ )
+ with patch(
+ "openjarvis.channels.twilio_sms"
+ "._create_twilio_client"
+ ):
+ ch.connect()
+ assert ch.status() == ChannelStatus.CONNECTED
+
+ def test_disconnected_after_disconnect(self):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ ch = TwilioSMSChannel(
+ account_sid="AC_test",
+ auth_token="token_test",
+ phone_number="+15551234567",
+ )
+ with patch(
+ "openjarvis.channels.twilio_sms"
+ "._create_twilio_client"
+ ):
+ ch.connect()
+ ch.disconnect()
+ assert ch.status() == ChannelStatus.DISCONNECTED
+
+
+class TestOnMessage:
+ def test_registers_handler(self):
+ from openjarvis.channels.twilio_sms import (
+ TwilioSMSChannel,
+ )
+
+ ch = TwilioSMSChannel(
+ account_sid="AC_test",
+ auth_token="token_test",
+ phone_number="+15551234567",
+ )
+ handler = MagicMock()
+ ch.on_message(handler)
+ assert handler in ch._handlers
diff --git a/tests/server/test_auth_middleware.py b/tests/server/test_auth_middleware.py
new file mode 100644
index 00000000..38bec7b3
--- /dev/null
+++ b/tests/server/test_auth_middleware.py
@@ -0,0 +1,75 @@
+"""Tests for API key authentication middleware."""
+
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip(
+ "fastapi", reason="openjarvis[server] not installed"
+)
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openjarvis.server.auth_middleware import AuthMiddleware
+
+
+def _make_app(api_key: str) -> FastAPI:
+ app = FastAPI()
+ app.add_middleware(AuthMiddleware, api_key=api_key)
+
+ @app.get("/v1/models")
+ async def models():
+ return {"models": []}
+
+ @app.get("/health")
+ async def health():
+ return {"status": "ok"}
+
+ @app.post("/webhooks/twilio")
+ async def twilio_webhook():
+ return {"status": "received"}
+
+ return app
+
+
+def client():
+ return TestClient(_make_app("oj_sk_test123"))
+
+
+class TestAuthMiddleware:
+ def test_rejects_missing_auth_header(self, client):
+ resp = client.get("/v1/models")
+ assert resp.status_code == 401
+ assert "missing" in resp.json()["detail"].lower()
+
+ def test_rejects_wrong_key(self, client):
+ resp = client.get(
+ "/v1/models",
+ headers={"Authorization": "Bearer wrong"},
+ )
+ assert resp.status_code == 401
+ assert "invalid" in resp.json()["detail"].lower()
+
+ def test_accepts_valid_key(self, client):
+ resp = client.get(
+ "/v1/models",
+ headers={
+ "Authorization": "Bearer oj_sk_test123"
+ },
+ )
+ assert resp.status_code == 200
+
+ def test_health_exempt(self, client):
+ resp = client.get("/health")
+ assert resp.status_code == 200
+
+ def test_webhooks_exempt(self, client):
+ resp = client.post("/webhooks/twilio")
+ assert resp.status_code == 200
+
+ def test_no_key_configured_allows_all(self):
+ client = TestClient(_make_app(""))
+ resp = client.get("/v1/models")
+ assert resp.status_code == 200
diff --git a/tests/server/test_channel_bridge.py b/tests/server/test_channel_bridge.py
new file mode 100644
index 00000000..ba06b10e
--- /dev/null
+++ b/tests/server/test_channel_bridge.py
@@ -0,0 +1,228 @@
+"""Tests for the ChannelBridge orchestrator."""
+
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+from typing import Any, Dict, List
+from unittest.mock import MagicMock
+
+import pytest
+
+pytest.importorskip(
+ "fastapi", reason="openjarvis[server] not installed"
+)
+
+from openjarvis.channels._stubs import (
+ BaseChannel,
+ ChannelHandler,
+ ChannelStatus,
+)
+from openjarvis.core.events import EventBus
+from openjarvis.server.channel_bridge import ChannelBridge
+from openjarvis.server.session_store import SessionStore
+
+
+class FakeChannel(BaseChannel):
+ """Minimal channel for testing."""
+
+ channel_id = "fake"
+
+ def __init__(self) -> None:
+ self._status = ChannelStatus.DISCONNECTED
+ self._handlers: List[ChannelHandler] = []
+ self.sent: List[Dict[str, Any]] = []
+
+ def connect(self) -> None:
+ self._status = ChannelStatus.CONNECTED
+
+ def disconnect(self) -> None:
+ self._status = ChannelStatus.DISCONNECTED
+
+ def send(
+ self,
+ channel: str,
+ content: str,
+ *,
+ conversation_id: str = "",
+ metadata: Dict[str, Any] | None = None,
+ ) -> bool:
+ self.sent.append(
+ {"channel": channel, "content": content}
+ )
+ return True
+
+ def status(self) -> ChannelStatus:
+ return self._status
+
+ def list_channels(self) -> List[str]:
+ return ["fake"]
+
+ def on_message(self, handler: ChannelHandler) -> None:
+ self._handlers.append(handler)
+
+
+def store():
+ with tempfile.TemporaryDirectory() as tmpdir:
+ s = SessionStore(
+ db_path=str(Path(tmpdir) / "sessions.db")
+ )
+ yield s
+ s.close()
+
+
+def bus():
+ return EventBus(record_history=True)
+
+
+def mock_system():
+ system = MagicMock()
+ system.ask.return_value = {"content": "Hello from Jarvis!"}
+ return system
+
+
+def bridge(store, bus, mock_system):
+ fake = FakeChannel()
+ fake.connect()
+ b = ChannelBridge(
+ channels={"fake": fake},
+ session_store=store,
+ bus=bus,
+ system=mock_system,
+ )
+ return b
+
+
+class TestBackwardCompatible:
+ """ChannelBridge must work as a drop-in for the old bridge."""
+
+ def test_list_channels(self, bridge):
+ assert "fake" in bridge.list_channels()
+
+ def test_status_connected(self, bridge):
+ assert bridge.status() == ChannelStatus.CONNECTED
+
+ def test_status_disconnected_when_none_connected(
+ self, store, bus, mock_system
+ ):
+ fake = FakeChannel() # not connected
+ b = ChannelBridge(
+ channels={"fake": fake},
+ session_store=store,
+ bus=bus,
+ system=mock_system,
+ )
+ assert b.status() == ChannelStatus.DISCONNECTED
+
+ def test_send_routes_to_adapter(self, bridge):
+ result = bridge.send("fake", "hello")
+ assert result is True
+ fake = bridge._channels["fake"]
+ assert fake.sent[-1]["content"] == "hello"
+
+
+class TestCommandParsing:
+ def test_help_command(self, bridge):
+ reply = bridge.handle_incoming("user1", "/help", "fake")
+ assert "agents" in reply.lower()
+ assert "notify" in reply.lower()
+
+ def test_notify_command(self, bridge, store):
+ reply = bridge.handle_incoming(
+ "user1", "/notify slack", "fake"
+ )
+ assert "slack" in reply.lower()
+ session = store.get_or_create("user1", "fake")
+ assert session["preferred_notification_channel"] == "slack"
+
+ def test_agents_command(self, bridge):
+ bridge._agent_manager = MagicMock()
+ bridge._agent_manager.list_agents.return_value = []
+ reply = bridge.handle_incoming(
+ "user1", "/agents", "fake"
+ )
+ assert (
+ "no" in reply.lower() or "agent" in reply.lower()
+ )
+
+ def test_unknown_command_falls_through_to_chat(
+ self, bridge, mock_system
+ ):
+ bridge.handle_incoming("user1", "/unknown_cmd", "fake")
+ # Should treat as regular chat
+ mock_system.ask.assert_called_once()
+
+ def test_more_command_returns_pending(self, bridge, store):
+ store.get_or_create("user1", "fake")
+ store.set_pending_response(
+ "user1", "fake", "the rest of the long response"
+ )
+ reply = bridge.handle_incoming("user1", "/more", "fake")
+ assert "the rest of the long response" in reply
+
+
+class TestChatRouting:
+ def test_routes_to_system_ask(self, bridge, mock_system):
+ reply = bridge.handle_incoming(
+ "user1", "what is 2+2?", "fake"
+ )
+ mock_system.ask.assert_called_once()
+ call_kwargs = mock_system.ask.call_args
+ assert "2+2" in str(call_kwargs)
+ assert reply == "Hello from Jarvis!"
+
+ def test_stores_conversation_history(
+ self, bridge, store, mock_system
+ ):
+ bridge.handle_incoming("user1", "hello", "fake")
+ session = store.get_or_create("user1", "fake")
+ # user + assistant
+ assert len(session["conversation_history"]) == 2
+ assert (
+ session["conversation_history"][0]["role"] == "user"
+ )
+ assert (
+ session["conversation_history"][1]["role"]
+ == "assistant"
+ )
+
+ def test_error_returns_friendly_message(
+ self, bridge, mock_system
+ ):
+ mock_system.ask.side_effect = RuntimeError("engine down")
+ reply = bridge.handle_incoming(
+ "user1", "hello", "fake"
+ )
+ assert (
+ "sorry" in reply.lower()
+ or "couldn't" in reply.lower()
+ )
+
+
+class TestResponseFormatting:
+ def test_truncates_long_sms_response(
+ self, bridge, mock_system
+ ):
+ mock_system.ask.return_value = {"content": "x" * 2000}
+ reply = bridge.handle_incoming(
+ "user1",
+ "tell me a story",
+ "fake",
+ max_length=1600,
+ )
+ assert len(reply) <= 1600
+ assert "/more" in reply
+
+ def test_short_response_not_truncated(
+ self, bridge, mock_system
+ ):
+ mock_system.ask.return_value = {
+ "content": "short answer"
+ }
+ reply = bridge.handle_incoming("user1", "hi", "fake")
+ assert reply == "short answer"
+ assert "/more" not in reply
diff --git a/tests/server/test_session_store.py b/tests/server/test_session_store.py
new file mode 100644
index 00000000..bff077a1
--- /dev/null
+++ b/tests/server/test_session_store.py
@@ -0,0 +1,144 @@
+"""Tests for channel session store."""
+
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from openjarvis.server.session_store import SessionStore
+
+
+def store():
+ with tempfile.TemporaryDirectory() as tmpdir:
+ s = SessionStore(
+ db_path=str(Path(tmpdir) / "sessions.db")
+ )
+ yield s
+ s.close()
+
+
+class TestGetOrCreate:
+ def test_creates_new_session(self, store):
+ session = store.get_or_create("user123", "twilio")
+ assert session["sender_id"] == "user123"
+ assert session["channel_type"] == "twilio"
+ assert session["conversation_history"] == []
+ assert session["preferred_notification_channel"] is None
+ assert session["pending_response"] is None
+
+ def test_returns_existing_session(self, store):
+ store.get_or_create("user123", "twilio")
+ store.append_message("user123", "twilio", "user", "hello")
+ session = store.get_or_create("user123", "twilio")
+ assert len(session["conversation_history"]) == 1
+
+ def test_separate_sessions_per_channel(self, store):
+ store.get_or_create("user123", "twilio")
+ store.get_or_create("user123", "slack")
+ store.append_message(
+ "user123", "twilio", "user", "hello via sms"
+ )
+ twilio_session = store.get_or_create("user123", "twilio")
+ slack_session = store.get_or_create("user123", "slack")
+ assert len(twilio_session["conversation_history"]) == 1
+ assert len(slack_session["conversation_history"]) == 0
+
+
+class TestAppendMessage:
+ def test_appends_message(self, store):
+ store.get_or_create("user1", "slack")
+ store.append_message("user1", "slack", "user", "hi")
+ store.append_message(
+ "user1", "slack", "assistant", "hello!"
+ )
+ session = store.get_or_create("user1", "slack")
+ assert len(session["conversation_history"]) == 2
+ assert session["conversation_history"][0] == {
+ "role": "user",
+ "content": "hi",
+ }
+ assert session["conversation_history"][1] == {
+ "role": "assistant",
+ "content": "hello!",
+ }
+
+ def test_caps_history_at_max_turns(self, store):
+ store.get_or_create("user1", "slack")
+ for i in range(25):
+ store.append_message(
+ "user1", "slack", "user", f"msg {i}"
+ )
+ session = store.get_or_create("user1", "slack")
+ assert len(session["conversation_history"]) == 20
+ assert (
+ session["conversation_history"][0]["content"]
+ == "msg 5"
+ )
+
+
+class TestNotificationPreference:
+ def test_set_and_get(self, store):
+ store.get_or_create("user1", "twilio")
+ store.set_notification_preference(
+ "user1", "twilio", "slack"
+ )
+ session = store.get_or_create("user1", "twilio")
+ assert (
+ session["preferred_notification_channel"] == "slack"
+ )
+
+
+class TestPendingResponse:
+ def test_set_and_get(self, store):
+ store.get_or_create("user1", "twilio")
+ store.set_pending_response(
+ "user1", "twilio", "full long response text here"
+ )
+ session = store.get_or_create("user1", "twilio")
+ assert (
+ session["pending_response"]
+ == "full long response text here"
+ )
+
+ def test_clear_pending(self, store):
+ store.get_or_create("user1", "twilio")
+ store.set_pending_response(
+ "user1", "twilio", "some text"
+ )
+ store.clear_pending_response("user1", "twilio")
+ session = store.get_or_create("user1", "twilio")
+ assert session["pending_response"] is None
+
+
+class TestExpireSessions:
+ def test_expire_clears_old_history(self, store):
+ store.get_or_create("user1", "twilio")
+ store.append_message(
+ "user1", "twilio", "user", "old message"
+ )
+ # Force the updated_at to be old
+ store._db.execute(
+ "UPDATE channel_sessions "
+ "SET updated_at = datetime('now', '-25 hours')"
+ )
+ store._db.commit()
+ store.expire_sessions(max_age_hours=24)
+ session = store.get_or_create("user1", "twilio")
+ assert session["conversation_history"] == []
+
+
+class TestLastActiveChannel:
+ def test_returns_most_recent(self, store):
+ store.get_or_create("user1", "twilio")
+ store.get_or_create("user1", "slack")
+ store.append_message(
+ "user1", "slack", "user", "latest"
+ )
+ result = store.get_last_active_channel("user1")
+ assert result == "slack"
+
+ def test_returns_none_for_unknown_user(self, store):
+ assert store.get_last_active_channel("nobody") is None
diff --git a/tests/server/test_webhook_routes.py b/tests/server/test_webhook_routes.py
new file mode 100644
index 00000000..856e7980
--- /dev/null
+++ b/tests/server/test_webhook_routes.py
@@ -0,0 +1,231 @@
+"""Tests for webhook routes."""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+pytest.importorskip(
+ "fastapi", reason="openjarvis[server] not installed"
+)
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openjarvis.server.webhook_routes import create_webhook_router
+
+
+def mock_bridge():
+ bridge = MagicMock()
+ bridge.handle_incoming.return_value = "Got it!"
+ return bridge
+
+
+class TestTwilioWebhook:
+ @pytest.fixture
+ def twilio_app(self, mock_bridge):
+ app = FastAPI()
+ router = create_webhook_router(
+ bridge=mock_bridge,
+ twilio_auth_token="test_token",
+ )
+ app.include_router(router)
+ return app
+
+ @pytest.fixture
+ def twilio_client(self, twilio_app):
+ return TestClient(twilio_app)
+
+ def test_valid_twilio_webhook(
+ self, twilio_client, mock_bridge
+ ):
+ with patch(
+ "openjarvis.server.webhook_routes"
+ "._validate_twilio_signature",
+ return_value=True,
+ ):
+ resp = twilio_client.post(
+ "/webhooks/twilio",
+ data={
+ "From": "+15551234567",
+ "Body": "hello jarvis",
+ "MessageSid": "SM123",
+ },
+ )
+ assert resp.status_code == 200
+ assert "<Response>" in resp.text # TwiML
+
+ def test_invalid_signature_rejected(self, twilio_client):
+ with patch(
+ "openjarvis.server.webhook_routes"
+ "._validate_twilio_signature",
+ return_value=False,
+ ):
+ resp = twilio_client.post(
+ "/webhooks/twilio",
+ data={
+ "From": "+15551234567",
+ "Body": "hello",
+ "MessageSid": "SM123",
+ },
+ )
+ assert resp.status_code == 403
+
+
+class TestBlueBubblesWebhook:
+ @pytest.fixture
+ def bb_app(self, mock_bridge):
+ app = FastAPI()
+ router = create_webhook_router(
+ bridge=mock_bridge,
+ bluebubbles_password="bb_secret",
+ )
+ app.include_router(router)
+ return app
+
+ @pytest.fixture
+ def bb_client(self, bb_app):
+ return TestClient(bb_app)
+
+ def test_valid_bluebubbles_webhook(
+ self, bb_client, mock_bridge
+ ):
+ resp = bb_client.post(
+ "/webhooks/bluebubbles",
+ json={
+ "type": "new-message",
+ "data": {
+ "handle": {
+ "address": "[email protected]"
+ },
+ "text": "hello from imessage",
+ "guid": "msg-123",
+ },
+ },
+ headers={"Authorization": "bb_secret"},
+ )
+ assert resp.status_code == 200
+
+ def test_wrong_password_rejected(self, bb_client):
+ resp = bb_client.post(
+ "/webhooks/bluebubbles",
+ json={"type": "new-message", "data": {}},
+ headers={"Authorization": "wrong_password"},
+ )
+ assert resp.status_code == 403
+
+
+class TestWhatsAppWebhook:
+ @pytest.fixture
+ def wa_app(self, mock_bridge):
+ app = FastAPI()
+ router = create_webhook_router(
+ bridge=mock_bridge,
+ whatsapp_verify_token="wa_verify_123",
+ whatsapp_app_secret="wa_secret",
+ )
+ app.include_router(router)
+ return app
+
+ @pytest.fixture
+ def wa_client(self, wa_app):
+ return TestClient(wa_app)
+
+ def test_verification_challenge(self, wa_client):
+ resp = wa_client.get(
+ "/webhooks/whatsapp",
+ params={
+ "hub.mode": "subscribe",
+ "hub.verify_token": "wa_verify_123",
+ "hub.challenge": "challenge_string_42",
+ },
+ )
+ assert resp.status_code == 200
+ assert resp.text == "challenge_string_42"
+
+ def test_verification_wrong_token(self, wa_client):
+ resp = wa_client.get(
+ "/webhooks/whatsapp",
+ params={
+ "hub.mode": "subscribe",
+ "hub.verify_token": "wrong_token",
+ "hub.challenge": "challenge_string_42",
+ },
+ )
+ assert resp.status_code == 403
+
+ def test_invalid_signature_rejected(self, wa_client):
+ payload = {
+ "entry": [
+ {
+ "changes": [
+ {
+ "value": {
+ "messages": [
+ {
+ "from": "123",
+ "text": {"body": "hi"},
+ "id": "x",
+ "type": "text",
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+ }
+ body_bytes = json.dumps(payload).encode()
+ resp = wa_client.post(
+ "/webhooks/whatsapp",
+ content=body_bytes,
+ headers={
+ "Content-Type": "application/json",
+ "X-Hub-Signature-256": "sha256=invalid",
+ },
+ )
+ assert resp.status_code == 403
+
+ def test_valid_message_webhook(
+ self, wa_client, mock_bridge
+ ):
+ payload = {
+ "entry": [
+ {
+ "changes": [
+ {
+ "value": {
+ "messages": [
+ {
+ "from": "15551234567",
+ "text": {
+ "body": "hello wa"
+ },
+ "id": "wamid.abc123",
+ "type": "text",
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+ }
+ body_bytes = json.dumps(payload).encode()
+ sig = hmac.new(
+ b"wa_secret", body_bytes, hashlib.sha256
+ ).hexdigest()
+ resp = wa_client.post(
+ "/webhooks/whatsapp",
+ content=body_bytes,
+ headers={
+ "Content-Type": "application/json",
+ "X-Hub-Signature-256": f"sha256={sig}",
+ },
+ )
+ assert resp.status_code == 200