diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index 6b94eb7..a223a13 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -5,7 +5,6 @@ "cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 39, "cognitive-complexity|memclaw/backends/claude.py|ClaudeAgentBackend.run_one_shot": 23, "cognitive-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 24, - "cognitive-complexity|memclaw/bot/whatsapp_handlers.py|WhatsAppBot._send_response": 16, "cognitive-complexity|memclaw/index.py|MemoryIndex.chunk_text": 27, "cognitive-complexity|memclaw/prompts.py|masked_input": 16, "cognitive-complexity|memclaw/search.py|HybridSearch._merge": 17 @@ -14,63 +13,40 @@ "type-errors|memclaw/agent.py|": 1, "type-errors|memclaw/backends/claude.py|": 1, "type-errors|memclaw/backends/mcp_bridge.py|": 1, - "type-errors|memclaw/bot/handlers.py|": 30, - "type-errors|memclaw/bot/whatsapp_handlers.py|": 3, "type-errors|memclaw/cli.py|": 2, "type-errors|memclaw/setup.py|": 5 }, "pylint": { "class-attributes|memclaw/agent.py|MemclawAgent": 18, "class-attributes|memclaw/backends/cursor.py|CursorAgentBackend": 13, - "duplicate-code|memclaw/bot/handlers.py|same code as memclaw/bot/slack_handlers.py": 15, - "duplicate-code|memclaw/bot/slack_handlers.py|same code as memclaw/bot/whatsapp_handlers.py": 16, "too-many-locals|memclaw/agent.py|MemclawAgent._handle": 19, "too-many-locals|memclaw/backends/claude.py|ClaudeAgentBackend.wizard_setup": 17, "too-many-locals|memclaw/backends/cursor.py|CursorAgentBackend.run_turn": 20, "too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19, - "too-many-locals|memclaw/bot/slack_handlers.py|SlackHandlers._handle_audio": 21, - "too-many-locals|memclaw/bot/slack_handlers.py|SlackHandlers._handle_image": 21, - "too-many-locals|memclaw/bot/whatsapp_handlers.py|WhatsAppBot._handle_audio": 17, - "too-many-locals|memclaw/bot/whatsapp_handlers.py|WhatsAppBot._handle_image": 19, "too-many-locals|memclaw/index.py|MemoryIndex.chunk_text": 17, "too-many-locals|memclaw/search.py|HybridSearch._merge": 22 }, "ruff": { - "banned-api|memclaw/bot/handlers.py|openai in ": 1, - "banned-api|memclaw/bot/link_processor.py|openai in ": 1, - "banned-api|memclaw/bot/slack_handlers.py|openai in ": 1, - "banned-api|memclaw/bot/whatsapp_handlers.py|openai in ": 1, - "banned-api|memclaw/cli.py|openai in _run_slack": 1, - "banned-api|memclaw/cli.py|openai in _run_whatsapp": 1, - "banned-api|memclaw/openai_health.py|openai in ": 1, "banned-api|memclaw/search.py|sqlite3 in ": 1, "function-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, "function-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 11, - "function-complexity|memclaw/bot/handlers.py|build_application": 15, "function-complexity|memclaw/index.py|MemoryIndex.chunk_text": 12, "private-access|memclaw/cli.py|_maybe_consolidate in consolidate._run": 1, "too-many-args|memclaw/backends/base.py|AgentBackend.run_turn": 10, "too-many-args|memclaw/backends/claude.py|ClaudeAgentBackend.run_turn": 10, "too-many-args|memclaw/backends/cursor.py|CursorAgentBackend.run_turn": 10, - "too-many-args|memclaw/bot/slack_handlers.py|SlackHandlers._handle_audio": 7, - "too-many-args|memclaw/bot/slack_handlers.py|SlackHandlers._handle_image": 7, "too-many-args|memclaw/tools.py|ToolExecutor.__init__": 7, "too-many-branches|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, - "too-many-positional|memclaw/bot/slack_handlers.py|SlackHandlers._handle_audio": 7, - "too-many-positional|memclaw/bot/slack_handlers.py|SlackHandlers._handle_image": 7, "too-many-positional|memclaw/tools.py|ToolExecutor.__init__": 7 }, "sizes": { "class-lines|memclaw/agent.py|MemclawAgent": 482, "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 501, "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 419, - "class-lines|memclaw/bot/handlers.py|MessageHandlers": 309, - "class-lines|memclaw/bot/slack_handlers.py|SlackHandlers": 306, - "class-lines|memclaw/index.py|MemoryIndex": 422, + "class-lines|memclaw/index.py|MemoryIndex": 419, "file-lines|memclaw/agent.py|": 699, "file-lines|memclaw/backends/claude.py|": 775, "file-lines|memclaw/backends/cursor.py|": 604, - "file-lines|memclaw/bot/handlers.py|": 570, "file-lines|memclaw/tools.py|": 577, "package-files|memclaw/|": 13 } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1a35c76..eddb704 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,10 +66,11 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co **memclaw's layout rules** are the import-linter contracts under `[tool.importlinter]` in `pyproject.toml`. `code-shape check` runs them (on their own: `lint-imports`): -- **Layers**: `cli` → `bot` / `setup` → `agent` → `backends` → `tools` → core modules (`search`, `store`, `reminders`, …) → `index` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. +- **Layers**: `cli` → `setup` → `bot` → `agent` → `backends` → `tools` → core modules (`search`, `store`, `reminders`, …) → `index` → `openai_client` → `config`. A module may import from layers below it, never above. A new top-level module must be added to a layer. - **No cycles inside subpackages** such as `memclaw.backends` and `memclaw.bot`. -- **Chat platforms are independent**: the Telegram (`bot/handlers.py`), Slack and WhatsApp handlers never import each other. Put shared code in `memclaw/bot/` or a lower layer. -- **Chat SDKs stay in `memclaw.bot`**: only `memclaw.bot` imports `telegram`, `slack_bolt` or `neonize`. +- **Chat platforms are independent**: `bot/telegram.py`, `bot/slack.py` and `bot/whatsapp.py` never import each other. What they share (voice to text, link summaries, the prompts, the agent call, reminders) is in `bot/inbound.py`. A new platform is one module with a `run(config)` plus one line in `PLATFORMS` (`bot/__init__.py`); the CLI and the setup wizard start and list platforms only through that registry. +- **Chat SDKs stay in their platform module**: only those three modules import `telegram`, `slack_bolt` or `neonize`. +- **One OpenAI adapter**: only `openai_client.py` imports `openai`; everyone else calls `OpenAIClient`. - **Backends are swappable**: only `memclaw.backends` itself imports the concrete backend modules (`claude.py`, `cursor.py`, …). Everyone else goes through `memclaw.backends` / `memclaw.backends.base`. - **`memclaw.defaults` stands alone**: the Cursor hook script there is copied out and run on its own, so it can't import memclaw. diff --git a/docs/memory-architecture.md b/docs/memory-architecture.md index 685429f..cfe2b2f 100644 --- a/docs/memory-architecture.md +++ b/docs/memory-architecture.md @@ -91,7 +91,7 @@ Details — credentials, document numbers, instructions, receipts — stay in th ### How Memories Get Saved -The agent — not the handler, not a pre-processing step — decides what to save. When you send a text message, voice note, photo, or link, the raw content is passed to the agent with a note saying it hasn't been saved yet. The agent reads it and decides: +The agent — not the chat platform's code, not a pre-processing step — decides what to save. When you send a text message, voice note, photo, or link, the raw content is passed to the agent with a note saying it hasn't been saved yet (the same prompt on every platform: `memclaw/bot/inbound.py`). The agent reads it and decides: - **Save it** if the content is useful (a fact, a note, a decision). - **Rephrase it** if the verbatim text is messy but the information matters. diff --git a/memclaw/bot/__init__.py b/memclaw/bot/__init__.py index 1935e42..aa1439b 100644 --- a/memclaw/bot/__init__.py +++ b/memclaw/bot/__init__.py @@ -1,3 +1,56 @@ +"""The chat apps Memclaw runs on. + +Each platform is one module here (`telegram.py`, `slack.py`, `whatsapp.py`) +that only does that app's I/O: receive a message, download its media, send +the reply. What happens in between (voice to text, link summaries, the +prompt, the agent call, reminders) is shared, in `inbound.py`. + +Each platform module has a `run(config)` that starts it. The bare `memclaw` +command and the setup wizard find the platforms in `PLATFORMS` below, so +adding one is a new module plus one line there. A platform module (and its +chat SDK) is only imported when that platform is started. +""" + +from __future__ import annotations + +import sys +from dataclasses import dataclass +from importlib import import_module +from pathlib import Path +from typing import TYPE_CHECKING + +from loguru import logger +from rich.console import Console + +if TYPE_CHECKING: + from ..config import MemclawConfig + +console = Console() + + +@dataclass(frozen=True) +class Platform: + """A chat app; its code is the module `memclaw/bot/.py`.""" + + name: str + label: str # shown by the setup wizard + + def run(self, config: MemclawConfig) -> None: + """Start the bot and block until it stops.""" + import_module(f"{__name__}.{self.name}").run(config) + + +# In the order the setup wizard lists them. +PLATFORMS: dict[str, Platform] = { + p.name: p + for p in ( + Platform("telegram", "Telegram"), + Platform("whatsapp", "WhatsApp"), + Platform("slack", "Slack"), + ) +} + + def mask_user_id(user_id: str | int) -> str: """Mask the middle of a user identifier for log safety. @@ -8,3 +61,22 @@ def mask_user_id(user_id: str | int) -> str: if len(s) <= 5: return "*" * len(s) return f"{s[:3]}{'*' * (len(s) - 5)}{s[-2:]}" + + +def require_setting(value: str, env_var: str) -> None: + """Exit with a hint unless *value* (the setting *env_var*) is set.""" + if not value: + console.print(f"[red]Error:[/red] {env_var} is not set.") + console.print("Run [bold]memclaw configure[/bold] to set it.") + raise SystemExit(1) + + +def log_to(log_file: Path) -> None: + """Log INFO to the terminal and DEBUG to *log_file* (rotated).""" + logger.remove() + logger.add( + sys.stderr, + level="INFO", + format="{time:HH:mm:ss} | {level:<8} | {message}", + ) + logger.add(str(log_file), rotation="10 MB", retention="7 days", level="DEBUG") diff --git a/memclaw/bot/commands.py b/memclaw/bot/commands.py new file mode 100644 index 0000000..51f1857 --- /dev/null +++ b/memclaw/bot/commands.py @@ -0,0 +1,58 @@ +"""What the /model and /effort chat commands say and do, apart from the +chat app's I/O (Telegram adds its buttons, in telegram.py).""" + +from __future__ import annotations + +from loguru import logger + +from ..backends import AgentBackend + +_APPLIES = "Applies from your next message; the conversation is kept." + + +def unsupported(backend: AgentBackend, what: str) -> str: + return f"{what} isn't supported for the {backend.display_name} backend yet." + + +async def load_models(backend: AgentBackend) -> list: + try: + return await backend.list_models() + except Exception as exc: + logger.warning("Could not fetch the model list: {exc}", exc=exc) + return [] + + +def status_lines(backend: AgentBackend, models: list, levels: list[str] | None) -> list[str]: + info = next((m for m in models if m.id == backend.model), None) + model = f"{info.display_name} ({info.id})" if info else backend.model + if levels == []: + effort = "not supported by this model" + else: + effort = backend.effort or "model default" + return [f"Model: {model}", f"Effort: {effort}"] + + +async def select_model(backend: AgentBackend, model_id: str) -> str: + """Switch to *model_id*. Returns a note for the user; raises ValueError + for an unknown model.""" + if model_id == backend.model: + return f"Already using {model_id}." + note = await backend.set_model(model_id) + return " ".join(p for p in (f"Switched to {backend.model}.", note, _APPLIES) if p) + + +async def select_effort(backend: AgentBackend, level: str) -> str: + """Set the effort level. Returns a note; raises ValueError if rejected.""" + await backend.set_effort(level) + return f"Effort set to {backend.effort}. {_APPLIES}" + + +async def resolve_model_arg(backend: AgentBackend, arg: str) -> str: + """`/model ` → model id. Raises ValueError.""" + if not arg.isdigit(): + return arg + models = await load_models(backend) + n = int(arg) + if not 1 <= n <= len(models): + raise ValueError(f"There's no model number {n}.") + return models[n - 1].id diff --git a/memclaw/bot/handlers.py b/memclaw/bot/handlers.py deleted file mode 100644 index c1ca119..0000000 --- a/memclaw/bot/handlers.py +++ /dev/null @@ -1,570 +0,0 @@ -"""Telegram bot message handlers for Memclaw. - -Every message (text, photo, voice) goes through the unified MemclawAgent, -which autonomously decides whether to store, search, or just respond. -""" - -from __future__ import annotations - -import asyncio -import base64 -import contextlib -import hashlib -import time - -from loguru import logger -from openai import AsyncOpenAI -from telegram import BotCommand, InlineKeyboardButton, InlineKeyboardMarkup, Update -from telegram.constants import ChatAction -from telegram.error import BadRequest, NetworkError, TelegramError, TimedOut -from telegram.ext import ( - Application, - CallbackQueryHandler, - CommandHandler, - ContextTypes, - MessageHandler, - filters, -) - -from ..agent import MemclawAgent -from ..backends import AgentBackend -from ..backends.base import ToolStep -from ..config import MemclawConfig -from ..reminders import ReminderScheduler -from . import mask_user_id -from .link_processor import LinkProcessor - - -async def _typing_loop(bot, chat_id: int): - """Send 'typing...' action every 4 seconds until cancelled.""" - try: - while True: - try: - await bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING) - except Exception: - pass # best-effort - await asyncio.sleep(4) - except asyncio.CancelledError: - pass - - -# Shown in Telegram's command menu (registered in build_application). -BOT_COMMANDS = [ - ("new", "Start a fresh conversation"), - ("model", "Show or change the model"), - ("effort", "Show or change the reasoning effort"), -] - -# Minimum seconds between edits of the "Working…" status message, to stay -# well under Telegram's rate limits. -STATUS_EDIT_INTERVAL_S = 2.0 - -# Telegram limits callback_data to 64 bytes. -CALLBACK_DATA_MAX_BYTES = 64 - -_APPLIES = "Applies from your next message; the conversation is kept." - - -def _model_key(model_id: str) -> str: - return hashlib.sha256(model_id.encode()).hexdigest()[:16] - - -def model_callback_data(model_id: str) -> str: - """``m:``, or ``mi:`` if the id would exceed - Telegram's limit. A hash rather than a list position, so a button still - picks its own model if the list has changed since the menu was shown.""" - data = f"m:{model_id}" - return data if len(data.encode()) <= CALLBACK_DATA_MAX_BYTES else f"mi:{_model_key(model_id)}" - - -def _unsupported(backend: AgentBackend, what: str) -> str: - return f"{what} isn't supported for the {backend.display_name} backend yet." - - -async def _load_models(backend: AgentBackend) -> list: - try: - return await backend.list_models() - except Exception as exc: - logger.warning("Could not fetch the model list: {exc}", exc=exc) - return [] - - -def _status_lines(backend: AgentBackend, models: list, levels: list[str] | None) -> list[str]: - info = next((m for m in models if m.id == backend.model), None) - model = f"{info.display_name} ({info.id})" if info else backend.model - if levels == []: - effort = "not supported by this model" - else: - effort = backend.effort or "model default" - return [f"Model: {model}", f"Effort: {effort}"] - - -async def model_menu( - backend: AgentBackend, note: str = "", -) -> tuple[str, InlineKeyboardMarkup | None]: - """`/model` reply: current settings plus one button per model.""" - if not backend.supports_model_selection: - return _unsupported(backend, "Switching models"), None - models = await _load_models(backend) - lines = _status_lines(backend, models, await backend.effort_levels()) - if note: - lines += ["", note] - lines.append("") - if not models: - lines.append("Couldn't load the model list right now; try /model again later.") - return "\n".join(lines), None - lines.append("Tap a model to switch, or send /model .") - keyboard = InlineKeyboardMarkup([ - [InlineKeyboardButton( - ("✓ " if m.id == backend.model else "") + m.display_name, - callback_data=model_callback_data(m.id), - )] - for m in models - ]) - return "\n".join(lines), keyboard - - -async def effort_menu( - backend: AgentBackend, note: str = "", -) -> tuple[str, InlineKeyboardMarkup | None]: - """`/effort` reply: current settings plus a row of level buttons.""" - if not backend.supports_model_selection: - return _unsupported(backend, "Changing the effort"), None - levels = await backend.effort_levels() - lines = _status_lines(backend, await _load_models(backend), levels) - if note: - lines += ["", note] - lines.append("") - if levels == []: - lines.append("This model doesn't support an effort setting.") - return "\n".join(lines), None - if levels is None: - lines.append("Send /effort to change it.") - return "\n".join(lines), None - lines.append("Tap a level, or send /effort .") - keyboard = InlineKeyboardMarkup([[ - InlineKeyboardButton( - ("✓ " if lv == backend.effort else "") + lv, callback_data=f"e:{lv}", - ) - for lv in levels - ]]) - return "\n".join(lines), keyboard - - -async def select_model(backend: AgentBackend, model_id: str) -> str: - """Switch to *model_id*. Returns a note for the user; raises ValueError - for an unknown model.""" - if model_id == backend.model: - return f"Already using {model_id}." - note = await backend.set_model(model_id) - return " ".join(p for p in (f"Switched to {backend.model}.", note, _APPLIES) if p) - - -async def select_effort(backend: AgentBackend, level: str) -> str: - """Set the effort level. Returns a note; raises ValueError if rejected.""" - await backend.set_effort(level) - return f"Effort set to {backend.effort}. {_APPLIES}" - - -async def _resolve_model_arg(backend: AgentBackend, arg: str) -> str: - """`/model ` → model id. Raises ValueError.""" - if not arg.isdigit(): - return arg - models = await _load_models(backend) - n = int(arg) - if not 1 <= n <= len(models): - raise ValueError(f"There's no model number {n}.") - return models[n - 1].id - - -class MessageHandlers: - """Routes every Telegram message through the unified Memclaw agent.""" - - def __init__(self, config: MemclawConfig, openai_client: AsyncOpenAI): - self.config = config - self.openai_client = openai_client - self.scheduler = ReminderScheduler(config) - self.agent = MemclawAgent(config, platform="telegram", scheduler=self.scheduler) - self.link_processor = LinkProcessor(openai_client) - self._bot = None - - def attach_bot(self, bot): - """Give the handler a reference to the Telegram Bot for reminder delivery.""" - self._bot = bot - self.scheduler.register_delivery("telegram", self._deliver_reminder) - - async def _deliver_reminder(self, chat_id: str, text: str): - if self._bot is None: - return - await self._bot.send_message(chat_id=int(chat_id), text=text) - self.agent.record_reminder_fired(text, chat_id) - - def _check_user(self, user_id: int) -> bool: - return user_id in self.config.telegram.allowed_user_ids_list - - async def _send_response( - self, - update: Update, - context: ContextTypes.DEFAULT_TYPE, - response_text: str, - found_images: list[dict], - ): - """Send agent response: images first, then text.""" - for img in found_images: - try: - await context.bot.send_photo( - chat_id=update.effective_chat.id, - photo=img["file_id"], - caption=img.get("caption") or None, - ) - except Exception as e: - logger.error(f"Failed to send image {img.get('file_id')}: {e}") - - if response_text: - try: - await update.message.reply_text(response_text[:4096], parse_mode="Markdown") - except Exception as e: - # Fall back to plain text if the agent emitted something Telegram's - # legacy Markdown parser rejects (unbalanced * or _, etc.). - logger.warning(f"Markdown parse failed, sending plain: {e}") - await update.message.reply_text(response_text[:4096]) - - async def _send_with_typing( - self, - update: Update, - context: ContextTypes.DEFAULT_TYPE, - prompt: str, - *, - image_b64: str | None = None, - image_media_type: str = "image/jpeg", - ): - """Run the agent with a typing indicator, then send the full response.""" - chat_id = update.effective_chat.id - typing_task = asyncio.create_task(_typing_loop(context.bot, chat_id)) - # One silent status message, edited as the agent works and deleted - # once the reply is ready. - status = None - last_edit = 0.0 - - async def on_tool(step: ToolStep) -> None: - nonlocal status, last_edit - now = time.monotonic() - if now - last_edit < STATUS_EDIT_INTERVAL_S: - return - last_edit = now - text = f"Working… step {step.index}: {step.summary}" - try: - if status is None: - status = await context.bot.send_message( - chat_id, text, disable_notification=True, - ) - else: - await status.edit_text(text) - except TelegramError as exc: - logger.debug("Status update failed: {exc}", exc=exc) - - try: - response_text, found_images = await self.agent.handle( - prompt, - image_b64=image_b64, - image_media_type=image_media_type, - chat_id=str(chat_id), - on_tool=on_tool, - ) - finally: - typing_task.cancel() - if status is not None: - with contextlib.suppress(TelegramError): - await status.delete() - await self._send_response(update, context, response_text, found_images) - - # ------------------------------------------------------------------ - # Commands - # ------------------------------------------------------------------ - - async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - if not self._check_user(update.effective_user.id): - return - - await update.message.reply_text( - "Hi! I'm your personal memory assistant powered by Memclaw.\n\n" - "Just send me anything — text, photos, or voice messages.\n\n" - "I'll automatically decide whether to remember it, search your " - "memories, or retrieve images. No commands needed, just talk to me.\n\n" - "/new - start a fresh conversation (your memories are kept)\n" - "/model - show or change the model\n" - "/effort - show or change the reasoning effort" - ) - - async def new_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - if not self._check_user(update.effective_user.id): - return - await self.agent.reset_conversation(str(update.effective_chat.id)) - await update.message.reply_text("Started a new conversation.") - - async def model_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - if not self._check_user(update.effective_user.id): - return - backend = self.agent.backend - arg = " ".join(context.args or []).strip() - note = "" - if arg and backend.supports_model_selection: - try: - note = await select_model(backend, await _resolve_model_arg(backend, arg)) - except ValueError as exc: - note = f"{exc} Pick one below." - text, keyboard = await model_menu(backend, note) - await update.message.reply_text(text, reply_markup=keyboard) - - async def effort_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - if not self._check_user(update.effective_user.id): - return - backend = self.agent.backend - arg = " ".join(context.args or []).strip() - note = "" - if arg and backend.supports_model_selection: - try: - note = await select_effort(backend, arg) - except ValueError as exc: - note = str(exc) - text, keyboard = await effort_menu(backend, note) - await update.message.reply_text(text, reply_markup=keyboard) - - async def handle_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - """Button presses on the /model and /effort menus.""" - query = update.callback_query - if query is None: - return - if not self._check_user(update.effective_user.id): - await query.answer("You're not allowed to use this bot.") - return - backend = self.agent.backend - kind, _, value = (query.data or "").partition(":") - if kind not in ("m", "mi", "e") or not backend.supports_model_selection: - await query.answer() - return - try: - if kind == "e": - note = await select_effort(backend, value) - await query.answer(f"Effort: {backend.effort}") - text, keyboard = await effort_menu(backend, note) - else: - model_id = value - if kind == "mi": - models = await _load_models(backend) - model_id = next((m.id for m in models if _model_key(m.id) == value), "") - if not model_id: - raise ValueError("That model is no longer available; send /model again.") - note = await select_model(backend, model_id) - await query.answer(f"Model: {backend.model}") - text, keyboard = await model_menu(backend, note) - except ValueError as exc: - await query.answer(str(exc)[:200], show_alert=True) - return - try: - await query.edit_message_text(text, reply_markup=keyboard) - except BadRequest as exc: # e.g. "message is not modified" - logger.debug("Editing the menu after a button press failed: {exc}", exc=exc) - - # ------------------------------------------------------------------ - # Message handlers — everything goes through the agent - # ------------------------------------------------------------------ - - async def handle_text(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - if not self._check_user(update.effective_user.id): - return - - text = update.message.text - logger.info(f"Text from user {mask_user_id(update.effective_user.id)}: {text[:100]}") - - prompt_parts: list[str] = [] - replied = update.message.reply_to_message - if replied is not None: - quoted = replied.text or replied.caption or "" - if quoted: - prompt_parts.append(f"[Replying to message] {quoted}") - - prompt_parts.append(text) - - links = await self.link_processor.process_links(text) - for link in links: - if link.get("summary"): - prompt_parts.append( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt = "\n".join(prompt_parts) - await self._send_with_typing(update, context, prompt) - - async def handle_photo(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - if not self._check_user(update.effective_user.id): - return - - photo = update.message.photo[-1] - caption = update.message.caption or "" - - logger.info(f"Photo from user {mask_user_id(update.effective_user.id)}, caption={caption!r}") - - # Download photo and base64 encode - file = await context.bot.get_file(photo.file_id) - photo_bytes = await file.download_as_bytearray() - base64_image = base64.b64encode(photo_bytes).decode("utf-8") - logger.debug(f"Downloaded photo: {len(photo_bytes)} bytes") - - # Process links in caption - link_info = "" - if caption: - links = await self.link_processor.process_links(caption) - for link in links: - if link.get("summary"): - link_info += ( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt_text = f"User sent a photo. media_ref={photo.file_id}" - if caption: - prompt_text += f"\nCaption: {caption}" - if link_info: - prompt_text += link_info - - await self._send_with_typing( - update, context, prompt_text, - image_b64=base64_image, image_media_type="image/jpeg", - ) - - async def handle_voice(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - if not self._check_user(update.effective_user.id): - return - - voice = update.message.voice - logger.info(f"Voice from user {mask_user_id(update.effective_user.id)}") - - # Download and transcribe - file = await context.bot.get_file(voice.file_id) - voice_bytes = await file.download_as_bytearray() - - try: - transcription = await self.openai_client.audio.transcriptions.create( - model="whisper-1", - file=("voice.ogg", bytes(voice_bytes), "audio/ogg"), - ) - except Exception as exc: - logger.exception("Whisper transcription failed: {exc}", exc=exc) - await update.message.reply_text( - "I couldn't transcribe that voice message. " - "If you set up Memclaw recently, run `memclaw doctor` to check " - "your OpenAI key has access to the whisper-1 model." - ) - return - text = transcription.text - logger.info(f"Transcribed: {text}") - - # Process links - link_info = "" - links = await self.link_processor.process_links(text) - for link in links: - if link.get("summary"): - link_info += ( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - # Send to agent so it can respond — transcription is NOT pre-saved - prompt = ( - f"[Voice message] {text}" - "\nThis transcription has NOT been saved yet. Save it if the content is worth remembering." - f"{link_info}" - ) - await self._send_with_typing(update, context, prompt) - - async def aclose(self): - await self.agent.aclose() - self.scheduler.close() - - def close(self): - self.scheduler.close() - self.agent.close() - - -def build_application(config: MemclawConfig) -> Application: - """Build the Telegram bot: MessageHandlers, command handlers, error - handler and command menu, wired into a python-telegram-bot Application. - """ - async def post_init(application: Application) -> None: - openai_client = AsyncOpenAI(api_key=config.openai.api_key) - handlers = MessageHandlers(config, openai_client) - application.bot_data["handlers"] = handlers - - await handlers.agent.start() - await handlers.agent.start_background_sync(interval=60) - - handlers.attach_bot(application.bot) - handlers.scheduler.start() - - try: - await application.bot.set_my_commands( - [BotCommand(name, description) for name, description in BOT_COMMANDS] - ) - except TelegramError as exc: - logger.warning(f"Could not register the bot command menu: {exc}") - - logger.info("Memclaw bot initialized") - - async def post_shutdown(application: Application) -> None: - handlers = application.bot_data.get("handlers") - if handlers: - await handlers.aclose() - logger.info("Memclaw bot shut down cleanly") - - app = ( - Application.builder() - .token(config.telegram.bot_token) - .post_init(post_init) - .post_shutdown(post_shutdown) - .build() - ) - - async def _start(update, context): - await context.bot_data["handlers"].start_command(update, context) - - async def _new(update, context): - await context.bot_data["handlers"].new_command(update, context) - - async def _model(update, context): - await context.bot_data["handlers"].model_command(update, context) - - async def _effort(update, context): - await context.bot_data["handlers"].effort_command(update, context) - - async def _callback(update, context): - await context.bot_data["handlers"].handle_callback(update, context) - - async def _text(update, context): - await context.bot_data["handlers"].handle_text(update, context) - - async def _photo(update, context): - await context.bot_data["handlers"].handle_photo(update, context) - - async def _voice(update, context): - await context.bot_data["handlers"].handle_voice(update, context) - - async def _on_error(update, context): - err = context.error - if isinstance(err, (NetworkError, TimedOut)): - logger.warning(f"Network blip ({type(err).__name__}): {err} — polling will retry") - return - logger.exception("Unhandled error in Telegram handler", exc_info=err) - - app.add_error_handler(_on_error) - app.add_handler(CommandHandler("start", _start)) - app.add_handler(CommandHandler("new", _new)) - app.add_handler(CommandHandler("model", _model)) - app.add_handler(CommandHandler("effort", _effort)) - app.add_handler(CallbackQueryHandler(_callback)) - app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, _text)) - app.add_handler(MessageHandler(filters.PHOTO, _photo)) - app.add_handler(MessageHandler(filters.VOICE, _voice)) - - return app diff --git a/memclaw/bot/inbound.py b/memclaw/bot/inbound.py new file mode 100644 index 0000000..c7f5d11 --- /dev/null +++ b/memclaw/bot/inbound.py @@ -0,0 +1,156 @@ +"""What every chat platform does with a message, apart from the platform I/O. + +A platform module receives a message, downloads its media and sends the +reply. Everything in between is here: voice to text, link summaries, the +prompt the agent gets, the agent call, and reminder delivery. + +The prompt texts are part of the agent's instructions (AGENTS.md tells it +that content marked "NOT been saved yet" is for it to save or not), so they +are written once, here. +""" + +from __future__ import annotations + +import base64 +import uuid +from pathlib import Path +from typing import Awaitable, Callable, Collection + +from loguru import logger + +from ..agent import MemclawAgent +from ..backends.base import ProgressCallback +from ..config import MemclawConfig +from ..openai_client import OpenAIClient +from ..reminders import ReminderScheduler +from .links import LinkProcessor + +TRANSCRIPTION_FAILED = ( + "I couldn't transcribe that voice message. " + "If you set up Memclaw recently, run `memclaw doctor` to check " + "your OpenAI key has access to the whisper-1 model." +) +NEW_CONVERSATION = "Started a new conversation." + +SendText = Callable[[str, str], Awaitable[None]] # (chat id, text) + + +def is_allowed(who: object, allowlist: Collection, *, empty_allows_all: bool) -> bool: + """Whether *who* may use the bot. The platforms disagree on what an + empty allowlist means, so each one says (see their access checks).""" + if not allowlist: + return empty_allows_all + return who in allowlist + + +def save_media(media_dir: Path, data: bytes, ext: str) -> Path: + """Keep a received file under a platform's media dir (a random name), so + the agent can refer to it and send it back later.""" + path = media_dir / f"{uuid.uuid4().hex}{ext}" + path.write_bytes(data) + return path + + +def _link_note(url: str, summary: str) -> str: + return ( + f"\n[Link summary] {url}: {summary}" + "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." + ) + + +class Inbound: + """The agent, its reminder scheduler and the message pipeline of one platform.""" + + def __init__(self, config: MemclawConfig, platform: str): + self.platform = platform + self.openai = OpenAIClient(config.openai.api_key) + self.links = LinkProcessor(self.openai) + self.scheduler = ReminderScheduler(config) + self.agent = MemclawAgent(config, platform=platform, scheduler=self.scheduler) + + # ── Prompts ────────────────────────────────────────────────────── + + async def _link_notes(self, text: str) -> list[str]: + links = await self.links.process_links(text) + return [_link_note(link["url"], link["summary"]) for link in links if link.get("summary")] + + async def text_prompt(self, text: str, *, quoted: str = "") -> str: + """A text message (and the message it replies to, if any), plus a + summary of each link in it.""" + parts = [f"[Replying to message] {quoted}"] if quoted else [] + return "\n".join([*parts, text, *await self._link_notes(text)]) + + async def photo_prompt(self, media_ref: str, caption: str) -> str: + """*media_ref* is how the agent refers to the image (image_save).""" + prompt = f"User sent a photo. media_ref={media_ref}" + if caption: + prompt += f"\nCaption: {caption}" + "".join(await self._link_notes(caption)) + return prompt + + async def voice_prompt(self, transcript: str) -> str: + # The transcription is NOT pre-saved: the agent decides. + return ( + f"[Voice message] {transcript}" + "\nThis transcription has NOT been saved yet. Save it if the content is worth remembering." + + "".join(await self._link_notes(transcript)) + ) + + async def transcribe(self, audio: bytes, *, filename: str, mime_type: str) -> str | None: + """The voice message's text, or None if Whisper failed (logged; the + platform replies with TRANSCRIPTION_FAILED).""" + try: + return await self.openai.transcribe(audio, filename=filename, mime_type=mime_type) + except Exception as exc: + logger.exception("Whisper transcription failed: {exc}", exc=exc) + return None + + # ── The agent ──────────────────────────────────────────────────── + + async def ask( + self, + prompt: str, + *, + chat_id: str, + image: tuple[bytes, str] | None = None, + on_tool: ProgressCallback | None = None, + ) -> tuple[str, list[dict]]: + """Run one agent turn. *image* is (bytes, media type). Returns the + reply text and the stored images the agent chose to send back.""" + data, media_type = image or (None, "image/jpeg") + return await self.agent.handle( + prompt, + image_b64=base64.b64encode(data).decode("utf-8") if data is not None else None, + image_media_type=media_type, + chat_id=chat_id, + on_tool=on_tool, + ) + + async def new_conversation(self, chat_id: str) -> str: + """The `/new` command; returns the reply.""" + await self.agent.reset_conversation(chat_id) + return NEW_CONVERSATION + + def deliver_reminders(self, send: SendText) -> None: + """Send this platform's due reminders with *send*; the chat's next + turn then knows about the reminder (for a reply to it).""" + async def deliver(chat_id: str, text: str) -> None: + await send(chat_id, text) + self.agent.record_reminder_fired(text, chat_id) + + self.scheduler.register_delivery(self.platform, deliver) + + # ── Lifecycle ──────────────────────────────────────────────────── + + async def start(self) -> None: + """Index the vault, keep it in sync, start firing reminders.""" + await self.agent.start() + await self.agent.start_background_sync(interval=60) + self.scheduler.start() + + async def aclose(self) -> None: + await self.agent.aclose() + self.scheduler.close() + + def close(self) -> None: + self.scheduler.close() + self.agent.close() diff --git a/memclaw/bot/link_processor.py b/memclaw/bot/links.py similarity index 77% rename from memclaw/bot/link_processor.py rename to memclaw/bot/links.py index 7139ea0..23307a2 100644 --- a/memclaw/bot/link_processor.py +++ b/memclaw/bot/links.py @@ -1,3 +1,5 @@ +"""Link summaries: find the URLs in a message, fetch each page and summarize it.""" + from __future__ import annotations import re @@ -6,14 +8,15 @@ from bs4 import BeautifulSoup from curl_cffi.requests import AsyncSession from loguru import logger -from openai import AsyncOpenAI + +from ..openai_client import OpenAIClient class LinkProcessor: """Extract URLs from text, fetch page content, and generate summaries.""" - def __init__(self, openai_client: AsyncOpenAI): - self.openai_client = openai_client + def __init__(self, openai: OpenAIClient): + self.openai = openai self._url_re = re.compile(r"https?://[^\s<>\"')\]]+", re.IGNORECASE) def extract_urls(self, text: str) -> list[str]: @@ -72,22 +75,16 @@ def _extract_text(html: str, max_chars: int = 5000) -> str: async def summarize(self, content: str, url: str) -> str: try: - response = await self.openai_client.chat.completions.create( - model="gpt-5-mini", - messages=[ - { - "role": "system", - "content": ( - "Summarize this web content concisely. " - "Focus on main points. Keep it under 50 tokens." - ), - }, - {"role": "user", "content": f"Summarize content from {url}:\n\n{content}"}, - ], - reasoning_effort="low", - max_completion_tokens=300, - ) - return response.choices[0].message.content or "" + return await self.openai.chat([ + { + "role": "system", + "content": ( + "Summarize this web content concisely. " + "Focus on main points. Keep it under 50 tokens." + ), + }, + {"role": "user", "content": f"Summarize content from {url}:\n\n{content}"}, + ]) except Exception as e: return f"Could not summarize: {e}" diff --git a/memclaw/bot/slack.py b/memclaw/bot/slack.py new file mode 100644 index 0000000..f761911 --- /dev/null +++ b/memclaw/bot/slack.py @@ -0,0 +1,279 @@ +"""Slack: receive messages and files, download them, send replies. + +Uses slack-bolt with Socket Mode — no public URL required. What happens to +a message in between is shared with the other platforms (memclaw.bot.inbound). +""" + +from __future__ import annotations + +import asyncio +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Awaitable, Callable + +import httpx +from loguru import logger +from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler +from slack_bolt.async_app import AsyncApp + +from ..config import MemclawConfig +from . import console, log_to, mask_user_id, require_setting +from .inbound import TRANSCRIPTION_FAILED, Inbound, is_allowed, save_media + +# Image MIME types we handle +_IMAGE_MIMES = {"image/jpeg", "image/png", "image/gif", "image/webp", "image/bmp"} + +_MIME_TO_EXT = { + "image/jpeg": ".jpg", + "image/png": ".png", + "image/webp": ".webp", + "image/gif": ".gif", + "image/bmp": ".bmp", + "audio/ogg": ".ogg", + "audio/mpeg": ".mp3", + "audio/mp4": ".m4a", + "audio/x-m4a": ".m4a", + "audio/wav": ".wav", + "audio/webm": ".webm", +} + + +@dataclass +class _Thread: + """Who sent a message, where, and how to answer in its thread.""" + + user: str + channel: str + ts: str + say: Callable[..., Awaitable[Any]] + + async def reply(self, text: str) -> None: + await self.say(text=text, thread_ts=self.ts) + + +class SlackBot: + """Receives Slack messages and files, and sends the replies.""" + + def __init__(self, config: MemclawConfig): + self.config = config + self.inbound = Inbound(config, "slack") + + self.app = AsyncApp(token=config.slack.bot_token) + self._register_handlers() + self.inbound.deliver_reminders(self._send_reminder) + + async def _send_reminder(self, chat_id: str, text: str) -> None: + await self.app.client.chat_postMessage(channel=chat_id, text=text) + + def _register_handlers(self): + """Register Slack event handlers on the bolt app.""" + + @self.app.event("message") + async def handle_message_event(event, say, client): + await self._route_event(event, say) + + @self.app.event("app_mention") + async def handle_mention(event, say, client): + await self._route_event(event, say) + + # ── Access control ─────────────────────────────────────────────── + # An empty SLACK_ALLOWED_CHANNELS / SLACK_ALLOWED_USERS lets everyone in. + + def _check_channel(self, channel: str) -> bool: + return is_allowed(channel, self.config.slack.allowed_channels_list, empty_allows_all=True) + + def _check_user(self, user: str) -> bool: + return is_allowed(user, self.config.slack.allowed_users_list, empty_allows_all=True) + + # ── Event routing ──────────────────────────────────────────────── + + async def _route_event(self, event: dict, say): + # Ignore bot messages to prevent loops + if event.get("bot_id") or event.get("subtype") == "bot_message": + return + + channel = event.get("channel", "") + if not self._check_channel(channel): + return + + user = event.get("user", "unknown") + if not self._check_user(user): + logger.debug("Ignoring Slack event from unauthorized user {u}", u=user) + return + thread = _Thread(user, channel, event.get("thread_ts") or event.get("ts", ""), say) + files = event.get("files", []) + + # Strip bot mention from text (e.g. "<@U123ABC> hello" → "hello") + text = self._strip_mention(event.get("text", "")) + + # Check if there are image files attached + image_files = [f for f in files if f.get("mimetype", "") in _IMAGE_MIMES] + audio_files = [f for f in files if f.get("mimetype", "").startswith("audio/")] + + if not files and text.lower() == "/new": + await thread.reply(await self.inbound.new_conversation(channel)) + elif image_files: + await self._handle_image(thread, text, image_files[0]) + elif audio_files: + await self._handle_audio(thread, audio_files[0]) + elif text: + await self._handle_text(thread, text) + else: + logger.debug("Ignoring Slack event with no text or supported files") + + @staticmethod + def _strip_mention(text: str) -> str: + """Remove bot mention tags like <@U123ABC> from the start of messages.""" + return re.sub(r"^\s*<@[A-Z0-9]+>\s*", "", text).strip() + + # ── Messages ───────────────────────────────────────────────────── + + async def _handle_text(self, thread: _Thread, text: str): + logger.info( + "Slack text from {u} in {c}: {t}", u=mask_user_id(thread.user), c=thread.channel, t=text[:100], + ) + prompt = await self.inbound.text_prompt(text) + await self._answer(thread, prompt) + + async def _handle_image(self, thread: _Thread, caption: str, file_info: dict): + file_name = file_info.get("name", "image") + logger.info( + "Slack image from {u}: {f}, caption={c!r}", u=mask_user_id(thread.user), f=file_name, c=caption, + ) + + # Download image via Slack file URL (requires bot token for auth) + image_bytes = await self._download_slack_file(file_info) + if image_bytes is None: + await thread.reply("Sorry, I couldn't download that image.") + return + + # Save locally under the slack media dir so retrievals can upload it back. + mime = file_info.get("mimetype", "image/jpeg") + local_path = save_media(self.config.slack_media_dir, image_bytes, _MIME_TO_EXT.get(mime) or ".jpg") + logger.debug("Downloaded Slack image: {n} bytes -> {p}", n=len(image_bytes), p=local_path) + + prompt = await self.inbound.photo_prompt(str(local_path), caption) + media_type = mime if mime.startswith("image/") else "image/jpeg" + await self._answer(thread, prompt, image=(image_bytes, media_type)) + + async def _handle_audio(self, thread: _Thread, file_info: dict): + file_name = file_info.get("name", "audio") + logger.info("Slack audio from {u}: {f}", u=mask_user_id(thread.user), f=file_name) + + audio_bytes = await self._download_slack_file(file_info) + if audio_bytes is None: + await thread.reply("Sorry, I couldn't download that audio file.") + return + + mime = file_info.get("mimetype", "audio/mp4") + ext = _MIME_TO_EXT.get(mime) or ".m4a" + text = await self.inbound.transcribe(audio_bytes, filename=f"audio{ext}", mime_type=mime) + if text is None: + await thread.reply(TRANSCRIPTION_FAILED) + return + logger.info("Transcribed Slack audio: {t}", t=text) + + await self._answer(thread, await self.inbound.voice_prompt(text)) + + async def _answer(self, thread: _Thread, prompt: str, *, image: tuple[bytes, str] | None = None): + response_text, found_images = await self.inbound.ask(prompt, chat_id=thread.channel, image=image) + await self._send_response(thread, response_text, found_images) + + # ── Slack API helpers ──────────────────────────────────────────── + + async def _download_slack_file(self, file_info: dict) -> bytes | None: + """Download a file from Slack using the url_private_download URL.""" + url = file_info.get("url_private_download") or file_info.get("url_private", "") + if not url: + logger.error("No download URL in Slack file info") + return None + + try: + async with httpx.AsyncClient( + headers={"Authorization": f"Bearer {self.config.slack.bot_token}"}, + timeout=30.0, + ) as client: + resp = await client.get(url) + resp.raise_for_status() + return resp.content + except Exception as exc: + logger.error("Failed to download Slack file: {exc}", exc=exc) + return None + + async def _upload_and_share_image(self, thread: _Thread, image_path: str, caption: str | None = None): + """Upload a local image to Slack and share it in a channel.""" + path = Path(image_path) + if not path.exists(): + logger.error("Image file not found for Slack upload: {p}", p=image_path) + return + + try: + result = await self.app.client.files_upload_v2( + channel=thread.channel, + file=str(path), + filename=path.name, + initial_comment=caption or "", + thread_ts=thread.ts if thread.ts else None, + ) + logger.debug("Uploaded image to Slack: {r}", r=result.get("ok")) + except Exception as exc: + logger.error("Failed to upload image to Slack: {exc}", exc=exc) + + async def _send_response(self, thread: _Thread, response_text: str, found_images: list[dict]): + """Send agent response: images first, then text.""" + for img in found_images: + platform = img.get("platform", "telegram") + media_ref = img.get("media_ref") or img.get("file_id", "") + caption = img.get("caption") or None + + if platform == "slack": + await self._upload_and_share_image(thread, media_ref, caption) + else: + # For images from other platforms (e.g. Telegram file_ids), + # include a note in the text response + desc = img.get("description", "an image") + if response_text: + response_text += f"\n\n_(Found image: {desc} -- originally saved via {platform})_" + else: + response_text = f"_(Found image: {desc} -- originally saved via {platform})_" + + if response_text: + await thread.reply(response_text[:4000]) + + # ── Lifecycle ──────────────────────────────────────────────────── + + async def start(self): + """Start the Slack bot via Socket Mode.""" + await self.inbound.start() + handler = AsyncSocketModeHandler(self.app, self.config.slack.app_token) + await handler.start_async() + + async def aclose(self): + await self.inbound.aclose() + + +def run(config: MemclawConfig) -> None: + """Start the Slack bot (Socket Mode) and block until it stops.""" + require_setting(config.slack.bot_token, "SLACK_BOT_TOKEN") + require_setting(config.slack.app_token, "SLACK_APP_TOKEN") + + log_to(config.memory_dir / "slack.log") + + bot = SlackBot(config) + + console.print( + f"[green]Starting Memclaw Slack bot (Socket Mode)...[/green] " + f"(allowed channels: {config.slack.allowed_channels_list or 'all'})" + ) + + async def _run(): + try: + await bot.start() + except KeyboardInterrupt: + pass + finally: + await bot.aclose() + console.print("\nMemclaw Slack bot shut down.") + + asyncio.run(_run()) diff --git a/memclaw/bot/slack_handlers.py b/memclaw/bot/slack_handlers.py deleted file mode 100644 index e55792e..0000000 --- a/memclaw/bot/slack_handlers.py +++ /dev/null @@ -1,358 +0,0 @@ -"""Slack bot event handlers for Memclaw. - -Every message (text, file/image) goes through the unified MemclawAgent, -which autonomously decides whether to store, search, or just respond. - -Uses slack-bolt with Socket Mode — no public URL required. -""" - -from __future__ import annotations - -import base64 -import re -import uuid -from pathlib import Path - -import httpx -from loguru import logger -from openai import AsyncOpenAI -from slack_bolt.async_app import AsyncApp -from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler - -from ..agent import MemclawAgent -from ..config import MemclawConfig -from ..reminders import ReminderScheduler -from . import mask_user_id -from .link_processor import LinkProcessor - -# Image MIME types we handle -_IMAGE_MIMES = {"image/jpeg", "image/png", "image/gif", "image/webp", "image/bmp"} - - -class SlackHandlers: - """Routes every Slack message through the unified Memclaw agent.""" - - def __init__(self, config: MemclawConfig, openai_client: AsyncOpenAI): - self.config = config - self.openai_client = openai_client - self.scheduler = ReminderScheduler(config) - self.agent = MemclawAgent(config, platform="slack", scheduler=self.scheduler) - self.link_processor = LinkProcessor(openai_client) - - self.app = AsyncApp(token=config.slack.bot_token) - self._register_handlers() - self.scheduler.register_delivery("slack", self._deliver_reminder) - - async def _deliver_reminder(self, chat_id: str, text: str): - await self.app.client.chat_postMessage(channel=chat_id, text=text) - self.agent.record_reminder_fired(text, chat_id) - - def _register_handlers(self): - """Register Slack event handlers on the bolt app.""" - - @self.app.event("message") - async def handle_message_event(event, say, client): - await self._route_event(event, say, client) - - @self.app.event("app_mention") - async def handle_mention(event, say, client): - await self._route_event(event, say, client) - - # ------------------------------------------------------------------ - # Access control - # ------------------------------------------------------------------ - - def _check_channel(self, channel: str) -> bool: - allowed = self.config.slack.allowed_channels_list - if not allowed: - return True # no allowlist = allow all - return channel in allowed - - def _check_user(self, user: str) -> bool: - allowed = self.config.slack.allowed_users_list - if not allowed: - return True # no allowlist = allow all - return user in allowed - - # ------------------------------------------------------------------ - # Event routing - # ------------------------------------------------------------------ - - async def _route_event(self, event: dict, say, client): - # Ignore bot messages to prevent loops - if event.get("bot_id") or event.get("subtype") == "bot_message": - return - - channel = event.get("channel", "") - if not self._check_channel(channel): - return - - user = event.get("user", "unknown") - if not self._check_user(user): - logger.debug("Ignoring Slack event from unauthorized user {u}", u=user) - return - thread_ts = event.get("thread_ts") or event.get("ts", "") - text = event.get("text", "") - files = event.get("files", []) - - # Strip bot mention from text (e.g. "<@U123ABC> hello" → "hello") - text = self._strip_mention(text) - - # Check if there are image files attached - image_files = [f for f in files if f.get("mimetype", "") in _IMAGE_MIMES] - audio_files = [f for f in files if f.get("mimetype", "").startswith("audio/")] - - if not files and text.lower() == "/new": - await self.agent.reset_conversation(channel) - await say(text="Started a new conversation.", thread_ts=thread_ts) - elif image_files: - await self._handle_image(user, channel, thread_ts, text, image_files[0], say, client) - elif audio_files: - await self._handle_audio(user, channel, thread_ts, text, audio_files[0], say, client) - elif text: - await self._handle_text(user, channel, thread_ts, text, say) - else: - logger.debug("Ignoring Slack event with no text or supported files") - - @staticmethod - def _strip_mention(text: str) -> str: - """Remove bot mention tags like <@U123ABC> from the start of messages.""" - return re.sub(r"^\s*<@[A-Z0-9]+>\s*", "", text).strip() - - # ------------------------------------------------------------------ - # Text messages - # ------------------------------------------------------------------ - - async def _handle_text(self, user: str, channel: str, thread_ts: str, text: str, say): - logger.info("Slack text from {u} in {c}: {t}", u=mask_user_id(user), c=channel, t=text[:100]) - - prompt_parts = [text] - links = await self.link_processor.process_links(text) - for link in links: - if link.get("summary"): - prompt_parts.append( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt = "\n".join(prompt_parts) - response_text, found_images = await self.agent.handle(prompt, chat_id=channel) - await self._send_response(channel, thread_ts, response_text, found_images, say) - - # ------------------------------------------------------------------ - # Image messages - # ------------------------------------------------------------------ - - async def _handle_image( - self, user: str, channel: str, thread_ts: str, caption: str, - file_info: dict, say, client, - ): - file_name = file_info.get("name", "image") - logger.info("Slack image from {u}: {f}, caption={c!r}", u=mask_user_id(user), f=file_name, c=caption) - - # Download image via Slack file URL (requires bot token for auth) - image_bytes = await self._download_slack_file(file_info) - if image_bytes is None: - await say(text="Sorry, I couldn't download that image.", thread_ts=thread_ts) - return - - # Save locally under the slack media dir so retrievals can upload it back. - mime = file_info.get("mimetype", "image/jpeg") - ext = _mime_to_ext(mime) or ".jpg" - local_path = self.config.slack_media_dir / f"{uuid.uuid4().hex}{ext}" - local_path.write_bytes(image_bytes) - - base64_image = base64.b64encode(image_bytes).decode("utf-8") - logger.debug("Downloaded Slack image: {n} bytes -> {p}", n=len(image_bytes), p=local_path) - - # Process links in caption - link_info = "" - if caption: - links = await self.link_processor.process_links(caption) - for link in links: - if link.get("summary"): - link_info += ( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt_text = f"User sent a photo. media_ref={local_path}" - if caption: - prompt_text += f"\nCaption: {caption}" - if link_info: - prompt_text += link_info - - media_type = mime if mime.startswith("image/") else "image/jpeg" - response_text, found_images = await self.agent.handle( - prompt_text, - image_b64=base64_image, - image_media_type=media_type, - chat_id=channel, - ) - await self._send_response(channel, thread_ts, response_text, found_images, say) - - # ------------------------------------------------------------------ - # Audio messages - # ------------------------------------------------------------------ - - async def _handle_audio( - self, user: str, channel: str, thread_ts: str, caption: str, - file_info: dict, say, client, - ): - file_name = file_info.get("name", "audio") - logger.info("Slack audio from {u}: {f}", u=mask_user_id(user), f=file_name) - - audio_bytes = await self._download_slack_file(file_info) - if audio_bytes is None: - await say(text="Sorry, I couldn't download that audio file.", thread_ts=thread_ts) - return - - mime = file_info.get("mimetype", "audio/mp4") - ext = _mime_to_ext(mime) or ".m4a" - - try: - transcription = await self.openai_client.audio.transcriptions.create( - model="whisper-1", - file=(f"audio{ext}", audio_bytes, mime), - ) - except Exception as exc: - logger.exception("Whisper transcription failed: {exc}", exc=exc) - await say( - text=( - "I couldn't transcribe that voice message. " - "If you set up Memclaw recently, run `memclaw doctor` to check " - "your OpenAI key has access to the whisper-1 model." - ), - thread_ts=thread_ts, - ) - return - text = transcription.text - logger.info("Transcribed Slack audio: {t}", t=text) - - link_info = "" - links = await self.link_processor.process_links(text) - for link in links: - if link.get("summary"): - link_info += ( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt = ( - f"[Voice message] {text}" - "\nThis transcription has NOT been saved yet. Save it if the content is worth remembering." - f"{link_info}" - ) - response_text, found_images = await self.agent.handle(prompt, chat_id=channel) - await self._send_response(channel, thread_ts, response_text, found_images, say) - - # ------------------------------------------------------------------ - # Slack API helpers - # ------------------------------------------------------------------ - - async def _download_slack_file(self, file_info: dict) -> bytes | None: - """Download a file from Slack using the url_private_download URL.""" - url = file_info.get("url_private_download") or file_info.get("url_private", "") - if not url: - logger.error("No download URL in Slack file info") - return None - - try: - async with httpx.AsyncClient( - headers={"Authorization": f"Bearer {self.config.slack.bot_token}"}, - timeout=30.0, - ) as client: - resp = await client.get(url) - resp.raise_for_status() - return resp.content - except Exception as exc: - logger.error("Failed to download Slack file: {exc}", exc=exc) - return None - - async def _upload_and_share_image(self, channel: str, thread_ts: str, image_path: str, caption: str | None = None): - """Upload a local image to Slack and share it in a channel.""" - path = Path(image_path) - if not path.exists(): - logger.error("Image file not found for Slack upload: {p}", p=image_path) - return - - try: - result = await self.app.client.files_upload_v2( - channel=channel, - file=str(path), - filename=path.name, - initial_comment=caption or "", - thread_ts=thread_ts if thread_ts else None, - ) - logger.debug("Uploaded image to Slack: {r}", r=result.get("ok")) - except Exception as exc: - logger.error("Failed to upload image to Slack: {exc}", exc=exc) - - async def _send_response( - self, - channel: str, - thread_ts: str, - response_text: str, - found_images: list[dict], - say, - ): - """Send agent response: images first, then text.""" - for img in found_images: - platform = img.get("platform", "telegram") - media_ref = img.get("media_ref") or img.get("file_id", "") - caption = img.get("caption") or None - - if platform == "slack": - await self._upload_and_share_image(channel, thread_ts, media_ref, caption) - else: - # For images from other platforms (e.g. Telegram file_ids), - # include a note in the text response - desc = img.get("description", "an image") - if response_text: - response_text += f"\n\n_(Found image: {desc} -- originally saved via {platform})_" - else: - response_text = f"_(Found image: {desc} -- originally saved via {platform})_" - - if response_text: - await say(text=response_text[:4000], thread_ts=thread_ts) - - # ------------------------------------------------------------------ - # Lifecycle - # ------------------------------------------------------------------ - - async def start(self): - """Start the Slack bot via Socket Mode.""" - await self.agent.start() - await self.agent.start_background_sync(interval=60) - self.scheduler.start() - handler = AsyncSocketModeHandler(self.app, self.config.slack.app_token) - await handler.start_async() - - async def aclose(self): - await self.agent.aclose() - self.scheduler.close() - - def close(self): - self.scheduler.close() - self.agent.close() - - -# ------------------------------------------------------------------ -# Utilities -# ------------------------------------------------------------------ - -def _mime_to_ext(mime_type: str) -> str: - mapping = { - "image/jpeg": ".jpg", - "image/png": ".png", - "image/webp": ".webp", - "image/gif": ".gif", - "image/bmp": ".bmp", - "audio/ogg": ".ogg", - "audio/mpeg": ".mp3", - "audio/mp4": ".m4a", - "audio/x-m4a": ".m4a", - "audio/wav": ".wav", - "audio/webm": ".webm", - } - return mapping.get(mime_type, "") diff --git a/memclaw/bot/telegram.py b/memclaw/bot/telegram.py new file mode 100644 index 0000000..800ad41 --- /dev/null +++ b/memclaw/bot/telegram.py @@ -0,0 +1,467 @@ +"""Telegram: receive messages, download their media, send replies, and the +/new, /model and /effort commands with their button menus. + +What happens to a message in between is shared with the other platforms +(memclaw.bot.inbound). +""" + +from __future__ import annotations + +import asyncio +import contextlib +import hashlib +import time +from typing import Awaitable, Callable + +from loguru import logger +from telegram import BotCommand, InlineKeyboardButton, InlineKeyboardMarkup, Message, Update +from telegram.constants import ChatAction +from telegram.error import BadRequest, NetworkError, TelegramError, TimedOut +from telegram.ext import ( + Application, + CallbackQueryHandler, + CommandHandler, + ContextTypes, + MessageHandler, + filters, +) + +from ..backends import AgentBackend +from ..backends.base import ToolStep +from ..config import MemclawConfig +from . import console, log_to, mask_user_id, require_setting +from .commands import ( + load_models, + resolve_model_arg, + select_effort, + select_model, + status_lines, + unsupported, +) +from .inbound import TRANSCRIPTION_FAILED, Inbound, is_allowed + + +async def _typing_loop(bot, chat_id: int): + """Send 'typing...' action every 4 seconds until cancelled.""" + try: + while True: + try: + await bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING) + except Exception: + pass # best-effort + await asyncio.sleep(4) + except asyncio.CancelledError: + pass + + +# Shown in Telegram's command menu (registered in build_application). +BOT_COMMANDS = [ + ("new", "Start a fresh conversation"), + ("model", "Show or change the model"), + ("effort", "Show or change the reasoning effort"), +] + +# Minimum seconds between edits of the "Working…" status message, to stay +# well under Telegram's rate limits. +STATUS_EDIT_INTERVAL_S = 2.0 + +# Telegram limits callback_data to 64 bytes. +CALLBACK_DATA_MAX_BYTES = 64 + + +def _model_key(model_id: str) -> str: + return hashlib.sha256(model_id.encode()).hexdigest()[:16] + + +def model_callback_data(model_id: str) -> str: + """``m:``, or ``mi:`` if the id would exceed + Telegram's limit. A hash rather than a list position, so a button still + picks its own model if the list has changed since the menu was shown.""" + data = f"m:{model_id}" + return data if len(data.encode()) <= CALLBACK_DATA_MAX_BYTES else f"mi:{_model_key(model_id)}" + + +async def model_menu( + backend: AgentBackend, note: str = "", +) -> tuple[str, InlineKeyboardMarkup | None]: + """`/model` reply: current settings plus one button per model.""" + if not backend.supports_model_selection: + return unsupported(backend, "Switching models"), None + models = await load_models(backend) + lines = status_lines(backend, models, await backend.effort_levels()) + if note: + lines += ["", note] + lines.append("") + if not models: + lines.append("Couldn't load the model list right now; try /model again later.") + return "\n".join(lines), None + lines.append("Tap a model to switch, or send /model .") + keyboard = InlineKeyboardMarkup([ + [InlineKeyboardButton( + ("✓ " if m.id == backend.model else "") + m.display_name, + callback_data=model_callback_data(m.id), + )] + for m in models + ]) + return "\n".join(lines), keyboard + + +async def effort_menu( + backend: AgentBackend, note: str = "", +) -> tuple[str, InlineKeyboardMarkup | None]: + """`/effort` reply: current settings plus a row of level buttons.""" + if not backend.supports_model_selection: + return unsupported(backend, "Changing the effort"), None + levels = await backend.effort_levels() + lines = status_lines(backend, await load_models(backend), levels) + if note: + lines += ["", note] + lines.append("") + if levels == []: + lines.append("This model doesn't support an effort setting.") + return "\n".join(lines), None + if levels is None: + lines.append("Send /effort to change it.") + return "\n".join(lines), None + lines.append("Tap a level, or send /effort .") + keyboard = InlineKeyboardMarkup([[ + InlineKeyboardButton( + ("✓ " if lv == backend.effort else "") + lv, callback_data=f"e:{lv}", + ) + for lv in levels + ]]) + return "\n".join(lines), keyboard + + +def _command_arg(context: ContextTypes.DEFAULT_TYPE) -> str: + return " ".join(context.args or []).strip() + + +def _who(update: Update) -> str: + """The sender's masked id, for the log.""" + user = update.effective_user + return mask_user_id(user.id if user else "") + + +class TelegramBot: + """Receives Telegram messages and commands, and sends the replies.""" + + def __init__(self, config: MemclawConfig): + self.config = config + self.inbound = Inbound(config, "telegram") + + def attach_bot(self, bot) -> None: + """Give the handler a reference to the Telegram Bot for reminder delivery.""" + async def send(chat_id: str, text: str) -> None: + await bot.send_message(chat_id=int(chat_id), text=text) + + self.inbound.deliver_reminders(send) + + def _allowed(self, update: Update) -> bool: + """Only the users in ALLOWED_USER_IDS; an empty list lets nobody in.""" + user = update.effective_user + return user is not None and is_allowed( + user.id, self.config.telegram.allowed_user_ids_list, empty_allows_all=False, + ) + + def _message(self, update: Update) -> Message | None: + """The update's message, if it comes from an allowed user.""" + return update.message if self._allowed(update) else None + + async def _send_response( + self, + message: Message, + context: ContextTypes.DEFAULT_TYPE, + response_text: str, + found_images: list[dict], + ): + """Send agent response: images first, then text.""" + for img in found_images: + try: + await context.bot.send_photo( + chat_id=message.chat_id, + photo=img["file_id"], + caption=img.get("caption") or None, + ) + except Exception as e: + logger.error(f"Failed to send image {img.get('file_id')}: {e}") + + if response_text: + try: + await message.reply_text(response_text[:4096], parse_mode="Markdown") + except Exception as e: + # Fall back to plain text if the agent emitted something Telegram's + # legacy Markdown parser rejects (unbalanced * or _, etc.). + logger.warning(f"Markdown parse failed, sending plain: {e}") + await message.reply_text(response_text[:4096]) + + async def _send_with_typing( + self, + message: Message, + context: ContextTypes.DEFAULT_TYPE, + prompt: str, + *, + image: tuple[bytes, str] | None = None, + ): + """Run the agent with a typing indicator, then send the full response.""" + chat_id = message.chat_id + typing_task = asyncio.create_task(_typing_loop(context.bot, chat_id)) + # One silent status message, edited as the agent works and deleted + # once the reply is ready. + status: Message | None = None + last_edit = 0.0 + + async def on_tool(step: ToolStep) -> None: + nonlocal status, last_edit + now = time.monotonic() + if now - last_edit < STATUS_EDIT_INTERVAL_S: + return + last_edit = now + text = f"Working… step {step.index}: {step.summary}" + try: + if status is None: + status = await context.bot.send_message( + chat_id, text, disable_notification=True, + ) + else: + await status.edit_text(text) + except TelegramError as exc: + logger.debug("Status update failed: {exc}", exc=exc) + + try: + response_text, found_images = await self.inbound.ask( + prompt, chat_id=str(chat_id), image=image, on_tool=on_tool, + ) + finally: + typing_task.cancel() + if status is not None: + with contextlib.suppress(TelegramError): + await status.delete() + await self._send_response(message, context, response_text, found_images) + + # ── Commands ───────────────────────────────────────────────────── + + async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + message = self._message(update) + if message is None: + return + + await message.reply_text( + "Hi! I'm your personal memory assistant powered by Memclaw.\n\n" + "Just send me anything — text, photos, or voice messages.\n\n" + "I'll automatically decide whether to remember it, search your " + "memories, or retrieve images. No commands needed, just talk to me.\n\n" + "/new - start a fresh conversation (your memories are kept)\n" + "/model - show or change the model\n" + "/effort - show or change the reasoning effort" + ) + + async def new_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + message = self._message(update) + if message is None: + return + await message.reply_text(await self.inbound.new_conversation(str(message.chat_id))) + + async def model_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + message = self._message(update) + if message is None: + return + backend, arg, note = self.inbound.agent.backend, _command_arg(context), "" + if arg and backend.supports_model_selection: + try: + note = await select_model(backend, await resolve_model_arg(backend, arg)) + except ValueError as exc: + note = f"{exc} Pick one below." + text, keyboard = await model_menu(backend, note) + await message.reply_text(text, reply_markup=keyboard) + + async def effort_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + message = self._message(update) + if message is None: + return + backend, arg, note = self.inbound.agent.backend, _command_arg(context), "" + if arg and backend.supports_model_selection: + try: + note = await select_effort(backend, arg) + except ValueError as exc: + note = str(exc) + text, keyboard = await effort_menu(backend, note) + await message.reply_text(text, reply_markup=keyboard) + + async def handle_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + """Button presses on the /model and /effort menus.""" + query = update.callback_query + if query is None: + return + if not self._allowed(update): + await query.answer("You're not allowed to use this bot.") + return + backend = self.inbound.agent.backend + kind, _, value = (query.data or "").partition(":") + if kind not in ("m", "mi", "e") or not backend.supports_model_selection: + await query.answer() + return + try: + if kind == "e": + note = await select_effort(backend, value) + await query.answer(f"Effort: {backend.effort}") + text, keyboard = await effort_menu(backend, note) + else: + model_id = value + if kind == "mi": + models = await load_models(backend) + model_id = next((m.id for m in models if _model_key(m.id) == value), "") + if not model_id: + raise ValueError("That model is no longer available; send /model again.") + note = await select_model(backend, model_id) + await query.answer(f"Model: {backend.model}") + text, keyboard = await model_menu(backend, note) + except ValueError as exc: + await query.answer(str(exc)[:200], show_alert=True) + return + try: + await query.edit_message_text(text, reply_markup=keyboard) + except BadRequest as exc: # e.g. "message is not modified" + logger.debug("Editing the menu after a button press failed: {exc}", exc=exc) + + # ── Messages: everything goes through the shared pipeline ──────── + + async def handle_text(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + message = self._message(update) + if message is None: + return + + text = message.text or "" + logger.info(f"Text from user {_who(update)}: {text[:100]}") + + replied = message.reply_to_message + quoted = (replied.text or replied.caption or "") if replied is not None else "" + prompt = await self.inbound.text_prompt(text, quoted=quoted) + await self._send_with_typing(message, context, prompt) + + async def handle_photo(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + message = self._message(update) + if message is None: + return + + photo = message.photo[-1] + caption = message.caption or "" + + logger.info(f"Photo from user {_who(update)}, caption={caption!r}") + + file = await context.bot.get_file(photo.file_id) + photo_bytes = bytes(await file.download_as_bytearray()) + logger.debug(f"Downloaded photo: {len(photo_bytes)} bytes") + + prompt = await self.inbound.photo_prompt(photo.file_id, caption) + await self._send_with_typing(message, context, prompt, image=(photo_bytes, "image/jpeg")) + + async def handle_voice(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + message = self._message(update) + if message is None or message.voice is None: + return + + logger.info(f"Voice from user {_who(update)}") + + file = await context.bot.get_file(message.voice.file_id) + voice_bytes = bytes(await file.download_as_bytearray()) + + text = await self.inbound.transcribe(voice_bytes, filename="voice.ogg", mime_type="audio/ogg") + if text is None: + await message.reply_text(TRANSCRIPTION_FAILED) + return + logger.info(f"Transcribed: {text}") + + await self._send_with_typing(message, context, await self.inbound.voice_prompt(text)) + + async def aclose(self): + await self.inbound.aclose() + + def close(self): + self.inbound.close() + + +Handler = Callable[[TelegramBot, Update, ContextTypes.DEFAULT_TYPE], Awaitable[None]] + + +def _route(method: Handler): + """A python-telegram-bot callback that calls *method* on the TelegramBot + (created in post_init, kept in bot_data).""" + async def callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + await method(context.bot_data["handlers"], update, context) + return callback + + +async def _on_error(update: object, context: ContextTypes.DEFAULT_TYPE) -> None: + err = context.error + if isinstance(err, (NetworkError, TimedOut)): + logger.warning(f"Network blip ({type(err).__name__}): {err} — polling will retry") + return + logger.exception("Unhandled error in Telegram handler", exc_info=err) + + +def build_application(config: MemclawConfig) -> Application: + """Build the Telegram bot: TelegramBot, command handlers, error + handler and command menu, wired into a python-telegram-bot Application. + """ + async def post_init(application: Application) -> None: + handlers = TelegramBot(config) + application.bot_data["handlers"] = handlers + + handlers.attach_bot(application.bot) + await handlers.inbound.start() + + try: + await application.bot.set_my_commands( + [BotCommand(name, description) for name, description in BOT_COMMANDS] + ) + except TelegramError as exc: + logger.warning(f"Could not register the bot command menu: {exc}") + + logger.info("Memclaw bot initialized") + + async def post_shutdown(application: Application) -> None: + handlers = application.bot_data.get("handlers") + if handlers: + await handlers.aclose() + logger.info("Memclaw bot shut down cleanly") + + app = ( + Application.builder() + .token(config.telegram.bot_token) + .post_init(post_init) + .post_shutdown(post_shutdown) + .build() + ) + + app.add_error_handler(_on_error) + for command, method in ( + ("start", TelegramBot.start_command), + ("new", TelegramBot.new_command), + ("model", TelegramBot.model_command), + ("effort", TelegramBot.effort_command), + ): + app.add_handler(CommandHandler(command, _route(method))) + app.add_handler(CallbackQueryHandler(_route(TelegramBot.handle_callback))) + app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, _route(TelegramBot.handle_text))) + app.add_handler(MessageHandler(filters.PHOTO, _route(TelegramBot.handle_photo))) + app.add_handler(MessageHandler(filters.VOICE, _route(TelegramBot.handle_voice))) + + return app + + +def run(config: MemclawConfig) -> None: + """Start the Telegram bot (long polling) and block until it stops.""" + require_setting(config.telegram.bot_token, "TELEGRAM_BOT_TOKEN") + + log_to(config.memory_dir / "bot.log") + + app = build_application(config) + + allowed = config.telegram.allowed_user_ids_list + masked = [mask_user_id(u) for u in allowed] if allowed else "all" + console.print( + f"[green]Starting Memclaw Telegram bot...[/green] " + f"(allowed users: {masked})" + ) + app.run_polling(allowed_updates=["message", "callback_query"]) diff --git a/memclaw/bot/whatsapp.py b/memclaw/bot/whatsapp.py new file mode 100644 index 0000000..f8c7490 --- /dev/null +++ b/memclaw/bot/whatsapp.py @@ -0,0 +1,246 @@ +"""WhatsApp (your personal account via WhatsApp Web): receive messages, +download their media, send replies. + +Uses `neonize` (whatsmeow Go library under the hood) to connect to the user's +personal WhatsApp account via QR code pairing — no Meta Business account, +no webhooks, no public server. Only your own notes to yourself are handled. +What happens to a message in between is shared with the other platforms +(memclaw.bot.inbound). +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +from loguru import logger +from neonize.aioze.client import NewAClient +from neonize.aioze.events import ConnectedEv, MessageEv, PairStatusEv +from neonize.utils.jid import build_jid + +from ..config import MemclawConfig +from . import console, log_to, mask_user_id +from .inbound import TRANSCRIPTION_FAILED, Inbound, save_media + +_MIME_TO_EXT = { + "image/jpeg": ".jpg", + "image/png": ".png", + "image/webp": ".webp", + "image/gif": ".gif", + "audio/ogg": ".ogg", + "audio/ogg; codecs=opus": ".ogg", + "audio/mpeg": ".mp3", + "audio/mp4": ".m4a", + "audio/aac": ".aac", +} + + +def _mime_to_ext(mime_type: str) -> str: + return _MIME_TO_EXT.get(mime_type, _MIME_TO_EXT.get(mime_type.split(";")[0].strip(), "")) + + +class WhatsAppBot: + """Personal WhatsApp bot backed by neonize and the shared pipeline.""" + + def __init__(self, config: MemclawConfig): + self.config = config + self.inbound = Inbound(config, "whatsapp") + + self.client = NewAClient(str(config.whatsapp_session_db)) + self._register_handlers() + self.inbound.deliver_reminders(self._send_reminder) + + async def _send_reminder(self, chat_id: str, text: str) -> None: + """chat_id is stored as 'user@server' (e.g. '12345@s.whatsapp.net').""" + if "@" in chat_id: + user, server = chat_id.split("@", 1) + else: + user, server = chat_id, "s.whatsapp.net" + await self.client.send_message(build_jid(user, server=server), text) + + def _register_handlers(self): + @self.client.event(ConnectedEv) + async def _on_connected(_cli: NewAClient, _ev: ConnectedEv): + logger.info("WhatsApp connected") + + @self.client.event(PairStatusEv) + async def _on_pair(_cli: NewAClient, ev: PairStatusEv): + logger.info("WhatsApp paired as +{jid}", jid=mask_user_id(ev.ID.User)) + + @self.client.event(MessageEv) + async def _on_message(cli: NewAClient, ev: MessageEv): + try: + await self._route_message(cli, ev) + except Exception as exc: + logger.exception("Error handling WhatsApp message: {exc}", exc=exc) + + # ── Access control ─────────────────────────────────────────────── + + def _check_sender(self, ev: MessageEv) -> bool: + """Only process self-notes (your own messages to yourself). + + IsFromMe alone is not enough — it also matches outgoing DMs to other + people. The chat JID must equal the sender JID, which is only true in + the self-chat. + """ + source = ev.Info.MessageSource + if source.IsGroup: + return False + if not source.IsFromMe: + return False + return source.Chat.User == source.Sender.User + + # ── Message routing ────────────────────────────────────────────── + + @staticmethod + def _chat_id(ev: MessageEv) -> str: + chat = ev.Info.MessageSource.Chat + return f"{chat.User}@{chat.Server}" + + async def _route_message(self, cli: NewAClient, ev: MessageEv): + if not self._check_sender(ev): + return + + msg = ev.Message + + if msg.imageMessage.ListFields(): + await self._handle_image(cli, ev) + return + if msg.audioMessage.ListFields(): + await self._handle_audio(cli, ev) + return + + text = msg.conversation or msg.extendedTextMessage.text + if text and text.strip().lower() == "/new": + reply = await self.inbound.new_conversation(self._chat_id(ev)) + await cli.send_message(ev.Info.MessageSource.Chat, reply) + elif text: + await self._handle_text(cli, ev, text) + else: + logger.debug("Ignoring unsupported WhatsApp message type") + + # ── Messages ───────────────────────────────────────────────────── + + async def _handle_text(self, cli: NewAClient, ev: MessageEv, text: str): + sender = ev.Info.MessageSource.Sender.User + logger.info("WhatsApp text from {s}: {t}", s=mask_user_id(sender), t=text[:100]) + + await self._answer(cli, ev, await self.inbound.text_prompt(text)) + + async def _handle_image(self, cli: NewAClient, ev: MessageEv): + img_msg = ev.Message.imageMessage + caption = img_msg.caption or "" + sender = ev.Info.MessageSource.Sender.User + logger.info("WhatsApp image from {s}, caption={c!r}", s=mask_user_id(sender), c=caption) + + try: + image_bytes = await cli.download_any(ev.Message) + except Exception as exc: + logger.error("Failed to download WhatsApp image: {exc}", exc=exc) + await cli.reply_message("Sorry, I couldn't download that image.", ev) + return + + mime_type = img_msg.mimetype or "image/jpeg" + local_path = save_media(self.config.whatsapp_media_dir, image_bytes, _mime_to_ext(mime_type) or ".jpg") + + prompt = await self.inbound.photo_prompt(str(local_path), caption) + media_type = mime_type if mime_type.startswith("image/") else "image/jpeg" + await self._answer(cli, ev, prompt, image=(image_bytes, media_type)) + + async def _handle_audio(self, cli: NewAClient, ev: MessageEv): + audio_msg = ev.Message.audioMessage + sender = ev.Info.MessageSource.Sender.User + logger.info("WhatsApp voice/audio from {s}", s=mask_user_id(sender)) + + try: + audio_bytes = await cli.download_any(ev.Message) + except Exception as exc: + logger.error("Failed to download WhatsApp audio: {exc}", exc=exc) + await cli.reply_message("Sorry, I couldn't download that audio message.", ev) + return + + mime_type = audio_msg.mimetype or "audio/ogg" + ext = _mime_to_ext(mime_type) or ".ogg" + text = await self.inbound.transcribe(audio_bytes, filename=f"voice{ext}", mime_type=mime_type) + if text is None: + await cli.reply_message(TRANSCRIPTION_FAILED, ev) + return + logger.info("Transcribed WhatsApp voice: {t}", t=text) + + await self._answer(cli, ev, await self.inbound.voice_prompt(text)) + + async def _answer( + self, cli: NewAClient, ev: MessageEv, prompt: str, *, image: tuple[bytes, str] | None = None, + ): + response_text, found_images = await self.inbound.ask(prompt, chat_id=self._chat_id(ev), image=image) + await self._send_response(cli, ev, response_text, found_images) + + # ── Sending replies ────────────────────────────────────────────── + + async def _send_response( + self, + cli: NewAClient, + ev: MessageEv, + response_text: str, + found_images: list[dict], + ): + """Send agent response: images first, then text.""" + chat = ev.Info.MessageSource.Chat + + for img in found_images: + note = await self._send_image(cli, chat, img) + if note: + response_text = f"{response_text}\n\n{note}" if response_text else note + + if response_text: + try: + await cli.send_message(chat, response_text) + except Exception as exc: + logger.error("Failed to send WhatsApp message: {exc}", exc=exc) + + @staticmethod + async def _send_image(cli: NewAClient, chat, img: dict) -> str: + """Send an image saved on WhatsApp. For one saved elsewhere, return a + note to add to the reply instead.""" + platform = img.get("platform", "telegram") + media_ref = img.get("media_ref") or img.get("file_id", "") + if not (platform == "whatsapp" and media_ref and Path(media_ref).exists()): + desc = img.get("description", "an image") + return f"(Found image: {desc} — originally saved via {platform})" + try: + await cli.send_image(chat, media_ref, caption=img.get("caption") or None) + except Exception as exc: + logger.error("Failed to send WhatsApp image: {exc}", exc=exc) + return "" + + # ── Lifecycle ──────────────────────────────────────────────────── + + async def start(self): + """Connect to WhatsApp. On first run, a QR code is printed to stdout.""" + await self.inbound.start() + await self.client.connect() + await self.client.idle() + + def close(self): + self.inbound.close() + + +def run(config: MemclawConfig) -> None: + """Start the WhatsApp bot and block until it stops.""" + log_to(config.memory_dir / "whatsapp.log") + + bot = WhatsAppBot(config) + + console.print("[green]Starting Memclaw WhatsApp bot[/green] (self-notes only)") + if not config.whatsapp_session_db.exists(): + console.print( + "[cyan]First run:[/cyan] a QR code will appear below. " + "Open WhatsApp → Settings → Linked Devices → Link a Device, and scan it." + ) + + try: + asyncio.run(bot.start()) + except KeyboardInterrupt: + pass + finally: + bot.close() diff --git a/memclaw/bot/whatsapp_handlers.py b/memclaw/bot/whatsapp_handlers.py deleted file mode 100644 index 8c4e7fc..0000000 --- a/memclaw/bot/whatsapp_handlers.py +++ /dev/null @@ -1,321 +0,0 @@ -"""WhatsApp bot handlers for Memclaw (personal account via WhatsApp Web). - -Uses `neonize` (whatsmeow Go library under the hood) to connect to the user's -personal WhatsApp account via QR code pairing — no Meta Business account, -no webhooks, no public server. - -Every incoming message (text, image, voice) goes through the unified -MemclawAgent, which decides whether to store, search, or just respond. -""" - -from __future__ import annotations - -import base64 -import uuid -from pathlib import Path - -from loguru import logger -from openai import AsyncOpenAI - -from neonize.aioze.client import NewAClient -from neonize.aioze.events import ConnectedEv, MessageEv, PairStatusEv -from neonize.utils.jid import build_jid - -from ..agent import MemclawAgent -from ..config import MemclawConfig -from ..reminders import ReminderScheduler -from . import mask_user_id -from .link_processor import LinkProcessor - - -class WhatsAppBot: - """Personal WhatsApp bot backed by neonize + MemclawAgent.""" - - def __init__(self, config: MemclawConfig, openai_client: AsyncOpenAI): - self.config = config - self.openai_client = openai_client - self.scheduler = ReminderScheduler(config) - self.agent = MemclawAgent(config, platform="whatsapp", scheduler=self.scheduler) - self.link_processor = LinkProcessor(openai_client) - - self.client = NewAClient(str(config.whatsapp_session_db)) - self._register_handlers() - self.scheduler.register_delivery("whatsapp", self._deliver_reminder) - - async def _deliver_reminder(self, chat_id: str, text: str): - """chat_id is stored as 'user@server' (e.g. '12345@s.whatsapp.net').""" - if "@" in chat_id: - user, server = chat_id.split("@", 1) - else: - user, server = chat_id, "s.whatsapp.net" - jid = build_jid(user, server=server) - await self.client.send_message(jid, text) - self.agent.record_reminder_fired(text, chat_id) - - # ------------------------------------------------------------------ - # Event registration - # ------------------------------------------------------------------ - - def _register_handlers(self): - @self.client.event(ConnectedEv) - async def _on_connected(_cli: NewAClient, _ev: ConnectedEv): - logger.info("WhatsApp connected") - - @self.client.event(PairStatusEv) - async def _on_pair(_cli: NewAClient, ev: PairStatusEv): - logger.info("WhatsApp paired as +{jid}", jid=mask_user_id(ev.ID.User)) - - @self.client.event(MessageEv) - async def _on_message(cli: NewAClient, ev: MessageEv): - try: - await self._route_message(cli, ev) - except Exception as exc: - logger.exception("Error handling WhatsApp message: {exc}", exc=exc) - - # ------------------------------------------------------------------ - # Access control - # ------------------------------------------------------------------ - - def _check_sender(self, ev: MessageEv) -> bool: - """Only process self-notes (your own messages to yourself). - - IsFromMe alone is not enough — it also matches outgoing DMs to other - people. The chat JID must equal the sender JID, which is only true in - the self-chat. - """ - source = ev.Info.MessageSource - if source.IsGroup: - return False - if not source.IsFromMe: - return False - return source.Chat.User == source.Sender.User - - # ------------------------------------------------------------------ - # Message routing - # ------------------------------------------------------------------ - - @staticmethod - def _chat_id(ev: MessageEv) -> str: - chat = ev.Info.MessageSource.Chat - return f"{chat.User}@{chat.Server}" - - async def _route_message(self, cli: NewAClient, ev: MessageEv): - if not self._check_sender(ev): - return - - msg = ev.Message - - if msg.imageMessage.ListFields(): - await self._handle_image(cli, ev) - return - if msg.audioMessage.ListFields(): - await self._handle_audio(cli, ev) - return - - text = msg.conversation or msg.extendedTextMessage.text - if text and text.strip().lower() == "/new": - await self.agent.reset_conversation(self._chat_id(ev)) - await cli.send_message(ev.Info.MessageSource.Chat, "Started a new conversation.") - elif text: - await self._handle_text(cli, ev, text) - else: - logger.debug("Ignoring unsupported WhatsApp message type") - - # ------------------------------------------------------------------ - # Text messages - # ------------------------------------------------------------------ - - async def _handle_text(self, cli: NewAClient, ev: MessageEv, text: str): - sender = ev.Info.MessageSource.Sender.User - logger.info("WhatsApp text from {s}: {t}", s=mask_user_id(sender), t=text[:100]) - - prompt_parts = [text] - links = await self.link_processor.process_links(text) - for link in links: - if link.get("summary"): - prompt_parts.append( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt = "\n".join(prompt_parts) - response_text, found_images = await self.agent.handle(prompt, chat_id=self._chat_id(ev)) - await self._send_response(cli, ev, response_text, found_images) - - # ------------------------------------------------------------------ - # Image messages - # ------------------------------------------------------------------ - - async def _handle_image(self, cli: NewAClient, ev: MessageEv): - img_msg = ev.Message.imageMessage - caption = img_msg.caption or "" - sender = ev.Info.MessageSource.Sender.User - logger.info("WhatsApp image from {s}, caption={c!r}", s=mask_user_id(sender), c=caption) - - try: - image_bytes = await cli.download_any(ev.Message) - except Exception as exc: - logger.error("Failed to download WhatsApp image: {exc}", exc=exc) - await cli.reply_message("Sorry, I couldn't download that image.", ev) - return - - mime_type = img_msg.mimetype or "image/jpeg" - ext = _mime_to_ext(mime_type) or ".jpg" - local_path = self.config.whatsapp_media_dir / f"{uuid.uuid4().hex}{ext}" - local_path.write_bytes(image_bytes) - - base64_image = base64.b64encode(image_bytes).decode("utf-8") - - link_info = "" - if caption: - links = await self.link_processor.process_links(caption) - for link in links: - if link.get("summary"): - link_info += ( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt_text = f"User sent a photo. media_ref={local_path}" - if caption: - prompt_text += f"\nCaption: {caption}" - if link_info: - prompt_text += link_info - - media_type = mime_type if mime_type.startswith("image/") else "image/jpeg" - response_text, found_images = await self.agent.handle( - prompt_text, - image_b64=base64_image, - image_media_type=media_type, - chat_id=self._chat_id(ev), - ) - await self._send_response(cli, ev, response_text, found_images) - - # ------------------------------------------------------------------ - # Audio / voice messages - # ------------------------------------------------------------------ - - async def _handle_audio(self, cli: NewAClient, ev: MessageEv): - audio_msg = ev.Message.audioMessage - sender = ev.Info.MessageSource.Sender.User - logger.info("WhatsApp voice/audio from {s}", s=mask_user_id(sender)) - - try: - audio_bytes = await cli.download_any(ev.Message) - except Exception as exc: - logger.error("Failed to download WhatsApp audio: {exc}", exc=exc) - await cli.reply_message("Sorry, I couldn't download that audio message.", ev) - return - - mime_type = audio_msg.mimetype or "audio/ogg" - ext = _mime_to_ext(mime_type) or ".ogg" - - try: - transcription = await self.openai_client.audio.transcriptions.create( - model="whisper-1", - file=(f"voice{ext}", audio_bytes, mime_type), - ) - except Exception as exc: - logger.exception("Whisper transcription failed: {exc}", exc=exc) - await cli.reply_message( - "I couldn't transcribe that voice message. " - "If you set up Memclaw recently, run `memclaw doctor` to check " - "your OpenAI key has access to the whisper-1 model.", - ev, - ) - return - text = transcription.text - logger.info("Transcribed WhatsApp voice: {t}", t=text) - - link_info = "" - links = await self.link_processor.process_links(text) - for link in links: - if link.get("summary"): - link_info += ( - f"\n[Link summary] {link['url']}: {link['summary']}" - "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." - ) - - prompt = ( - f"[Voice message] {text}" - "\nThis transcription has NOT been saved yet. Save it if the content is worth remembering." - f"{link_info}" - ) - response_text, found_images = await self.agent.handle(prompt, chat_id=self._chat_id(ev)) - await self._send_response(cli, ev, response_text, found_images) - - # ------------------------------------------------------------------ - # Sending replies - # ------------------------------------------------------------------ - - async def _send_response( - self, - cli: NewAClient, - ev: MessageEv, - response_text: str, - found_images: list[dict], - ): - """Send agent response: images first, then text.""" - chat = ev.Info.MessageSource.Chat - - for img in found_images: - platform = img.get("platform", "telegram") - media_ref = img.get("media_ref") or img.get("file_id", "") - caption = img.get("caption") or None - - if platform == "whatsapp" and media_ref and Path(media_ref).exists(): - try: - await cli.send_image(chat, media_ref, caption=caption) - except Exception as exc: - logger.error("Failed to send WhatsApp image: {exc}", exc=exc) - else: - desc = img.get("description", "an image") - note = f"(Found image: {desc} — originally saved via {platform})" - response_text = f"{response_text}\n\n{note}" if response_text else note - - if response_text: - try: - await cli.send_message(chat, response_text) - except Exception as exc: - logger.error("Failed to send WhatsApp message: {exc}", exc=exc) - - # ------------------------------------------------------------------ - # Lifecycle - # ------------------------------------------------------------------ - - async def start(self): - """Connect to WhatsApp. On first run, a QR code is printed to stdout.""" - await self.agent.start() - await self.agent.start_background_sync(interval=60) - self.scheduler.start() - await self.client.connect() - await self.client.idle() - - async def aclose(self): - await self.agent.aclose() - self.scheduler.close() - - def close(self): - self.scheduler.close() - self.agent.close() - - -# ------------------------------------------------------------------ -# Utilities -# ------------------------------------------------------------------ - -_MIME_TO_EXT = { - "image/jpeg": ".jpg", - "image/png": ".png", - "image/webp": ".webp", - "image/gif": ".gif", - "audio/ogg": ".ogg", - "audio/ogg; codecs=opus": ".ogg", - "audio/mpeg": ".mp3", - "audio/mp4": ".m4a", - "audio/aac": ".aac", -} - - -def _mime_to_ext(mime_type: str) -> str: - return _MIME_TO_EXT.get(mime_type, _MIME_TO_EXT.get(mime_type.split(";")[0].strip(), "")) diff --git a/memclaw/cli.py b/memclaw/cli.py index 743e845..f885649 100644 --- a/memclaw/cli.py +++ b/memclaw/cli.py @@ -8,11 +8,11 @@ from rich.markdown import Markdown from rich.panel import Panel -from .bot import mask_user_id +from .bot import PLATFORMS from .config import MemclawConfig, reload_env_file from .index import MemoryIndex from .search import HybridSearch -from .setup import needs_setup, print_logo, run_setup +from .setup import needs_setup, print_logo, print_probe_report, run_setup from .store import MemoryStore console = Console() @@ -82,13 +82,9 @@ def cli(ctx, memory_dir): _require_backend_auth(config) _require_openai(config) - platform = config.platform or "terminal" - if platform == "telegram": - _run_telegram(config) - elif platform == "slack": - _run_slack(config) - elif platform == "whatsapp": - _run_whatsapp(config) + platform = PLATFORMS.get(config.platform) + if platform is not None: + platform.run(config) else: asyncio.run(_interactive(config)) @@ -161,106 +157,6 @@ async def _interactive(config: MemclawConfig): console.print("\nGoodbye! Your memories are safe.") -# ------------------------------------------------------------------ -# Bot launchers (dispatched from the bare `memclaw` command) -# ------------------------------------------------------------------ - -def _setup_bot_logging(log_file: Path) -> None: - import sys - - from loguru import logger - - logger.remove() - logger.add( - sys.stderr, - level="INFO", - format="{time:HH:mm:ss} | {level:<8} | {message}", - ) - logger.add(str(log_file), rotation="10 MB", retention="7 days", level="DEBUG") - - -def _run_telegram(config: MemclawConfig) -> None: - from .bot.handlers import build_application - - if not config.telegram.bot_token: - console.print("[red]Error:[/red] TELEGRAM_BOT_TOKEN is not set.") - console.print("Run [bold]memclaw configure[/bold] to set it.") - raise SystemExit(1) - - _setup_bot_logging(config.memory_dir / "bot.log") - - app = build_application(config) - - allowed = config.telegram.allowed_user_ids_list - masked = [mask_user_id(u) for u in allowed] if allowed else "all" - console.print( - f"[green]Starting Memclaw Telegram bot...[/green] " - f"(allowed users: {masked})" - ) - app.run_polling(allowed_updates=["message", "callback_query"]) - - -def _run_whatsapp(config: MemclawConfig) -> None: - from openai import AsyncOpenAI - - from .bot.whatsapp_handlers import WhatsAppBot - - _setup_bot_logging(config.memory_dir / "whatsapp.log") - - openai_client = AsyncOpenAI(api_key=config.openai.api_key) - bot_ = WhatsAppBot(config, openai_client) - - console.print("[green]Starting Memclaw WhatsApp bot[/green] (self-notes only)") - if not config.whatsapp_session_db.exists(): - console.print( - "[cyan]First run:[/cyan] a QR code will appear below. " - "Open WhatsApp → Settings → Linked Devices → Link a Device, and scan it." - ) - - try: - asyncio.run(bot_.start()) - except KeyboardInterrupt: - pass - finally: - bot_.close() - - -def _run_slack(config: MemclawConfig) -> None: - from openai import AsyncOpenAI - - from .bot.slack_handlers import SlackHandlers - - if not config.slack.bot_token: - console.print("[red]Error:[/red] SLACK_BOT_TOKEN is not set.") - console.print("Run [bold]memclaw configure[/bold] to set it.") - raise SystemExit(1) - if not config.slack.app_token: - console.print("[red]Error:[/red] SLACK_APP_TOKEN is not set.") - console.print("Run [bold]memclaw configure[/bold] to set it.") - raise SystemExit(1) - - _setup_bot_logging(config.memory_dir / "slack.log") - - openai_client = AsyncOpenAI(api_key=config.openai.api_key) - handlers = SlackHandlers(config, openai_client) - - console.print( - f"[green]Starting Memclaw Slack bot (Socket Mode)...[/green] " - f"(allowed channels: {config.slack.allowed_channels_list or 'all'})" - ) - - async def _run(): - try: - await handlers.start() - except KeyboardInterrupt: - pass - finally: - await handlers.aclose() - console.print("\nMemclaw Slack bot shut down.") - - asyncio.run(_run()) - - # ------------------------------------------------------------------ # Direct commands (work without the Claude agent / Anthropic key) # ------------------------------------------------------------------ @@ -412,7 +308,7 @@ def configure(ctx): @click.pass_context def doctor(ctx): """Check that your OpenAI key can reach every model Memclaw uses.""" - from .openai_health import print_probe_report, probe_openai + from .openai_client import probe_openai config: MemclawConfig = ctx.obj["config"] _require_openai(config) diff --git a/memclaw/index.py b/memclaw/index.py index a3eb4d1..f2880e6 100644 --- a/memclaw/index.py +++ b/memclaw/index.py @@ -6,9 +6,9 @@ from pathlib import Path import numpy as np -from openai import AsyncOpenAI from .config import MemclawConfig +from .openai_client import OpenAIClient @dataclass @@ -29,7 +29,7 @@ class MemoryIndex: def __init__(self, config: MemclawConfig): self.config = config - self._openai: AsyncOpenAI | None = None + self._openai: OpenAIClient | None = None self._init_db() def _init_db(self): @@ -140,9 +140,9 @@ def _migrate_telegram_images(self): """) @property - def openai(self) -> AsyncOpenAI: + def openai(self) -> OpenAIClient: if self._openai is None: - self._openai = AsyncOpenAI(api_key=self.config.openai.api_key) + self._openai = OpenAIClient(self.config.openai.api_key) return self._openai # ------------------------------------------------------------------ @@ -233,11 +233,8 @@ async def get_embeddings(self, texts: list[str]) -> list[np.ndarray]: # Fetch embeddings for uncached texts only if uncached_indices: uncached_texts = [texts[i] for i in uncached_indices] - response = await self.openai.embeddings.create( - model=model, - input=uncached_texts, - ) - new_embeddings = [np.array(item.embedding, dtype=np.float32) for item in response.data] + vectors = await self.openai.embed(uncached_texts, model=model) + new_embeddings = [np.array(v, dtype=np.float32) for v in vectors] for idx, emb in zip(uncached_indices, new_embeddings): results[idx] = emb diff --git a/memclaw/openai_health.py b/memclaw/openai_client.py similarity index 60% rename from memclaw/openai_health.py rename to memclaw/openai_client.py index a813fc6..13cb5e5 100644 --- a/memclaw/openai_health.py +++ b/memclaw/openai_client.py @@ -1,4 +1,4 @@ -"""Probe the user's OpenAI key for access to every model Memclaw depends on. +"""The one module that talks to OpenAI. Memclaw uses three OpenAI capabilities: @@ -6,8 +6,10 @@ - chat (gpt-5-mini) — link summarization - audio.transcriptions (whisper-1) — voice messages -A brand-new project on the OpenAI platform may have any of these disabled. -This module makes a minimal call to each one and reports which work. +Everything else calls `OpenAIClient`. A brand-new project on the OpenAI +platform may have any of these models disabled, so `probe_openai` (the +`memclaw doctor` check) makes a minimal call to each one and reports which +work. """ from __future__ import annotations @@ -16,14 +18,50 @@ from dataclasses import dataclass from openai import AsyncOpenAI -from rich.panel import Panel -from rich.text import Text CHAT_MODEL = "gpt-5-mini" EMBEDDING_MODEL = "text-embedding-3-small" WHISPER_MODEL = "whisper-1" +class OpenAIClient: + """The OpenAI calls Memclaw makes. Errors from the SDK are raised as is.""" + + def __init__(self, api_key: str): + self._sdk = AsyncOpenAI(api_key=api_key) + + async def embed(self, texts: list[str], *, model: str = EMBEDDING_MODEL) -> list[list[float]]: + """One embedding vector per text, in order.""" + response = await self._sdk.embeddings.create(model=model, input=texts) + return [item.embedding for item in response.data] + + async def transcribe(self, audio: bytes, *, filename: str, mime_type: str) -> str: + """Speech to text with Whisper; *filename*'s extension tells OpenAI the format.""" + result = await self._sdk.audio.transcriptions.create( + model=WHISPER_MODEL, file=(filename, audio, mime_type), + ) + return result.text + + async def chat(self, messages: list) -> str: + """A short answer from the small chat model ("" if it gives none). + + *messages* are OpenAI chat messages: ``{"role": ..., "content": ...}``. + """ + response = await self._sdk.chat.completions.create( + model=CHAT_MODEL, + messages=messages, + reasoning_effort="low", + max_completion_tokens=300, + ) + return response.choices[0].message.content or "" + + async def close(self) -> None: + await self._sdk.close() + + +# ── The `memclaw doctor` probe ─────────────────────────────────────── + + @dataclass class ProbeOutcome: name: str @@ -63,28 +101,23 @@ def _short(err: BaseException, limit: int = 180) -> str: return msg if len(msg) <= limit else msg[:limit] + "..." -async def _probe_embedding(client: AsyncOpenAI) -> ProbeOutcome: +async def _probe_embedding(client: OpenAIClient) -> ProbeOutcome: try: - await client.embeddings.create(model=EMBEDDING_MODEL, input="ok") + await client.embed(["ok"]) return ProbeOutcome("Embeddings (search)", EMBEDDING_MODEL, True) except Exception as exc: return ProbeOutcome("Embeddings (search)", EMBEDDING_MODEL, False, _short(exc)) -async def _probe_chat(client: AsyncOpenAI) -> ProbeOutcome: +async def _probe_chat(client: OpenAIClient) -> ProbeOutcome: try: - await client.chat.completions.create( - model=CHAT_MODEL, - messages=[{"role": "user", "content": "ok"}], - reasoning_effort="low", - max_completion_tokens=300, - ) + await client.chat([{"role": "user", "content": "ok"}]) return ProbeOutcome("Chat (link summaries)", CHAT_MODEL, True) except Exception as exc: return ProbeOutcome("Chat (link summaries)", CHAT_MODEL, False, _short(exc)) -async def _probe_whisper(client: AsyncOpenAI) -> ProbeOutcome: +async def _probe_whisper(client: OpenAIClient) -> ProbeOutcome: """Whisper is harder to probe — a real audio file is needed. We send 0.5s of silence and inspect the result: @@ -93,10 +126,7 @@ async def _probe_whisper(client: AsyncOpenAI) -> ProbeOutcome: - Anything else → treat as failure and surface the error. """ try: - await client.audio.transcriptions.create( - model=WHISPER_MODEL, - file=("probe.wav", _silent_wav(), "audio/wav"), - ) + await client.transcribe(_silent_wav(), filename="probe.wav", mime_type="audio/wav") return ProbeOutcome("Audio (voice messages)", WHISPER_MODEL, True) except Exception as exc: status = getattr(exc, "status_code", None) or getattr( @@ -110,7 +140,7 @@ async def _probe_whisper(client: AsyncOpenAI) -> ProbeOutcome: async def probe_openai(api_key: str) -> ProbeReport: - client = AsyncOpenAI(api_key=api_key) + client = OpenAIClient(api_key) try: embedding = await _probe_embedding(client) chat = await _probe_chat(client) @@ -118,32 +148,3 @@ async def probe_openai(api_key: str) -> ProbeReport: finally: await client.close() return ProbeReport(embedding=embedding, chat=chat, whisper=whisper) - - -def print_probe_report(report: ProbeReport, console) -> None: - """Render a probe report as a Rich table-ish summary.""" - body = Text() - for outcome in report: - marker = "[green]✓[/green]" if outcome.ok else "[red]✗[/red]" - line = f"{marker} {outcome.name} [dim]({outcome.model})[/dim]" - if not outcome.ok and outcome.error: - line += f"\n [red]{outcome.error}[/red]" - body.append_text(Text.from_markup(line)) - body.append("\n") - - if not report.all_ok: - body.append("\n", style="") - body.append_text( - Text.from_markup( - "[yellow]Enable the missing models for your project at[/yellow]\n" - "[bold]https://platform.openai.com/settings/organization/limits[/bold]" - ) - ) - - console.print( - Panel( - body, - title="OpenAI model access", - border_style="green" if report.all_ok else "yellow", - ) - ) diff --git a/memclaw/setup.py b/memclaw/setup.py index 7707909..f07b7b2 100644 --- a/memclaw/setup.py +++ b/memclaw/setup.py @@ -18,7 +18,8 @@ set_environment, write_env_file, ) -from .openai_health import print_probe_report, probe_openai +from .bot import PLATFORMS as CHAT_PLATFORMS +from .openai_client import ProbeReport, probe_openai from .prompts import choose, masked_input console = Console() @@ -66,15 +67,15 @@ def print_logo() -> None: console.print() -# Supported front-end platforms in display order. The first one is also the -# default when nothing has been configured yet. +# Supported front-end platforms (name, label) in display order: the chat +# apps of memclaw.bot, then the terminal. The first one is also the default +# when nothing has been configured yet. PLATFORMS: list[tuple[str, str]] = [ - ("telegram", "Telegram"), - ("whatsapp", "WhatsApp"), - ("slack", "Slack"), + *((p.name, p.label) for p in CHAT_PLATFORMS.values()), ("terminal", "Terminal chat"), ] + def questions(platform: str | None = None) -> list[Setting]: """The settings the wizard asks for (those declared with a `prompt=` in memclaw.config), in declaration order. @@ -255,3 +256,32 @@ def _check_openai(api_key: str | None) -> None: print_probe_report(report, console) except Exception as exc: console.print(f"[yellow]Skipping model check:[/yellow] {exc}") + + +def print_probe_report(report: ProbeReport, console: Console) -> None: + """Render a probe report (memclaw.openai_client.probe_openai) as a panel.""" + body = Text() + for outcome in report: + marker = "[green]✓[/green]" if outcome.ok else "[red]✗[/red]" + line = f"{marker} {outcome.name} [dim]({outcome.model})[/dim]" + if not outcome.ok and outcome.error: + line += f"\n [red]{outcome.error}[/red]" + body.append_text(Text.from_markup(line)) + body.append("\n") + + if not report.all_ok: + body.append("\n", style="") + body.append_text( + Text.from_markup( + "[yellow]Enable the missing models for your project at[/yellow]\n" + "[bold]https://platform.openai.com/settings/organization/limits[/bold]" + ) + ) + + console.print( + Panel( + body, + title="OpenAI model access", + border_style="green" if report.all_ok else "yellow", + ) + ) diff --git a/pyproject.toml b/pyproject.toml index 6880ece..c1bc94b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -105,7 +105,7 @@ baseline = ".code-shape/baseline.json" [tool.shape.banned_api] # Outside systems should be reached through one module each. Existing direct # uses are in the baseline; new ones fail. -"openai" = { msg = "Don't import the OpenAI SDK in another module. Call the existing code that uses it (memclaw/index.py for embeddings), or move the call there; the goal is one OpenAI adapter module.", allowed = ["memclaw/index.py"] } +"openai" = { msg = "Only memclaw/openai_client.py imports the OpenAI SDK. Call OpenAIClient (embed, transcribe, chat), or add the call there.", allowed = ["memclaw/openai_client.py"] } "sqlite3" = { msg = "Only the storage modules (memclaw/index.py, memclaw/reminders.py) open SQLite; call their methods instead.", allowed = ["memclaw/index.py", "memclaw/reminders.py"] } # Settings come from memclaw/config.py only (config_modules above bans os.environ elsewhere); .env files too. "dotenv" = { msg = "Only memclaw/config.py loads .env files. Use its read_env_file / update_env_file / reload_env_file, or add a setting there and read it from MemclawConfig.", allowed = ["memclaw/config.py"] } @@ -118,6 +118,11 @@ deptry = ["--optional-dependencies-dev-groups", "dev", "--extend-exclude", "docs # - functions registered by decorator are called by their framework, not by name. vulture = ["--ignore-decorators", "@cli.command,@*.event,@server.list_tools,@server.call_tool"] +[[tool.mypy.overrides]] +# neonize (WhatsApp) ships no type hints or stubs. +module = ["neonize.*"] +ignore_missing_imports = true + [tool.vulture] # Names a library uses by reflection, which vulture would call dead code. ignore_names = [ @@ -134,13 +139,13 @@ ignore_names = [ "settings storage (.env)" = { terms = ["read_env_file", "update_env_file", "write_env_file", "os\\.environ"], home = "memclaw/config.py" } "AI backends" = { terms = ["AgentBackend", "build_backend", "agent_backend", "AGENT_BACKEND"], home = "memclaw/backends/base.py" } "model / effort selection" = { terms = ["set_model", "set_effort", "list_models", "effort_levels"], home = "memclaw/backends/model_selection.py" } -"chat platforms" = { terms = ["telegram", "slack", "whatsapp"], home = "memclaw/bot/handlers.py" } -"voice transcription" = { terms = ["whisper", "transcri"], home = "memclaw/bot/handlers.py" } +"chat platforms" = { terms = ["telegram", "slack", "whatsapp"], home = "memclaw/bot/__init__.py" } +"voice transcription" = { terms = ["whisper", "transcri"], home = "memclaw/bot/inbound.py" } "images" = { terms = ["image_save", "image_search", "platform_image"], home = "memclaw/index.py" } "agent tools" = { terms = ["TOOL_DEFINITIONS", "ToolExecutor"], home = "memclaw/tools.py" } "conversations / sessions" = { terms = ["SessionStore", "session_key", "reset_session"], home = "memclaw/sessions.py" } "setup wizard" = { terms = ["run_setup", "wizard", "needs_setup"], home = "memclaw/setup.py" } -"links" = { terms = ["LinkProcessor", "process_links"], home = "memclaw/bot/link_processor.py" } +"links" = { terms = ["LinkProcessor", "process_links"], home = "memclaw/bot/links.py" } # --------------------------------------------------------------------------- # Module-structure rules (import-linter contracts): memclaw's own layout. @@ -162,9 +167,11 @@ containers = ["memclaw"] layers = [ # Entry point: the `memclaw` command. "cli", - # Front-ends started by the CLI: the chat bots and the interactive setup - # wizard. Independent (`|`): bots don't run the wizard and vice versa. - "bot | setup", + # The interactive setup wizard. It lists the chat platforms from + # memclaw.bot's registry. + "setup", + # The chat bots (memclaw.bot): one module per chat app, plus what they share. + "bot", # Platform-agnostic assistant: wires backends, tools and storage together. "agent", # AI agent backends (Claude, Cursor) and their MCP plumbing. @@ -172,9 +179,11 @@ layers = [ # The memory tools the agent can call. "tools", # Independent building blocks (`|`: they don't import each other). - "search | store | reminders | sessions | memory_refs | prompts | openai_health", + "search | store | reminders | sessions | memory_refs | prompts", # SQLite + embeddings index, used by search. "index", + # The OpenAI adapter (embeddings, transcription, chat), used by index and bot. + "openai_client", # Settings read from the environment. Imports nothing from memclaw. "config", ] @@ -195,20 +204,38 @@ ancestors = ["memclaw.*"] [[tool.importlinter.contracts]] id = "chat-platforms-independent" -name = "Chat platforms are independent: the Telegram, Slack and WhatsApp handlers never import each other (share code via memclaw.bot or lower layers)" +name = "Chat platforms are independent: the Telegram, Slack and WhatsApp modules never import each other (share code via memclaw.bot.inbound or lower layers)" type = "independence" modules = [ - "memclaw.bot.handlers", # Telegram - "memclaw.bot.slack_handlers", - "memclaw.bot.whatsapp_handlers", + "memclaw.bot.telegram", + "memclaw.bot.slack", + "memclaw.bot.whatsapp", ] +[[tool.importlinter.contracts]] +id = "platforms-via-registry" +name = "Only memclaw.bot imports the platform modules: everyone else starts a platform through memclaw.bot.PLATFORMS" +type = "protected" +protected_modules = [ + "memclaw.bot.telegram", + "memclaw.bot.slack", + "memclaw.bot.whatsapp", +] +allowed_importers = ["memclaw.bot"] + [[tool.importlinter.contracts]] id = "chat-sdks-only-in-bot" -name = "Chat-platform SDKs (telegram, slack_bolt, neonize) are only imported inside memclaw.bot" +name = "Chat-platform SDKs (telegram, slack_bolt, neonize) are only imported by the platform modules in memclaw.bot" type = "protected" protected_modules = ["telegram", "slack_bolt", "neonize"] -allowed_importers = ["memclaw.bot"] +allowed_importers = ["memclaw.bot.telegram", "memclaw.bot.slack", "memclaw.bot.whatsapp"] + +[[tool.importlinter.contracts]] +id = "openai-only-in-adapter" +name = "Only memclaw.openai_client imports the OpenAI SDK (everyone else calls OpenAIClient)" +type = "protected" +protected_modules = ["openai"] +allowed_importers = ["memclaw.openai_client"] [[tool.importlinter.contracts]] id = "defaults-standalone" diff --git a/tests/backends/test_cursor.py b/tests/backends/test_cursor.py index 0172cec..74729d8 100644 --- a/tests/backends/test_cursor.py +++ b/tests/backends/test_cursor.py @@ -856,7 +856,8 @@ async def test_switching_to_model_without_effort_clears_it(self, tmp_path): @pytest.mark.asyncio async def test_model_and_effort_menus_list_cursor_models(self, tmp_path): - from memclaw.bot.handlers import effort_menu, model_menu, select_model + from memclaw.bot.commands import select_model + from memclaw.bot.telegram import effort_menu, model_menu backend = _backend(tmp_path) client = _make_client() diff --git a/tests/bot/__init__.py b/tests/bot/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/bot/test_inbound.py b/tests/bot/test_inbound.py new file mode 100644 index 0000000..7a8fe4f --- /dev/null +++ b/tests/bot/test_inbound.py @@ -0,0 +1,55 @@ +"""The shared message pipeline (memclaw.bot.inbound). Its prompts and +replies are checked on every platform in test_parity.py; here: what the +pipeline must not do, and the agent instructions its prompts rely on.""" +from __future__ import annotations + +import inspect + +import memclaw.bot.inbound as inbound +from memclaw.bot.inbound import is_allowed + + +def test_pipeline_never_saves_on_its_own(): + """Voice transcriptions, link summaries and photos are left for the agent + to save (spec #7: no double storage): the prompts say they are NOT saved + yet (test_parity.py) and nothing here calls the store.""" + assert "store.save" not in inspect.getsource(inbound) + + +def test_is_allowed(): + assert is_allowed("a", ["a", "b"], empty_allows_all=False) + assert not is_allowed("c", ["a", "b"], empty_allows_all=True) + assert is_allowed("c", [], empty_allows_all=True) + assert not is_allowed("c", [], empty_allows_all=False) + + +class TestAgentsFile: + """Verify AGENTS.md (the externalized system prompt) has the right content.""" + + def _read_agents(self, tmp_config) -> str: + agents_path = tmp_config.agent_file + assert agents_path.exists(), f"AGENTS.md not found at {agents_path}" + return agents_path.read_text() + + def test_mentions_permanent_memory(self, tmp_config): + content = self._read_agents(tmp_config) + assert "MEMORY.md" in content + assert "memory_save" in content + assert "permanent=true" not in content + + def test_mentions_not_saved_yet(self, tmp_config): + content = self._read_agents(tmp_config) + assert "NOT" in content + assert "saved" in content.lower() + + def test_mentions_voice_not_saved(self, tmp_config): + content = self._read_agents(tmp_config) + assert "Voice message" in content + + def test_mentions_link_not_saved(self, tmp_config): + content = self._read_agents(tmp_config) + assert "Link summary" in content + + def test_has_user_instructions_section(self, tmp_config): + content = self._read_agents(tmp_config) + assert "User instructions" in content diff --git a/tests/bot/test_links.py b/tests/bot/test_links.py new file mode 100644 index 0000000..f9e106e --- /dev/null +++ b/tests/bot/test_links.py @@ -0,0 +1,24 @@ +"""memclaw.bot.links: URLs in a message, and what a failed summary says.""" +from __future__ import annotations + +import pytest + +from memclaw.bot.links import LinkProcessor + + +class _FailingOpenAI: + async def chat(self, messages): + raise RuntimeError("quota") + + +def test_extract_urls(): + links = LinkProcessor(_FailingOpenAI()) + text = "see https://a.com/x, and (https://b.org/y). again: https://a.com/x!" + assert links.extract_urls(text) == ["https://a.com/x", "https://b.org/y"] + + +@pytest.mark.asyncio +async def test_failed_summary_is_reported_as_the_summary(): + """The error text becomes the summary the agent sees (as before).""" + links = LinkProcessor(_FailingOpenAI()) + assert await links.summarize("page", "https://a.com") == "Could not summarize: quota" diff --git a/tests/bot/test_parity.py b/tests/bot/test_parity.py new file mode 100644 index 0000000..0526fc9 --- /dev/null +++ b/tests/bot/test_parity.py @@ -0,0 +1,711 @@ +"""One set of scenarios run through Telegram, Slack and WhatsApp. + +Each platform is driven at its SDK boundary with fakes (the Telegram Update, +the Slack event + `say`, the WhatsApp MessageEv + client) and a fake agent, +OpenAI client and web page. The tests pin what the agent receives (prompt, +image, chat id) and what the user sees, so the three platforms provably run +the same message pipeline, and the platform quirks that differ are written +down here on purpose. +""" +from __future__ import annotations + +import base64 +import importlib +import sys +import types +from datetime import datetime, timedelta +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from memclaw.config import MemclawConfig, OpenAISettings, SlackSettings, TelegramSettings +from memclaw.reminders import ReminderScheduler + +URL = "https://example.com/post" +PAGE_TEXT = "The page text." +SUMMARY = "A post about testing." +LINK_TEXT = f"read {URL} later" +NOTE = ( + f"\n[Link summary] {URL}: {SUMMARY}" + "\nThis summary has NOT been saved yet. Save it if the content is worth remembering." +) +VOICE_TEXT = f"call mom about {URL}" +VOICE_PROMPT = ( + f"[Voice message] {VOICE_TEXT}" + "\nThis transcription has NOT been saved yet. Save it if the content is worth remembering." + f"{NOTE}" +) +TRANSCRIPTION_FAILED = ( + "I couldn't transcribe that voice message. " + "If you set up Memclaw recently, run `memclaw doctor` to check " + "your OpenAI key has access to the whisper-1 model." +) +PHOTO = b"\x89PNG fake image bytes" +AUDIO = b"OggS fake audio bytes" +SUMMARIZE_MESSAGES = [ + {"role": "system", "content": ( + "Summarize this web content concisely. Focus on main points. Keep it under 50 tokens." + )}, + {"role": "user", "content": f"Summarize content from {URL}:\n\n{PAGE_TEXT}"}, +] + +pytestmark = pytest.mark.asyncio + +# ── Where the code lives: the only part that differs between layouts ── + +TELEGRAM = "memclaw.bot.telegram" +SLACK = "memclaw.bot.slack" +WHATSAPP = "memclaw.bot.whatsapp" +LINKS = "memclaw.bot.links" +# The modules that construct MemclawAgent (replaced by FakeAgent). +AGENT_HOMES = ["memclaw.bot.inbound"] + + +def make_bot(module, config, openai): + """Construct the platform's bot object the way its launcher does.""" + cls = {TELEGRAM: "TelegramBot", SLACK: "SlackBot", WHATSAPP: "WhatsAppBot"} + return getattr(module, cls[module.__name__])(config) + + +def attach_telegram(bot, tg_bot): + """What post_init does once python-telegram-bot has a Bot.""" + bot.attach_bot(tg_bot) + + +def install_openai(monkeypatch, fake): + """Make *fake* the OpenAI SDK client the bots use.""" + monkeypatch.setattr("memclaw.openai_client.AsyncOpenAI", lambda **kwargs: fake) + + +# ── Fakes shared by every platform ─────────────────────────────────────── + + +class FakeAgent: + instances: list["FakeAgent"] = [] + + def __init__(self, config, platform=None, *, scheduler=None, backend=None): + self.platform = platform + self.scheduler = scheduler + self.calls: list[dict] = [] + self.fired: list[tuple] = [] + self.resets: list = [] + self.reply: tuple[str, list[dict]] = ("Got it.", []) + FakeAgent.instances.append(self) + + async def handle(self, message, *, image_b64=None, image_media_type="image/jpeg", + chat_id=None, on_tool=None): + self.calls.append({ + "prompt": message, "image_b64": image_b64, + "image_media_type": image_media_type, "chat_id": chat_id, + }) + return self.reply + + def record_reminder_fired(self, text, chat_id=None): + self.fired.append((text, chat_id)) + + async def reset_conversation(self, chat_id=None): + self.resets.append(chat_id) + + async def start(self, **kw): + pass + + async def start_background_sync(self, interval=60): + pass + + async def aclose(self): + pass + + def close(self): + pass + + +class FakeOpenAI: + def __init__(self, *args, **kwargs): + self.transcriptions: list[tuple] = [] + self.chats: list[dict] = [] + self.fail_transcription = False + self.audio = SimpleNamespace(transcriptions=SimpleNamespace(create=self._transcribe)) + self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._chat)) + + async def _transcribe(self, *, model, file): + self.transcriptions.append((model, file)) + if self.fail_transcription: + raise RuntimeError("model not available") + return SimpleNamespace(text=VOICE_TEXT) + + async def _chat(self, **kwargs): + self.chats.append(kwargs) + return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=SUMMARY))]) + + async def close(self): + pass + + +async def fake_fetch(self, url, timeout=10.0): + return PAGE_TEXT if url == URL else None + + +@pytest.fixture +def env(tmp_path, monkeypatch): + FakeAgent.instances.clear() + for module in AGENT_HOMES: + monkeypatch.setattr(f"{module}.MemclawAgent", FakeAgent) + monkeypatch.setattr(f"{LINKS}.LinkProcessor.fetch_content", fake_fetch) + openai = FakeOpenAI() + install_openai(monkeypatch, openai) + config = MemclawConfig( + memory_dir=tmp_path / "m", + openai=OpenAISettings(api_key="sk-test"), + telegram=TelegramSettings(bot_token="123:abc", allowed_user_ids="1"), + slack=SlackSettings(bot_token="xoxb-1", app_token="xapp-1", allowed_users="U1"), + ) + return SimpleNamespace(config=config, openai=openai, monkeypatch=monkeypatch) + + +# ── Telegram driver ────────────────────────────────────────────────────── + + +class FakeTelegramBot: + def __init__(self): + self.sent: list[dict] = [] + self.photos: list[dict] = [] + self.files: dict[str, bytes] = {} + + async def send_chat_action(self, **kw): + pass + + async def send_message(self, *args, **kw): + self.sent.append({"args": args, **kw}) + return SimpleNamespace(edit_text=_anoop, delete=_anoop) + + async def send_photo(self, **kw): + self.photos.append(kw) + + async def get_file(self, file_id): + data = self.files[file_id] + + async def download_as_bytearray(): + return bytearray(data) + return SimpleNamespace(download_as_bytearray=download_as_bytearray) + + +async def _anoop(*a, **kw): + pass + + +class TelegramDriver: + name = "telegram" + chat_id = "42" + + def __init__(self, env): + self.env = env + self.bot = make_bot(importlib.import_module(TELEGRAM), env.config, env.openai) + self.tg = FakeTelegramBot() + attach_telegram(self.bot, self.tg) + self.replies: list[str] = [] + self.reply_kwargs: list[dict] = [] + self.markdown_fails = False + + @property + def agent(self) -> FakeAgent: + return FakeAgent.instances[-1] + + def _update(self, *, user=1, text=None, caption=None, photo=None, voice=None, reply_to=None): + async def reply_text(text, **kw): + if self.markdown_fails and kw.get("parse_mode"): + raise ValueError("Can't parse entities") + self.replies.append(text) + self.reply_kwargs.append(kw) + + message = SimpleNamespace( + text=text, caption=caption, photo=photo, voice=voice, chat_id=int(self.chat_id), + reply_to_message=reply_to, reply_text=reply_text, + ) + return SimpleNamespace( + effective_user=SimpleNamespace(id=user), + effective_chat=SimpleNamespace(id=int(self.chat_id)), + message=message, + ) + + def _context(self): + return SimpleNamespace(bot=self.tg, args=[]) + + async def text(self, text, *, stranger=False): + await self.bot.handle_text(self._update(user=7 if stranger else 1, text=text), self._context()) + + async def photo(self, caption): + self.tg.files["PHOTO1"] = PHOTO + photo = [SimpleNamespace(file_id="small"), SimpleNamespace(file_id="PHOTO1")] + await self.bot.handle_photo(self._update(photo=photo, caption=caption), self._context()) + + async def voice(self): + self.tg.files["VOICE1"] = AUDIO + await self.bot.handle_voice(self._update(voice=SimpleNamespace(file_id="VOICE1")), self._context()) + + async def new(self): + await self.bot.new_command(self._update(text="/new"), self._context()) + + def delivered(self): + return [(m["chat_id"], m["text"]) for m in self.tg.sent] + + +# ── Slack driver ───────────────────────────────────────────────────────── + + +class FakeSlackApp: + def __init__(self, token=None, **kw): + self.token = token + self.events: dict = {} + self.posted: list[dict] = [] + self.uploads: list[dict] = [] + self.client = SimpleNamespace(chat_postMessage=self._post, files_upload_v2=self._upload) + + def event(self, name): + def register(fn): + self.events[name] = fn + return fn + return register + + async def _post(self, **kw): + self.posted.append(kw) + + async def _upload(self, **kw): + self.uploads.append(kw) + return {"ok": True} + + +class FakeHttpx: + """Stands in for httpx.AsyncClient (the Slack file download).""" + + content = PHOTO + fail = False + calls: list = [] + + def __init__(self, *, headers=None, timeout=None): + FakeHttpx.calls.append(headers) + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + async def get(self, url): + if FakeHttpx.fail: + raise RuntimeError("404") + return SimpleNamespace(content=FakeHttpx.content, raise_for_status=lambda: None) + + +class SlackDriver: + name = "slack" + chat_id = "C1" + + def __init__(self, env): + self.env = env + env.monkeypatch.setattr(f"{SLACK}.AsyncApp", FakeSlackApp) + env.monkeypatch.setattr("httpx.AsyncClient", FakeHttpx) + FakeHttpx.fail = False + FakeHttpx.calls = [] + self.bot = make_bot(importlib.import_module(SLACK), env.config, env.openai) + self.app = _only_instance_of(self.bot, FakeSlackApp) + self.said: list[dict] = [] + + @property + def replies(self) -> list[str]: + return [s["text"] for s in self.said] + + @property + def agent(self) -> FakeAgent: + return FakeAgent.instances[-1] + + async def _event(self, event, kind="message"): + async def say(**kw): + self.said.append(kw) + await self.app.events[kind](event=event, say=say, client=None) + + async def text(self, text, *, stranger=False, user=None): + user = user or ("U9" if stranger else "U1") + await self._event({"channel": "C1", "user": user, "text": text, "ts": "1.0"}) + + async def photo(self, caption): + FakeHttpx.content = PHOTO + await self._event({ + "channel": "C1", "user": "U1", "text": f"<@UBOT> {caption}", "ts": "1.0", + "files": [{"mimetype": "image/png", "name": "p.png", "url_private_download": "https://f/p"}], + }, kind="app_mention") + + async def voice(self): + FakeHttpx.content = AUDIO + await self._event({ + "channel": "C1", "user": "U1", "text": "", "ts": "1.0", + "files": [{"mimetype": "audio/mp4", "name": "a.m4a", "url_private": "https://f/a"}], + }) + + async def new(self): + await self._event({"channel": "C1", "user": "U1", "text": "<@UBOT> /new", "ts": "1.0"}) + + def delivered(self): + return [(m["channel"], m["text"]) for m in self.app.posted] + + +def _only_instance_of(obj, cls): + """The one attribute of *obj* (one level deep) that is a *cls*.""" + seen = [v for v in vars(obj).values() if isinstance(v, cls)] + for v in vars(obj).values(): + if hasattr(v, "__dict__") and not isinstance(v, type): + seen += [w for w in vars(v).values() if isinstance(w, cls)] + assert len(seen) == 1, seen + return seen[0] + + +# ── WhatsApp driver (neonize is replaced by fakes: it needs libmagic) ──── + + +class FakeNeonizeClient: + def __init__(self, path): + self.path = path + self.events: dict = {} + self.sent: list[tuple] = [] + self.replied: list[str] = [] + self.images: list[tuple] = [] + self.download: bytes | Exception = PHOTO + + def event(self, ev_type): + def register(fn): + self.events[ev_type] = fn + return fn + return register + + async def send_message(self, jid, text): + self.sent.append((jid, text)) + + async def reply_message(self, text, ev): + self.replied.append(text) + + async def download_any(self, message): + if isinstance(self.download, Exception): + raise self.download + return self.download + + async def send_image(self, chat, path, caption=None): + self.images.append((chat, path, caption)) + + +def _ensure_neonize_importable(): + """neonize needs the libmagic system library; without it, stand in + placeholder modules so the WhatsApp module imports (the tests replace + the client anyway).""" + try: + import neonize.aioze.client # noqa: F401 + import neonize.aioze.events # noqa: F401 + import neonize.utils.jid # noqa: F401 + except ImportError: + names = ["neonize", "neonize.aioze", "neonize.aioze.client", "neonize.aioze.events", + "neonize.utils", "neonize.utils.jid"] + stubs = {name: types.ModuleType(name) for name in names} + stubs["neonize.aioze.client"].NewAClient = FakeNeonizeClient + for event in ("ConnectedEv", "MessageEv", "PairStatusEv"): + setattr(stubs["neonize.aioze.events"], event, type(event, (), {})) + stubs["neonize.utils.jid"].build_jid = None + sys.modules.update(stubs) + + +_ensure_neonize_importable() + + +def _fields(present: bool): + return lambda: [1] if present else [] + + +def _wa_event(*, text="", image=None, audio=None, from_me=True, chat_user="111", group=False): + message = SimpleNamespace( + conversation=text, + extendedTextMessage=SimpleNamespace(text=""), + imageMessage=SimpleNamespace( + ListFields=_fields(image is not None), + caption=(image or {}).get("caption", ""), mimetype=(image or {}).get("mimetype", ""), + ), + audioMessage=SimpleNamespace( + ListFields=_fields(audio is not None), mimetype=(audio or {}).get("mimetype", ""), + ), + ) + chat = SimpleNamespace(User=chat_user, Server="s.whatsapp.net") + source = SimpleNamespace( + IsGroup=group, IsFromMe=from_me, Chat=chat, + Sender=SimpleNamespace(User="111" if from_me else chat_user), + ) + return SimpleNamespace(Info=SimpleNamespace(MessageSource=source), Message=message) + + +class WhatsAppDriver: + name = "whatsapp" + chat_id = "111@s.whatsapp.net" + + def __init__(self, env): + self.env = env + self.module = importlib.import_module(WHATSAPP) + env.monkeypatch.setattr(self.module, "NewAClient", FakeNeonizeClient) + env.monkeypatch.setattr(self.module, "build_jid", lambda user, server: f"jid:{user}@{server}") + self.bot = make_bot(self.module, env.config, env.openai) + self.client = _only_instance_of(self.bot, FakeNeonizeClient) + + @property + def agent(self) -> FakeAgent: + return FakeAgent.instances[-1] + + @property + def replies(self) -> list[str]: + return self.client.replied + [text for _, text in self.client.sent] + + async def _message(self, ev): + await self.client.events[self.module.MessageEv](self.client, ev) + + async def text(self, text, *, stranger=False): + await self._message(_wa_event(text=text, from_me=not stranger, chat_user="222" if stranger else "111")) + + async def photo(self, caption): + self.client.download = PHOTO + await self._message(_wa_event(image={"caption": caption, "mimetype": "image/jpeg"})) + + async def voice(self): + self.client.download = AUDIO + await self._message(_wa_event(audio={"mimetype": "audio/ogg; codecs=opus"})) + + async def new(self): + await self._message(_wa_event(text=" /NEW ")) + + def delivered(self): + return [(jid, text) for jid, text in self.client.sent] + + +DRIVERS = [TelegramDriver, SlackDriver, WhatsAppDriver] + + +@pytest.fixture(params=DRIVERS, ids=lambda d: d.name) +def chat(request, env): + return request.param(env) + + +# ── The same scenarios on every platform ───────────────────────────────── + + +async def test_plain_text(chat): + await chat.text("remember the milk") + assert chat.agent.calls == [{ + "prompt": "remember the milk", "image_b64": None, + "image_media_type": "image/jpeg", "chat_id": chat.chat_id, + }] + assert chat.replies == ["Got it."] + + +async def test_text_with_a_link(chat): + await chat.text(LINK_TEXT) + assert [c["prompt"] for c in chat.agent.calls] == [f"{LINK_TEXT}\n{NOTE}"] + assert chat.env.openai.chats == [{ + "model": "gpt-5-mini", "messages": SUMMARIZE_MESSAGES, + "reasoning_effort": "low", "max_completion_tokens": 300, + }] + assert chat.replies == ["Got it."] + + +async def test_link_that_cannot_be_fetched_adds_nothing(chat): + await chat.text("see https://example.com/elsewhere") + assert [c["prompt"] for c in chat.agent.calls] == ["see https://example.com/elsewhere"] + assert chat.env.openai.chats == [] + + +async def test_photo_with_a_link_in_the_caption(chat): + await chat.photo(LINK_TEXT) + [call] = chat.agent.calls + media_ref = { + "telegram": "PHOTO1", + "slack": str(chat.env.config.slack_media_dir), + "whatsapp": str(chat.env.config.whatsapp_media_dir), + }[chat.name] + prefix = f"User sent a photo. media_ref={media_ref}" + assert call["prompt"].startswith(prefix) + ref = call["prompt"].split("media_ref=", 1)[1].split("\n", 1)[0] + assert call["prompt"] == f"User sent a photo. media_ref={ref}\nCaption: {LINK_TEXT}{NOTE}" + assert call["image_b64"] == base64.b64encode(PHOTO).decode() + assert call["chat_id"] == chat.chat_id + if chat.name == "telegram": + assert call["image_media_type"] == "image/jpeg" + else: + # Slack and WhatsApp keep a copy under their media dir. + assert Path(ref).read_bytes() == PHOTO + assert Path(ref).suffix == {"slack": ".png", "whatsapp": ".jpg"}[chat.name] + assert call["image_media_type"] == {"slack": "image/png", "whatsapp": "image/jpeg"}[chat.name] + assert chat.replies == ["Got it."] + + +async def test_photo_without_caption(chat): + await chat.photo("") + [call] = chat.agent.calls + assert "\n" not in call["prompt"] + assert call["prompt"].startswith("User sent a photo. media_ref=") + assert chat.env.openai.chats == [] + + +async def test_failed_voice_transcription(chat): + chat.env.openai.fail_transcription = True + await chat.voice() + assert chat.agent.calls == [] + assert chat.replies == [TRANSCRIPTION_FAILED] + assert chat.env.openai.transcriptions == [("whisper-1", { + "telegram": ("voice.ogg", AUDIO, "audio/ogg"), + "slack": ("audio.m4a", AUDIO, "audio/mp4"), + "whatsapp": ("voice.ogg", AUDIO, "audio/ogg; codecs=opus"), + }[chat.name])] + + +async def test_voice_note(chat): + await chat.voice() + assert chat.agent.calls == [{ + "prompt": VOICE_PROMPT, "image_b64": None, + "image_media_type": "image/jpeg", "chat_id": chat.chat_id, + }] + assert chat.replies == ["Got it."] + + +async def test_stranger_is_ignored(chat): + await chat.text("hello") + await chat.text("let me in", stranger=True) + assert [c["prompt"] for c in chat.agent.calls] == ["hello"] + assert chat.replies == ["Got it."] + + +async def test_new_conversation(chat): + await chat.new() + assert chat.agent.resets == [chat.chat_id] + assert chat.agent.calls == [] + assert chat.replies == ["Started a new conversation."] + + +async def test_reminder_delivery(chat): + scheduler: ReminderScheduler = chat.agent.scheduler + assert chat.agent.platform == chat.name + scheduler.create( + platform=chat.name, chat_id=chat.chat_id, text="stretch", + fire_at=datetime.now() - timedelta(seconds=5), + ) + await scheduler._tick() + target = int(chat.chat_id) if chat.name == "telegram" else chat.chat_id + if chat.name == "whatsapp": + target = "jid:111@s.whatsapp.net" + assert chat.delivered() == [(target, "⏰ Reminder: stretch")] + assert chat.agent.fired == [("⏰ Reminder: stretch", chat.chat_id)] + assert scheduler.list_for(chat.name, chat.chat_id) == [] + + +async def test_long_reply(chat): + chat.agent.reply = ("x" * 5000, []) + await chat.text("hi") + limit = {"telegram": 4096, "slack": 4000, "whatsapp": 5000}[chat.name] + assert chat.replies == ["x" * limit] + + +# ── Where the platforms differ (kept as they are; see the docstrings) ──── + + +async def test_found_images(chat, tmp_path): + own = tmp_path / "own.jpg" + own.write_bytes(b"img") + chat.agent.reply = ("Here.", [ + {"platform": chat.name, "media_ref": str(own), "file_id": str(own), "caption": "mine"}, + {"platform": "elsewhere", "media_ref": "X", "file_id": "X", "description": "a cat"}, + ]) + await chat.text("show me") + if chat.name == "telegram": + # Telegram sends every image by file_id, whatever platform saved it. + assert [p["photo"] for p in chat.tg.photos] == [str(own), "X"] + assert [p["caption"] for p in chat.tg.photos] == ["mine", None] + assert chat.replies == ["Here."] + elif chat.name == "slack": + assert [(u["file"], u["initial_comment"]) for u in chat.app.uploads] == [(str(own), "mine")] + assert chat.replies == ["Here.\n\n_(Found image: a cat -- originally saved via elsewhere)_"] + else: + assert [(path, caption) for _, path, caption in chat.client.images] == [(str(own), "mine")] + assert chat.replies == ["Here.\n\n(Found image: a cat — originally saved via elsewhere)"] + + +async def test_reply_formatting(chat): + await chat.text("hi") + if chat.name == "telegram": + assert chat.reply_kwargs == [{"parse_mode": "Markdown"}] + elif chat.name == "slack": + assert chat.said == [{"text": "Got it.", "thread_ts": "1.0"}] + + +async def test_telegram_falls_back_to_plain_text(env): + chat = TelegramDriver(env) + chat.markdown_fails = True + await chat.text("hi") + assert chat.replies == ["Got it."] and chat.reply_kwargs == [{}] + + +async def test_telegram_quotes_the_replied_message(env): + chat = TelegramDriver(env) + update = chat._update(text=LINK_TEXT, reply_to=SimpleNamespace(text=None, caption="the photo caption")) + await chat.bot.handle_text(update, chat._context()) + assert [c["prompt"] for c in chat.agent.calls] == [ + f"[Replying to message] the photo caption\n{LINK_TEXT}\n{NOTE}" + ] + + +async def test_telegram_empty_allowlist_blocks_everyone(env): + """Quirk: on Telegram an empty ALLOWED_USER_IDS lets nobody in...""" + env.config.telegram.allowed_user_ids = "" + chat = TelegramDriver(env) + await chat.text("hello") + assert chat.agent.calls == [] and chat.replies == [] + + +async def test_slack_empty_allowlist_lets_everyone_in(env): + """...while on Slack an empty SLACK_ALLOWED_USERS lets everyone in.""" + env.config.slack.allowed_users = "" + chat = SlackDriver(env) + await chat.text("hello", user="U-anyone") + assert [c["prompt"] for c in chat.agent.calls] == ["hello"] + + +async def test_slack_allowlists(env): + env.config.slack.allowed_users = "U1" + env.config.slack.allowed_channels = "C1" + chat = SlackDriver(env) + await chat.text("from a stranger", stranger=True) + await chat._event({"channel": "C2", "user": "U1", "text": "other channel", "ts": "1.0"}) + await chat._event({"channel": "C1", "user": "U1", "text": "a bot", "ts": "1.0", "bot_id": "B1"}) + await chat.text("ok") + assert [c["prompt"] for c in chat.agent.calls] == ["ok"] + + +async def test_slack_download_failure(env): + chat = SlackDriver(env) + FakeHttpx.fail = True + await chat.photo("x") + await chat.voice() + assert chat.agent.calls == [] + assert chat.replies == [ + "Sorry, I couldn't download that image.", "Sorry, I couldn't download that audio file.", + ] + assert FakeHttpx.calls[0] == {"Authorization": "Bearer xoxb-1"} + + +async def test_whatsapp_download_failure(env): + chat = WhatsAppDriver(env) + chat.client.download = RuntimeError("gone") + await chat._message(_wa_event(image={"caption": "", "mimetype": "image/jpeg"})) + await chat._message(_wa_event(audio={"mimetype": "audio/ogg"})) + assert chat.agent.calls == [] + assert chat.replies == [ + "Sorry, I couldn't download that image.", "Sorry, I couldn't download that audio message.", + ] + + +async def test_whatsapp_only_self_chat(env): + chat = WhatsAppDriver(env) + await chat._message(_wa_event(text="to a friend", chat_user="222")) # my DM to someone else + await chat._message(_wa_event(text="group", group=True)) + await chat.text("note to self") + assert [c["prompt"] for c in chat.agent.calls] == ["note to self"] diff --git a/tests/bot/test_slack.py b/tests/bot/test_slack.py new file mode 100644 index 0000000..7032f68 --- /dev/null +++ b/tests/bot/test_slack.py @@ -0,0 +1,31 @@ +"""Slack: the /new command. (What Slack shares with the other platforms is +tested in test_parity.py.)""" +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock + +import pytest + + +@pytest.mark.asyncio +async def test_new_message_resets_the_channel(): + from memclaw.bot.inbound import Inbound + from memclaw.bot.slack import SlackBot + + handlers = SlackBot.__new__(SlackBot) + handlers.config = MagicMock() + handlers.config.slack.allowed_channels_list = [] + handlers.config.slack.allowed_users_list = [] + handlers.inbound = Inbound.__new__(Inbound) + handlers.inbound.agent = agent = MagicMock() + agent.reset_conversation = AsyncMock() + agent.handle = AsyncMock() + say = AsyncMock() + + await handlers._route_event( + {"channel": "C1", "user": "U1", "text": "<@UBOT> /new", "ts": "1.0"}, say, + ) + + agent.reset_conversation.assert_awaited_once_with("C1") + agent.handle.assert_not_awaited() + say.assert_awaited_once_with(text="Started a new conversation.", thread_ts="1.0") diff --git a/tests/test_handlers.py b/tests/bot/test_telegram.py similarity index 55% rename from tests/test_handlers.py rename to tests/bot/test_telegram.py index fac04e8..0ef1d07 100644 --- a/tests/test_handlers.py +++ b/tests/bot/test_telegram.py @@ -1,76 +1,21 @@ -"""Tests for Telegram handlers — double storage prevention (spec #7) + typing indicator.""" +"""Telegram: the typing indicator, the "Working…" status message and the +/new, /model and /effort commands. (What Telegram shares with the other +platforms is tested in test_parity.py.)""" from __future__ import annotations import asyncio -import inspect from unittest.mock import AsyncMock, MagicMock, patch import pytest -# ──────────────────────────────────────────────────────────────────── -# Spec #7: Double Storage Prevention -# ──────────────────────────────────────────────────────────────────── - -class TestHandlerSourceCode: - """Static analysis tests — verify that handlers don't call store.save() - for voice transcriptions and link summaries.""" - - def test_handle_voice_no_store_save(self): - """handle_voice should NOT call store.save() for transcriptions.""" - from memclaw.bot.handlers import MessageHandlers - source = inspect.getsource(MessageHandlers.handle_voice) - assert "store.save" not in source, ( - "handle_voice still calls store.save — voice transcriptions " - "should be left for the agent to decide" - ) - - def test_handle_voice_has_not_saved_directive(self): - """handle_voice should include 'NOT been saved yet' in the prompt.""" - from memclaw.bot.handlers import MessageHandlers - source = inspect.getsource(MessageHandlers.handle_voice) - assert "NOT been saved yet" in source - - def test_handle_text_no_store_save(self): - """handle_text should NOT call store.save() for link summaries.""" - from memclaw.bot.handlers import MessageHandlers - source = inspect.getsource(MessageHandlers.handle_text) - assert "store.save" not in source - - def test_handle_text_has_not_saved_directive(self): - """handle_text should include 'NOT been saved yet' for links.""" - from memclaw.bot.handlers import MessageHandlers - source = inspect.getsource(MessageHandlers.handle_text) - assert "NOT been saved yet" in source - - def test_handle_photo_no_store_save(self): - """handle_photo should NOT call store.save() for link summaries.""" - from memclaw.bot.handlers import MessageHandlers - source = inspect.getsource(MessageHandlers.handle_photo) - assert "store.save" not in source - - def test_handle_photo_has_not_saved_directive(self): - """handle_photo should include 'NOT been saved yet' for links.""" - from memclaw.bot.handlers import MessageHandlers - source = inspect.getsource(MessageHandlers.handle_photo) - assert "NOT been saved yet" in source - - # ──────────────────────────────────────────────────────────────────── # Typing indicator # ──────────────────────────────────────────────────────────────────── class TestTypingIndicator: def _make_handlers(self): - from memclaw.bot.handlers import MessageHandlers - - with patch.object(MessageHandlers, "__init__", lambda self, *a, **kw: None): - handlers = MessageHandlers.__new__(MessageHandlers) - handlers.agent = MagicMock() - handlers.config = MagicMock() - handlers.openai_client = MagicMock() - handlers.link_processor = MagicMock() - return handlers + return _telegram_handlers() @pytest.mark.asyncio async def test_typing_sent_during_processing(self): @@ -78,9 +23,7 @@ async def test_typing_sent_during_processing(self): from telegram.constants import ChatAction handlers = self._make_handlers() - update = MagicMock() - update.effective_chat.id = 123 - update.message.reply_text = AsyncMock() + update = _command_update(chat_id=123) context = MagicMock() context.bot.send_chat_action = AsyncMock() context.bot.send_photo = AsyncMock() @@ -89,9 +32,9 @@ async def slow_handle(prompt, **kw): await asyncio.sleep(0.05) return ("Response", []) - handlers.agent.handle = slow_handle + handlers.inbound.agent.handle = slow_handle - await handlers._send_with_typing(update, context, "Hi") + await handlers._send_with_typing(update.message, context, "Hi") context.bot.send_chat_action.assert_called() call_args = context.bot.send_chat_action.call_args @@ -102,127 +45,31 @@ async def slow_handle(prompt, **kw): async def test_response_sent_after_agent(self): """_send_with_typing should send the agent response via reply_text.""" handlers = self._make_handlers() - update = MagicMock() - update.effective_chat.id = 123 - update.message.reply_text = AsyncMock() + update = _command_update(chat_id=123) context = MagicMock() context.bot.send_chat_action = AsyncMock() context.bot.send_photo = AsyncMock() - handlers.agent.handle = AsyncMock(return_value=("Hello!", [])) + handlers.inbound.agent.handle = AsyncMock(return_value=("Hello!", [])) - await handlers._send_with_typing(update, context, "Hi") + await handlers._send_with_typing(update.message, context, "Hi") update.message.reply_text.assert_called_once_with("Hello!", parse_mode="Markdown") -class TestAgentsFile: - """Verify AGENTS.md (the externalized system prompt) has the right content.""" - - def _read_agents(self, tmp_config) -> str: - agents_path = tmp_config.agent_file - assert agents_path.exists(), f"AGENTS.md not found at {agents_path}" - return agents_path.read_text() - - def test_mentions_permanent_memory(self, tmp_config): - content = self._read_agents(tmp_config) - assert "MEMORY.md" in content - assert "memory_save" in content - assert "permanent=true" not in content - - def test_mentions_not_saved_yet(self, tmp_config): - content = self._read_agents(tmp_config) - assert "NOT" in content - assert "saved" in content.lower() - - def test_mentions_voice_not_saved(self, tmp_config): - content = self._read_agents(tmp_config) - assert "Voice message" in content - - def test_mentions_link_not_saved(self, tmp_config): - content = self._read_agents(tmp_config) - assert "Link summary" in content - - def test_has_user_instructions_section(self, tmp_config): - content = self._read_agents(tmp_config) - assert "User instructions" in content - - -# ──────────────────────────────────────────────────────────────────── -# WhatsApp self-chat scoping (regression: outgoing DMs to friends -# were being processed because IsFromMe alone matches them too) -# ──────────────────────────────────────────────────────────────────── - -class TestWhatsAppSelfChatOnly: - """Read whatsapp_handlers.py source directly to avoid needing neonize installed.""" - - def _source(self) -> str: - from pathlib import Path - path = Path(__file__).parent.parent / "memclaw" / "bot" / "whatsapp_handlers.py" - return path.read_text() - - def test_check_sender_requires_self_chat(self): - """_check_sender must compare Chat.User to Sender.User, not just IsFromMe.""" - import ast - src = self._source() - tree = ast.parse(src) - fn = next( - n for n in ast.walk(tree) - if isinstance(n, ast.FunctionDef) and n.name == "_check_sender" - ) - body_src = ast.unparse(fn) - assert "Chat.User" in body_src and "Sender.User" in body_src, ( - "_check_sender must require Chat.User == Sender.User to scope to the " - "self-chat — IsFromMe alone matches outgoing DMs to friends too" - ) - - def test_check_sender_behaviour(self): - """Simulate the three relevant cases against the real method.""" - from types import SimpleNamespace - import ast - - src = self._source() - tree = ast.parse(src) - fn = next( - n for n in ast.walk(tree) - if isinstance(n, ast.FunctionDef) and n.name == "_check_sender" - ) - ns: dict = {} - exec(compile(ast.Module(body=[fn], type_ignores=[]), "<_check_sender>", "exec"), ns) - check = ns["_check_sender"] - - def ev(*, is_group: bool, is_from_me: bool, chat_user: str, sender_user: str): - return SimpleNamespace( - Info=SimpleNamespace(MessageSource=SimpleNamespace( - IsGroup=is_group, - IsFromMe=is_from_me, - Chat=SimpleNamespace(User=chat_user), - Sender=SimpleNamespace(User=sender_user), - )) - ) - - self_note = ev(is_group=False, is_from_me=True, chat_user="me", sender_user="me") - out_to_friend = ev(is_group=False, is_from_me=True, chat_user="friend", sender_user="me") - in_from_friend = ev(is_group=False, is_from_me=False, chat_user="friend", sender_user="friend") - group = ev(is_group=True, is_from_me=True, chat_user="grp", sender_user="me") - - assert check(None, self_note) is True - assert check(None, out_to_friend) is False, "outgoing DM to friend must be ignored" - assert check(None, in_from_friend) is False - assert check(None, group) is False - - # ──────────────────────────────────────────────────────────────────── # /new, /model, /effort # ──────────────────────────────────────────────────────────────────── def _telegram_handlers(*, allowed: bool = True): - from memclaw.bot.handlers import MessageHandlers - - with patch.object(MessageHandlers, "__init__", lambda self, *a, **kw: None): - handlers = MessageHandlers.__new__(MessageHandlers) - handlers.agent = MagicMock() - handlers.agent.reset_conversation = AsyncMock() + """A TelegramBot whose agent is a mock (no backend, no vault).""" + from memclaw.bot.inbound import Inbound + from memclaw.bot.telegram import TelegramBot + + handlers = TelegramBot.__new__(TelegramBot) + handlers.inbound = Inbound.__new__(Inbound) + handlers.inbound.agent = MagicMock() + handlers.inbound.agent.reset_conversation = AsyncMock() handlers.config = MagicMock() handlers.config.telegram.allowed_user_ids_list = [1] if allowed else [] return handlers @@ -231,7 +78,7 @@ def _telegram_handlers(*, allowed: bool = True): def _command_update(chat_id: int = 99): update = MagicMock() update.effective_user.id = 1 - update.effective_chat.id = chat_id + update.message.chat_id = chat_id update.message.reply_text = AsyncMock() return update @@ -280,7 +127,7 @@ async def test_resets_the_chat(self): handlers = _telegram_handlers() update = _command_update(chat_id=99) await handlers.new_command(update, MagicMock()) - handlers.agent.reset_conversation.assert_awaited_once_with("99") + handlers.inbound.agent.reset_conversation.assert_awaited_once_with("99") update.message.reply_text.assert_awaited_once() @pytest.mark.asyncio @@ -288,33 +135,9 @@ async def test_ignores_unknown_users(self): handlers = _telegram_handlers(allowed=False) update = _command_update() await handlers.new_command(update, MagicMock()) - handlers.agent.reset_conversation.assert_not_awaited() + handlers.inbound.agent.reset_conversation.assert_not_awaited() update.message.reply_text.assert_not_awaited() - @pytest.mark.asyncio - async def test_slack_new_message_resets_the_channel(self): - from memclaw.bot.slack_handlers import SlackHandlers - - with patch.object(SlackHandlers, "__init__", lambda self, *a, **kw: None): - handlers = SlackHandlers.__new__(SlackHandlers) - handlers.config = MagicMock() - handlers.config.slack.allowed_channels_list = [] - handlers.config.slack.allowed_users_list = [] - handlers.agent = MagicMock() - handlers.agent.reset_conversation = AsyncMock() - handlers.agent.handle = AsyncMock() - say = AsyncMock() - - await handlers._route_event( - {"channel": "C1", "user": "U1", "text": "<@UBOT> /new", "ts": "1.0"}, - say, MagicMock(), - ) - - handlers.agent.reset_conversation.assert_awaited_once_with("C1") - handlers.agent.handle.assert_not_awaited() - say.assert_awaited_once() - - def _buttons(keyboard): return [(b.text, b.callback_data) for row in keyboard.inline_keyboard for b in row] @@ -331,7 +154,7 @@ def _callback_update(data: str, *, allowed_user: int = 1): class TestModelCommand: @pytest.mark.asyncio async def test_menu_has_a_button_per_model(self): - from memclaw.bot.handlers import model_menu + from memclaw.bot.telegram import model_menu text, keyboard = await model_menu(_SelectableBackend()) assert "Model: Claude Opus 5 (claude-opus-5)" in text @@ -342,7 +165,7 @@ async def test_menu_has_a_button_per_model(self): ] def test_long_model_id_falls_back_to_a_hash(self): - from memclaw.bot.handlers import _model_key, model_callback_data + from memclaw.bot.telegram import _model_key, model_callback_data assert model_callback_data("x" * 70) == f"mi:{_model_key('x' * 70)}" assert len(model_callback_data("x" * 70).encode()) <= 64 @@ -351,7 +174,7 @@ def test_long_model_id_falls_back_to_a_hash(self): @pytest.mark.asyncio async def test_button_press_switches_and_edits_the_menu(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _callback_update("m:claude-haiku-4-5") await handlers.handle_callback(update, MagicMock()) @@ -368,8 +191,8 @@ async def test_button_press_switches_and_edits_the_menu(self): @pytest.mark.asyncio async def test_index_button_press(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() - from memclaw.bot.handlers import _model_key + handlers.inbound.agent.backend = backend = _SelectableBackend() + from memclaw.bot.telegram import _model_key await handlers.handle_callback( _callback_update(f"mi:{_model_key('claude-haiku-4-5')}"), MagicMock(), @@ -379,7 +202,7 @@ async def test_index_button_press(self): @pytest.mark.asyncio async def test_stale_button_alerts(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _callback_update("m:claude-gone") await handlers.handle_callback(update, MagicMock()) assert backend.model == "claude-opus-5" @@ -389,7 +212,7 @@ async def test_stale_button_alerts(self): @pytest.mark.asyncio async def test_button_press_from_unknown_user_is_ignored(self): handlers = _telegram_handlers(allowed=False) - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _callback_update("m:claude-haiku-4-5") await handlers.handle_callback(update, MagicMock()) assert backend.model == "claude-opus-5" @@ -398,7 +221,7 @@ async def test_button_press_from_unknown_user_is_ignored(self): @pytest.mark.asyncio async def test_command_with_number_or_id(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _command_update() context = MagicMock() @@ -414,7 +237,7 @@ async def test_command_with_number_or_id(self): @pytest.mark.asyncio async def test_bad_number_and_unknown_id(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _command_update() context = MagicMock() for arg, expected in (("9", "no model number 9"), ("claude-nope", "Unknown model")): @@ -425,7 +248,7 @@ async def test_bad_number_and_unknown_id(self): @pytest.mark.asyncio async def test_unsupported_backend(self): - from memclaw.bot.handlers import effort_menu, model_menu + from memclaw.bot.telegram import effort_menu, model_menu backend = MagicMock(supports_model_selection=False, display_name="Cursor SDK") text, keyboard = await model_menu(backend) @@ -439,7 +262,7 @@ async def test_unsupported_backend(self): class TestEffortCommand: @pytest.mark.asyncio async def test_menu_has_a_button_per_level(self): - from memclaw.bot.handlers import effort_menu + from memclaw.bot.telegram import effort_menu text, keyboard = await effort_menu(_SelectableBackend()) assert "Effort: high" in text @@ -449,7 +272,7 @@ async def test_menu_has_a_button_per_level(self): @pytest.mark.asyncio async def test_model_without_effort_has_no_buttons(self): - from memclaw.bot.handlers import effort_menu + from memclaw.bot.telegram import effort_menu backend = _SelectableBackend() backend.model, backend.effort = "claude-haiku-4-5", None @@ -460,7 +283,7 @@ async def test_model_without_effort_has_no_buttons(self): @pytest.mark.asyncio async def test_button_press_sets_level(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _callback_update("e:low") await handlers.handle_callback(update, MagicMock()) assert backend.effort == "low" @@ -470,7 +293,7 @@ async def test_button_press_sets_level(self): @pytest.mark.asyncio async def test_command_sets_level(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _command_update() context = MagicMock() context.args = ["low"] @@ -480,7 +303,7 @@ async def test_command_sets_level(self): @pytest.mark.asyncio async def test_rejected_level(self): handlers = _telegram_handlers() - handlers.agent.backend = backend = _SelectableBackend() + handlers.inbound.agent.backend = backend = _SelectableBackend() update = _command_update() context = MagicMock() context.args = ["max"] @@ -493,7 +316,7 @@ class TestStepStatusMessage: @pytest.mark.asyncio async def test_status_message_is_sent_edited_and_deleted(self): from memclaw.backends.base import ToolStep - from memclaw.bot import handlers as handlers_mod + from memclaw.bot import telegram as handlers_mod handlers = _telegram_handlers() handlers._send_response = AsyncMock() @@ -507,9 +330,9 @@ async def handle(prompt, *, on_tool, **kwargs): await on_tool(ToolStep(2, "memory_save", "Saving to memory")) return "Bruno", [] - handlers.agent.handle = handle + handlers.inbound.agent.handle = handle with patch.object(handlers_mod, "STATUS_EDIT_INTERVAL_S", 0): - await handlers._send_with_typing(_command_update(), context, "hi") + await handlers._send_with_typing(_command_update().message, context, "hi") context.bot.send_message.assert_awaited_once() assert context.bot.send_message.await_args.args[1] == ( @@ -526,9 +349,9 @@ async def test_no_status_message_without_tool_calls(self): context = MagicMock() context.bot.send_message = AsyncMock() context.bot.send_chat_action = AsyncMock() - handlers.agent.handle = AsyncMock(return_value=("hello", [])) + handlers.inbound.agent.handle = AsyncMock(return_value=("hello", [])) - await handlers._send_with_typing(_command_update(), context, "hi") + await handlers._send_with_typing(_command_update().message, context, "hi") context.bot.send_message.assert_not_awaited() diff --git a/tests/bot/test_whatsapp.py b/tests/bot/test_whatsapp.py new file mode 100644 index 0000000..3e68c83 --- /dev/null +++ b/tests/bot/test_whatsapp.py @@ -0,0 +1,67 @@ +"""WhatsApp: only your notes to yourself are handled. (What WhatsApp shares +with the other platforms is tested in test_parity.py.)""" +from __future__ import annotations + + +# ──────────────────────────────────────────────────────────────────── +# WhatsApp self-chat scoping (regression: outgoing DMs to friends +# were being processed because IsFromMe alone matches them too) +# ──────────────────────────────────────────────────────────────────── + +class TestWhatsAppSelfChatOnly: + """Read whatsapp.py source directly to avoid needing neonize installed.""" + + def _source(self) -> str: + from pathlib import Path + path = Path(__file__).parents[2] / "memclaw" / "bot" / "whatsapp.py" + return path.read_text() + + def test_check_sender_requires_self_chat(self): + """_check_sender must compare Chat.User to Sender.User, not just IsFromMe.""" + import ast + src = self._source() + tree = ast.parse(src) + fn = next( + n for n in ast.walk(tree) + if isinstance(n, ast.FunctionDef) and n.name == "_check_sender" + ) + body_src = ast.unparse(fn) + assert "Chat.User" in body_src and "Sender.User" in body_src, ( + "_check_sender must require Chat.User == Sender.User to scope to the " + "self-chat — IsFromMe alone matches outgoing DMs to friends too" + ) + + def test_check_sender_behaviour(self): + """Simulate the three relevant cases against the real method.""" + from types import SimpleNamespace + import ast + + src = self._source() + tree = ast.parse(src) + fn = next( + n for n in ast.walk(tree) + if isinstance(n, ast.FunctionDef) and n.name == "_check_sender" + ) + ns: dict = {} + exec(compile(ast.Module(body=[fn], type_ignores=[]), "<_check_sender>", "exec"), ns) + check = ns["_check_sender"] + + def ev(*, is_group: bool, is_from_me: bool, chat_user: str, sender_user: str): + return SimpleNamespace( + Info=SimpleNamespace(MessageSource=SimpleNamespace( + IsGroup=is_group, + IsFromMe=is_from_me, + Chat=SimpleNamespace(User=chat_user), + Sender=SimpleNamespace(User=sender_user), + )) + ) + + self_note = ev(is_group=False, is_from_me=True, chat_user="me", sender_user="me") + out_to_friend = ev(is_group=False, is_from_me=True, chat_user="friend", sender_user="me") + in_from_friend = ev(is_group=False, is_from_me=False, chat_user="friend", sender_user="friend") + group = ev(is_group=True, is_from_me=True, chat_user="grp", sender_user="me") + + assert check(None, self_note) is True + assert check(None, out_to_friend) is False, "outgoing DM to friend must be ignored" + assert check(None, in_from_friend) is False + assert check(None, group) is False diff --git a/tests/conftest.py b/tests/conftest.py index 3f7ce1b..3228419 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -41,7 +41,7 @@ def _offline_embeddings(request, monkeypatch): """Unit tests never call OpenAI; tests/e2e uses the real API.""" if f"{os.sep}e2e{os.sep}" in str(request.node.fspath): return - monkeypatch.setattr("memclaw.index.AsyncOpenAI", _FakeOpenAI) + monkeypatch.setattr("memclaw.openai_client.AsyncOpenAI", _FakeOpenAI) @pytest.fixture diff --git a/tests/e2e/test_agent_e2e.py b/tests/e2e/test_agent_e2e.py index cc63f07..80007fd 100644 --- a/tests/e2e/test_agent_e2e.py +++ b/tests/e2e/test_agent_e2e.py @@ -11,6 +11,7 @@ from memclaw.agent import MemclawAgent from memclaw.memory_refs import check_references +from memclaw.openai_client import OpenAIClient from .conftest import days_ago, write_daily @@ -106,7 +107,7 @@ async def test_instruction_is_saved_and_followed(agent_vault): async def test_turn_survives_openai_outage(agent_vault): """Context search failing (bad OpenAI key) must not fail the message.""" agent = await _agent(agent_vault) - agent.index.openai.api_key = "sk-invalid" + agent.index._openai = OpenAIClient("sk-invalid") try: reply, _ = await agent.handle("Just say hi.", chat_id="1") assert reply and reply != "I couldn't generate a response." @@ -212,7 +213,7 @@ async def test_agent_follows_a_reference_for_an_exact_value(agent_vault): f"- HERE Maps API key → memory/{day.isoformat()}.md\n" ) agent = await _agent(agent_vault) - agent.index.openai.api_key = "sk-invalid" + agent.index._openai = OpenAIClient("sk-invalid") try: reply, _ = await agent.handle("What's my HERE API key? I need the exact value.", chat_id="1") assert "-6ANtobEtBwi4s3mKHlqSPbM1VSbXlQdXkAo7tXNQoU" in reply diff --git a/tests/e2e/test_retrieval_e2e.py b/tests/e2e/test_retrieval_e2e.py index 6ddfded..21fb288 100644 --- a/tests/e2e/test_retrieval_e2e.py +++ b/tests/e2e/test_retrieval_e2e.py @@ -7,6 +7,7 @@ from memclaw.agent import MemclawAgent from memclaw.index import MemoryIndex +from memclaw.openai_client import OpenAIClient from memclaw.search import HybridSearch from memclaw.store import MemoryStore from memclaw.tools import ToolExecutor @@ -233,7 +234,7 @@ async def test_context_survives_embedding_failure(vault, monkeypatch): """If OpenAI is unreachable, the per-turn context still builds (without memories) instead of failing the whole message.""" agent = MemclawAgent(vault, backend=_NoBackend()) - monkeypatch.setattr(agent.index.openai, "api_key", "sk-invalid") + monkeypatch.setattr(agent.index, "_openai", OpenAIClient("sk-invalid")) context = await agent.build_context("hello there") assert context.startswith("") and context.endswith("") agent._close_sync_only() diff --git a/tests/test_index.py b/tests/test_index.py index 0390f78..4f108fd 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -3,7 +3,7 @@ import hashlib from pathlib import Path -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, patch import numpy as np import pytest @@ -48,18 +48,16 @@ class TestEmbeddingCacheBehavior: async def test_cache_miss_calls_api(self, idx: MemoryIndex): """On cache miss, the OpenAI API is called.""" fake_emb = np.random.randn(1536).astype(np.float32) - mock_response = MagicMock() - mock_response.data = [MagicMock(embedding=fake_emb.tolist())] + vectors = [fake_emb.tolist()] with patch.object(idx, "_openai") as mock_openai: - mock_openai.embeddings = MagicMock() - mock_openai.embeddings.create = AsyncMock(return_value=mock_response) + mock_openai.embed = AsyncMock(return_value=vectors) idx._openai = mock_openai result = await idx.get_embeddings(["hello world"]) assert len(result) == 1 assert result[0].shape == (1536,) - mock_openai.embeddings.create.assert_called_once() + mock_openai.embed.assert_called_once() @pytest.mark.asyncio async def test_cache_hit_skips_api(self, idx: MemoryIndex): @@ -76,15 +74,14 @@ async def test_cache_hit_skips_api(self, idx: MemoryIndex): idx.db.commit() with patch.object(idx, "_openai") as mock_openai: - mock_openai.embeddings = MagicMock() - mock_openai.embeddings.create = AsyncMock() + mock_openai.embed = AsyncMock() idx._openai = mock_openai result = await idx.get_embeddings([text]) assert len(result) == 1 np.testing.assert_array_almost_equal(result[0], fake_emb, decimal=5) # API should NOT have been called - mock_openai.embeddings.create.assert_not_called() + mock_openai.embed.assert_not_called() @pytest.mark.asyncio async def test_cache_miss_on_different_model(self, idx: MemoryIndex): @@ -101,17 +98,15 @@ async def test_cache_miss_on_different_model(self, idx: MemoryIndex): idx.db.commit() new_emb = np.random.randn(1536).astype(np.float32) - mock_response = MagicMock() - mock_response.data = [MagicMock(embedding=new_emb.tolist())] + vectors = [new_emb.tolist()] with patch.object(idx, "_openai") as mock_openai: - mock_openai.embeddings = MagicMock() - mock_openai.embeddings.create = AsyncMock(return_value=mock_response) + mock_openai.embed = AsyncMock(return_value=vectors) idx._openai = mock_openai await idx.get_embeddings([text]) # API should have been called because model doesn't match - mock_openai.embeddings.create.assert_called_once() + mock_openai.embed.assert_called_once() @pytest.mark.asyncio async def test_mixed_cache_hits_and_misses(self, idx: MemoryIndex): @@ -128,12 +123,10 @@ async def test_mixed_cache_hits_and_misses(self, idx: MemoryIndex): idx.db.commit() uncached_emb = np.random.randn(1536).astype(np.float32) - mock_response = MagicMock() - mock_response.data = [MagicMock(embedding=uncached_emb.tolist())] + vectors = [uncached_emb.tolist()] with patch.object(idx, "_openai") as mock_openai: - mock_openai.embeddings = MagicMock() - mock_openai.embeddings.create = AsyncMock(return_value=mock_response) + mock_openai.embed = AsyncMock(return_value=vectors) idx._openai = mock_openai result = await idx.get_embeddings([cached_text, uncached_text]) @@ -141,8 +134,8 @@ async def test_mixed_cache_hits_and_misses(self, idx: MemoryIndex): # First result should be the cached one np.testing.assert_array_almost_equal(result[0], cached_emb, decimal=5) # API called with only the uncached text - call_args = mock_openai.embeddings.create.call_args - assert call_args.kwargs["input"] == [uncached_text] + call_args = mock_openai.embed.call_args + assert call_args.args[0] == [uncached_text] @pytest.mark.asyncio async def test_empty_input(self, idx: MemoryIndex): diff --git a/tests/test_openai_client.py b/tests/test_openai_client.py new file mode 100644 index 0000000..7e082af --- /dev/null +++ b/tests/test_openai_client.py @@ -0,0 +1,77 @@ +"""memclaw.openai_client: the calls Memclaw makes, and the doctor's probe.""" +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from memclaw import openai_client +from memclaw.openai_client import OpenAIClient, probe_openai + + +class _SDK: + """Records calls; whisper fails with *whisper_status* if set.""" + + def __init__(self, *, api_key, whisper_status=None): + self.calls: list[tuple] = [] + self.whisper_status = whisper_status + self.embeddings = SimpleNamespace(create=self._embed) + self.audio = SimpleNamespace(transcriptions=SimpleNamespace(create=self._transcribe)) + self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._chat)) + self.closed = False + + async def _embed(self, **kw): + self.calls.append(("embed", kw)) + return SimpleNamespace(data=[SimpleNamespace(embedding=[0.5, 1.0]) for _ in kw["input"]]) + + async def _transcribe(self, **kw): + self.calls.append(("transcribe", kw)) + if self.whisper_status: + raise type("APIError", (Exception,), {"status_code": self.whisper_status})("nope") + return SimpleNamespace(text="hello") + + async def _chat(self, **kw): + self.calls.append(("chat", kw)) + return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=None))]) + + async def close(self): + self.closed = True + + +@pytest.fixture +def sdk(monkeypatch): + made: list[_SDK] = [] + + def factory(**kw): + made.append(_SDK(**kw, whisper_status=getattr(factory, "whisper_status", None))) + return made[-1] + + monkeypatch.setattr(openai_client, "AsyncOpenAI", factory) + factory.made = made + return factory + + +@pytest.mark.asyncio +async def test_calls(sdk): + client = OpenAIClient("sk-1") + assert await client.embed(["a", "b"], model="m") == [[0.5, 1.0], [0.5, 1.0]] + assert await client.transcribe(b"ogg", filename="voice.ogg", mime_type="audio/ogg") == "hello" + assert await client.chat([{"role": "user", "content": "hi"}]) == "" + assert sdk.made[0].calls == [ + ("embed", {"model": "m", "input": ["a", "b"]}), + ("transcribe", {"model": "whisper-1", "file": ("voice.ogg", b"ogg", "audio/ogg")}), + ("chat", {"model": "gpt-5-mini", "messages": [{"role": "user", "content": "hi"}], + "reasoning_effort": "low", "max_completion_tokens": 300}), + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status, whisper_ok", [(None, True), (400, True), (401, False)]) +async def test_probe(sdk, status, whisper_ok): + """A 400 from Whisper on the silent probe file still proves access.""" + sdk.whisper_status = status + report = await probe_openai("sk-1") + assert [o.ok for o in report] == [True, True, whisper_ok] + assert report.all_ok is whisper_ok + assert sdk.made[0].closed + assert [name for name, _ in sdk.made[0].calls] == ["embed", "chat", "transcribe"] diff --git a/tests/test_setup.py b/tests/test_setup.py index f03e183..5a972f2 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -26,6 +26,12 @@ def test_asked_per_platform(self): ] assert setup.questions("whatsapp") == setup.questions("terminal") == [] + def test_platforms_come_from_the_bot_registry(self): + assert setup.PLATFORMS == [ + ("telegram", "Telegram"), ("whatsapp", "WhatsApp"), ("slack", "Slack"), + ("terminal", "Terminal chat"), + ] + def test_every_question_belongs_to_a_known_platform_or_none(self): platforms = {name for name, _ in setup.PLATFORMS} asked = setup.questions() + [s for p in platforms for s in setup.questions(p)]