diff --git a/.code-shape/baseline.json b/.code-shape/baseline.json index b7ad607..516f21d 100644 --- a/.code-shape/baseline.json +++ b/.code-shape/baseline.json @@ -1,34 +1,5 @@ { "about": "Known shape violations. Shrink it with `code-shape tighten`; never edit by hand to add.", - "entries": { - "complexipy": { - "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 - }, - "mypy": { - "type-errors|memclaw/backends/claude.py|": 1, - "type-errors|memclaw/backends/mcp_bridge.py|": 1 - }, - "pylint": { - "class-attributes|memclaw/backends/cursor.py|CursorAgentBackend": 13, - "too-many-locals|memclaw/backends/claude.py|ClaudeAgentBackend.wizard_setup": 17, - "too-many-locals|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 19 - }, - "ruff": { - "function-complexity|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, - "function-complexity|memclaw/backends/cursor_sdk_adapter.py|collect_run_result": 11, - "too-many-args|memclaw/tools.py|ToolExecutor.__init__": 7, - "too-many-branches|memclaw/backends/claude.py|ClaudeAgentBackend._query": 13, - "too-many-positional|memclaw/tools.py|ToolExecutor.__init__": 7 - }, - "sizes": { - "class-lines|memclaw/backends/claude.py|ClaudeAgentBackend": 488, - "class-lines|memclaw/backends/cursor.py|CursorAgentBackend": 406, - "file-lines|memclaw/backends/claude.py|": 762, - "file-lines|memclaw/backends/cursor.py|": 590, - "file-lines|memclaw/tools.py|": 575 - } - }, + "entries": {}, "version": 1 } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 41f1cfa..5d0a505 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,8 +72,9 @@ Claude Code uses `.claude/settings.json` automatically: when Claude runs `git co - **Chat SDKs stay in their platform module**: only the three chat-app modules import `telegram`, `slack_bolt` or `neonize`. - **One OpenAI adapter**: only `openai_client.py` imports `openai`; everyone else calls `OpenAIClient`. - **Memory through its package**: other code uses what `memclaw.memory` exports (`MemoryStore`, `MemoryIndex`, `HybridSearch`, `Consolidator`, `MemoryVault`, …), not the modules inside (`notes.py`, `index.py`, `search.py`, …). Inside, `vault` (what the one-off `memclaw` commands call) sits on top, `consolidation` and `search` build on `notes` and `index`, never the other way round, and only `index.py` runs SQL on the search index. `memory/consolidation.py` is the only code that writes MEMORY.md; it reaches the LLM through the backend the agent hands it, so it doesn't import `memclaw.backends`. +- **Tools through their package**: other code uses what `memclaw.tools` exports (`TOOL_DEFINITIONS`, `ToolExecutor`, `ToolContext`, `describe_tool_call`). Inside, there is one module per kind of tool (`memory.py`, `images.py`, `files.py`, `reminders.py`), each holding its tools' definitions and code; `catalog.py` lists them in order and `executor.py` runs a call. - **Setup through its package**: other code uses what `memclaw.setup` exports (`run_setup`, `needs_setup`, `print_logo`, `run_doctor`), not `setup/wizard.py` or `setup/doctor.py`. -- **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`. +- **Backends are swappable**: only `memclaw.backends` itself imports the concrete backends (the `claude/` and `cursor/` packages). 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. If a new dependency between modules is legitimate, move the module to another layer in the same PR; don't add an ignore line. diff --git a/docs/upgrading.md b/docs/upgrading.md index fdb6e23..df93dac 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -8,6 +8,10 @@ The store, index and search moved into the `memclaw.memory` package: `from memcl A custom agent backend's `run_turn` now takes `run_turn(request, tool_executor)`, where `request` is a `memclaw.backends.TurnRequest` holding the fields that used to be keyword arguments (`system_prompt`, `context`, `user_message`, `session_key`, `resume_session_id`, ...). `ModelInfo` lives in `memclaw.backends.model_selection`. +The Claude and Cursor backends are packages now: `ClaudeAgentBackend` and `CursorAgentBackend` import from `memclaw.backends` (or `memclaw.backends.claude` / `memclaw.backends.cursor`) as before. Their internal modules moved inside: `memclaw.backends.claude_models` is `memclaw.backends.claude.models`, `memclaw.backends.cursor_hooks` is `memclaw.backends.cursor.hooks`, and `memclaw.backends.cursor_sdk_adapter` is `memclaw.backends.cursor.sdk_adapter`. + +`memclaw.tools` is now a package. `TOOL_DEFINITIONS`, `ToolExecutor` and `describe_tool_call` import from it as before, but `ToolExecutor` takes one `ToolContext` holding what it used to take as arguments: `ToolExecutor(config, store, index, search, found_images, platform=..., scheduler=...)` is now `ToolExecutor(ToolContext(config, store, index, search, found_images, platform=..., scheduler=...))`, and the current chat is `executor.context.chat_id` (was `executor.chat_id`). + ## From 2.x to 3.0 ```bash diff --git a/memclaw/agent.py b/memclaw/agent.py index 127278e..7473847 100644 --- a/memclaw/agent.py +++ b/memclaw/agent.py @@ -34,7 +34,7 @@ from .memory import Consolidator, HybridSearch, MemoryIndex, MemoryStore from .reminders import ReminderScheduler from .sessions import ChatSessions -from .tools import ToolExecutor +from .tools import ToolContext, ToolExecutor # Per-turn memory search results. Kept small because every context block # stays in the session transcript. @@ -63,7 +63,7 @@ def __init__( self.index = MemoryIndex(config) self.search = HybridSearch(config, self.index) self._found_images: list[dict] = [] - self._tools = ToolExecutor( + self._tools = ToolExecutor(ToolContext( config=config, store=self.store, index=self.index, @@ -71,7 +71,7 @@ def __init__( found_images=self._found_images, platform=platform, scheduler=scheduler, - ) + )) self.backend: AgentBackend = backend or build_backend(config) self._backend_started = False self.sessions = ChatSessions( @@ -217,7 +217,7 @@ async def _handle( on_tool: ProgressCallback | None, ) -> tuple[str, list[dict]]: self._found_images.clear() - self._tools.chat_id = chat_id + self._tools.context.chat_id = chat_id turn = self.sessions.begin(chat_id) agent_instructions = load_agent_instructions(self.config) diff --git a/memclaw/backends/__init__.py b/memclaw/backends/__init__.py index 2c05fca..74c8acf 100644 --- a/memclaw/backends/__init__.py +++ b/memclaw/backends/__init__.py @@ -1,6 +1,6 @@ """Agent-backend registry. -Each backend module (e.g. `claude.py`) exposes a class that satisfies the +Each backend package (e.g. `claude/`) exposes a class that satisfies the `AgentBackend` protocol. To register one, add it to `REGISTRY` below. Selection at runtime is driven by the `AGENT_BACKEND` env var (mirrored on diff --git a/memclaw/backends/claude.py b/memclaw/backends/claude.py deleted file mode 100644 index 450204d..0000000 --- a/memclaw/backends/claude.py +++ /dev/null @@ -1,762 +0,0 @@ -"""Claude Agent SDK backend for Memclaw. - -Wraps `claude-agent-sdk` (which itself shells out to the Claude CLI) into the -neutral `AgentBackend` protocol. All Claude-specific glue — env scrubbing, -MCP server wrapping for tools, stream-json image protocol, response parsing, -per-chat CLI sessions — lives in this file. - -Each chat keeps one connected `ClaudeSDKClient` (one Claude CLI process) -that is reused across turns, so the conversation lives in the CLI's own -session instead of being re-sent with every message. -""" - -from __future__ import annotations - -import asyncio -import json -from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, AsyncIterator, ClassVar - -from claude_agent_sdk import ( - AssistantMessage, - ClaudeAgentOptions, - ClaudeSDKClient, - ResultMessage, - TextBlock, - ToolUseBlock, - create_sdk_mcp_server, - tool, -) -from loguru import logger -from ..config import process_environment -from ..terminal_input import choose, masked_input -from ..tools import TOOL_DEFINITIONS -from .base import ProgressCallback, TurnRequest, TurnResult, report_tool_step -from .claude_models import SDK_EFFORT_LEVELS, fetch_models -from .mcp_tools import MCP_SERVER_NAME -from .model_selection import ModelInfo, ModelSelectionMixin - -if TYPE_CHECKING: - from rich.console import Console - - from ..config import ClaudeSettings, MemclawConfig - from ..tools import ToolExecutor - - -_DEFAULT_MODEL = "claude-sonnet-5-5" - -# Memory consolidation: rare and one-shot, so a stronger model is worth it. -_DEFAULT_CONSOLIDATION_MODEL = "claude-opus-5-5" -_DEFAULT_CONSOLIDATION_EFFORT = "medium" - -# Used when CLAUDE_EFFORT is unset and the default model runs, and -# preselected in the wizard for any model that supports effort at all. -_DEFAULT_EFFORT = "medium" - -# Anthropic list prices, (input, output) USD per 1M tokens. Only used as a -# fallback when the SDK doesn't return total_cost_usd for an API-key turn. -# Ids are matched by prefix, so dated snapshots (claude-haiku-4-5-20251001) -# resolve too. A model missing here (an alias, or one released later) is -# estimated at the default model's price, so the figure is approximate. -_PRICES_PER_M: dict[str, tuple[float, float]] = { - "claude-fable-5-1": (10.0, 50.0), - "claude-fable-5": (10.0, 50.0), - "claude-opus-5-5": (4.0, 20.0), - "claude-opus-5": (5.0, 25.0), - "claude-opus-4-8": (5.0, 25.0), - "claude-opus-4-7": (5.0, 25.0), - "claude-opus-4-6": (5.0, 25.0), - "claude-sonnet-5-5": (2.0, 10.0), - "claude-sonnet-5": (2.0, 10.0), - "claude-sonnet-4-6": (3.0, 15.0), - "claude-haiku-4-5": (1.0, 5.0), -} - -# Cache reads are billed at a tenth of the input price, cache writes at -# 1.25 times it. -_CACHE_READ_MULTIPLIER = 0.1 -_CACHE_WRITE_MULTIPLIER = 1.25 - -_ALLOWED_TOOLS = [ - f"mcp__{MCP_SERVER_NAME}__{t['name']}" for t in TOOL_DEFINITIONS -] - - -# ── Env / auth helpers ────────────────────────────────────────────── - -def _claude_auth_mode(config: "MemclawConfig") -> str: - """Which Claude credential is configured. - - Returns "subscription" when CLAUDE_CODE_OAUTH_TOKEN is set (billed - against the Claude plan, no per-message cost), "api_key" when only - ANTHROPIC_API_KEY is set, or "" when neither is set. - """ - if config.claude.oauth_token: - return "subscription" - if config.claude.api_key: - return "api_key" - return "" - - -def _resolve_model(config: "MemclawConfig") -> str: - """The configured model, or the built-in default when unset.""" - return (config.claude.model or "").strip() or _DEFAULT_MODEL - - -def _prices_per_m(model: str) -> tuple[float, float]: - """(input, output) USD per 1M tokens for *model*; see _PRICES_PER_M.""" - # Longest prefix first, so claude-opus-5-5 doesn't match claude-opus-5. - for prefix in sorted(_PRICES_PER_M, key=len, reverse=True): - if model == prefix or model.startswith(f"{prefix}-"): - return _PRICES_PER_M[prefix] - return _PRICES_PER_M[_DEFAULT_MODEL] - - -def _resolve_effort(config: "MemclawConfig") -> str | None: - """The configured effort level, or None to let the model decide. - - Anything the SDK does not recognise is treated as unset: ~/.memclaw/.env - is a plain text file, and a typo there should not reach the CLI as an - argument it will reject. An unset level means `_DEFAULT_EFFORT` on the - default model and None (the SDK omits the flag) on any other model. - - Whether the chosen *model* accepts an effort level is a separate question, - settled in the wizard and by /model — they store no level for a model - that reports none. - """ - effort = (config.claude.effort or "").strip().lower() - if effort in SDK_EFFORT_LEVELS: - return effort - return _DEFAULT_EFFORT if _resolve_model(config) == _DEFAULT_MODEL else None - - -def _resolve_consolidation(config: "MemclawConfig") -> tuple[str, str | None]: - """(model, effort) for consolidation: CLAUDE_CONSOLIDATION_MODEL / - CLAUDE_CONSOLIDATION_EFFORT, else Opus 5.5 at medium. As in - `_resolve_effort`, an unknown level counts as unset, and an unset level - means the default effort only on the default model (another model may - not take an effort at all).""" - model = (config.claude.consolidation_model or "").strip() or _DEFAULT_CONSOLIDATION_MODEL - effort = (config.claude.consolidation_effort or "").strip().lower() - if effort in SDK_EFFORT_LEVELS: - return model, effort - if model == _DEFAULT_CONSOLIDATION_MODEL: - return model, _DEFAULT_CONSOLIDATION_EFFORT - return model, None - - -def _fit_effort(levels: list[str], preferred: str) -> str | None: - """The level to use on a model supporting *levels* when *preferred* is - wanted: *preferred* itself, else the nearest supported level below it - (else the lowest). None when the model takes no effort at all.""" - if not levels: - return None - if preferred in levels: - return preferred - order = list(SDK_EFFORT_LEVELS) - rank = order.index(preferred) if preferred in order else len(order) - below = [lv for lv in levels if lv in order and order.index(lv) < rank] - return below[-1] if below else levels[0] - - -def _credential(config: "MemclawConfig") -> str: - """The credential matching `_claude_auth_mode`.""" - if _claude_auth_mode(config) == "subscription": - return config.claude.oauth_token - return config.claude.api_key - - -def _build_env(config: "MemclawConfig") -> dict[str, str]: - """Build the env dict for the Claude CLI subprocess. - - Scrubs every credential env var first so the subprocess never inherits - a stale token from the parent shell, then injects exactly one credential - based on the configured auth mode: - - - subscription → CLAUDE_CODE_OAUTH_TOKEN, billed against the Claude plan. - - api_key → ANTHROPIC_API_KEY, billed against Console credits. - """ - env = { - k: v for k, v in process_environment().items() - if k not in ( - "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", - "CLAUDE_CODE_OAUTH_TOKEN", - "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", - "CLAUDE_CODE_USE_FOUNDRY", - ) - } - mode = _claude_auth_mode(config) - if mode == "subscription": - env["CLAUDE_CODE_OAUTH_TOKEN"] = config.claude.oauth_token - elif mode == "api_key": - env["ANTHROPIC_API_KEY"] = config.claude.api_key - return env - - -# ── MCP server (tools) ────────────────────────────────────────────── - -def _build_mcp_server(executor: "ToolExecutor"): - """Wrap each TOOL_DEFINITIONS entry as an @tool-decorated async function - bound to *executor*, and bundle them into an in-process SDK MCP server. - - Claude sees these as `mcp__memclaw__`. - """ - - def _make_wrapper(tool_name: str): - async def wrapper(args: dict[str, Any]) -> dict[str, Any]: - result_text = await executor.execute(tool_name, args) - return {"content": [{"type": "text", "text": result_text}]} - wrapper.__name__ = f"tool_{tool_name}" - return wrapper - - sdk_tools = [] - for defn in TOOL_DEFINITIONS: - wrapped = tool( - name=defn["name"], - description=defn["description"], - input_schema=defn["input_schema"], - )(_make_wrapper(defn["name"])) - sdk_tools.append(wrapped) - - return create_sdk_mcp_server(name=MCP_SERVER_NAME, version="1.0.0", tools=sdk_tools) - - -# ── Image-input streaming protocol ────────────────────────────────── - -def _compose_prompt(context: str, user_message: str) -> str: - """The per-turn context block goes at the top of the user message, so - the session's system prompt stays static and cacheable.""" - return f"{context}\n\n{user_message}" if context else user_message - - -async def _image_prompt_stream( - message: str, image_b64: str, image_media_type: str, -) -> AsyncIterator[dict[str, Any]]: - """Yield a single streaming-input user message containing an image + text. - - The Claude CLI's stream-json protocol expects Anthropic-style content - blocks here, so we pass an "image" block with a base64 source followed - by the user's text. Targets claude-agent-sdk 0.2.x. - """ - yield { - "type": "user", - "message": { - "role": "user", - "content": [ - { - "type": "image", - "source": { - "type": "base64", - "media_type": image_media_type, - "data": image_b64, - }, - }, - {"type": "text", "text": message}, - ], - }, - "parent_tool_use_id": None, - } - - -# ── Backend ───────────────────────────────────────────────────────── - -@dataclass -class _Session: - """One chat's live Claude CLI connection.""" - - # Serializes turns (and /new) within one chat. - lock: asyncio.Lock = field(default_factory=asyncio.Lock) - client: ClaudeSDKClient | None = None - # (model, effort) the client was started with. After /model or /effort - # the next turn reconnects, resuming the same session with the new ones. - options_key: tuple[str, str | None] | None = None - - -class ClaudeAgentBackend(ModelSelectionMixin): - """Claude Agent SDK implementation of the AgentBackend protocol.""" - - _label = "Claude" - _settings_group = "claude" - name: ClassVar[str] = "claude" - display_name: ClassVar[str] = "Claude Agent SDK" - supports_model_selection: ClassVar[bool] = True - - def __init__(self, config: "MemclawConfig") -> None: - self.config = config - self._env = _build_env(config) - self._model = _resolve_model(config) - self._effort = _resolve_effort(config) - self._mcp_server: Any = None # built lazily, needs a ToolExecutor - self._sessions: dict[str, _Session] = {} - self._models: list[ModelInfo] = [] # filled by list_models() - # Last total_cost_usd seen per session id. The CLI reports a running - # total for the session (carried over on resume), not a per-turn cost. - self._session_costs: dict[str, float] = {} - # Subscription billing → no per-message dollar figure in logs. - self.bills_per_token = _claude_auth_mode(config) == "api_key" - - # -- Configuration --------------------------------------------------- - - @classmethod - def is_configured(cls, config: "MemclawConfig") -> bool: - return bool(_claude_auth_mode(config)) - - @classmethod - def configuration_help(cls) -> str: - return ( - "no Claude credential is configured.\n" - "Choose one:\n" - " • Claude subscription — generate a token with `claude setup-token` " - "and save it as CLAUDE_CODE_OAUTH_TOKEN.\n" - " • Anthropic API key — set ANTHROPIC_API_KEY (billed per token)." - ) - - @classmethod - def status_rows(cls, config: "MemclawConfig") -> list[tuple[str, str]]: - consolidation_model, consolidation_effort = _resolve_consolidation(config) - return [ - ("Model", _resolve_model(config)), - ("Effort", _resolve_effort(config) or "default"), - ("Consolidation", f"{consolidation_model} ({consolidation_effort or 'default'})"), - ] - - @classmethod - def wizard_setup( - cls, - console: "Console", - existing: dict[str, str], - *, - config: "MemclawConfig", - ) -> tuple[dict[str, str], list[str]]: - """Ask whether to use a subscription or API key, then prompt the - chosen credential. Returns (values_to_save, env_keys_to_drop). - """ - if existing.get("ANTHROPIC_API_KEY") and not existing.get("CLAUDE_CODE_OAUTH_TOKEN"): - default = 1 - else: - default = 0 - choice = choose( - console, - title="How do you want to authenticate with Claude?", - rows=[ - "Claude subscription (Pro / Max / Team)\n" - " No per-message cost — uses your subscription quota.\n" - " Generate a token with: [bold]claude setup-token[/bold]", - "Anthropic API key (pay-as-you-go)\n" - " Billed per token against your console credits.\n" - " Get a key at: console.anthropic.com", - ], - default=default, - separator="\n\n", - ) - - if choice == 0: - auth_mode = "subscription" - env_key = "CLAUDE_CODE_OAUTH_TOKEN" - label = "Claude subscription OAuth token (run `claude setup-token`)" - drop_key = "ANTHROPIC_API_KEY" - else: - auth_mode = "api_key" - env_key = "ANTHROPIC_API_KEY" - label = "Anthropic API key (sk-ant-...)" - drop_key = "CLAUDE_CODE_OAUTH_TOKEN" - - current = existing.get(env_key, "") - answer = masked_input(console, f"{label} (required)") - value = answer or current - if not value: - console.print(f"[red]Error:[/red] {label} is required.") - raise SystemExit(1) - - values = {env_key: value} - drop_keys = [drop_key] - - model_values, model_drops = cls._ask_model_and_effort( - console, existing, auth_mode=auth_mode, credential=value, settings=config.claude, - ) - values.update(model_values) - drop_keys.extend(model_drops) - return values, drop_keys - - @classmethod - def _ask_model_and_effort( - cls, - console: "Console", - existing: dict[str, str], - *, - auth_mode: str, - credential: str, - settings: "ClaudeSettings", - ) -> tuple[dict[str, str], list[str]]: - """Ask which model to run and, if it supports one, which effort level. - - Returns (values_to_save, env_keys_to_drop). The list is fetched from - Anthropic rather than hardcoded, so a newly released model shows up - here with no code change. - - Every failure path returns empty, which leaves whatever the user - already had in place: picking a model is a convenience, and it must - never be the reason `memclaw configure` cannot finish. - """ - # Like CURSOR_MODEL, a value exported only in the shell still counts - # as the current one, so accepting the defaults never replaces it. - current_model = (existing.get("CLAUDE_MODEL") or settings.model).strip() or _DEFAULT_MODEL - current_effort = (existing.get("CLAUDE_EFFORT") or settings.effort).strip().lower() - - def _keep_current(reason: str) -> tuple[dict[str, str], list[str]]: - console.print( - f"[yellow]Could not fetch the model list ({reason}) — " - f"keeping [bold]{current_model}[/bold].[/yellow]" - ) - return {}, [] - - try: - with console.status("[cyan]Fetching available Claude models...[/cyan]"): - models = asyncio.run(fetch_models(auth_mode, credential)) - except Exception as exc: - return _keep_current(f"{type(exc).__name__}: {exc}") - - if not models: - return _keep_current("the API returned none") - - picked = cls._pick_model(console, models, current_model) - if picked is None: - # Kept a current model the list doesn't name. Its effort support - # is unknown, so leave both settings exactly as they were. - return {}, [] - values = {"CLAUDE_MODEL": picked.id} - - if not picked.effort_levels: - # This model takes no effort value. Skip the question with no - # message, and drop any level left over from a previous choice so - # it can't be sent to a model that would reject it. - return values, ["CLAUDE_EFFORT"] - - values["CLAUDE_EFFORT"] = cls._pick_effort( - console, picked.effort_levels, current_effort, - ) - return values, [] - - @staticmethod - def _pick_model( - console: "Console", models: list[ModelInfo], current_model: str, - ) -> ModelInfo | None: - """Show the numbered model picker, preselecting *current_model*. - - A current model the list doesn't name (an alias like `opus`, or an id - this credential can't list) gets its own row at the end and stays the - default, so pressing Enter never changes the model. Picking that row - returns None. - """ - current = " [dim](current)[/dim]" - rows = [ - f"{m.display_name} [dim]{m.id}[/dim]{current if m.id == current_model else ''}" - for m in models - ] - ids = [m.id for m in models] - if current_model in ids: - default = ids.index(current_model) - else: - rows.append(f"{current_model}{current}") - default = len(models) - - index = choose( - console, title="Which Claude model?", rows=rows, default=default, - ) - return models[index] if index < len(models) else None - - @staticmethod - def _pick_effort( - console: "Console", levels: list[str], current_effort: str, - ) -> str: - """Show the effort picker for a model that supports one. - - *levels* only ever holds levels this model accepts, so the preselected - value falls back to the first one when the model has no `medium`. - """ - preferred = current_effort if current_effort in levels else _DEFAULT_EFFORT - index = choose( - console, - title="Effort level?", - rows=levels, - default=levels.index(preferred) if preferred in levels else 0, - footer=( - "[dim]How deeply Claude thinks before answering. " - "Lower is faster and cheaper.[/dim]" - ), - separator=" ", - ) - return levels[index] - - # -- Lifecycle --------------------------------------------------------- - - async def on_agent_start(self, tool_executor: "ToolExecutor") -> None: - pass - - async def on_agent_shutdown(self) -> None: - for session in self._sessions.values(): - await self._disconnect(session) - self._sessions.clear() - - # -- Sessions ---------------------------------------------------------- - - def _options( - self, *, model: str, effort: str | None, system_prompt: str, max_turns: int, **extra: Any, - ) -> ClaudeAgentOptions: - """The locked-down CLI options every call shares (chat sessions and - consolidation alike), plus *extra*.""" - return ClaudeAgentOptions( - env=self._env, - model=model, - effort=effort, - system_prompt=system_prompt, - # Don't load ~/.claude settings, plugins, CLAUDE.md or the user's - # MCP servers: faster startup and nothing outside our control. - setting_sources=[], - strict_mcp_config=True, - # No built-in tools at all; only our in-process mcp__memclaw__*. - tools=[], - # Anything not in allowed_tools is denied, never prompted for. - permission_mode="dontAsk", - # No @file expansion / slash commands from chat text. - verbatim_prompts=True, - max_turns=max_turns, - stderr=lambda line: logger.debug("claude-cli: {line}", line=line.rstrip()), - **extra, - ) - - def _session_options( - self, *, system_prompt: str, resume: str | None, max_turns: int, - ) -> ClaudeAgentOptions: - return self._options( - model=self._model, - effort=self._effort, - system_prompt=system_prompt, - max_turns=max_turns, - # Claude Code stores sessions per working directory; a fixed one - # lets a restarted process find (and resume) them. - cwd=str(self.config.memory_dir), - mcp_servers={MCP_SERVER_NAME: self._mcp_server}, - allowed_tools=_ALLOWED_TOOLS, - resume=resume, - ) - - async def _connect( - self, *, system_prompt: str, resume: str | None, max_turns: int, - ) -> ClaudeSDKClient: - """Start a CLI for one chat, resuming *resume* when given. A session - that can't be resumed (deleted, from another machine, ...) is - replaced by a fresh one rather than failing the turn.""" - if resume: - client = ClaudeSDKClient(options=self._session_options( - system_prompt=system_prompt, resume=resume, max_turns=max_turns, - )) - try: - await client.connect() - return client - except Exception as exc: - logger.warning( - "Could not resume Claude session {id} ({exc}); starting a fresh one", - id=resume, exc=exc, - ) - client = ClaudeSDKClient(options=self._session_options( - system_prompt=system_prompt, resume=None, max_turns=max_turns, - )) - await client.connect() - return client - - @staticmethod - async def _disconnect(session: _Session) -> None: - client, session.client = session.client, None - if client is None: - return - try: - await client.disconnect() - except Exception as exc: - logger.warning("Error while disconnecting Claude CLI: {exc}", exc=exc) - - async def reset_session(self, session_key: str) -> None: - session = self._sessions.get(session_key) - if session is None: - return - async with session.lock: - await self._disconnect(session) - - # -- Model selection --------------------------------------------------- - - async def list_models(self) -> list[ModelInfo]: - self._models = await fetch_models(_claude_auth_mode(self.config), _credential(self.config)) - return self._models - - async def set_model(self, model_id: str) -> str: - """Switch from the next turn on. Live chats then reconnect, resuming - their session (Claude Code resumes fine under a different model).""" - info = await self._known_model(model_id.strip()) - # Keep the effort if the new model takes it, otherwise the nearest - # level it does take (or none at all). - effort = _fit_effort(info.effort_levels, self._effort or _DEFAULT_EFFORT) - note = "" - if self._effort and effort is None: - note = f"{info.display_name} doesn't support an effort setting, so none is used." - elif self._effort and effort != self._effort: - note = ( - f"{info.display_name} doesn't support '{self._effort}' effort; " - f"using '{effort}' instead." - ) - self._apply_model(info.id, effort) - return note - - async def set_effort(self, level: str) -> None: - level = level.strip().lower() - if level not in SDK_EFFORT_LEVELS: - raise ValueError( - f"Unknown effort '{level}'. Levels: {', '.join(SDK_EFFORT_LEVELS)}." - ) - levels = await self.effort_levels() - if levels == []: - raise ValueError("The current model doesn't support an effort setting.") - if levels is not None and level not in levels: - raise ValueError( - f"The current model doesn't support '{level}'. " - f"Supported: {', '.join(levels)}." - ) - self._apply_model(self._model, level) - - # -- Runtime --------------------------------------------------------- - - async def run_one_shot( - self, - *, - system_prompt: str, - user_message: str, - ) -> str: - # Only memory consolidation uses one-shot calls. - model, effort = _resolve_consolidation(self.config) - options = self._options(model=model, effort=effort, system_prompt=system_prompt, max_turns=1) - - result_text = "" - error: str | None = None - async with ClaudeSDKClient(options=options) as client: - await client.query(user_message) - async for msg in client.receive_response(): - if isinstance(msg, AssistantMessage): - if msg.error: - error = msg.error - for block in msg.content: - if isinstance(block, TextBlock): - result_text += block.text - elif isinstance(msg, ResultMessage): - if msg.is_error: - error = error or msg.subtype - if msg.result and not result_text: - result_text = msg.result - # A failed call (network, auth, rate limit) still comes back as text, - # e.g. "API Error: Connection refused"; it must never be taken as the - # answer, or consolidation writes it over MEMORY.md. - if error: - raise RuntimeError(f"Claude one-shot failed ({error}): {result_text[:200]}") - return result_text - - async def run_turn(self, request: TurnRequest, tool_executor: "ToolExecutor") -> TurnResult: - if self._mcp_server is None: - self._mcp_server = _build_mcp_server(tool_executor) - - session = self._sessions.setdefault(request.session_key, _Session()) - async with session.lock: - options_key = (self._model, self._effort) - if session.client is not None and session.options_key != options_key: - await self._disconnect(session) - if session.client is None: - session.client = await self._connect( - system_prompt=request.system_prompt, - resume=request.resume_session_id, - max_turns=request.max_turns, - ) - session.options_key = options_key - try: - result = await self._query( - session.client, - _compose_prompt(request.context, request.user_message), - image_b64=request.image_b64, - image_media_type=request.image_media_type, - on_tool=request.on_tool, - ) - except BaseException: - # The CLI may be dead or mid-turn; reconnect (resuming) next time. - await self._disconnect(session) - raise - - result.cost_usd = self._turn_cost(result, request.resume_session_id) - return result - - def _turn_cost(self, result: TurnResult, resume_session_id: str | None) -> float | None: - """This turn's cost from the session's running total, which is what - the CLI reports. Without a baseline (the first turn after a restart - resumed the session) it is estimated from the token counts instead.""" - total = result.cost_usd - if total is not None and result.session_id: - previous = self._session_costs.get(result.session_id) - self._session_costs[result.session_id] = total - if previous is not None or resume_session_id != result.session_id: - return max(total - (previous or 0.0), 0.0) - if not self.bills_per_token: - return None - input_per_m, output_per_m = _prices_per_m(self._model) - return ( - result.input_tokens * input_per_m - + result.output_tokens * output_per_m - + result.cache_read_tokens * input_per_m * _CACHE_READ_MULTIPLIER - + result.cache_creation_tokens * input_per_m * _CACHE_WRITE_MULTIPLIER - ) / 1_000_000 - - @staticmethod - async def _query( - client: ClaudeSDKClient, - prompt: str, - *, - image_b64: str | None, - image_media_type: str, - on_tool: ProgressCallback | None = None, - ) -> TurnResult: - """Send one user message on a connected client and collect the reply.""" - if image_b64: - await client.query(_image_prompt_stream(prompt, image_b64, image_media_type)) - else: - await client.query(prompt) - - last_text = "" - result = TurnResult(text="") - steps = 0 - async for msg in client.receive_response(): - if isinstance(msg, AssistantMessage): - turn_text = "" - for block in msg.content: - if isinstance(block, TextBlock): - turn_text += block.text - elif isinstance(block, ToolUseBlock): - args_str = json.dumps(block.input, ensure_ascii=False) - if len(args_str) > 300: - args_str = args_str[:300] + "..." - tool_name = block.name - prefix = f"mcp__{MCP_SERVER_NAME}__" - if tool_name.startswith(prefix): - tool_name = tool_name[len(prefix):] - logger.info("Tool call: {name}({args})", name=tool_name, args=args_str) - steps += 1 - await report_tool_step(on_tool, steps, tool_name, block.input) - if turn_text: - last_text = turn_text - elif isinstance(msg, ResultMessage): - result.session_id = msg.session_id or None - result.num_turns = msg.num_turns - result.cost_usd = msg.total_cost_usd - if msg.usage: - result.input_tokens = msg.usage.get("input_tokens", 0) or 0 - result.output_tokens = msg.usage.get("output_tokens", 0) or 0 - result.cache_read_tokens = msg.usage.get("cache_read_input_tokens", 0) or 0 - result.cache_creation_tokens = msg.usage.get("cache_creation_input_tokens", 0) or 0 - if msg.result and not last_text: - last_text = msg.result - - result.text = last_text - return result diff --git a/memclaw/backends/claude/__init__.py b/memclaw/backends/claude/__init__.py new file mode 100644 index 0000000..abeadac --- /dev/null +++ b/memclaw/backends/claude/__init__.py @@ -0,0 +1,12 @@ +"""The Claude Agent SDK backend. + +`backend` is the `AgentBackend` itself. `cli` runs the Claude CLI (one +connected process per chat, and one-shot calls) and `replies` reads what +comes back; `settings` holds the credential, model and effort resolution, +`cost` a turn's cost, `models` the model list, and `configure` the setup +questions. +""" + +from .backend import ClaudeAgentBackend + +__all__ = ["ClaudeAgentBackend"] diff --git a/memclaw/backends/claude/backend.py b/memclaw/backends/claude/backend.py new file mode 100644 index 0000000..a1145b5 --- /dev/null +++ b/memclaw/backends/claude/backend.py @@ -0,0 +1,162 @@ +"""Claude Agent SDK backend for Memclaw. + +Wraps `claude-agent-sdk` (which itself shells out to the Claude CLI) into the +neutral `AgentBackend` protocol: the settings and credentials, /model and +/effort, and the turns, which run on each chat's own CLI process (`cli`). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, ClassVar + +from ..base import TurnRequest, TurnResult +from ..model_selection import ModelInfo, ModelSelectionMixin +from .cli import ClaudeCli +from .configure import ask_claude_settings +from .models import SDK_EFFORT_LEVELS, fetch_models +from .settings import ( + DEFAULT_EFFORT, + claude_auth_mode, + credential, + fit_effort, + resolve_consolidation, + resolve_effort, + resolve_model, +) + +if TYPE_CHECKING: + from rich.console import Console + + from ...config import MemclawConfig + from ...tools import ToolExecutor + + +class ClaudeAgentBackend(ModelSelectionMixin): + """Claude Agent SDK implementation of the AgentBackend protocol.""" + + _label = "Claude" + _settings_group = "claude" + name: ClassVar[str] = "claude" + display_name: ClassVar[str] = "Claude Agent SDK" + supports_model_selection: ClassVar[bool] = True + + def __init__(self, config: "MemclawConfig") -> None: + self.config = config + self._model = resolve_model(config) + self._effort = resolve_effort(config) + self._models: list[ModelInfo] = [] # filled by list_models() + # Subscription billing → no per-message dollar figure in logs. + self.bills_per_token = claude_auth_mode(config) == "api_key" + self._cli = ClaudeCli(config, bills_per_token=self.bills_per_token) + + # -- Configuration --------------------------------------------------- + + @classmethod + def is_configured(cls, config: "MemclawConfig") -> bool: + return bool(claude_auth_mode(config)) + + @classmethod + def configuration_help(cls) -> str: + return ( + "no Claude credential is configured.\n" + "Choose one:\n" + " • Claude subscription — generate a token with `claude setup-token` " + "and save it as CLAUDE_CODE_OAUTH_TOKEN.\n" + " • Anthropic API key — set ANTHROPIC_API_KEY (billed per token)." + ) + + @classmethod + def status_rows(cls, config: "MemclawConfig") -> list[tuple[str, str]]: + consolidation_model, consolidation_effort = resolve_consolidation(config) + return [ + ("Model", resolve_model(config)), + ("Effort", resolve_effort(config) or "default"), + ("Consolidation", f"{consolidation_model} ({consolidation_effort or 'default'})"), + ] + + @classmethod + def wizard_setup( + cls, + console: "Console", + existing: dict[str, str], + *, + config: "MemclawConfig", + ) -> tuple[dict[str, str], list[str]]: + """Ask whether to use a subscription or API key, then prompt the + chosen credential. Returns (values_to_save, env_keys_to_drop). + """ + return ask_claude_settings(console, existing, config) + + # -- Lifecycle --------------------------------------------------------- + + async def on_agent_start(self, tool_executor: "ToolExecutor") -> None: + pass + + async def on_agent_shutdown(self) -> None: + await self._cli.close_all() + + async def reset_session(self, session_key: str) -> None: + await self._cli.reset(session_key) + + # -- Model selection --------------------------------------------------- + + async def list_models(self) -> list[ModelInfo]: + self._models = await fetch_models(claude_auth_mode(self.config), credential(self.config)) + return self._models + + async def set_model(self, model_id: str) -> str: + """Switch from the next turn on. Live chats then reconnect, resuming + their session (Claude Code resumes fine under a different model).""" + info = await self._known_model(model_id.strip()) + # Keep the effort if the new model takes it, otherwise the nearest + # level it does take (or none at all). + effort = fit_effort(info.effort_levels, self._effort or DEFAULT_EFFORT) + note = "" + if self._effort and effort is None: + note = f"{info.display_name} doesn't support an effort setting, so none is used." + elif self._effort and effort != self._effort: + note = ( + f"{info.display_name} doesn't support '{self._effort}' effort; " + f"using '{effort}' instead." + ) + self._apply_model(info.id, effort) + return note + + async def set_effort(self, level: str) -> None: + level = level.strip().lower() + if level not in SDK_EFFORT_LEVELS: + raise ValueError( + f"Unknown effort '{level}'. Levels: {', '.join(SDK_EFFORT_LEVELS)}." + ) + levels = await self.effort_levels() + if levels == []: + raise ValueError("The current model doesn't support an effort setting.") + if levels is not None and level not in levels: + raise ValueError( + f"The current model doesn't support '{level}'. " + f"Supported: {', '.join(levels)}." + ) + self._apply_model(self._model, level) + + # -- Runtime --------------------------------------------------------- + + async def run_one_shot( + self, + *, + system_prompt: str, + user_message: str, + ) -> str: + # Only memory consolidation uses one-shot calls. + model, effort = resolve_consolidation(self.config) + return await self._cli.ask_once( + model=model, effort=effort, system_prompt=system_prompt, user_message=user_message, + ) + + async def run_turn(self, request: TurnRequest, tool_executor: "ToolExecutor") -> TurnResult: + result = await self._cli.run_turn( + request, tool_executor, lambda: (self._model, self._effort), + ) + result.cost_usd = self._cli.costs.turn_cost( + result, request.resume_session_id, model=self._model, + ) + return result diff --git a/memclaw/backends/claude/cli.py b/memclaw/backends/claude/cli.py new file mode 100644 index 0000000..6367676 --- /dev/null +++ b/memclaw/backends/claude/cli.py @@ -0,0 +1,225 @@ +"""Running the Claude CLI: the locked-down options every call shares, one +connected `ClaudeSDKClient` (one CLI process) per chat, reused across +turns, and one-shot calls. + +Keeping the client connected means the conversation lives in the CLI's own +session instead of being re-sent with every message. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Callable + +from claude_agent_sdk import ( + ClaudeAgentOptions, + ClaudeSDKClient, + create_sdk_mcp_server, + tool, +) +from loguru import logger + +from ...tools import TOOL_DEFINITIONS +from ..base import TurnRequest, TurnResult +from ..mcp_tools import MCP_SERVER_NAME +from .cost import SessionCosts +from .models import sdk_effort +from .replies import compose_prompt, read_one_shot, read_turn +from .settings import build_env + +if TYPE_CHECKING: + from ...config import MemclawConfig + from ...tools import ToolExecutor + +ALLOWED_TOOLS = [ + f"mcp__{MCP_SERVER_NAME}__{t['name']}" for t in TOOL_DEFINITIONS +] + +# The (model, effort) to run with, read when a turn starts. +ModelChoice = Callable[[], "tuple[str, str | None]"] + + +def _build_mcp_server(executor: "ToolExecutor"): + """Wrap each TOOL_DEFINITIONS entry as an @tool-decorated async function + bound to *executor*, and bundle them into an in-process SDK MCP server. + + Claude sees these as `mcp__memclaw__`. + """ + + def _make_wrapper(tool_name: str): + async def wrapper(args: dict[str, Any]) -> dict[str, Any]: + result_text = await executor.execute(tool_name, args) + return {"content": [{"type": "text", "text": result_text}]} + wrapper.__name__ = f"tool_{tool_name}" + return wrapper + + sdk_tools = [] + for defn in TOOL_DEFINITIONS: + wrapped = tool( + name=defn["name"], + description=defn["description"], + input_schema=defn["input_schema"], + )(_make_wrapper(defn["name"])) + sdk_tools.append(wrapped) + + return create_sdk_mcp_server(name=MCP_SERVER_NAME, version="1.0.0", tools=sdk_tools) + + +@dataclass +class _Session: + """One chat's live Claude CLI connection.""" + + # Serializes turns (and /new) within one chat. + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + client: ClaudeSDKClient | None = None + # (model, effort) the client was started with. After /model or /effort + # the next turn reconnects, resuming the same session with the new ones. + options_key: tuple[str, str | None] | None = None + + +class ClaudeCli: + """The Claude CLI processes of one backend: a connection per chat, and + the cost of each chat's turns.""" + + def __init__(self, config: "MemclawConfig", *, bills_per_token: bool) -> None: + self._env = build_env(config) + self._cwd = str(config.memory_dir) + self._mcp_server: Any = None # built lazily, needs a ToolExecutor + self._sessions: dict[str, _Session] = {} + self.costs = SessionCosts(bills_per_token=bills_per_token) + + def options( + self, *, model: str, effort: str | None, system_prompt: str, max_turns: int, **extra: Any, + ) -> ClaudeAgentOptions: + """The locked-down CLI options every call shares (chat sessions and + consolidation alike), plus *extra*.""" + return ClaudeAgentOptions( + env=self._env, + model=model, + effort=sdk_effort(effort), + system_prompt=system_prompt, + # Don't load ~/.claude settings, plugins, CLAUDE.md or the user's + # MCP servers: faster startup and nothing outside our control. + setting_sources=[], + strict_mcp_config=True, + # No built-in tools at all; only our in-process mcp__memclaw__*. + tools=[], + # Anything not in allowed_tools is denied, never prompted for. + permission_mode="dontAsk", + # No @file expansion / slash commands from chat text. + verbatim_prompts=True, + max_turns=max_turns, + stderr=lambda line: logger.debug("claude-cli: {line}", line=line.rstrip()), + **extra, + ) + + # -- One-shot calls ---------------------------------------------------- + + async def ask_once( + self, *, model: str, effort: str | None, system_prompt: str, user_message: str, + ) -> str: + """Answer *user_message* in a throwaway CLI with no tools.""" + options = self.options(model=model, effort=effort, system_prompt=system_prompt, max_turns=1) + async with ClaudeSDKClient(options=options) as client: + reply = await read_one_shot(client, user_message) + return reply.answer() + + # -- Chat sessions ----------------------------------------------------- + + def _session_options( + self, choice: ModelChoice, *, system_prompt: str, resume: str | None, max_turns: int, + ) -> ClaudeAgentOptions: + model, effort = choice() + return self.options( + model=model, + effort=effort, + system_prompt=system_prompt, + max_turns=max_turns, + # Claude Code stores sessions per working directory; a fixed one + # lets a restarted process find (and resume) them. + cwd=self._cwd, + mcp_servers={MCP_SERVER_NAME: self._mcp_server}, + allowed_tools=ALLOWED_TOOLS, + resume=resume, + ) + + async def _connect( + self, choice: ModelChoice, *, system_prompt: str, resume: str | None, max_turns: int, + ) -> ClaudeSDKClient: + """Start a CLI for one chat, resuming *resume* when given. A session + that can't be resumed (deleted, from another machine, ...) is + replaced by a fresh one rather than failing the turn.""" + if resume: + client = ClaudeSDKClient(options=self._session_options( + choice, system_prompt=system_prompt, resume=resume, max_turns=max_turns, + )) + try: + await client.connect() + return client + except Exception as exc: + logger.warning( + "Could not resume Claude session {id} ({exc}); starting a fresh one", + id=resume, exc=exc, + ) + client = ClaudeSDKClient(options=self._session_options( + choice, system_prompt=system_prompt, resume=None, max_turns=max_turns, + )) + await client.connect() + return client + + @staticmethod + async def _disconnect(session: _Session) -> None: + client, session.client = session.client, None + if client is None: + return + try: + await client.disconnect() + except Exception as exc: + logger.warning("Error while disconnecting Claude CLI: {exc}", exc=exc) + + async def reset(self, session_key: str) -> None: + session = self._sessions.get(session_key) + if session is None: + return + async with session.lock: + await self._disconnect(session) + + async def close_all(self) -> None: + for session in self._sessions.values(): + await self._disconnect(session) + self._sessions.clear() + + async def run_turn( + self, request: TurnRequest, tool_executor: "ToolExecutor", choice: ModelChoice, + ) -> TurnResult: + """Run *request* on its chat's CLI, connecting (or reconnecting with + the model and effort *choice* gives now) first if needed.""" + if self._mcp_server is None: + self._mcp_server = _build_mcp_server(tool_executor) + + session = self._sessions.setdefault(request.session_key, _Session()) + async with session.lock: + options_key = choice() + if session.client is not None and session.options_key != options_key: + await self._disconnect(session) + if session.client is None: + session.client = await self._connect( + choice, + system_prompt=request.system_prompt, + resume=request.resume_session_id, + max_turns=request.max_turns, + ) + session.options_key = options_key + try: + return await read_turn( + session.client, + compose_prompt(request.context, request.user_message), + image_b64=request.image_b64, + image_media_type=request.image_media_type, + on_tool=request.on_tool, + ) + except BaseException: + # The CLI may be dead or mid-turn; reconnect (resuming) next time. + await self._disconnect(session) + raise diff --git a/memclaw/backends/claude/configure.py b/memclaw/backends/claude/configure.py new file mode 100644 index 0000000..aa0b340 --- /dev/null +++ b/memclaw/backends/claude/configure.py @@ -0,0 +1,205 @@ +"""The Claude backend's questions in `memclaw configure`: how to +authenticate, the credential, then the model and effort level. One function +per question, called in that order by `ask_claude_settings`.""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from ...terminal_input import choose, masked_input +from ..model_selection import ModelInfo +from .models import fetch_models +from .settings import DEFAULT_EFFORT, DEFAULT_MODEL + +if TYPE_CHECKING: + from rich.console import Console + + from ...config import ClaudeSettings, MemclawConfig + + +@dataclass(frozen=True) +class _Credential: + """One way to authenticate: the env var it is saved in, how it is + asked for, and the other credential's env var, dropped when it's saved.""" + + auth_mode: str + env_key: str + label: str + drop_key: str + + +_SUBSCRIPTION = _Credential( + auth_mode="subscription", + env_key="CLAUDE_CODE_OAUTH_TOKEN", + label="Claude subscription OAuth token (run `claude setup-token`)", + drop_key="ANTHROPIC_API_KEY", +) +_API_KEY = _Credential( + auth_mode="api_key", + env_key="ANTHROPIC_API_KEY", + label="Anthropic API key (sk-ant-...)", + drop_key="CLAUDE_CODE_OAUTH_TOKEN", +) + + +def ask_claude_settings( + console: "Console", existing: dict[str, str], config: "MemclawConfig", +) -> tuple[dict[str, str], list[str]]: + """Ask whether to use a subscription or API key, then prompt the + chosen credential. Returns (values_to_save, env_keys_to_drop). + """ + credential = _ask_auth_mode(console, existing) + value = _ask_credential(console, existing, credential) + + values = {credential.env_key: value} + drop_keys = [credential.drop_key] + + model_values, model_drops = ask_model_and_effort( + console, existing, auth_mode=credential.auth_mode, credential=value, + settings=config.claude, + ) + values.update(model_values) + drop_keys.extend(model_drops) + return values, drop_keys + + +def _ask_auth_mode(console: "Console", existing: dict[str, str]) -> _Credential: + if existing.get("ANTHROPIC_API_KEY") and not existing.get("CLAUDE_CODE_OAUTH_TOKEN"): + default = 1 + else: + default = 0 + choice = choose( + console, + title="How do you want to authenticate with Claude?", + rows=[ + "Claude subscription (Pro / Max / Team)\n" + " No per-message cost — uses your subscription quota.\n" + " Generate a token with: [bold]claude setup-token[/bold]", + "Anthropic API key (pay-as-you-go)\n" + " Billed per token against your console credits.\n" + " Get a key at: console.anthropic.com", + ], + default=default, + separator="\n\n", + ) + return _SUBSCRIPTION if choice == 0 else _API_KEY + + +def _ask_credential(console: "Console", existing: dict[str, str], credential: _Credential) -> str: + """The credential typed, or the saved one on Enter; exits without one.""" + current = existing.get(credential.env_key, "") + answer = masked_input(console, f"{credential.label} (required)") + value = answer or current + if not value: + console.print(f"[red]Error:[/red] {credential.label} is required.") + raise SystemExit(1) + return value + + +def ask_model_and_effort( + console: "Console", + existing: dict[str, str], + *, + auth_mode: str, + credential: str, + settings: "ClaudeSettings", +) -> tuple[dict[str, str], list[str]]: + """Ask which model to run and, if it supports one, which effort level. + + Returns (values_to_save, env_keys_to_drop). The list is fetched from + Anthropic rather than hardcoded, so a newly released model shows up + here with no code change. + + Every failure path returns empty, which leaves whatever the user + already had in place: picking a model is a convenience, and it must + never be the reason `memclaw configure` cannot finish. + """ + # Like CURSOR_MODEL, a value exported only in the shell still counts + # as the current one, so accepting the defaults never replaces it. + current_model = (existing.get("CLAUDE_MODEL") or settings.model).strip() or DEFAULT_MODEL + current_effort = (existing.get("CLAUDE_EFFORT") or settings.effort).strip().lower() + + def _keep_current(reason: str) -> tuple[dict[str, str], list[str]]: + console.print( + f"[yellow]Could not fetch the model list ({reason}) — " + f"keeping [bold]{current_model}[/bold].[/yellow]" + ) + return {}, [] + + try: + with console.status("[cyan]Fetching available Claude models...[/cyan]"): + models = asyncio.run(fetch_models(auth_mode, credential)) + except Exception as exc: + return _keep_current(f"{type(exc).__name__}: {exc}") + + if not models: + return _keep_current("the API returned none") + + picked = _pick_model(console, models, current_model) + if picked is None: + # Kept a current model the list doesn't name. Its effort support + # is unknown, so leave both settings exactly as they were. + return {}, [] + values = {"CLAUDE_MODEL": picked.id} + + if not picked.effort_levels: + # This model takes no effort value. Skip the question with no + # message, and drop any level left over from a previous choice so + # it can't be sent to a model that would reject it. + return values, ["CLAUDE_EFFORT"] + + values["CLAUDE_EFFORT"] = _pick_effort( + console, picked.effort_levels, current_effort, + ) + return values, [] + +def _pick_model( + console: "Console", models: list[ModelInfo], current_model: str, +) -> ModelInfo | None: + """Show the numbered model picker, preselecting *current_model*. + + A current model the list doesn't name (an alias like `opus`, or an id + this credential can't list) gets its own row at the end and stays the + default, so pressing Enter never changes the model. Picking that row + returns None. + """ + current = " [dim](current)[/dim]" + rows = [ + f"{m.display_name} [dim]{m.id}[/dim]{current if m.id == current_model else ''}" + for m in models + ] + ids = [m.id for m in models] + if current_model in ids: + default = ids.index(current_model) + else: + rows.append(f"{current_model}{current}") + default = len(models) + + index = choose( + console, title="Which Claude model?", rows=rows, default=default, + ) + return models[index] if index < len(models) else None + +def _pick_effort( + console: "Console", levels: list[str], current_effort: str, +) -> str: + """Show the effort picker for a model that supports one. + + *levels* only ever holds levels this model accepts, so the preselected + value falls back to the first one when the model has no `medium`. + """ + preferred = current_effort if current_effort in levels else DEFAULT_EFFORT + index = choose( + console, + title="Effort level?", + rows=levels, + default=levels.index(preferred) if preferred in levels else 0, + footer=( + "[dim]How deeply Claude thinks before answering. " + "Lower is faster and cheaper.[/dim]" + ), + separator=" ", + ) + return levels[index] diff --git a/memclaw/backends/claude/cost.py b/memclaw/backends/claude/cost.py new file mode 100644 index 0000000..160fb3f --- /dev/null +++ b/memclaw/backends/claude/cost.py @@ -0,0 +1,73 @@ +"""What a Claude turn costs: the CLI's running session total turned into a +per-turn figure, or an estimate from the token counts.""" + +from __future__ import annotations + +from ..base import TurnResult +from .settings import DEFAULT_MODEL + +# Anthropic list prices, (input, output) USD per 1M tokens. Only used as a +# fallback when the SDK doesn't return total_cost_usd for an API-key turn. +# Ids are matched by prefix, so dated snapshots (claude-haiku-4-5-20251001) +# resolve too. A model missing here (an alias, or one released later) is +# estimated at the default model's price, so the figure is approximate. +_PRICES_PER_M: dict[str, tuple[float, float]] = { + "claude-fable-5-1": (10.0, 50.0), + "claude-fable-5": (10.0, 50.0), + "claude-opus-5-5": (4.0, 20.0), + "claude-opus-5": (5.0, 25.0), + "claude-opus-4-8": (5.0, 25.0), + "claude-opus-4-7": (5.0, 25.0), + "claude-opus-4-6": (5.0, 25.0), + "claude-sonnet-5-5": (2.0, 10.0), + "claude-sonnet-5": (2.0, 10.0), + "claude-sonnet-4-6": (3.0, 15.0), + "claude-haiku-4-5": (1.0, 5.0), +} + +# Cache reads are billed at a tenth of the input price, cache writes at +# 1.25 times it. +_CACHE_READ_MULTIPLIER = 0.1 +_CACHE_WRITE_MULTIPLIER = 1.25 + + +def _prices_per_m(model: str) -> tuple[float, float]: + """(input, output) USD per 1M tokens for *model*; see _PRICES_PER_M.""" + # Longest prefix first, so claude-opus-5-5 doesn't match claude-opus-5. + for prefix in sorted(_PRICES_PER_M, key=len, reverse=True): + if model == prefix or model.startswith(f"{prefix}-"): + return _PRICES_PER_M[prefix] + return _PRICES_PER_M[DEFAULT_MODEL] + + +class SessionCosts: + """Turns the running cost total the CLI reports per session into each + turn's cost.""" + + def __init__(self, *, bills_per_token: bool) -> None: + self._bills_per_token = bills_per_token + # Last total_cost_usd seen per session id. The CLI reports a running + # total for the session (carried over on resume), not a per-turn cost. + self._totals: dict[str, float] = {} + + def turn_cost( + self, result: TurnResult, resume_session_id: str | None, *, model: str, + ) -> float | None: + """This turn's cost from the session's running total, which is what + the CLI reports. Without a baseline (the first turn after a restart + resumed the session) it is estimated from the token counts instead.""" + total = result.cost_usd + if total is not None and result.session_id: + previous = self._totals.get(result.session_id) + self._totals[result.session_id] = total + if previous is not None or resume_session_id != result.session_id: + return max(total - (previous or 0.0), 0.0) + if not self._bills_per_token: + return None + input_per_m, output_per_m = _prices_per_m(model) + return ( + result.input_tokens * input_per_m + + result.output_tokens * output_per_m + + result.cache_read_tokens * input_per_m * _CACHE_READ_MULTIPLIER + + result.cache_creation_tokens * input_per_m * _CACHE_WRITE_MULTIPLIER + ) / 1_000_000 diff --git a/memclaw/backends/claude_models.py b/memclaw/backends/claude/models.py similarity index 88% rename from memclaw/backends/claude_models.py rename to memclaw/backends/claude/models.py index 7413103..a870f13 100644 --- a/memclaw/backends/claude_models.py +++ b/memclaw/backends/claude/models.py @@ -13,11 +13,11 @@ from __future__ import annotations from datetime import datetime, timezone -from typing import Any +from typing import Any, Literal import httpx -from .model_selection import ModelInfo +from ..model_selection import ModelInfo MODELS_URL = "https://api.anthropic.com/v1/models" API_VERSION = "2023-06-01" @@ -32,7 +32,15 @@ # Optional[Literal["low", "medium", "high", "xhigh", "max"]]. The API may # report a level a newer SDK understands and ours does not, so anything # outside this set is dropped. Widen the tuple when the SDK gains a level. -SDK_EFFORT_LEVELS = ("low", "medium", "high", "xhigh", "max") +EffortLevel = Literal["low", "medium", "high", "xhigh", "max"] +SDK_EFFORT_LEVELS: tuple[EffortLevel, ...] = ("low", "medium", "high", "xhigh", "max") + + +def sdk_effort(level: str | None) -> EffortLevel | None: + """*level* as the SDK's effort type. Every level Memclaw keeps is one of + SDK_EFFORT_LEVELS (checked where it is read or set), so this only + narrows the type; anything else would be None, i.e. no effort flag.""" + return next((known for known in SDK_EFFORT_LEVELS if known == level), None) # ── Request building ──────────────────────────────────────────────── diff --git a/memclaw/backends/claude/replies.py b/memclaw/backends/claude/replies.py new file mode 100644 index 0000000..7c7c426 --- /dev/null +++ b/memclaw/backends/claude/replies.py @@ -0,0 +1,170 @@ +"""Talking to a connected Claude CLI: what a user message is sent as (text, +or the stream-json image protocol), and how the messages that come back +become a turn's result or a one-shot answer.""" + +from __future__ import annotations + +import json +from typing import Any, AsyncIterator + +from claude_agent_sdk import ( + AssistantMessage, + ClaudeSDKClient, + ResultMessage, + TextBlock, + ToolUseBlock, +) +from loguru import logger + +from ..base import ProgressCallback, TurnResult, report_tool_step +from ..mcp_tools import MCP_SERVER_NAME + +# Claude sees Memclaw's tools as mcp__memclaw__. +_TOOL_PREFIX = f"mcp__{MCP_SERVER_NAME}__" + + +def compose_prompt(context: str, user_message: str) -> str: + """The per-turn context block goes at the top of the user message, so + the session's system prompt stays static and cacheable.""" + return f"{context}\n\n{user_message}" if context else user_message + + +async def _image_prompt_stream( + message: str, image_b64: str, image_media_type: str, +) -> AsyncIterator[dict[str, Any]]: + """Yield a single streaming-input user message containing an image + text. + + The Claude CLI's stream-json protocol expects Anthropic-style content + blocks here, so we pass an "image" block with a base64 source followed + by the user's text. Targets claude-agent-sdk 0.2.x. + """ + yield { + "type": "user", + "message": { + "role": "user", + "content": [ + { + "type": "image", + "source": { + "type": "base64", + "media_type": image_media_type, + "data": image_b64, + }, + }, + {"type": "text", "text": message}, + ], + }, + "parent_tool_use_id": None, + } + + +class _TurnReply: + """One turn's reply, read message by message: the last assistant text, + the tool calls (logged and reported as steps), and the final result's + session, turn count, cost and token usage.""" + + def __init__(self, on_tool: ProgressCallback | None) -> None: + self.result = TurnResult(text="") + self.last_text = "" + self._steps = 0 + self._on_tool = on_tool + + async def on_assistant(self, msg: AssistantMessage) -> None: + turn_text = "" + for block in msg.content: + if isinstance(block, TextBlock): + turn_text += block.text + elif isinstance(block, ToolUseBlock): + await self._on_tool_use(block) + if turn_text: + self.last_text = turn_text + + async def _on_tool_use(self, block: ToolUseBlock) -> None: + args_str = json.dumps(block.input, ensure_ascii=False) + if len(args_str) > 300: + args_str = args_str[:300] + "..." + tool_name = block.name.removeprefix(_TOOL_PREFIX) + logger.info("Tool call: {name}({args})", name=tool_name, args=args_str) + self._steps += 1 + await report_tool_step(self._on_tool, self._steps, tool_name, block.input) + + def on_result(self, msg: ResultMessage) -> None: + result = self.result + result.session_id = msg.session_id or None + result.num_turns = msg.num_turns + result.cost_usd = msg.total_cost_usd + if msg.usage: + usage = msg.usage + result.input_tokens = usage.get("input_tokens", 0) or 0 + result.output_tokens = usage.get("output_tokens", 0) or 0 + result.cache_read_tokens = usage.get("cache_read_input_tokens", 0) or 0 + result.cache_creation_tokens = usage.get("cache_creation_input_tokens", 0) or 0 + if msg.result and not self.last_text: + self.last_text = msg.result + + +async def read_turn( + client: ClaudeSDKClient, + prompt: str, + *, + image_b64: str | None, + image_media_type: str, + on_tool: ProgressCallback | None = None, +) -> TurnResult: + """Send one user message on a connected client and collect the reply.""" + if image_b64: + await client.query(_image_prompt_stream(prompt, image_b64, image_media_type)) + else: + await client.query(prompt) + + reply = _TurnReply(on_tool) + async for msg in client.receive_response(): + if isinstance(msg, AssistantMessage): + await reply.on_assistant(msg) + elif isinstance(msg, ResultMessage): + reply.on_result(msg) + + reply.result.text = reply.last_text + return reply.result + + +class OneShotReply: + """A one-shot call's answer: all its text, and the error, if any, the + CLI reported along the way.""" + + def __init__(self) -> None: + self.text = "" + self.error: str | None = None + + def on_assistant(self, msg: AssistantMessage) -> None: + if msg.error: + self.error = msg.error + for block in msg.content: + if isinstance(block, TextBlock): + self.text += block.text + + def on_result(self, msg: ResultMessage) -> None: + if msg.is_error: + self.error = self.error or msg.subtype + if msg.result and not self.text: + self.text = msg.result + + def answer(self) -> str: + # A failed call (network, auth, rate limit) still comes back as text, + # e.g. "API Error: Connection refused"; it must never be taken as the + # answer, or consolidation writes it over MEMORY.md. + if self.error: + raise RuntimeError(f"Claude one-shot failed ({self.error}): {self.text[:200]}") + return self.text + + +async def read_one_shot(client: ClaudeSDKClient, user_message: str) -> OneShotReply: + """Send *user_message* on *client* and read the whole reply.""" + await client.query(user_message) + reply = OneShotReply() + async for msg in client.receive_response(): + if isinstance(msg, AssistantMessage): + reply.on_assistant(msg) + elif isinstance(msg, ResultMessage): + reply.on_result(msg) + return reply diff --git a/memclaw/backends/claude/settings.py b/memclaw/backends/claude/settings.py new file mode 100644 index 0000000..7aff052 --- /dev/null +++ b/memclaw/backends/claude/settings.py @@ -0,0 +1,123 @@ +"""The Claude backend's settings: which credential is configured, the +environment the CLI runs with, and the model and effort to use.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ...config import process_environment +from .models import SDK_EFFORT_LEVELS + +if TYPE_CHECKING: + from ...config import MemclawConfig + + +DEFAULT_MODEL = "claude-sonnet-5-5" + +# Memory consolidation: rare and one-shot, so a stronger model is worth it. +DEFAULT_CONSOLIDATION_MODEL = "claude-opus-5-5" +DEFAULT_CONSOLIDATION_EFFORT = "medium" + +# Used when CLAUDE_EFFORT is unset and the default model runs, and +# preselected in the wizard for any model that supports effort at all. +DEFAULT_EFFORT = "medium" + + +def claude_auth_mode(config: "MemclawConfig") -> str: + """Which Claude credential is configured. + + Returns "subscription" when CLAUDE_CODE_OAUTH_TOKEN is set (billed + against the Claude plan, no per-message cost), "api_key" when only + ANTHROPIC_API_KEY is set, or "" when neither is set. + """ + if config.claude.oauth_token: + return "subscription" + if config.claude.api_key: + return "api_key" + return "" + + +def resolve_model(config: "MemclawConfig") -> str: + """The configured model, or the built-in default when unset.""" + return (config.claude.model or "").strip() or DEFAULT_MODEL + + +def resolve_effort(config: "MemclawConfig") -> str | None: + """The configured effort level, or None to let the model decide. + + Anything the SDK does not recognise is treated as unset: ~/.memclaw/.env + is a plain text file, and a typo there should not reach the CLI as an + argument it will reject. An unset level means `DEFAULT_EFFORT` on the + default model and None (the SDK omits the flag) on any other model. + + Whether the chosen *model* accepts an effort level is a separate question, + settled in the wizard and by /model — they store no level for a model + that reports none. + """ + effort = (config.claude.effort or "").strip().lower() + if effort in SDK_EFFORT_LEVELS: + return effort + return DEFAULT_EFFORT if resolve_model(config) == DEFAULT_MODEL else None + + +def resolve_consolidation(config: "MemclawConfig") -> tuple[str, str | None]: + """(model, effort) for consolidation: CLAUDE_CONSOLIDATION_MODEL / + CLAUDE_CONSOLIDATION_EFFORT, else Opus 5.5 at medium. As in + `resolve_effort`, an unknown level counts as unset, and an unset level + means the default effort only on the default model (another model may + not take an effort at all).""" + model = (config.claude.consolidation_model or "").strip() or DEFAULT_CONSOLIDATION_MODEL + effort = (config.claude.consolidation_effort or "").strip().lower() + if effort in SDK_EFFORT_LEVELS: + return model, effort + if model == DEFAULT_CONSOLIDATION_MODEL: + return model, DEFAULT_CONSOLIDATION_EFFORT + return model, None + + +def fit_effort(levels: list[str], preferred: str) -> str | None: + """The level to use on a model supporting *levels* when *preferred* is + wanted: *preferred* itself, else the nearest supported level below it + (else the lowest). None when the model takes no effort at all.""" + if not levels: + return None + if preferred in levels: + return preferred + order = list(SDK_EFFORT_LEVELS) + rank = order.index(preferred) if preferred in order else len(order) + below = [lv for lv in levels if lv in order and order.index(lv) < rank] + return below[-1] if below else levels[0] + + +def credential(config: "MemclawConfig") -> str: + """The credential matching `claude_auth_mode`.""" + if claude_auth_mode(config) == "subscription": + return config.claude.oauth_token + return config.claude.api_key + + +def build_env(config: "MemclawConfig") -> dict[str, str]: + """Build the env dict for the Claude CLI subprocess. + + Scrubs every credential env var first so the subprocess never inherits + a stale token from the parent shell, then injects exactly one credential + based on the configured auth mode: + + - subscription → CLAUDE_CODE_OAUTH_TOKEN, billed against the Claude plan. + - api_key → ANTHROPIC_API_KEY, billed against Console credits. + """ + env = { + k: v for k, v in process_environment().items() + if k not in ( + "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + ) + } + mode = claude_auth_mode(config) + if mode == "subscription": + env["CLAUDE_CODE_OAUTH_TOKEN"] = config.claude.oauth_token + elif mode == "api_key": + env["ANTHROPIC_API_KEY"] = config.claude.api_key + return env diff --git a/memclaw/backends/cursor.py b/memclaw/backends/cursor.py deleted file mode 100644 index 48b8c6c..0000000 --- a/memclaw/backends/cursor.py +++ /dev/null @@ -1,590 +0,0 @@ -"""Cursor Python SDK agent backend. - -One `cursor-sdk-bridge` process (a Node subprocess) serves the whole Memclaw -process. Each chat keeps one open local agent on it, reused across turns: the -agent stores its own conversation on disk, so follow-up messages only carry -the per-turn context and the new message, and a restarted process resumes the -agent by id. -""" - -from __future__ import annotations - -import asyncio -from dataclasses import dataclass, field -from pathlib import Path -from typing import TYPE_CHECKING, Any, ClassVar, Literal - -import httpx -from loguru import logger -from rich.prompt import Prompt - -from ..config import set_environment -from ..terminal_input import masked_input -from .base import ProgressCallback, TurnRequest, TurnResult -from .cursor_hooks import cursor_hooks_status, ensure_cursor_hooks -from .cursor_sdk_adapter import RunUsageTracker, collect_run_result, extract_run_text -from .mcp_bridge import HttpMcpServer, mcp_servers_for -from .model_selection import ModelInfo, ModelSelectionMixin - -if TYPE_CHECKING: - from rich.console import Console - - from ..config import MemclawConfig - from ..tools import ToolExecutor - -_DEFAULT_MODEL = "composer-2.5" - -# Composer 2.5 default pricing (per 1M tokens) — fallback when the SDK -# doesn't return total cost on a turn-ended usage payload. -_INPUT_COST_PER_M = 0.5 -_OUTPUT_COST_PER_M = 2.5 - -# Scrub Claude credentials when switching to Cursor so they can't shadow selection. -_DROP_KEYS = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"] - -# A model parameter whose id contains one of these is treated as its effort -# setting (/effort). Cursor reports parameters per model, so there is no -# fixed list of levels. -_EFFORT_PARAM_HINTS = ("effort", "reasoning") - - -def _cursor_api_key(config: "MemclawConfig") -> str: - return config.cursor.api_key.strip() - - -def _cursor_model(config: "MemclawConfig") -> str: - model = config.cursor.model.strip() - return model or _DEFAULT_MODEL - - -def _cursor_effort(config: "MemclawConfig") -> str | None: - effort = config.cursor.effort.strip() - return effort or None - - -def _apply_cost_fallback(result: TurnResult, *, bills_per_token: bool) -> None: - if result.cost_usd is not None or not bills_per_token: - return - if not (result.input_tokens or result.output_tokens or result.cache_read_tokens): - return - cache_read_cost = result.cache_read_tokens * _INPUT_COST_PER_M * 0.1 / 1_000_000 - result.cost_usd = ( - result.input_tokens * _INPUT_COST_PER_M / 1_000_000 - + result.output_tokens * _OUTPUT_COST_PER_M / 1_000_000 - + cache_read_cost - ) - - -def _build_combined_prompt(*, system_prompt: str, user_message: str) -> str: - return "\n".join( - [ - system_prompt.strip(), - "", - "---", - "", - user_message.strip(), - ] - ) - - -def _build_user_message( - *, - system_prompt: str, - user_message: str, - context: str = "", - image_b64: str | None = None, - image_media_type: str = "image/jpeg", -) -> str | Any: - """The message to send. Cursor agents have no system prompt field, so a - new agent gets it at the top of its first message; follow-ups pass "".""" - from cursor_sdk import SDKImage, UserMessage # optional dependency (cursor-sdk) - - body = "\n\n".join(p for p in (context, user_message) if p) - prompt = ( - _build_combined_prompt(system_prompt=system_prompt, user_message=body) - if system_prompt - else body - ) - if not image_b64: - return prompt - return UserMessage( - text=prompt, - images=[SDKImage.from_data(image_b64, image_media_type)], - ) - - -def _local_agent_options(*, cwd: str) -> Any: - from cursor_sdk import LocalAgentOptions # optional dependency (cursor-sdk) - - return LocalAgentOptions( - cwd=cwd, - # Load ~/.memclaw/.cursor/hooks.json (project hooks for this cwd). - setting_sources=["project"], - ) - - -def _agent_options( - *, - api_key: str, - cwd: str, - model: Any, - mcp_servers: dict[str, Any] | None = None, -) -> Any: - from cursor_sdk import AgentOptions # optional dependency (cursor-sdk) - - return AgentOptions( - api_key=api_key, - model=model, - local=_local_agent_options(cwd=cwd), - mcp_servers=mcp_servers, - ) - - -def _effort_param(model: Any) -> Any | None: - """The parameter of an SDKModel that acts as its effort level, if any.""" - for param in model.parameters: - if param.values and any(h in param.id.lower() for h in _EFFORT_PARAM_HINTS): - return param - return None - - -async def _drain_stderr(stream: asyncio.StreamReader) -> None: - """Keep reading the bridge's stderr. The SDK only reads it until the - bridge is up, and a long-lived bridge would block once the pipe fills. - Read in chunks: readline() fails on a line over 64 KiB, which would end - the drain.""" - while chunk := await stream.read(65536): - logger.debug("cursor-sdk-bridge: {out}", out=chunk.decode(errors="replace").rstrip()) - - -def _bridge_failed(exc: BaseException) -> bool: - """True when *exc* came from not reaching the bridge process at all - (it crashed), rather than from the agent or Cursor's API. A timeout - doesn't count: a slow run says nothing about the bridge, and dropping it - would abort other chats' runs.""" - cause = exc.__cause__ - return isinstance(cause, httpx.RequestError) and not isinstance(cause, httpx.TimeoutException) - - -def _bridge_process(client: Any) -> asyncio.subprocess.Process | None: - # The SDK keeps the subprocess it launched on a private attribute. - return getattr(getattr(client, "_owned_bridge", None), "process", None) - - -@dataclass -class _Session: - """One chat's open Cursor agent.""" - - # Serializes turns (and /new) within one chat. - lock: asyncio.Lock = field(default_factory=asyncio.Lock) - agent: Any = None - # The bridge client *agent* lives on; a relaunched bridge doesn't know it. - client: Any = None - - -class CursorAgentBackend(ModelSelectionMixin): - """Cursor Python SDK implementation of the AgentBackend protocol.""" - - _label = "Cursor" - _settings_group = "cursor" - name: ClassVar[str] = "cursor" - display_name: ClassVar[str] = "Cursor SDK" - supports_model_selection: ClassVar[bool] = True - - def __init__(self, config: "MemclawConfig") -> None: - self.config = config - self._api_key = _cursor_api_key(config) - self._model = _cursor_model(config) - self._effort = _cursor_effort(config) - self._cwd = str(config.memory_dir) - # Read by the Cursor hook script, which runs in a child process. - set_environment({"MEMCLAW_MEMORY_DIR": self._cwd}) - self.bills_per_token = True - self._mcp_server = HttpMcpServer() - self._client: Any = None # the shared bridge client, launched lazily - self._client_lock = asyncio.Lock() - self._background: set[asyncio.Task] = set() # stderr drains - self._sessions: dict[str, _Session] = {} - self._models: list[ModelInfo] = [] # filled by list_models() - self._effort_params: dict[str, str] = {} # model id -> effort param id - - @classmethod - def is_configured(cls, config: "MemclawConfig") -> bool: - return bool(_cursor_api_key(config)) - - @classmethod - def configuration_help(cls) -> str: - return ( - "Cursor SDK backend requires CURSOR_API_KEY " - "(Cursor Dashboard → Integrations, or a team service account key).\n" - "Optional: CURSOR_MODEL (default: composer-2.5).\n" - "Optional: MEMCLAW_MCP_PORT (default: 17373) for the local MCP HTTP server.\n" - "Project hooks under ~/.memclaw/.cursor/ restrict the agent to Memclaw MCP tools.\n" - "Set AGENT_BACKEND=cursor in ~/.memclaw/.env to use this backend.\n" - "Memclaw installs ~/.memclaw/.cursor/hooks.json to block built-in " - "Cursor tools and allow only Memclaw MCP tools." - ) - - @classmethod - def status_rows(cls, config: "MemclawConfig") -> list[tuple[str, str]]: - return [ - ("Model", _cursor_model(config)), - ("Effort", _cursor_effort(config) or "default"), - ] - - @classmethod - def wizard_setup( - cls, - console: "Console", - existing: dict[str, str], - *, - config: "MemclawConfig", - ) -> tuple[dict[str, str], list[str]]: - current = existing.get("CURSOR_API_KEY", config.cursor.api_key) - answer = masked_input(console, "Cursor API key (required)") - value = answer or current - if not value: - console.print("[red]Error:[/red] Cursor API key is required.") - raise SystemExit(1) - - values: dict[str, str] = {"CURSOR_API_KEY": value} - drop_keys = list(_DROP_KEYS) - - model_current = existing.get("CURSOR_MODEL", config.cursor.model) - model_answer = Prompt.ask( - r"Cursor model \[composer-2.5 is default, optional]", - default="", - show_default=False, - ) - if model_answer.strip(): - values["CURSOR_MODEL"] = model_answer.strip() - if model_answer.strip() != model_current: - # An effort level picked with /effort belongs to the old model. - drop_keys.append("CURSOR_EFFORT") - elif model_current: - values["CURSOR_MODEL"] = model_current - - if not ensure_cursor_hooks(config.memory_dir): - status = cursor_hooks_status(config.memory_dir) - logger.warning( - "Cursor tool-restriction hooks are not ready ({status}). " - "Built-in Cursor tools may be used until hooks are installed.", - status=status, - ) - - return values, drop_keys - - # -- Lifecycle --------------------------------------------------------- - - async def on_agent_start(self, tool_executor: "ToolExecutor") -> None: - await self._ensure_mcp_server(tool_executor) - if ensure_cursor_hooks(self.config.memory_dir): - status = cursor_hooks_status(self.config.memory_dir) - logger.info("Cursor tool-restriction hooks: {status}", status=status) - else: - status = cursor_hooks_status(self.config.memory_dir) - logger.warning( - "Cursor tool-restriction hooks are not ready ({status}). " - "Built-in Cursor tools may be used until hooks are installed.", - status=status, - ) - - async def on_agent_shutdown(self) -> None: - # A copy: a message arriving mid-shutdown may add a session. - for session in list(self._sessions.values()): - await self._close_agent(session) - self._sessions.clear() - if self._client is not None: - await self._drop_client(self._client) - await self._mcp_server.stop() - - async def _ensure_mcp_server(self, tool_executor: "ToolExecutor") -> None: - await self._mcp_server.start( - tool_executor, - port=self.config.cursor.mcp_http_port, - ) - - # -- Bridge ------------------------------------------------------------ - - async def _launch_client(self) -> Any: - from cursor_sdk import AsyncClient # optional dependency (cursor-sdk) - from cursor_sdk._vendor import resolve_bridge_path # optional dependency (cursor-sdk) - - # Local agents are stored under a path derived from the bridge - # process's working directory (not LocalAgentOptions.cwd), and - # launch_bridge can't set it, so start the bridge through `sh` in - # the memory dir. A restarted process then finds its agents again. - Path(self._cwd).mkdir(parents=True, exist_ok=True) - client = await AsyncClient.launch_bridge( - ["/bin/sh", "-c", 'cd "$0" && exec "$@"', self._cwd, resolve_bridge_path()], - workspace=self._cwd, - ) - process = _bridge_process(client) - if process is not None and process.stderr is not None: - task = asyncio.create_task(_drain_stderr(process.stderr)) - self._background.add(task) - task.add_done_callback(self._background.discard) - return client - - async def _get_client(self) -> Any: - async with self._client_lock: - client = self._client - if client is not None: - process = _bridge_process(client) - if process is not None and process.returncode is not None: - # The bridge died between calls: relaunch now rather than - # failing the next message (or /model) first. - logger.warning("Cursor SDK bridge exited ({rc}); relaunching", rc=process.returncode) - await self._drop_client(client) - if self._client is None: - self._client = await self._launch_client() - return self._client - - async def _drop_client(self, client: Any) -> None: - """Shut *client*'s bridge down; the next call launches a new one.""" - if self._client is client: - self._client = None - try: - await client.aclose() - except Exception as exc: - logger.warning("Error while closing the Cursor SDK bridge: {exc}", exc=exc) - - # -- Sessions ---------------------------------------------------------- - - @staticmethod - async def _close_agent(session: _Session) -> None: - """Release the agent's executor. Its conversation stays on disk.""" - agent, session.agent, session.client = session.agent, None, None - if agent is None: - return - try: - await agent.close() - except Exception as exc: - logger.warning("Error while closing Cursor agent: {exc}", exc=exc) - - async def _open_agent( - self, client: Any, *, resume: str | None, mcp_servers: dict[str, Any], - ) -> tuple[Any, bool]: - """Resume agent *resume*, or create a new one when there is none or it - can't be resumed (deleted, from another machine, ...). Returns the - agent and whether it is new.""" - from cursor_sdk import CursorAgentError # optional dependency (cursor-sdk) - - # Local resume doesn't restore the model; pass it along explicitly. - options = _agent_options( - api_key=self._api_key, - cwd=self._cwd, - model=await self._model_selection(), - mcp_servers=mcp_servers, - ) - if resume: - try: - return await client.agents.resume(resume, options), False - except CursorAgentError as exc: - if _bridge_failed(exc): - raise - logger.warning( - "Could not resume Cursor agent {id} ({exc}); starting a fresh one", - id=resume, exc=exc.message, - ) - return await client.agents.create(options), True - - async def _ensure_agent( - self, session: _Session, client: Any, *, resume: str | None, mcp_servers: dict[str, Any], - ) -> Literal["open", "resumed", "created"]: - """Give *session* an open agent on *client*: the one it already has, - else agent *resume* resumed, else a new one. Returns which.""" - if session.agent is not None and session.client is client: - return "open" - # None yet, or it lived on a bridge that has since been relaunched. - session.agent, is_new = await self._open_agent( - client, resume=resume, mcp_servers=mcp_servers, - ) - session.client = client - return "created" if is_new else "resumed" - - async def _send( - self, - agent: Any, - message: Any, - *, - mcp_servers: dict[str, Any], - force: bool, - max_turns: int, - on_tool: ProgressCallback | None, - ) -> TurnResult: - from cursor_sdk import LocalSendOptions, SendOptions # optional dependency (cursor-sdk) - - usage_tracker = RunUsageTracker() - run = await agent.send( - message, - SendOptions( - # Passed on every send: a resumed agent doesn't remember its - # model, and /model takes effect here. - model=await self._model_selection(), - mcp_servers=mcp_servers, - on_delta=usage_tracker.on_delta, - local=LocalSendOptions(force=True) if force else None, - ), - ) - result = await collect_run_result( - run, max_turns=max_turns, usage_tracker=usage_tracker, on_tool=on_tool, - ) - result.session_id = agent.agent_id - return result - - async def reset_session(self, session_key: str) -> None: - session = self._sessions.get(session_key) - if session is None: - return - async with session.lock: - await self._close_agent(session) - - # -- Model selection --------------------------------------------------- - - async def list_models(self) -> list[ModelInfo]: - client = await self._get_client() - models = await client.models.list(api_key=self._api_key) - infos: list[ModelInfo] = [] - params: dict[str, str] = {} - for m in models: - param = _effort_param(m) - if param is not None: - params[m.id] = param.id - infos.append(ModelInfo( - id=m.id, - display_name=m.display_name or m.id, - created_at="", - effort_levels=[v.value for v in param.values] if param else [], - )) - self._models, self._effort_params = infos, params - return infos - - async def _model_selection(self) -> Any: - """The model (and effort parameter, if set) to run with.""" - from cursor_sdk import ModelParameterValue, ModelSelection # optional dependency (cursor-sdk) - - if not self._effort: - return ModelSelection(id=self._model) - if self._model not in self._effort_params: - await self._model_info(self._model) # learn the parameter's id - param = self._effort_params.get(self._model) - if param is None: - return ModelSelection(id=self._model) - return ModelSelection( - id=self._model, - params=[ModelParameterValue(id=param, value=self._effort)], - ) - - async def set_model(self, model_id: str) -> str: - """Switch from the next turn on. The model is passed with every send, - so open agents keep their conversation and need no reconnect.""" - info = await self._known_model(model_id.strip()) - effort = self._effort - note = "" - if self._effort and self._effort not in info.effort_levels: - effort = None - note = ( - f"{info.display_name} doesn't support '{self._effort}' effort, " - "so its default is used." - ) - self._apply_model(info.id, effort) - return note - - async def set_effort(self, level: str) -> None: - level = level.strip() - levels = await self.effort_levels() - if levels is None: - raise ValueError("Couldn't load the model list right now; try again later.") - if not levels: - raise ValueError("The current model doesn't support an effort setting.") - match = next((v for v in levels if v.lower() == level.lower()), None) - if match is None: - raise ValueError( - f"The current model doesn't support '{level}'. " - f"Supported: {', '.join(levels)}." - ) - self._apply_model(self._model, match) - - # -- Runtime ----------------------------------------------------------- - - async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: - from cursor_sdk import AsyncAgent, CursorAgentError # optional dependency (cursor-sdk) - - if not self._api_key: - raise RuntimeError("CURSOR_API_KEY is not configured") - - prompt = _build_combined_prompt( - system_prompt=system_prompt, - user_message=user_message, - ) - options = _agent_options( - api_key=self._api_key, - cwd=self._cwd, - model=await self._model_selection(), - ) - - client = await self._get_client() - try: - # A throwaway agent on the shared bridge (created, run, closed). - result = await AsyncAgent.prompt(prompt, options, client=client) - except CursorAgentError as exc: - if _bridge_failed(exc): - await self._drop_client(client) - logger.error("Cursor SDK one-shot failed: {msg}", msg=exc.message) - raise RuntimeError(f"Cursor SDK error: {exc.message}") from exc - text = extract_run_text(result) - if not text.strip(): - # Consolidation would write a placeholder reply over MEMORY.md. - raise RuntimeError("Cursor SDK one-shot returned no text") - return text - - async def run_turn(self, request: TurnRequest, tool_executor: "ToolExecutor") -> TurnResult: - from cursor_sdk import CursorAgentError # optional dependency (cursor-sdk) - - if not self._api_key: - raise RuntimeError("CURSOR_API_KEY is not configured") - - await self._ensure_mcp_server(tool_executor) - mcp_config = self._mcp_server.config - if mcp_config is None: - raise RuntimeError("MCP server failed to start") - mcp_servers = mcp_servers_for(mcp_config) - - session = self._sessions.setdefault(request.session_key, _Session()) - async with session.lock: - client = await self._get_client() - try: - agent = await self._ensure_agent( - session, client, resume=request.resume_session_id, mcp_servers=mcp_servers, - ) - message = _build_user_message( - # A Cursor agent has no system-prompt field; a new one - # gets it at the top of its first message. - system_prompt=request.system_prompt if agent == "created" else "", - context=request.context, - user_message=request.user_message, - image_b64=request.image_b64, - image_media_type=request.image_media_type, - ) - result = await self._send( - session.agent, message, mcp_servers=mcp_servers, - # A resumed agent may still show a run that died with - # the previous process; take it over. - force=agent == "resumed", - max_turns=request.max_turns, on_tool=request.on_tool, - ) - except BaseException as exc: - # The agent may be mid-run or gone; reopen (resuming) next time. - await self._close_agent(session) - if _bridge_failed(exc): - await self._drop_client(client) - if isinstance(exc, CursorAgentError): - logger.error("Cursor SDK turn failed: {msg}", msg=exc.message) - raise RuntimeError(f"Cursor SDK error: {exc.message}") from exc - raise - - if not result.text.strip(): - result.text = "I couldn't generate a response." - _apply_cost_fallback(result, bills_per_token=self.bills_per_token) - return result diff --git a/memclaw/backends/cursor/__init__.py b/memclaw/backends/cursor/__init__.py new file mode 100644 index 0000000..23e07d2 --- /dev/null +++ b/memclaw/backends/cursor/__init__.py @@ -0,0 +1,11 @@ +"""The Cursor Python SDK backend. + +`backend` is the `AgentBackend` itself. Each chat's agent (`agents`) runs +on one shared bridge process (`bridge`); `sdk_adapter` reads a run's event +stream; `hooks` restricts the agent to Memclaw's tools; `configure` asks +the setup questions and installs the hooks. +""" + +from .backend import CursorAgentBackend + +__all__ = ["CursorAgentBackend"] diff --git a/memclaw/backends/cursor/agents.py b/memclaw/backends/cursor/agents.py new file mode 100644 index 0000000..770f5ec --- /dev/null +++ b/memclaw/backends/cursor/agents.py @@ -0,0 +1,164 @@ +"""Talking to Cursor agents: one chat's agent (`ChatAgent`), the options +and messages it is opened and sent with, and one-shot prompts.""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field +from typing import Any + +from loguru import logger + +from ..base import ProgressCallback, TurnResult +from .bridge import bridge_failed +from .sdk_adapter import RunUsageTracker, collect_run_result, extract_run_text + + +def build_combined_prompt(*, system_prompt: str, user_message: str) -> str: + return "\n".join( + [ + system_prompt.strip(), + "", + "---", + "", + user_message.strip(), + ] + ) + + +def build_user_message( + *, + system_prompt: str, + user_message: str, + context: str = "", + image_b64: str | None = None, + image_media_type: str = "image/jpeg", +) -> str | Any: + """The message to send. Cursor agents have no system prompt field, so a + new agent gets it at the top of its first message; follow-ups pass "".""" + from cursor_sdk import SDKImage, UserMessage # optional dependency (cursor-sdk) + + body = "\n\n".join(p for p in (context, user_message) if p) + prompt = ( + build_combined_prompt(system_prompt=system_prompt, user_message=body) + if system_prompt + else body + ) + if not image_b64: + return prompt + return UserMessage( + text=prompt, + images=[SDKImage.from_data(image_b64, image_media_type)], + ) + + +def _local_agent_options(*, cwd: str) -> Any: + from cursor_sdk import LocalAgentOptions # optional dependency (cursor-sdk) + + return LocalAgentOptions( + cwd=cwd, + # Load ~/.memclaw/.cursor/hooks.json (project hooks for this cwd). + setting_sources=["project"], + ) + + +def agent_options( + *, + api_key: str, + cwd: str, + model: Any, + mcp_servers: dict[str, Any] | None = None, +) -> Any: + from cursor_sdk import AgentOptions # optional dependency (cursor-sdk) + + return AgentOptions( + api_key=api_key, + model=model, + local=_local_agent_options(cwd=cwd), + mcp_servers=mcp_servers, + ) + + +async def prompt_once(prompt: str, options: Any, client: Any) -> str: + """Run *prompt* on a throwaway agent on the shared bridge (created, run, + closed) and return its reply text.""" + from cursor_sdk import AsyncAgent # optional dependency (cursor-sdk) + + result = await AsyncAgent.prompt(prompt, options, client=client) + return extract_run_text(result) + + +@dataclass +class ChatAgent: + """One chat's open Cursor agent.""" + + # Serializes turns (and /new) within one chat. + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + agent: Any = None + # The bridge client *agent* lives on; a relaunched bridge doesn't know it. + client: Any = None + + def is_open_on(self, client: Any) -> bool: + return self.agent is not None and self.client is client + + async def open(self, client: Any, options: Any, *, resume: str | None) -> bool: + """Resume agent *resume* on *client*, or create a new one when there + is none or it can't be resumed (deleted, from another machine, ...). + Returns whether the agent is new.""" + from cursor_sdk import CursorAgentError # optional dependency (cursor-sdk) + + if resume: + try: + agent = await client.agents.resume(resume, options) + except CursorAgentError as exc: + if bridge_failed(exc): + raise + logger.warning( + "Could not resume Cursor agent {id} ({exc}); starting a fresh one", + id=resume, exc=exc.message, + ) + else: + self.agent, self.client = agent, client + return False + self.agent = await client.agents.create(options) + self.client = client + return True + + async def send( + self, + message: Any, + *, + model: Any, + mcp_servers: dict[str, Any], + force: bool, + max_turns: int, + on_tool: ProgressCallback | None, + ) -> TurnResult: + """Send *message* on the open agent and collect the run's reply.""" + from cursor_sdk import LocalSendOptions, SendOptions # optional dependency (cursor-sdk) + + usage_tracker = RunUsageTracker() + run = await self.agent.send( + message, + SendOptions( + model=model, + mcp_servers=mcp_servers, + on_delta=usage_tracker.on_delta, + local=LocalSendOptions(force=True) if force else None, + ), + ) + result = await collect_run_result( + run, max_turns=max_turns, usage_tracker=usage_tracker, on_tool=on_tool, + ) + result.session_id = self.agent.agent_id + return result + + async def close(self) -> None: + """Release the agent's executor. Its conversation stays on disk.""" + agent, self.agent, self.client = self.agent, None, None + if agent is None: + return + try: + await agent.close() + except Exception as exc: + logger.warning("Error while closing Cursor agent: {exc}", exc=exc) diff --git a/memclaw/backends/cursor/backend.py b/memclaw/backends/cursor/backend.py new file mode 100644 index 0000000..a141a9f --- /dev/null +++ b/memclaw/backends/cursor/backend.py @@ -0,0 +1,339 @@ +"""Cursor Python SDK agent backend. + +One `cursor-sdk-bridge` process (a Node subprocess) serves the whole Memclaw +process. Each chat keeps one open local agent on it, reused across turns: the +agent stores its own conversation on disk, so follow-up messages only carry +the per-turn context and the new message, and a restarted process resumes the +agent by id. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, ClassVar, Literal + +from loguru import logger + +from ...config import set_environment +from ..base import TurnRequest, TurnResult +from ..mcp_bridge import HttpMcpServer, mcp_servers_for +from ..model_selection import ModelInfo, ModelSelectionMixin +from .agents import ( + ChatAgent, + agent_options, + build_combined_prompt, + build_user_message, + prompt_once, +) +from .bridge import CursorBridge, bridge_failed +from .configure import ask_cursor_settings, install_hooks + +if TYPE_CHECKING: + from rich.console import Console + + from ...config import MemclawConfig + from ...tools import ToolExecutor + +_DEFAULT_MODEL = "composer-2.5" + +# Composer 2.5 default pricing (per 1M tokens) — fallback when the SDK +# doesn't return total cost on a turn-ended usage payload. +_INPUT_COST_PER_M = 0.5 +_OUTPUT_COST_PER_M = 2.5 + +# A model parameter whose id contains one of these is treated as its effort +# setting (/effort). Cursor reports parameters per model, so there is no +# fixed list of levels. +_EFFORT_PARAM_HINTS = ("effort", "reasoning") + + +def _cursor_api_key(config: "MemclawConfig") -> str: + return config.cursor.api_key.strip() + + +def _cursor_model(config: "MemclawConfig") -> str: + model = config.cursor.model.strip() + return model or _DEFAULT_MODEL + + +def _cursor_effort(config: "MemclawConfig") -> str | None: + effort = config.cursor.effort.strip() + return effort or None + + +def _apply_cost_fallback(result: TurnResult, *, bills_per_token: bool) -> None: + if result.cost_usd is not None or not bills_per_token: + return + if not (result.input_tokens or result.output_tokens or result.cache_read_tokens): + return + cache_read_cost = result.cache_read_tokens * _INPUT_COST_PER_M * 0.1 / 1_000_000 + result.cost_usd = ( + result.input_tokens * _INPUT_COST_PER_M / 1_000_000 + + result.output_tokens * _OUTPUT_COST_PER_M / 1_000_000 + + cache_read_cost + ) + + +def _effort_param(model: Any) -> Any | None: + """The parameter of an SDKModel that acts as its effort level, if any.""" + for param in model.parameters: + if param.values and any(h in param.id.lower() for h in _EFFORT_PARAM_HINTS): + return param + return None + + +class CursorAgentBackend(ModelSelectionMixin): + """Cursor Python SDK implementation of the AgentBackend protocol.""" + + _label = "Cursor" + _settings_group = "cursor" + name: ClassVar[str] = "cursor" + display_name: ClassVar[str] = "Cursor SDK" + supports_model_selection: ClassVar[bool] = True + + def __init__(self, config: "MemclawConfig") -> None: + self.config = config + self._api_key = _cursor_api_key(config) + self._model = _cursor_model(config) + self._effort = _cursor_effort(config) + self._cwd = str(config.memory_dir) + # Read by the Cursor hook script, which runs in a child process. + set_environment({"MEMCLAW_MEMORY_DIR": self._cwd}) + self.bills_per_token = True + self._mcp_server = HttpMcpServer() + self._bridge = CursorBridge(self._cwd) + self._sessions: dict[str, ChatAgent] = {} + self._models: list[ModelInfo] = [] # filled by list_models() + self._effort_params: dict[str, str] = {} # model id -> effort param id + + @classmethod + def is_configured(cls, config: "MemclawConfig") -> bool: + return bool(_cursor_api_key(config)) + + @classmethod + def configuration_help(cls) -> str: + return ( + "Cursor SDK backend requires CURSOR_API_KEY " + "(Cursor Dashboard → Integrations, or a team service account key).\n" + "Optional: CURSOR_MODEL (default: composer-2.5).\n" + "Optional: MEMCLAW_MCP_PORT (default: 17373) for the local MCP HTTP server.\n" + "Project hooks under ~/.memclaw/.cursor/ restrict the agent to Memclaw MCP tools.\n" + "Set AGENT_BACKEND=cursor in ~/.memclaw/.env to use this backend.\n" + "Memclaw installs ~/.memclaw/.cursor/hooks.json to block built-in " + "Cursor tools and allow only Memclaw MCP tools." + ) + + @classmethod + def status_rows(cls, config: "MemclawConfig") -> list[tuple[str, str]]: + return [ + ("Model", _cursor_model(config)), + ("Effort", _cursor_effort(config) or "default"), + ] + + @classmethod + def wizard_setup( + cls, + console: "Console", + existing: dict[str, str], + *, + config: "MemclawConfig", + ) -> tuple[dict[str, str], list[str]]: + return ask_cursor_settings(console, existing, config) + + # -- Lifecycle --------------------------------------------------------- + + async def on_agent_start(self, tool_executor: "ToolExecutor") -> None: + await self._ensure_mcp_server(tool_executor) + install_hooks(self.config.memory_dir, log_ready=True) + + async def on_agent_shutdown(self) -> None: + # A copy: a message arriving mid-shutdown may add a session. + for session in list(self._sessions.values()): + await session.close() + self._sessions.clear() + if self._bridge.client is not None: + await self._bridge.drop(self._bridge.client) + await self._mcp_server.stop() + + async def _ensure_mcp_server(self, tool_executor: "ToolExecutor") -> None: + await self._mcp_server.start( + tool_executor, + port=self.config.cursor.mcp_http_port, + ) + + # -- Sessions ---------------------------------------------------------- + + async def _ensure_agent( + self, session: ChatAgent, client: Any, *, resume: str | None, mcp_servers: dict[str, Any], + ) -> Literal["open", "resumed", "created"]: + """Give *session* an open agent on *client*: the one it already has, + else agent *resume* resumed, else a new one. Returns which.""" + if session.is_open_on(client): + return "open" + # None yet, or it lived on a bridge that has since been relaunched. + # Local resume doesn't restore the model; pass it along explicitly. + options = agent_options( + api_key=self._api_key, + cwd=self._cwd, + model=await self._model_selection(), + mcp_servers=mcp_servers, + ) + is_new = await session.open(client, options, resume=resume) + return "created" if is_new else "resumed" + + async def reset_session(self, session_key: str) -> None: + session = self._sessions.get(session_key) + if session is None: + return + async with session.lock: + await session.close() + + # -- Model selection --------------------------------------------------- + + async def list_models(self) -> list[ModelInfo]: + client = await self._bridge.get() + models = await client.models.list(api_key=self._api_key) + infos: list[ModelInfo] = [] + params: dict[str, str] = {} + for m in models: + param = _effort_param(m) + if param is not None: + params[m.id] = param.id + infos.append(ModelInfo( + id=m.id, + display_name=m.display_name or m.id, + created_at="", + effort_levels=[v.value for v in param.values] if param else [], + )) + self._models, self._effort_params = infos, params + return infos + + async def _model_selection(self) -> Any: + """The model (and effort parameter, if set) to run with.""" + from cursor_sdk import ModelParameterValue, ModelSelection # optional dependency (cursor-sdk) + + if not self._effort: + return ModelSelection(id=self._model) + if self._model not in self._effort_params: + await self._model_info(self._model) # learn the parameter's id + param = self._effort_params.get(self._model) + if param is None: + return ModelSelection(id=self._model) + return ModelSelection( + id=self._model, + params=[ModelParameterValue(id=param, value=self._effort)], + ) + + async def set_model(self, model_id: str) -> str: + """Switch from the next turn on. The model is passed with every send, + so open agents keep their conversation and need no reconnect.""" + info = await self._known_model(model_id.strip()) + effort = self._effort + note = "" + if self._effort and self._effort not in info.effort_levels: + effort = None + note = ( + f"{info.display_name} doesn't support '{self._effort}' effort, " + "so its default is used." + ) + self._apply_model(info.id, effort) + return note + + async def set_effort(self, level: str) -> None: + level = level.strip() + levels = await self.effort_levels() + if levels is None: + raise ValueError("Couldn't load the model list right now; try again later.") + if not levels: + raise ValueError("The current model doesn't support an effort setting.") + match = next((v for v in levels if v.lower() == level.lower()), None) + if match is None: + raise ValueError( + f"The current model doesn't support '{level}'. " + f"Supported: {', '.join(levels)}." + ) + self._apply_model(self._model, match) + + # -- Runtime ----------------------------------------------------------- + + async def run_one_shot(self, *, system_prompt: str, user_message: str) -> str: + from cursor_sdk import CursorAgentError # optional dependency (cursor-sdk) + + if not self._api_key: + raise RuntimeError("CURSOR_API_KEY is not configured") + + prompt = build_combined_prompt( + system_prompt=system_prompt, + user_message=user_message, + ) + options = agent_options( + api_key=self._api_key, + cwd=self._cwd, + model=await self._model_selection(), + ) + + client = await self._bridge.get() + try: + text = await prompt_once(prompt, options, client) + except CursorAgentError as exc: + if bridge_failed(exc): + await self._bridge.drop(client) + logger.error("Cursor SDK one-shot failed: {msg}", msg=exc.message) + raise RuntimeError(f"Cursor SDK error: {exc.message}") from exc + if not text.strip(): + # Consolidation would write a placeholder reply over MEMORY.md. + raise RuntimeError("Cursor SDK one-shot returned no text") + return text + + async def run_turn(self, request: TurnRequest, tool_executor: "ToolExecutor") -> TurnResult: + from cursor_sdk import CursorAgentError # optional dependency (cursor-sdk) + + if not self._api_key: + raise RuntimeError("CURSOR_API_KEY is not configured") + + await self._ensure_mcp_server(tool_executor) + mcp_config = self._mcp_server.config + if mcp_config is None: + raise RuntimeError("MCP server failed to start") + mcp_servers = mcp_servers_for(mcp_config) + + session = self._sessions.setdefault(request.session_key, ChatAgent()) + async with session.lock: + client = await self._bridge.get() + try: + agent = await self._ensure_agent( + session, client, resume=request.resume_session_id, mcp_servers=mcp_servers, + ) + message = build_user_message( + # A Cursor agent has no system-prompt field; a new one + # gets it at the top of its first message. + system_prompt=request.system_prompt if agent == "created" else "", + context=request.context, + user_message=request.user_message, + image_b64=request.image_b64, + image_media_type=request.image_media_type, + ) + result = await session.send( + message, + # Passed on every send: a resumed agent doesn't remember + # its model, and /model takes effect here. + model=await self._model_selection(), + mcp_servers=mcp_servers, + # A resumed agent may still show a run that died with + # the previous process; take it over. + force=agent == "resumed", + max_turns=request.max_turns, on_tool=request.on_tool, + ) + except BaseException as exc: + # The agent may be mid-run or gone; reopen (resuming) next time. + await session.close() + if bridge_failed(exc): + await self._bridge.drop(client) + if isinstance(exc, CursorAgentError): + logger.error("Cursor SDK turn failed: {msg}", msg=exc.message) + raise RuntimeError(f"Cursor SDK error: {exc.message}") from exc + raise + + if not result.text.strip(): + result.text = "I couldn't generate a response." + _apply_cost_fallback(result, bills_per_token=self.bills_per_token) + return result diff --git a/memclaw/backends/cursor/bridge.py b/memclaw/backends/cursor/bridge.py new file mode 100644 index 0000000..ae2c51d --- /dev/null +++ b/memclaw/backends/cursor/bridge.py @@ -0,0 +1,88 @@ +"""The `cursor-sdk-bridge` process (a Node subprocess) that every chat's +agent runs on: launched lazily, relaunched when it dies, shut down with +the backend.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +import httpx +from loguru import logger + + +async def drain_stderr(stream: asyncio.StreamReader) -> None: + """Keep reading the bridge's stderr. The SDK only reads it until the + bridge is up, and a long-lived bridge would block once the pipe fills. + Read in chunks: readline() fails on a line over 64 KiB, which would end + the drain.""" + while chunk := await stream.read(65536): + logger.debug("cursor-sdk-bridge: {out}", out=chunk.decode(errors="replace").rstrip()) + + +def bridge_failed(exc: BaseException) -> bool: + """True when *exc* came from not reaching the bridge process at all + (it crashed), rather than from the agent or Cursor's API. A timeout + doesn't count: a slow run says nothing about the bridge, and dropping it + would abort other chats' runs.""" + cause = exc.__cause__ + return isinstance(cause, httpx.RequestError) and not isinstance(cause, httpx.TimeoutException) + + +def _bridge_process(client: Any) -> asyncio.subprocess.Process | None: + # The SDK keeps the subprocess it launched on a private attribute. + return getattr(getattr(client, "_owned_bridge", None), "process", None) + + +class CursorBridge: + """The one bridge client the whole Memclaw process shares.""" + + def __init__(self, cwd: str) -> None: + self._cwd = cwd + self.client: Any = None # launched lazily + self._lock = asyncio.Lock() + self._background: set[asyncio.Task] = set() # stderr drains + + async def launch(self) -> Any: + from cursor_sdk import AsyncClient # optional dependency (cursor-sdk) + from cursor_sdk._vendor import resolve_bridge_path # optional dependency (cursor-sdk) + + # Local agents are stored under a path derived from the bridge + # process's working directory (not LocalAgentOptions.cwd), and + # launch_bridge can't set it, so start the bridge through `sh` in + # the memory dir. A restarted process then finds its agents again. + Path(self._cwd).mkdir(parents=True, exist_ok=True) + client = await AsyncClient.launch_bridge( + ["/bin/sh", "-c", 'cd "$0" && exec "$@"', self._cwd, resolve_bridge_path()], + workspace=self._cwd, + ) + process = _bridge_process(client) + if process is not None and process.stderr is not None: + task = asyncio.create_task(drain_stderr(process.stderr)) + self._background.add(task) + task.add_done_callback(self._background.discard) + return client + + async def get(self) -> Any: + async with self._lock: + client = self.client + if client is not None: + process = _bridge_process(client) + if process is not None and process.returncode is not None: + # The bridge died between calls: relaunch now rather than + # failing the next message (or /model) first. + logger.warning("Cursor SDK bridge exited ({rc}); relaunching", rc=process.returncode) + await self.drop(client) + if self.client is None: + self.client = await self.launch() + return self.client + + async def drop(self, client: Any) -> None: + """Shut *client*'s bridge down; the next call launches a new one.""" + if self.client is client: + self.client = None + try: + await client.aclose() + except Exception as exc: + logger.warning("Error while closing the Cursor SDK bridge: {exc}", exc=exc) diff --git a/memclaw/backends/cursor/configure.py b/memclaw/backends/cursor/configure.py new file mode 100644 index 0000000..9e0eefa --- /dev/null +++ b/memclaw/backends/cursor/configure.py @@ -0,0 +1,71 @@ +"""Setting the Cursor backend up: its questions in `memclaw configure`, and +the tool-restriction hooks it installs.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from loguru import logger +from rich.prompt import Prompt + +from ...terminal_input import masked_input +from .hooks import cursor_hooks_status, ensure_cursor_hooks + +if TYPE_CHECKING: + from rich.console import Console + + from ...config import MemclawConfig + +# Scrub Claude credentials when switching to Cursor so they can't shadow selection. +_DROP_KEYS = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"] + + +def ask_cursor_settings( + console: "Console", existing: dict[str, str], config: "MemclawConfig", +) -> tuple[dict[str, str], list[str]]: + """Ask for the API key and the model, and install the tool-restriction + hooks. Returns (values_to_save, env_keys_to_drop).""" + current = existing.get("CURSOR_API_KEY", config.cursor.api_key) + answer = masked_input(console, "Cursor API key (required)") + value = answer or current + if not value: + console.print("[red]Error:[/red] Cursor API key is required.") + raise SystemExit(1) + + values: dict[str, str] = {"CURSOR_API_KEY": value} + drop_keys = list(_DROP_KEYS) + + model_current = existing.get("CURSOR_MODEL", config.cursor.model) + model_answer = Prompt.ask( + r"Cursor model \[composer-2.5 is default, optional]", + default="", + show_default=False, + ) + if model_answer.strip(): + values["CURSOR_MODEL"] = model_answer.strip() + if model_answer.strip() != model_current: + # An effort level picked with /effort belongs to the old model. + drop_keys.append("CURSOR_EFFORT") + elif model_current: + values["CURSOR_MODEL"] = model_current + + install_hooks(config.memory_dir) + return values, drop_keys + + +def install_hooks(memory_dir: Path, *, log_ready: bool = False) -> None: + """Install or refresh the hooks that restrict the agent to Memclaw's + tools, warning when they aren't ready (and, with *log_ready*, logging + their status when they are).""" + if ensure_cursor_hooks(memory_dir): + if log_ready: + status = cursor_hooks_status(memory_dir) + logger.info("Cursor tool-restriction hooks: {status}", status=status) + return + status = cursor_hooks_status(memory_dir) + logger.warning( + "Cursor tool-restriction hooks are not ready ({status}). " + "Built-in Cursor tools may be used until hooks are installed.", + status=status, + ) diff --git a/memclaw/backends/cursor_hooks.py b/memclaw/backends/cursor/hooks.py similarity index 96% rename from memclaw/backends/cursor_hooks.py rename to memclaw/backends/cursor/hooks.py index f2c3362..ed99565 100644 --- a/memclaw/backends/cursor_hooks.py +++ b/memclaw/backends/cursor/hooks.py @@ -9,9 +9,9 @@ import sys from pathlib import Path -from ..config import MemclawConfig -from .mcp_tools import MCP_SERVER_NAME -from .tool_policy import CURSOR_PRETOOLUSE_MATCHER, HOOKS_VERSION, hook_policy_payload +from ...config import MemclawConfig +from ..mcp_tools import MCP_SERVER_NAME +from ..tool_policy import CURSOR_PRETOOLUSE_MATCHER, HOOKS_VERSION, hook_policy_payload _HOOKS_JSON = "hooks.json" _HOOK_SCRIPT = "allow_memclaw_tools.py" diff --git a/memclaw/backends/cursor_sdk_adapter.py b/memclaw/backends/cursor/sdk_adapter.py similarity index 79% rename from memclaw/backends/cursor_sdk_adapter.py rename to memclaw/backends/cursor/sdk_adapter.py index b36d1a8..6fed84f 100644 --- a/memclaw/backends/cursor_sdk_adapter.py +++ b/memclaw/backends/cursor/sdk_adapter.py @@ -7,8 +7,8 @@ from loguru import logger -from .base import ProgressCallback, TurnResult, report_tool_step -from .mcp_tools import MCP_SERVER_NAME +from ..base import ProgressCallback, TurnResult, report_tool_step +from ..mcp_tools import MCP_SERVER_NAME def normalize_tool_call(name: str, args: Any) -> tuple[str, Any]: @@ -274,6 +274,68 @@ def _handle_sdk_message(message: Any, *, pending_tools: dict[str, str]) -> str: return "" +def _is_running_tool_call(message: Any) -> bool: + return getattr(message, "type", None) == "tool_call" and str( + getattr(message, "status", "") + ) == "running" + + +class _RunStream: + """What a run's event stream has shown so far: the latest assistant + text, the tool calls still running, and the calls reported as steps.""" + + def __init__(self, on_tool: ProgressCallback | None) -> None: + self.last_text = "" + self.pending_tools: dict[str, str] = {} + self._reported: set[str] = set() + self._on_tool = on_tool + + async def handle(self, message: Any) -> None: + turn_text = _handle_sdk_message(message, pending_tools=self.pending_tools) + if turn_text: + self.last_text = turn_text + if _is_running_tool_call(message): + await self._report_step(message) + + async def _report_step(self, message: Any) -> None: + """Report a running tool call as a progress step, once per call.""" + name, args = normalize_tool_call( + getattr(message, "name", ""), getattr(message, "args", None), + ) + call_id = str(getattr(message, "call_id", "") or len(self._reported)) + if call_id in self._reported: + return + self._reported.add(call_id) + await report_tool_step(self._on_tool, len(self._reported), name, args) + + def warn_unfinished(self) -> None: + for call_id, name in self.pending_tools.items(): + tool_name, _ = normalize_tool_call(name, {}) + logger.warning( + "Tool {name} started but never completed (call_id={call_id}). " + "It may have been blocked by a Cursor hook or failed before MCP execution.", + name=tool_name, + call_id=call_id or "(unknown)", + ) + + +def _count_turns( + wait_result: Any, *, max_turns: int, usage_tracker: RunUsageTracker | None, +) -> int: + """The run's turn count (at least 1), warning when it passed *max_turns*.""" + reported_turns = getattr(wait_result, "num_turns", 0) or 0 + tracked_turns = int(usage_tracker.totals.get("turn_count") or 0) if usage_tracker else 0 + num_turns = max(tracked_turns, reported_turns, 1) + if num_turns > max_turns: + logger.warning( + "Cursor SDK reported {reported} turns (Memclaw max_turns={max}); " + "the SDK does not expose a turn cap — tighten prompts or hooks if needed.", + reported=num_turns, + max=max_turns, + ) + return num_turns + + async def collect_run_result( run: Any, *, @@ -282,57 +344,21 @@ async def collect_run_result( on_tool: ProgressCallback | None = None, ) -> TurnResult: """Drain the run stream for logging and return a normalized TurnResult.""" - last_text = "" - pending_tools: dict[str, str] = {} - reported: set[str] = set() - + stream = _RunStream(on_tool) async for event in run.events(): message = getattr(event, "sdk_message", None) if message is not None: - turn_text = _handle_sdk_message(message, pending_tools=pending_tools) - if turn_text: - last_text = turn_text - if getattr(message, "type", None) == "tool_call" and str( - getattr(message, "status", "") - ) == "running": - name, args = normalize_tool_call( - getattr(message, "name", ""), getattr(message, "args", None), - ) - call_id = str(getattr(message, "call_id", "") or len(reported)) - if call_id not in reported: - reported.add(call_id) - await report_tool_step(on_tool, len(reported), name, args) - - for call_id, name in pending_tools.items(): - tool_name, _ = normalize_tool_call(name, {}) - logger.warning( - "Tool {name} started but never completed (call_id={call_id}). " - "It may have been blocked by a Cursor hook or failed before MCP execution.", - name=tool_name, - call_id=call_id or "(unknown)", - ) + await stream.handle(message) + stream.warn_unfinished() wait_result = await run.wait() wait_text = extract_run_text(wait_result) - if len(wait_text) > len(last_text): - last_text = wait_text - elif not last_text: + # The streamed text, unless the final result says more. + last_text = stream.last_text + if len(wait_text) > len(last_text) or not last_text: last_text = wait_text - reported_turns = getattr(wait_result, "num_turns", 0) or 0 - num_turns = max( - int(getattr(usage_tracker, "totals", {}).get("turn_count") or 0) if usage_tracker else 0, - reported_turns, - 1, - ) - if num_turns > max_turns: - logger.warning( - "Cursor SDK reported {reported} turns (Memclaw max_turns={max}); " - "the SDK does not expose a turn cap — tighten prompts or hooks if needed.", - reported=num_turns, - max=max_turns, - ) - + num_turns = _count_turns(wait_result, max_turns=max_turns, usage_tracker=usage_tracker) result = TurnResult(text=last_text, num_turns=num_turns) if usage_tracker is not None: usage_tracker.apply_to_result(result) diff --git a/memclaw/backends/mcp_bridge.py b/memclaw/backends/mcp_bridge.py index 621c538..3b61513 100644 --- a/memclaw/backends/mcp_bridge.py +++ b/memclaw/backends/mcp_bridge.py @@ -102,13 +102,14 @@ async def lifespan(_app: Starlette): ) listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + handed_over = False try: listen_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_sock.bind((host, port)) listen_sock.listen(2048) self._port = int(listen_sock.getsockname()[1]) self._listen_sock = listen_sock - listen_sock = None + handed_over = True except OSError as exc: await self.stop() raise OSError( @@ -117,14 +118,14 @@ async def lifespan(_app: Starlette): f"({exc})" ) from exc finally: - if listen_sock is not None: + if not handed_over: listen_sock.close() uvicorn_config = uvicorn.Config( starlette_app, host=host, port=self._port, - fd=self._listen_sock.fileno(), + fd=listen_sock.fileno(), log_level="warning", ) self._uvicorn_server = uvicorn.Server(uvicorn_config) diff --git a/memclaw/tools.py b/memclaw/tools.py deleted file mode 100644 index 07ba3b8..0000000 --- a/memclaw/tools.py +++ /dev/null @@ -1,575 +0,0 @@ -"""Tool definitions and executor for the Memclaw agent.""" - -from __future__ import annotations - -from datetime import datetime, timedelta -from pathlib import Path -from typing import Any - -from loguru import logger - -from .config import MemclawConfig -from .memory import HybridSearch, MemoryIndex, MemoryStore, SearchResult -from .reminders import ReminderScheduler - -# ── Tool definitions (JSON schema) ─────────────────────────────────── - -TOOL_DEFINITIONS: list[dict[str, Any]] = [ - { - "name": "memory_save", - "description": ( - "Save a new memory, thought, or note — durable facts and preferences " - "included — to today's notes. MEMORY.md (permanent memory) is " - "distilled from the notes automatically once a day." - ), - "input_schema": { - "type": "object", - "properties": { - "content": {"type": "string", "description": "The content to save"}, - "entry_type": { - "type": "string", - "description": "Type of entry: note, image, link, voice", - }, - "tags": { - "type": "array", - "items": {"type": "string"}, - "description": "Optional tags for categorization", - }, - }, - "required": ["content"], - }, - }, - { - "name": "memory_search", - "description": "Search through stored memories using natural language", - "input_schema": { - "type": "object", - "properties": { - "query": {"type": "string", "description": "Natural language search query"}, - "limit": { - "type": "integer", - "description": "Maximum number of results (default 10)", - }, - }, - "required": ["query"], - }, - }, - { - "name": "image_save", - "description": ( - "Save an image with your description so it can be retrieved later. " - "You MUST call this when you receive an image with a media_ref in " - "the prompt, or when the user shares a local image path. Describe " - "the image in detail and pass the media_ref verbatim." - ), - "input_schema": { - "type": "object", - "properties": { - "description": {"type": "string", "description": "Detailed image description"}, - "media_ref": { - "type": "string", - "description": "Opaque reference (file_id, local path, etc.) from the prompt", - }, - "caption": {"type": "string", "description": "Optional caption"}, - }, - "required": ["description", "media_ref"], - }, - }, - { - "name": "image_search", - "description": ( - "Find previously stored images when the user asks to retrieve, show, " - "or send one. Returns the closest matches with their ids and " - "descriptions; nothing is sent. Then call image_send with the ids of " - "the images that are what the user asked for." - ), - "input_schema": { - "type": "object", - "properties": { - "query": {"type": "string", "description": "Search query for images"}, - }, - "required": ["query"], - }, - }, - { - "name": "image_send", - "description": ( - "Send stored images to the user, by the ids image_search returned. " - "Pass only the images that match the request (e.g. just the passport " - "when the user asks for their passport)." - ), - "input_schema": { - "type": "object", - "properties": { - "ids": { - "type": "array", - "items": {"type": "integer"}, - "description": "Image ids from image_search", - }, - }, - "required": ["ids"], - }, - }, - { - "name": "update_instructions", - "description": ( - "Save a new behavioural instruction to AGENTS.md. Call this whenever " - "the user tells you to behave a certain way, respond in a certain style, " - "or gives any standing directive (e.g. 'always reply in Serbian', " - "'be more concise', 'never use emojis'). Pass a short, clear rule." - ), - "input_schema": { - "type": "object", - "properties": { - "instruction": {"type": "string", "description": "The instruction to save"}, - }, - "required": ["instruction"], - }, - }, - { - "name": "file_write", - "description": ( - "Create or overwrite a file inside the memory directory (~/.memclaw/). " - "Use this when the user asks you to create a file such as todos.md, " - "notes.md, etc. The path must be relative to ~/.memclaw/ or an " - "absolute path under it." - ), - "input_schema": { - "type": "object", - "properties": { - "file_path": {"type": "string", "description": "File path (relative or absolute under ~/.memclaw/)"}, - "content": {"type": "string", "description": "File content to write"}, - }, - "required": ["file_path", "content"], - }, - }, - { - "name": "file_read", - "description": ( - "Read a file from the memory directory (~/.memclaw/). " - "The path must be under ~/.memclaw/." - ), - "input_schema": { - "type": "object", - "properties": { - "file_path": {"type": "string", "description": "File path to read"}, - }, - "required": ["file_path"], - }, - }, - { - "name": "reminder_create", - "description": ( - "Schedule a reminder to be sent back to the user at a specific " - "local time, or on a recurring interval. Use when the user says " - "things like 'remind me tomorrow at 9am to call Alex' (one-shot) " - "or 'remind me every 5 hours to drink water' (recurring). " - "For recurring-only reminders without a user-specified start, " - "you may omit fire_at and the first fire will be interval_seconds " - "from now. Always convert the user's natural-language time to a " - "local ISO 8601 datetime using the current local time in the system " - "prompt as reference. Do NOT use this tool to store notes — use " - "memory_save for that." - ), - "input_schema": { - "type": "object", - "properties": { - "text": { - "type": "string", - "description": "What to remind the user about (short, in their own words)", - }, - "fire_at": { - "type": "string", - "description": ( - "Local ISO 8601 datetime for the first (or only) fire, " - "e.g. '2026-04-13T21:30:00'. Omit to start a recurring " - "reminder interval_seconds from now." - ), - }, - "interval_seconds": { - "type": "integer", - "description": ( - "If set, the reminder recurs every N seconds after " - "fire_at. Convert the user's unit to seconds (e.g. " - "'every 5 hours' -> 18000)." - ), - }, - }, - "required": ["text"], - }, - }, - { - "name": "reminder_list", - "description": "List the user's pending reminders.", - "input_schema": {"type": "object", "properties": {}}, - }, - { - "name": "reminder_cancel", - "description": ( - "Cancel a pending reminder by its id. Call reminder_list first if " - "the user refers to a reminder by description." - ), - "input_schema": { - "type": "object", - "properties": { - "id": {"type": "integer", "description": "Reminder id"}, - }, - "required": ["id"], - }, - }, -] - - -# ── Helpers ────────────────────────────────────────────────────────── - -_MAX_SEARCH_RESULTS = 25 - -# image_search: how many candidates the agent chooses from, and how much of -# each description it sees. -_IMAGE_CANDIDATES = 5 -_IMAGE_DESCRIPTION_CHARS = 300 - -# Progress-message wording per tool: (label, argument shown after it). -_STEP_LABELS: dict[str, tuple[str, str | None]] = { - "memory_save": ("Saving to memory", None), - "memory_search": ("Searching memories", "query"), - "image_save": ("Saving the image", None), - "image_search": ("Searching images", "query"), - "image_send": ("Sending images", None), - "update_instructions": ("Updating my instructions", None), - "file_write": ("Writing", "file_path"), - "file_read": ("Reading", "file_path"), - "reminder_create": ("Setting a reminder", "text"), - "reminder_list": ("Checking reminders", None), - "reminder_cancel": ("Cancelling a reminder", None), -} - - -def describe_tool_call(name: str, args: Any, limit: int = 80) -> str: - """A short one-line description of a tool call for progress messages.""" - label, arg = _STEP_LABELS.get(name, (name, None)) - value = args.get(arg) if arg and isinstance(args, dict) else None - if not isinstance(value, str) or not value.strip(): - return label - value = " ".join(value.split()) - if len(value) > limit: - value = value[: limit - 1] + "…" - return f"{label}: {value}" - - -def _format_results(results: list[SearchResult]) -> str: - parts = [] - for i, r in enumerate(results, 1): - source = Path(r.file_path).stem - if source == "MEMORY": - source = "permanent memory" - parts.append(f"**[{i}]** (score: {r.score:.2f}, source: {source})\n{r.content.strip()}") - return "\n\n---\n\n".join(parts) if parts else "No matching memories found." - - -# Memclaw's own state inside the memory dir. The agent may not read or -# write it: the database, the session store and the consolidation marker -# would be corrupted by a write, .env holds the API keys, and the WhatsApp / -# Slack dirs hold the pairing session and downloaded media. Hidden -# directories (e.g. .cursor/, holding the Cursor tool-restriction hooks) are -# covered by the dot-prefix rule. -_INTERNAL_NAMES = frozenset({"sessions.json", "sessions.tmp", "meta.json"}) -_INTERNAL_DIRS = frozenset({"whatsapp", "slack"}) - - -def _resolve_safe(raw_path: str, memory_dir: Path) -> Path | None: - """Resolve *raw_path* and return it only if under *memory_dir* and not - one of Memclaw's internal files.""" - safe_root = memory_dir.resolve() - p = Path(raw_path).expanduser() - if not p.is_absolute(): - p = memory_dir / p - resolved = p.resolve() - try: - rel = resolved.relative_to(safe_root) - except ValueError: - return None - parts = rel.parts - if not parts: - return None - if any(part.startswith(".") for part in parts): - return None - if parts[0] in _INTERNAL_DIRS or rel.name in _INTERNAL_NAMES: - return None - if rel.name.startswith("memclaw.db") or rel.suffix == ".log": - return None - return resolved - - -# ── Tool executor ──────────────────────────────────────────────────── - -class ToolExecutor: - """Executes tool calls on behalf of the agent. - - Holds references to the store, index, search engine, and config so - that individual tool implementations can access them without the - agent having to pass them on every call. - """ - - def __init__( - self, - config: MemclawConfig, - store: MemoryStore, - index: MemoryIndex, - search: HybridSearch, - found_images: list[dict], - platform: str | None = None, - scheduler: ReminderScheduler | None = None, - ): - self.config = config - self.store = store - self.index = index - self.search = search - self.found_images = found_images - self.platform = platform - self.scheduler = scheduler - self.chat_id: str | None = None - - self._dispatch: dict[str, Any] = { - "memory_save": self._memory_save, - "memory_search": self._memory_search, - "image_save": self._image_save, - "image_search": self._image_search, - "image_send": self._image_send, - "update_instructions": self._update_instructions, - "file_write": self._file_write, - "file_read": self._file_read, - "reminder_create": self._reminder_create, - "reminder_list": self._reminder_list, - "reminder_cancel": self._reminder_cancel, - } - - async def execute(self, name: str, tool_input: dict[str, Any]) -> str: - func = self._dispatch.get(name) - if func is None: - return f"Error: Unknown tool '{name}'" - try: - return await func(tool_input) - except Exception as e: - return f"Error executing {name}: {e}" - - # ── Implementations ────────────────────────────────────────────── - - async def _memory_save(self, args: dict) -> str: - content: str = args["content"] - entry_type: str = args.get("entry_type", "note") - tags = args.get("tags") - # A "permanent" flag from an older session is ignored: MEMORY.md is - # written only by consolidation. - file_path = self.store.save(content, entry_type=entry_type, tags=tags) - logger.info(" → memory_save result: saved to {file}", file=file_path.name) - return f"Memory saved to {file_path.name}" + await self._index(file_path) - - async def _index(self, path: Path) -> str: - """Index a just-written file. The write already succeeded, so an - indexing failure (e.g. OpenAI unreachable) is reported, not raised: - the next index sync picks the file up.""" - try: - await self.index.index_file(path) - except Exception as exc: - logger.warning("Indexing {p} failed, will retry on next sync: {exc}", p=path, exc=exc) - return " (search indexing is delayed; it will be searchable soon)" - return "" - - async def _memory_search(self, args: dict) -> str: - try: - limit = max(1, min(int(args.get("limit") or 10), _MAX_SEARCH_RESULTS)) - except (TypeError, ValueError): - limit = 10 - results = await self.search.search(args["query"], limit=limit) - formatted = _format_results(results) - logger.info(" → memory_search result: {n} hits", n=len(results)) - for i, r in enumerate(results, 1): - source = Path(r.file_path).stem - snippet = r.content.strip().replace("\n", " ") - if len(snippet) > 120: - snippet = snippet[:120] + "..." - logger.info(" [{i}] ({score:.2f}, {src}) {snippet}", i=i, score=r.score, src=source, snippet=snippet) - return formatted - - async def _image_save(self, args: dict) -> str: - description: str = args["description"] - media_ref: str = args["media_ref"] - caption: str = args.get("caption", "") - platform = self.platform or "local" - - combined = f"Image: {description}" - if caption: - combined += f" Caption: {caption}" - # Register the image first: it needs an embedding, and if that fails - # nothing has been written yet, so a retry doesn't save the note twice. - await self.index.store_platform_image( - platform=platform, - media_ref=media_ref, - description=combined, - caption=caption, - ) - store_path = self.store.save(combined, entry_type="image") - await self._index(store_path) - logger.info( - " → image_save({platform}) result: {desc}", - platform=platform, desc=description[:100], - ) - return f"Image saved: {description[:100]}" - - async def _image_search(self, args: dict) -> str: - # Only images saved on this platform can be sent back on it (a - # Telegram file_id means nothing to Slack). The terminal has no - # platform and can describe images from anywhere. - candidates = await self.search.search_images( - args["query"], limit=_IMAGE_CANDIDATES, platform=self.platform, - ) - logger.info(" → image_search result: {n} candidate(s)", n=len(candidates)) - if not candidates: - return "No matching images found." - lines = [] - for r in candidates: - description = " ".join(r["description"].split()) - if len(description) > _IMAGE_DESCRIPTION_CHARS: - description = description[:_IMAGE_DESCRIPTION_CHARS] + "…" - lines.append(f"- id {r['id']} (match {r['score']:.2f}): {description}") - return ( - "Closest stored images, best first (nothing sent yet):\n" - + "\n".join(lines) - + "\nCall image_send with the ids of the ones the user asked for." - ) - - async def _image_send(self, args: dict) -> str: - ids = [int(i) for i in args.get("ids") or []] - images = self.index.get_platform_images(ids, platform=self.platform) - queued = {img["id"] for img in self.found_images} - new = [img for img in images if img["id"] not in queued] - self.found_images.extend(new) - logger.info(" → image_send: {n} image(s) queued", n=len(new)) - missing = sorted(set(ids) - {img["id"] for img in images}) - note = f" No stored image with id {', '.join(map(str, missing))}." if missing else "" - if not images: - return "Nothing to send." + note - return f"Sending {len(images)} image(s) with your reply." + note - - async def _update_instructions(self, args: dict) -> str: - instruction: str = args["instruction"].strip() - agent_file = self.config.agent_file - entry = f"\n- {instruction}\n" - with open(agent_file, "a") as f: - f.write(entry) - logger.info(" → update_instructions: appended to AGENTS.md") - return f"Instruction saved: {instruction}" - - async def _file_write(self, args: dict) -> str: - resolved = _resolve_safe(args["file_path"], self.config.memory_dir) - if resolved is None: - safe_root = self.config.memory_dir.resolve() - msg = ( - f"Blocked: path is outside {safe_root} or is one of Memclaw's " - "internal files. Files must be under ~/.memclaw/" - ) - logger.warning(msg) - return msg - rel = resolved.relative_to(self.config.memory_dir.resolve()) - if rel == Path(self.config.memory_file.name) or rel.parts[0] == self.config.memory_subdir.name: - # MEMORY.md is written only by consolidation, and the daily notes - # are the append-only record it is rebuilt from. - return ( - "Blocked: MEMORY.md and the daily notes in memory/ are maintained " - "by Memclaw. Use memory_save to add a memory." - ) - resolved.parent.mkdir(parents=True, exist_ok=True) - resolved.write_text(args["content"]) - logger.info(" → file_write: wrote {path}", path=resolved) - # Index under the same (unresolved) path the index sync uses. - path = self.config.memory_dir / rel - note = await self._index(path) if self.index.is_indexable(path) else "" - return f"File written: {resolved}{note}" - - async def _file_read(self, args: dict) -> str: - resolved = _resolve_safe(args["file_path"], self.config.memory_dir) - if resolved is None: - safe_root = self.config.memory_dir.resolve() - return f"Blocked: path is outside {safe_root} or is one of Memclaw's internal files." - if not resolved.exists(): - return f"File not found: {resolved}" - text = resolved.read_text() - logger.info(" → file_read: read {path} ({n} chars)", path=resolved, n=len(text)) - return text - - # ── Reminders ──────────────────────────────────────────────────── - - def _require_reminder_ctx(self) -> str | None: - if self.scheduler is None: - return "Reminders are only available when running in a messaging bot (telegram/whatsapp/slack)." - if not self.platform or not self.chat_id: - return "Reminders require a messaging context (missing platform/chat_id)." - return None - - async def _reminder_create(self, args: dict) -> str: - err = self._require_reminder_ctx() - if err: - return err - - text: str = args["text"].strip() - interval: int | None = args.get("interval_seconds") - fire_at_str: str | None = args.get("fire_at") - - if fire_at_str: - try: - fire_at = datetime.fromisoformat(fire_at_str) - except ValueError: - return f"Invalid fire_at: {fire_at_str!r}. Use local ISO 8601." - if fire_at.tzinfo is not None: - fire_at = fire_at.astimezone().replace(tzinfo=None) - elif interval: - fire_at = datetime.now() + timedelta(seconds=interval) - else: - return "Provide either fire_at or interval_seconds (or both)." - - if interval is not None and interval < 60: - return "interval_seconds must be at least 60." - - rid = self.scheduler.create( # type: ignore[union-attr] - platform=self.platform, # type: ignore[arg-type] - chat_id=self.chat_id, # type: ignore[arg-type] - text=text, - fire_at=fire_at, - interval_seconds=interval, - ) - logger.info( - " → reminder_create: id={id} fire_at={f} every={i}s", - id=rid, f=fire_at.isoformat(), i=interval, - ) - if interval: - return ( - f"Reminder #{rid} scheduled for {fire_at.isoformat(timespec='minutes')} " - f"and every {interval} seconds after." - ) - return f"Reminder #{rid} scheduled for {fire_at.isoformat(timespec='minutes')}." - - async def _reminder_list(self, args: dict) -> str: - err = self._require_reminder_ctx() - if err: - return err - items = self.scheduler.list_for(self.platform, self.chat_id) # type: ignore[union-attr,arg-type] - if not items: - return "No pending reminders." - lines = [] - for it in items: - line = f"#{it['id']} at {it['fire_at']}: {it['text']}" - if it["interval_seconds"]: - line += f" (every {it['interval_seconds']}s)" - lines.append(line) - return "\n".join(lines) - - async def _reminder_cancel(self, args: dict) -> str: - err = self._require_reminder_ctx() - if err: - return err - rid = int(args["id"]) - ok = self.scheduler.cancel( # type: ignore[union-attr] - rid, platform=self.platform, chat_id=self.chat_id, # type: ignore[arg-type] - ) - return f"Reminder #{rid} cancelled." if ok else f"No pending reminder #{rid}." diff --git a/memclaw/tools/__init__.py b/memclaw/tools/__init__.py new file mode 100644 index 0000000..f6be376 --- /dev/null +++ b/memclaw/tools/__init__.py @@ -0,0 +1,13 @@ +"""The tools the Memclaw agent can call. + +One module per kind of tool (`memory`, `images`, `files`, `reminders`), +each listing its tools' definitions and code; `catalog` puts them in order +and `ToolExecutor` runs a call against a `ToolContext`. Other code uses +what this package exports, not the modules inside. +""" + +from .catalog import TOOL_DEFINITIONS, describe_tool_call +from .context import ToolContext +from .executor import ToolExecutor + +__all__ = ["TOOL_DEFINITIONS", "ToolContext", "ToolExecutor", "describe_tool_call"] diff --git a/memclaw/tools/catalog.py b/memclaw/tools/catalog.py new file mode 100644 index 0000000..14760a0 --- /dev/null +++ b/memclaw/tools/catalog.py @@ -0,0 +1,34 @@ +"""Every tool, in the order the LLM sees them, and how a call to one is +worded in progress messages.""" + +from __future__ import annotations + +from typing import Any + +from . import files, images, memory, reminders +from .context import Tool + +TOOLS: list[Tool] = [*memory.TOOLS, *images.TOOLS, *files.TOOLS, *reminders.TOOLS] + +# The JSON-schema definitions the backends hand to the LLM. The Cursor hook +# policy and the backends' allow-lists are built from these names. +TOOL_DEFINITIONS: list[dict[str, Any]] = [tool.definition for tool in TOOLS] + +_BY_NAME: dict[str, Tool] = {tool.name: tool for tool in TOOLS} + + +def describe_tool_call(name: str, args: Any, limit: int = 80) -> str: + """A short one-line description of a tool call for progress messages.""" + tool = find_tool(name) + label, arg = (tool.step_label, tool.step_arg) if tool else (name, None) + value = args.get(arg) if arg and isinstance(args, dict) else None + if not isinstance(value, str) or not value.strip(): + return label + value = " ".join(value.split()) + if len(value) > limit: + value = value[: limit - 1] + "…" + return f"{label}: {value}" + + +def find_tool(name: str) -> Tool | None: + return _BY_NAME.get(name) diff --git a/memclaw/tools/context.py b/memclaw/tools/context.py new file mode 100644 index 0000000..028df4f --- /dev/null +++ b/memclaw/tools/context.py @@ -0,0 +1,65 @@ +"""What every tool works on (`ToolContext`), and the `Tool` record each +tool module lists its tools with.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Awaitable, Callable + +from loguru import logger + +from ..config import MemclawConfig +from ..memory import HybridSearch, MemoryIndex, MemoryStore +from ..reminders import ReminderScheduler + + +@dataclass +class ToolContext: + """The storage the tools read and write, and the chat they run for. + + The agent builds one and updates `chat_id` before each turn; the tools + queue the images to send with the reply in `found_images`. + """ + + config: MemclawConfig + store: MemoryStore + index: MemoryIndex + search: HybridSearch + found_images: list[dict] = field(default_factory=list) + # The chat platform ("telegram", ...); None in the terminal. + platform: str | None = None + # Only the messaging bots run reminders. + scheduler: ReminderScheduler | None = None + chat_id: str | None = None + + +ToolHandler = Callable[[ToolContext, dict], Awaitable[str]] + + +@dataclass(frozen=True) +class Tool: + """One tool: the definition the LLM sees, the code that runs it, and + its wording in progress messages (`step_label`, then the `step_arg` + argument's value if it has one).""" + + definition: dict[str, Any] + run: ToolHandler + step_label: str + step_arg: str | None = None + + @property + def name(self) -> str: + return self.definition["name"] + + +async def index_written(ctx: ToolContext, path: Path) -> str: + """Index a just-written file. The write already succeeded, so an + indexing failure (e.g. OpenAI unreachable) is reported, not raised: + the next index sync picks the file up.""" + try: + await ctx.index.index_file(path) + except Exception as exc: + logger.warning("Indexing {p} failed, will retry on next sync: {exc}", p=path, exc=exc) + return " (search indexing is delayed; it will be searchable soon)" + return "" diff --git a/memclaw/tools/executor.py b/memclaw/tools/executor.py new file mode 100644 index 0000000..fb07478 --- /dev/null +++ b/memclaw/tools/executor.py @@ -0,0 +1,29 @@ +"""Runs the agent's tool calls.""" + +from __future__ import annotations + +from typing import Any + +from .catalog import find_tool +from .context import ToolContext + + +class ToolExecutor: + """Executes tool calls on behalf of the agent. + + Holds the `ToolContext` (the store, index, search engine, config and + the current chat) so that individual tools can reach them without the + agent having to pass them on every call. + """ + + def __init__(self, context: ToolContext): + self.context = context + + async def execute(self, name: str, tool_input: dict[str, Any]) -> str: + tool = find_tool(name) + if tool is None: + return f"Error: Unknown tool '{name}'" + try: + return await tool.run(self.context, tool_input) + except Exception as e: + return f"Error executing {name}: {e}" diff --git a/memclaw/tools/files.py b/memclaw/tools/files.py new file mode 100644 index 0000000..8511cad --- /dev/null +++ b/memclaw/tools/files.py @@ -0,0 +1,151 @@ +"""Tools for files in the memory directory: AGENTS.md instructions, and +reading and writing the user's own files (never Memclaw's internal ones).""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from loguru import logger + +from .context import Tool, ToolContext, index_written + +# Memclaw's own state inside the memory dir. The agent may not read or +# write it: the database, the session store and the consolidation marker +# would be corrupted by a write, .env holds the API keys, and the WhatsApp / +# Slack dirs hold the pairing session and downloaded media. Hidden +# directories (e.g. .cursor/, holding the Cursor tool-restriction hooks) are +# covered by the dot-prefix rule. +_INTERNAL_NAMES = frozenset({"sessions.json", "sessions.tmp", "meta.json"}) +_INTERNAL_DIRS = frozenset({"whatsapp", "slack"}) + +UPDATE_INSTRUCTIONS: dict[str, Any] = { + "name": "update_instructions", + "description": ( + "Save a new behavioural instruction to AGENTS.md. Call this whenever " + "the user tells you to behave a certain way, respond in a certain style, " + "or gives any standing directive (e.g. 'always reply in Serbian', " + "'be more concise', 'never use emojis'). Pass a short, clear rule." + ), + "input_schema": { + "type": "object", + "properties": { + "instruction": {"type": "string", "description": "The instruction to save"}, + }, + "required": ["instruction"], + }, +} + +FILE_WRITE: dict[str, Any] = { + "name": "file_write", + "description": ( + "Create or overwrite a file inside the memory directory (~/.memclaw/). " + "Use this when the user asks you to create a file such as todos.md, " + "notes.md, etc. The path must be relative to ~/.memclaw/ or an " + "absolute path under it." + ), + "input_schema": { + "type": "object", + "properties": { + "file_path": {"type": "string", "description": "File path (relative or absolute under ~/.memclaw/)"}, + "content": {"type": "string", "description": "File content to write"}, + }, + "required": ["file_path", "content"], + }, +} + +FILE_READ: dict[str, Any] = { + "name": "file_read", + "description": ( + "Read a file from the memory directory (~/.memclaw/). " + "The path must be under ~/.memclaw/." + ), + "input_schema": { + "type": "object", + "properties": { + "file_path": {"type": "string", "description": "File path to read"}, + }, + "required": ["file_path"], + }, +} + + +def _resolve_safe(raw_path: str, memory_dir: Path) -> Path | None: + """Resolve *raw_path* and return it only if under *memory_dir* and not + one of Memclaw's internal files.""" + safe_root = memory_dir.resolve() + p = Path(raw_path).expanduser() + if not p.is_absolute(): + p = memory_dir / p + resolved = p.resolve() + try: + rel = resolved.relative_to(safe_root) + except ValueError: + return None + parts = rel.parts + if not parts: + return None + if any(part.startswith(".") for part in parts): + return None + if parts[0] in _INTERNAL_DIRS or rel.name in _INTERNAL_NAMES: + return None + if rel.name.startswith("memclaw.db") or rel.suffix == ".log": + return None + return resolved + + +async def update_instructions(ctx: ToolContext, args: dict) -> str: + instruction: str = args["instruction"].strip() + agent_file = ctx.config.agent_file + entry = f"\n- {instruction}\n" + with open(agent_file, "a") as f: + f.write(entry) + logger.info(" → update_instructions: appended to AGENTS.md") + return f"Instruction saved: {instruction}" + + +async def file_write(ctx: ToolContext, args: dict) -> str: + config = ctx.config + resolved = _resolve_safe(args["file_path"], config.memory_dir) + if resolved is None: + safe_root = config.memory_dir.resolve() + msg = ( + f"Blocked: path is outside {safe_root} or is one of Memclaw's " + "internal files. Files must be under ~/.memclaw/" + ) + logger.warning(msg) + return msg + rel = resolved.relative_to(config.memory_dir.resolve()) + if rel == Path(config.memory_file.name) or rel.parts[0] == config.memory_subdir.name: + # MEMORY.md is written only by consolidation, and the daily notes + # are the append-only record it is rebuilt from. + return ( + "Blocked: MEMORY.md and the daily notes in memory/ are maintained " + "by Memclaw. Use memory_save to add a memory." + ) + resolved.parent.mkdir(parents=True, exist_ok=True) + resolved.write_text(args["content"]) + logger.info(" → file_write: wrote {path}", path=resolved) + # Index under the same (unresolved) path the index sync uses. + path = config.memory_dir / rel + note = await index_written(ctx, path) if ctx.index.is_indexable(path) else "" + return f"File written: {resolved}{note}" + + +async def file_read(ctx: ToolContext, args: dict) -> str: + resolved = _resolve_safe(args["file_path"], ctx.config.memory_dir) + if resolved is None: + safe_root = ctx.config.memory_dir.resolve() + return f"Blocked: path is outside {safe_root} or is one of Memclaw's internal files." + if not resolved.exists(): + return f"File not found: {resolved}" + text = resolved.read_text() + logger.info(" → file_read: read {path} ({n} chars)", path=resolved, n=len(text)) + return text + + +TOOLS = [ + Tool(UPDATE_INSTRUCTIONS, update_instructions, "Updating my instructions"), + Tool(FILE_WRITE, file_write, "Writing", "file_path"), + Tool(FILE_READ, file_read, "Reading", "file_path"), +] diff --git a/memclaw/tools/images.py b/memclaw/tools/images.py new file mode 100644 index 0000000..185a80a --- /dev/null +++ b/memclaw/tools/images.py @@ -0,0 +1,144 @@ +"""Tools for images: save one with its description, find stored ones, and +queue them to be sent with the reply.""" + +from __future__ import annotations + +from typing import Any + +from loguru import logger + +from .context import Tool, ToolContext, index_written + +# image_search: how many candidates the agent chooses from, and how much of +# each description it sees. +_IMAGE_CANDIDATES = 5 +_IMAGE_DESCRIPTION_CHARS = 300 + +IMAGE_SAVE: dict[str, Any] = { + "name": "image_save", + "description": ( + "Save an image with your description so it can be retrieved later. " + "You MUST call this when you receive an image with a media_ref in " + "the prompt, or when the user shares a local image path. Describe " + "the image in detail and pass the media_ref verbatim." + ), + "input_schema": { + "type": "object", + "properties": { + "description": {"type": "string", "description": "Detailed image description"}, + "media_ref": { + "type": "string", + "description": "Opaque reference (file_id, local path, etc.) from the prompt", + }, + "caption": {"type": "string", "description": "Optional caption"}, + }, + "required": ["description", "media_ref"], + }, +} + +IMAGE_SEARCH: dict[str, Any] = { + "name": "image_search", + "description": ( + "Find previously stored images when the user asks to retrieve, show, " + "or send one. Returns the closest matches with their ids and " + "descriptions; nothing is sent. Then call image_send with the ids of " + "the images that are what the user asked for." + ), + "input_schema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Search query for images"}, + }, + "required": ["query"], + }, +} + +IMAGE_SEND: dict[str, Any] = { + "name": "image_send", + "description": ( + "Send stored images to the user, by the ids image_search returned. " + "Pass only the images that match the request (e.g. just the passport " + "when the user asks for their passport)." + ), + "input_schema": { + "type": "object", + "properties": { + "ids": { + "type": "array", + "items": {"type": "integer"}, + "description": "Image ids from image_search", + }, + }, + "required": ["ids"], + }, +} + + +async def image_save(ctx: ToolContext, args: dict) -> str: + description: str = args["description"] + media_ref: str = args["media_ref"] + caption: str = args.get("caption", "") + platform = ctx.platform or "local" + + combined = f"Image: {description}" + if caption: + combined += f" Caption: {caption}" + # Register the image first: it needs an embedding, and if that fails + # nothing has been written yet, so a retry doesn't save the note twice. + await ctx.index.store_platform_image( + platform=platform, + media_ref=media_ref, + description=combined, + caption=caption, + ) + store_path = ctx.store.save(combined, entry_type="image") + await index_written(ctx, store_path) + logger.info( + " → image_save({platform}) result: {desc}", + platform=platform, desc=description[:100], + ) + return f"Image saved: {description[:100]}" + + +async def image_search(ctx: ToolContext, args: dict) -> str: + # Only images saved on this platform can be sent back on it (a + # Telegram file_id means nothing to Slack). The terminal has no + # platform and can describe images from anywhere. + candidates = await ctx.search.search_images( + args["query"], limit=_IMAGE_CANDIDATES, platform=ctx.platform, + ) + logger.info(" → image_search result: {n} candidate(s)", n=len(candidates)) + if not candidates: + return "No matching images found." + lines = [] + for r in candidates: + description = " ".join(r["description"].split()) + if len(description) > _IMAGE_DESCRIPTION_CHARS: + description = description[:_IMAGE_DESCRIPTION_CHARS] + "…" + lines.append(f"- id {r['id']} (match {r['score']:.2f}): {description}") + return ( + "Closest stored images, best first (nothing sent yet):\n" + + "\n".join(lines) + + "\nCall image_send with the ids of the ones the user asked for." + ) + + +async def image_send(ctx: ToolContext, args: dict) -> str: + ids = [int(i) for i in args.get("ids") or []] + images = ctx.index.get_platform_images(ids, platform=ctx.platform) + queued = {img["id"] for img in ctx.found_images} + new = [img for img in images if img["id"] not in queued] + ctx.found_images.extend(new) + logger.info(" → image_send: {n} image(s) queued", n=len(new)) + missing = sorted(set(ids) - {img["id"] for img in images}) + note = f" No stored image with id {', '.join(map(str, missing))}." if missing else "" + if not images: + return "Nothing to send." + note + return f"Sending {len(images)} image(s) with your reply." + note + + +TOOLS = [ + Tool(IMAGE_SAVE, image_save, "Saving the image"), + Tool(IMAGE_SEARCH, image_search, "Searching images", "query"), + Tool(IMAGE_SEND, image_send, "Sending images"), +] diff --git a/memclaw/tools/memory.py b/memclaw/tools/memory.py new file mode 100644 index 0000000..48424f8 --- /dev/null +++ b/memclaw/tools/memory.py @@ -0,0 +1,98 @@ +"""Tools for the notes: save a memory, search them.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from loguru import logger + +from ..memory import SearchResult +from .context import Tool, ToolContext, index_written + +_MAX_SEARCH_RESULTS = 25 + +MEMORY_SAVE: dict[str, Any] = { + "name": "memory_save", + "description": ( + "Save a new memory, thought, or note — durable facts and preferences " + "included — to today's notes. MEMORY.md (permanent memory) is " + "distilled from the notes automatically once a day." + ), + "input_schema": { + "type": "object", + "properties": { + "content": {"type": "string", "description": "The content to save"}, + "entry_type": { + "type": "string", + "description": "Type of entry: note, image, link, voice", + }, + "tags": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional tags for categorization", + }, + }, + "required": ["content"], + }, +} + +MEMORY_SEARCH: dict[str, Any] = { + "name": "memory_search", + "description": "Search through stored memories using natural language", + "input_schema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Natural language search query"}, + "limit": { + "type": "integer", + "description": "Maximum number of results (default 10)", + }, + }, + "required": ["query"], + }, +} + + +def _format_results(results: list[SearchResult]) -> str: + parts = [] + for i, r in enumerate(results, 1): + source = Path(r.file_path).stem + if source == "MEMORY": + source = "permanent memory" + parts.append(f"**[{i}]** (score: {r.score:.2f}, source: {source})\n{r.content.strip()}") + return "\n\n---\n\n".join(parts) if parts else "No matching memories found." + + +async def memory_save(ctx: ToolContext, args: dict) -> str: + content: str = args["content"] + entry_type: str = args.get("entry_type", "note") + tags = args.get("tags") + # A "permanent" flag from an older session is ignored: MEMORY.md is + # written only by consolidation. + file_path = ctx.store.save(content, entry_type=entry_type, tags=tags) + logger.info(" → memory_save result: saved to {file}", file=file_path.name) + return f"Memory saved to {file_path.name}" + await index_written(ctx, file_path) + + +async def memory_search(ctx: ToolContext, args: dict) -> str: + try: + limit = max(1, min(int(args.get("limit") or 10), _MAX_SEARCH_RESULTS)) + except (TypeError, ValueError): + limit = 10 + results = await ctx.search.search(args["query"], limit=limit) + formatted = _format_results(results) + logger.info(" → memory_search result: {n} hits", n=len(results)) + for i, r in enumerate(results, 1): + source = Path(r.file_path).stem + snippet = r.content.strip().replace("\n", " ") + if len(snippet) > 120: + snippet = snippet[:120] + "..." + logger.info(" [{i}] ({score:.2f}, {src}) {snippet}", i=i, score=r.score, src=source, snippet=snippet) + return formatted + + +TOOLS = [ + Tool(MEMORY_SAVE, memory_save, "Saving to memory"), + Tool(MEMORY_SEARCH, memory_search, "Searching memories", "query"), +] diff --git a/memclaw/tools/reminders.py b/memclaw/tools/reminders.py new file mode 100644 index 0000000..7699ab0 --- /dev/null +++ b/memclaw/tools/reminders.py @@ -0,0 +1,168 @@ +"""Tools for reminders: schedule one, list them, cancel one. They only work +in a messaging bot, which runs the scheduler and has a chat to send to.""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +from loguru import logger + +from ..reminders import ReminderScheduler +from .context import Tool, ToolContext + +REMINDER_CREATE: dict[str, Any] = { + "name": "reminder_create", + "description": ( + "Schedule a reminder to be sent back to the user at a specific " + "local time, or on a recurring interval. Use when the user says " + "things like 'remind me tomorrow at 9am to call Alex' (one-shot) " + "or 'remind me every 5 hours to drink water' (recurring). " + "For recurring-only reminders without a user-specified start, " + "you may omit fire_at and the first fire will be interval_seconds " + "from now. Always convert the user's natural-language time to a " + "local ISO 8601 datetime using the current local time in the system " + "prompt as reference. Do NOT use this tool to store notes — use " + "memory_save for that." + ), + "input_schema": { + "type": "object", + "properties": { + "text": { + "type": "string", + "description": "What to remind the user about (short, in their own words)", + }, + "fire_at": { + "type": "string", + "description": ( + "Local ISO 8601 datetime for the first (or only) fire, " + "e.g. '2026-04-13T21:30:00'. Omit to start a recurring " + "reminder interval_seconds from now." + ), + }, + "interval_seconds": { + "type": "integer", + "description": ( + "If set, the reminder recurs every N seconds after " + "fire_at. Convert the user's unit to seconds (e.g. " + "'every 5 hours' -> 18000)." + ), + }, + }, + "required": ["text"], + }, +} + +REMINDER_LIST: dict[str, Any] = { + "name": "reminder_list", + "description": "List the user's pending reminders.", + "input_schema": {"type": "object", "properties": {}}, +} + +REMINDER_CANCEL: dict[str, Any] = { + "name": "reminder_cancel", + "description": ( + "Cancel a pending reminder by its id. Call reminder_list first if " + "the user refers to a reminder by description." + ), + "input_schema": { + "type": "object", + "properties": { + "id": {"type": "integer", "description": "Reminder id"}, + }, + "required": ["id"], + }, +} + + +def _reminder_chat(ctx: ToolContext) -> tuple[ReminderScheduler, str, str] | str: + """(scheduler, platform, chat_id) for this chat's reminders, or why + there are none here.""" + if ctx.scheduler is None: + return "Reminders are only available when running in a messaging bot (telegram/whatsapp/slack)." + if not ctx.platform or not ctx.chat_id: + return "Reminders require a messaging context (missing platform/chat_id)." + return ctx.scheduler, ctx.platform, ctx.chat_id + + +def _first_fire(fire_at_str: str | None, interval: int | None) -> datetime | str: + """When the reminder first fires (local time), or why it can't be set.""" + if fire_at_str: + try: + fire_at = datetime.fromisoformat(fire_at_str) + except ValueError: + return f"Invalid fire_at: {fire_at_str!r}. Use local ISO 8601." + if fire_at.tzinfo is not None: + fire_at = fire_at.astimezone().replace(tzinfo=None) + return fire_at + if interval: + return datetime.now() + timedelta(seconds=interval) + return "Provide either fire_at or interval_seconds (or both)." + + +async def reminder_create(ctx: ToolContext, args: dict) -> str: + chat = _reminder_chat(ctx) + if isinstance(chat, str): + return chat + scheduler, platform, chat_id = chat + + text: str = args["text"].strip() + interval: int | None = args.get("interval_seconds") + fire_at = _first_fire(args.get("fire_at"), interval) + if isinstance(fire_at, str): + return fire_at + + if interval is not None and interval < 60: + return "interval_seconds must be at least 60." + + rid = scheduler.create( + platform=platform, + chat_id=chat_id, + text=text, + fire_at=fire_at, + interval_seconds=interval, + ) + logger.info( + " → reminder_create: id={id} fire_at={f} every={i}s", + id=rid, f=fire_at.isoformat(), i=interval, + ) + if interval: + return ( + f"Reminder #{rid} scheduled for {fire_at.isoformat(timespec='minutes')} " + f"and every {interval} seconds after." + ) + return f"Reminder #{rid} scheduled for {fire_at.isoformat(timespec='minutes')}." + + +async def reminder_list(ctx: ToolContext, args: dict) -> str: + chat = _reminder_chat(ctx) + if isinstance(chat, str): + return chat + scheduler, platform, chat_id = chat + items = scheduler.list_for(platform, chat_id) + if not items: + return "No pending reminders." + lines = [] + for it in items: + line = f"#{it['id']} at {it['fire_at']}: {it['text']}" + if it["interval_seconds"]: + line += f" (every {it['interval_seconds']}s)" + lines.append(line) + return "\n".join(lines) + + +async def reminder_cancel(ctx: ToolContext, args: dict) -> str: + chat = _reminder_chat(ctx) + if isinstance(chat, str): + return chat + scheduler, platform, chat_id = chat + rid = int(args["id"]) + ok = scheduler.cancel(rid, platform=platform, chat_id=chat_id) + return f"Reminder #{rid} cancelled." if ok else f"No pending reminder #{rid}." + + +TOOLS = [ + Tool(REMINDER_CREATE, reminder_create, "Setting a reminder", "text"), + Tool(REMINDER_LIST, reminder_list, "Checking reminders"), + Tool(REMINDER_CANCEL, reminder_cancel, "Cancelling a reminder"), +] diff --git a/pyproject.toml b/pyproject.toml index 4b8a677..95864aa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -148,7 +148,7 @@ ignore_names = [ "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/memory/index.py" } -"agent tools" = { terms = ["TOOL_DEFINITIONS", "ToolExecutor"], home = "memclaw/tools.py" } +"agent tools" = { terms = ["TOOL_DEFINITIONS", "ToolExecutor"], home = "memclaw/tools/catalog.py" } "conversations / sessions" = { terms = ["SessionStore", "session_key", "reset_session"], home = "memclaw/sessions.py" } "setup wizard" = { terms = ["run_setup", "wizard", "needs_setup"], home = "memclaw/setup/wizard.py" } "links" = { terms = ["LinkProcessor", "process_links"], home = "memclaw/bot/links.py" } @@ -285,6 +285,21 @@ layers = [ # A new module inside memclaw.memory must be placed in a layer above. exhaustive = true +[[tool.importlinter.contracts]] +id = "tools-via-package" +name = "Only memclaw.tools imports its own modules: everyone else uses what memclaw.tools exports (TOOL_DEFINITIONS, ToolExecutor, ToolContext, describe_tool_call)" +type = "protected" +protected_modules = [ + "memclaw.tools.catalog", + "memclaw.tools.context", + "memclaw.tools.executor", + "memclaw.tools.files", + "memclaw.tools.images", + "memclaw.tools.memory", + "memclaw.tools.reminders", +] +allowed_importers = ["memclaw.tools"] + [[tool.importlinter.contracts]] id = "setup-via-package" name = "Only memclaw.setup imports its own modules: everyone else uses what memclaw.setup exports (run_setup, needs_setup, print_logo, run_doctor)" @@ -304,11 +319,9 @@ id = "backend-internals-private" name = "Only memclaw.backends itself imports the concrete backends (everyone else goes through memclaw.backends / memclaw.backends.base)" type = "protected" protected_modules = [ + # Packages: their modules are protected with them. "memclaw.backends.claude", - "memclaw.backends.claude_models", "memclaw.backends.cursor", - "memclaw.backends.cursor_hooks", - "memclaw.backends.cursor_sdk_adapter", "memclaw.backends.mcp_bridge", "memclaw.backends.mcp_tools", "memclaw.backends.model_selection", diff --git a/tests/backends/test_claude.py b/tests/backends/test_claude.py index bc033b4..7160afc 100644 --- a/tests/backends/test_claude.py +++ b/tests/backends/test_claude.py @@ -7,12 +7,18 @@ import httpx import pytest -from memclaw.backends import claude as claude_backend +from memclaw.backends.claude import cli as claude_cli +from memclaw.backends.claude import configure as claude_configure +from memclaw.backends.claude import cost as claude_cost +from memclaw.backends.claude import settings as claude_settings from memclaw.backends.base import TurnRequest from memclaw.backends.claude import ClaudeAgentBackend from memclaw.backends.model_selection import ModelInfo from memclaw.config import ClaudeSettings +# Where the backend looks ClaudeSDKClient up. +_SDK_CLIENT = "memclaw.backends.claude.cli.ClaudeSDKClient" + # ──────────────────────────────────────────────────────────────────── # Helpers @@ -87,19 +93,19 @@ def _model_info(model_id: str, *, effort_levels: list[str] | None = None): class TestAuthMode: def test_subscription_when_oauth_set(self, claude_config): cfg = claude_config(oauth="oauth-token") - assert claude_backend._claude_auth_mode(cfg) == "subscription" + assert claude_settings.claude_auth_mode(cfg) == "subscription" def test_api_key_when_only_api_key_set(self, claude_config): cfg = claude_config(api_key="sk-ant-test") - assert claude_backend._claude_auth_mode(cfg) == "api_key" + assert claude_settings.claude_auth_mode(cfg) == "api_key" def test_oauth_wins_when_both_set(self, claude_config): cfg = claude_config(oauth="oauth-token", api_key="sk-ant-test") - assert claude_backend._claude_auth_mode(cfg) == "subscription" + assert claude_settings.claude_auth_mode(cfg) == "subscription" def test_empty_when_neither_set(self, claude_config): cfg = claude_config() - assert claude_backend._claude_auth_mode(cfg) == "" + assert claude_settings.claude_auth_mode(cfg) == "" def test_bills_per_token_only_for_api_key(self, claude_config): sub = ClaudeAgentBackend(claude_config(oauth="oauth-token")) @@ -118,7 +124,7 @@ def test_strips_stale_credentials(self, claude_config): "CLAUDE_CODE_USE_BEDROCK": "1", "PATH": "/usr/bin", }, clear=True): - env = claude_backend._build_env(cfg) + env = claude_settings.build_env(cfg) # Stale credentials are dropped; the chosen one is set. assert "ANTHROPIC_API_KEY" not in env @@ -131,14 +137,14 @@ def test_strips_stale_credentials(self, claude_config): def test_injects_api_key_when_configured(self, claude_config): cfg = claude_config(api_key="my-api-key") with patch.dict(os.environ, {}, clear=True): - env = claude_backend._build_env(cfg) + env = claude_settings.build_env(cfg) assert env["ANTHROPIC_API_KEY"] == "my-api-key" assert "CLAUDE_CODE_OAUTH_TOKEN" not in env def test_no_credential_injected_when_unconfigured(self, claude_config): cfg = claude_config() with patch.dict(os.environ, {}, clear=True): - env = claude_backend._build_env(cfg) + env = claude_settings.build_env(cfg) assert "ANTHROPIC_API_KEY" not in env assert "CLAUDE_CODE_OAUTH_TOKEN" not in env @@ -167,7 +173,7 @@ class TestRunOneShot: async def test_returns_text(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) ctx_factory, client = _mock_sdk_client("hello world") - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=ctx_factory): + with patch(_SDK_CLIENT, side_effect=ctx_factory): text = await backend.run_one_shot( system_prompt="be nice", user_message="hi", ) @@ -184,7 +190,7 @@ async def test_api_error_text_raises(self, claude_config): ctx_factory, _client = _mock_sdk_client( "API Error: Connection refused", error="unknown", is_error=True, ) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=ctx_factory): + with patch(_SDK_CLIENT, side_effect=ctx_factory): with pytest.raises(RuntimeError, match="Connection refused"): await backend.run_one_shot(system_prompt="s", user_message="u") @@ -192,18 +198,18 @@ async def test_api_error_text_raises(self, claude_config): async def test_error_result_raises(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) ctx_factory, _client = _mock_sdk_client("partial", is_error=True) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=ctx_factory): + with patch(_SDK_CLIENT, side_effect=ctx_factory): with pytest.raises(RuntimeError): await backend.run_one_shot(system_prompt="s", user_message="u") def _executor(cfg): - from memclaw.tools import ToolExecutor + from memclaw.tools import ToolContext, ToolExecutor - return ToolExecutor( + return ToolExecutor(ToolContext( config=cfg, store=MagicMock(), index=MagicMock(), search=MagicMock(), found_images=[], platform="test", - ) + )) class _FakeClients: @@ -249,7 +255,7 @@ class TestRunTurn: async def test_returns_turn_result(self, claude_config): backend = ClaudeAgentBackend(claude_config(api_key="x")) fake = _FakeClients("done", session_id="sess-1") - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): result = await _turn(backend, _executor(backend.config)) assert result.text == "done" @@ -266,7 +272,7 @@ async def test_fallback_cost_uses_the_configured_models_price(self, claude_confi cfg = claude_config(api_key="x") cfg.claude.model = "claude-opus-5" backend = ClaudeAgentBackend(cfg) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=_FakeClients()): + with patch(_SDK_CLIENT, side_effect=_FakeClients()): result = await _turn(backend, _executor(cfg)) # 100 input tokens at $5/M + 50 output tokens at $25/M (Opus 5). @@ -277,7 +283,7 @@ async def test_cost_is_per_turn_not_the_session_running_total(self, claude_confi backend = ClaudeAgentBackend(claude_config(api_key="x")) fake = _FakeClients(costs=[0.01, 0.025]) executor = _executor(backend.config) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): first = await _turn(backend, executor) second = await _turn(backend, executor, resume="sess-1") @@ -290,17 +296,17 @@ async def test_resumed_session_without_baseline_estimates_cost(self, claude_conf # token-based estimate is used instead. backend = ClaudeAgentBackend(claude_config(api_key="x")) fake = _FakeClients(costs=[5.0]) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): result = await _turn(backend, _executor(backend.config), resume="sess-1") - input_per_m, output_per_m = claude_backend._prices_per_m(backend.model) + input_per_m, output_per_m = claude_cost._prices_per_m(backend.model) assert result.cost_usd == pytest.approx((100 * input_per_m + 50 * output_per_m) / 1_000_000) @pytest.mark.asyncio async def test_session_options_are_locked_down(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, _executor(backend.config), max_turns=7) options = fake.options[0] @@ -309,7 +315,7 @@ async def test_session_options_are_locked_down(self, claude_config): assert options.tools == [] assert options.permission_mode == "dontAsk" assert options.verbatim_prompts is True - assert options.allowed_tools == claude_backend._ALLOWED_TOOLS + assert options.allowed_tools == claude_cli.ALLOWED_TOOLS assert all(t.startswith("mcp__memclaw__") for t in options.allowed_tools) assert options.disallowed_tools == [] assert options.system_prompt == "sys" @@ -321,7 +327,7 @@ async def test_session_options_are_locked_down(self, claude_config): async def test_context_block_is_prefixed_to_the_message(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, _executor(backend.config), context="ctx", message="hi there") @@ -332,7 +338,7 @@ async def test_context_block_is_prefixed_to_the_message(self, claude_config): async def test_image_turn_streams_context_in_the_text_part(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, _executor(backend.config), context="ctx", message="a photo", image_b64="aGVsbG8=", image_media_type="image/png") @@ -352,7 +358,7 @@ async def test_client_is_reused_across_turns(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() executor = _executor(backend.config) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, executor, message="one") await _turn(backend, executor, message="two", resume="sess-1") @@ -367,7 +373,7 @@ async def test_each_chat_gets_its_own_client(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() executor = _executor(backend.config) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, executor, key="telegram:1") await _turn(backend, executor, key="telegram:2") assert len(fake.clients) == 2 @@ -376,7 +382,7 @@ async def test_each_chat_gets_its_own_client(self, claude_config): async def test_resume_id_reaches_the_cli(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, _executor(backend.config), resume="old-session") assert fake.options[0].resume == "old-session" @@ -384,7 +390,7 @@ async def test_resume_id_reaches_the_cli(self, claude_config): async def test_failed_resume_falls_back_to_a_fresh_session(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients("fresh", session_id="new-session", fail_resume=True) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): result = await _turn(backend, _executor(backend.config), resume="gone") assert [o.resume for o in fake.options] == ["gone", None] @@ -396,7 +402,7 @@ async def test_reset_session_closes_the_client(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() executor = _executor(backend.config) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, executor) await backend.reset_session("telegram:1") fake.clients[0].disconnect.assert_awaited_once() @@ -415,7 +421,7 @@ async def test_failed_turn_drops_the_client_so_the_next_one_resumes(self, claude backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() executor = _executor(backend.config) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, executor) fake.clients[0].query = AsyncMock(side_effect=RuntimeError("CLI died")) with pytest.raises(RuntimeError): @@ -435,7 +441,7 @@ async def test_model_change_reconnects_resuming_the_session( backend._models = [_model_info("claude-opus-5", effort_levels=["low", "medium"])] fake = _FakeClients() executor = _executor(backend.config) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, executor) await backend.set_model("claude-opus-5") # The live client is only replaced on the next turn. @@ -452,7 +458,7 @@ async def test_shutdown_closes_every_client(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="x")) fake = _FakeClients() executor = _executor(backend.config) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, executor, key="a") await _turn(backend, executor, key="b") await backend.on_agent_shutdown() @@ -485,7 +491,7 @@ def _backend(self, claude_config, effort="high"): async def test_list_models_uses_the_configured_credential(self, claude_config): backend = ClaudeAgentBackend(claude_config(oauth="tok")) fetch = AsyncMock(return_value=self.MODELS) - with patch("memclaw.backends.claude.fetch_models", fetch): + with patch("memclaw.backends.claude.backend.fetch_models", fetch): assert await backend.list_models() == self.MODELS fetch.assert_awaited_once_with("subscription", "tok") @@ -539,7 +545,7 @@ async def test_switch_is_refused_when_the_list_is_unavailable( is fixed by hand, so nothing is switched or saved.""" backend = self._backend(claude_config) before = backend.model, backend.effort - with patch("memclaw.backends.claude.fetch_models", + with patch("memclaw.backends.claude.backend.fetch_models", AsyncMock(side_effect=httpx.ConnectError("offline"))): with pytest.raises(ValueError, match="Couldn't load the model list"): await backend.set_model("claude-opsu-5") @@ -582,12 +588,12 @@ class TestPrices: ("claude-haiku-4-5-20251001", (1.0, 5.0)), # dated snapshot ]) def test_known_models(self, model, prices): - assert claude_backend._prices_per_m(model) == prices + assert claude_cost._prices_per_m(model) == prices @pytest.mark.parametrize("model", ["opus", "claude-future-9"]) def test_unknown_model_uses_the_default_models_price(self, model): - assert claude_backend._prices_per_m(model) == claude_backend._prices_per_m( - claude_backend._DEFAULT_MODEL, + assert claude_cost._prices_per_m(model) == claude_cost._prices_per_m( + claude_settings.DEFAULT_MODEL, ) @@ -598,59 +604,59 @@ def test_unknown_model_uses_the_default_models_price(self, model): class TestResolveModel: def test_falls_back_to_default_when_unset(self, claude_config): cfg = claude_config(oauth="x") - assert claude_backend._resolve_model(cfg) == claude_backend._DEFAULT_MODEL + assert claude_settings.resolve_model(cfg) == claude_settings.DEFAULT_MODEL def test_configured_model_wins(self, claude_config): cfg = claude_config(oauth="x") cfg.claude.model = "claude-opus-5" - assert claude_backend._resolve_model(cfg) == "claude-opus-5" + assert claude_settings.resolve_model(cfg) == "claude-opus-5" def test_blank_value_falls_back(self, claude_config): cfg = claude_config(oauth="x") cfg.claude.model = " " - assert claude_backend._resolve_model(cfg) == claude_backend._DEFAULT_MODEL + assert claude_settings.resolve_model(cfg) == claude_settings.DEFAULT_MODEL class TestResolveEffort: def test_unset_gives_the_default_on_the_default_model(self, claude_config): cfg = claude_config(oauth="x") - assert claude_backend._resolve_effort(cfg) == claude_backend._DEFAULT_EFFORT == "medium" + assert claude_settings.resolve_effort(cfg) == claude_settings.DEFAULT_EFFORT == "medium" def test_unset_gives_none_on_another_model(self, claude_config): """Another model may not take an effort at all, so leave it to the model.""" cfg = claude_config(oauth="x") cfg.claude.model = "claude-haiku-4-5" - assert claude_backend._resolve_effort(cfg) is None + assert claude_settings.resolve_effort(cfg) is None def test_known_level_passes_through(self, claude_config): cfg = claude_config(oauth="x") cfg.claude.effort = "xhigh" - assert claude_backend._resolve_effort(cfg) == "xhigh" + assert claude_settings.resolve_effort(cfg) == "xhigh" def test_case_and_padding_are_normalised(self, claude_config): cfg = claude_config(oauth="x") cfg.claude.effort = " HIGH " - assert claude_backend._resolve_effort(cfg) == "high" + assert claude_settings.resolve_effort(cfg) == "high" def test_level_the_sdk_does_not_know_is_ignored(self, claude_config): """A typo in ~/.memclaw/.env must not reach the CLI as an argument.""" cfg = claude_config(oauth="x") cfg.claude.model = "claude-opus-5" cfg.claude.effort = "ultra" - assert claude_backend._resolve_effort(cfg) is None + assert claude_settings.resolve_effort(cfg) is None class TestConsolidationEffort: def test_other_model_without_effort_gets_none(self, claude_config): cfg = claude_config(oauth="x") cfg.claude.consolidation_model = "claude-haiku-4-5" - assert claude_backend._resolve_consolidation(cfg) == ("claude-haiku-4-5", None) + assert claude_settings.resolve_consolidation(cfg) == ("claude-haiku-4-5", None) def test_configured_effort_is_used_on_any_model(self, claude_config): cfg = claude_config(oauth="x") cfg.claude.consolidation_model = "claude-sonnet-5-5" cfg.claude.consolidation_effort = "high" - assert claude_backend._resolve_consolidation(cfg) == ("claude-sonnet-5-5", "high") + assert claude_settings.resolve_consolidation(cfg) == ("claude-sonnet-5-5", "high") class TestStatusRows: @@ -687,7 +693,7 @@ def _capture(options, *args, **kwargs): seen["options"] = options return ctx_factory() - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=_capture): + with patch(_SDK_CLIENT, side_effect=_capture): await backend.run_one_shot(system_prompt="s", user_message="u") assert seen["options"].model == "claude-opus-5" @@ -707,7 +713,7 @@ def _capture(options, *args, **kwargs): seen["options"] = options return ctx_factory() - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=_capture): + with patch(_SDK_CLIENT, side_effect=_capture): await backend.run_one_shot(system_prompt="s", user_message="u") assert seen["options"].model == "claude-opus-5-5" @@ -724,7 +730,7 @@ def _capture(options, *args, **kwargs): seen["options"] = options return ctx_factory() - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=_capture): + with patch(_SDK_CLIENT, side_effect=_capture): await backend.run_one_shot(system_prompt="s", user_message="u") options = seen["options"] @@ -754,9 +760,9 @@ def _prompt(text, **kwargs): prompts.append({"text": text, **kwargs}) return answers[len(prompts) - 1] - with patch("memclaw.backends.claude.fetch_models", fetch), \ + with patch("memclaw.backends.claude.configure.fetch_models", fetch), \ patch("memclaw.terminal_input.Prompt.ask", side_effect=_prompt): - values, drops = ClaudeAgentBackend._ask_model_and_effort( + values, drops = claude_configure.ask_model_and_effort( console, existing or {}, auth_mode="api_key", credential="sk-ant-test", settings=ClaudeSettings(), # loads CLAUDE_MODEL / CLAUDE_EFFORT from the shell ) @@ -900,8 +906,8 @@ def _wizard(*, answers, credential="", existing=None, models=None, with patch("memclaw.terminal_input.Prompt.ask", side_effect=lambda *a, **k: next(answer_iter)), \ - patch("memclaw.backends.claude.masked_input", return_value=credential), \ - patch("memclaw.backends.claude.fetch_models", fetch): + patch("memclaw.backends.claude.configure.masked_input", return_value=credential), \ + patch("memclaw.backends.claude.configure.fetch_models", fetch): values, drops = ClaudeAgentBackend.wizard_setup( MagicMock(), existing or {}, config=MagicMock(claude=ClaudeSettings()), ) @@ -968,7 +974,7 @@ async def test_each_tool_call_is_reported(self, claude_config): async def on_tool(step): steps.append(step) - with patch("memclaw.backends.claude.ClaudeSDKClient", side_effect=fake): + with patch(_SDK_CLIENT, side_effect=fake): await _turn(backend, _executor(backend.config)) # builds the client client = fake.clients[0] original = client.receive_response.side_effect @@ -1001,3 +1007,135 @@ async def broken(step): raise RuntimeError("telegram down") await report_tool_step(broken, 1, "memory_save", {}) # no exception + + +class _ScriptedClient: + """A connected client that answers every query with *messages*.""" + + def __init__(self, messages): + self.messages = messages + self.queries: list = [] + + async def connect(self): + pass + + async def disconnect(self): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return None + + async def query(self, prompt): + self.queries.append(prompt) + + def receive_response(self): + async def _gen(): + for msg in self.messages: + yield msg + return _gen() + + +def _result_message(**kw): + from claude_agent_sdk import ResultMessage + + fields = dict(subtype="success", duration_ms=1, duration_api_ms=1, is_error=False, + num_turns=3, session_id="s-9", total_cost_usd=None, usage=None, result=None) + fields.update(kw) + return ResultMessage(**fields) + + +def _logged(): + from loguru import logger + + lines: list[str] = [] + sink = logger.add(lambda m: lines.append(f"{m.record['level'].name} {m.record['message']}"), + filter=lambda r: r["level"].name != "DEBUG") + return lines, lambda: logger.remove(sink) + + +class TestReplyReading: + """How the CLI's messages become a turn's result or a one-shot answer.""" + + @pytest.mark.asyncio + async def test_turn_reply(self, claude_config): + from claude_agent_sdk import AssistantMessage, TextBlock, ToolUseBlock + + messages = [ + AssistantMessage(content=[ + TextBlock(text="Let me "), TextBlock(text="check."), + ToolUseBlock(id="1", name="mcp__memclaw__file_read", input={"file_path": "x" * 400}), + ToolUseBlock(id="2", name="OtherTool", input={}), + ], model="m"), + AssistantMessage(content=[], model="m"), + _result_message( + total_cost_usd=0.5, result="the result text", + usage={"input_tokens": 7, "output_tokens": None, "cache_read_input_tokens": 3}, + ), + ] + client = _ScriptedClient(messages) + backend = ClaudeAgentBackend(claude_config(oauth="x")) + steps = [] + + async def on_tool(step): + steps.append((step.index, step.name, step.summary)) + + lines, stop = _logged() + try: + with patch(_SDK_CLIENT, return_value=client): + result = await _turn(backend, _executor(backend.config), on_tool=on_tool) + finally: + stop() + assert client.queries == ["now\n\nhello"] + assert (result.text, result.session_id, result.num_turns) == ("Let me check.", "s-9", 3) + assert (result.input_tokens, result.output_tokens) == (7, 0) + assert (result.cache_read_tokens, result.cache_creation_tokens) == (3, 0) + assert result.cost_usd == 0.5 + assert steps == [(1, "file_read", "Reading: " + "x" * 79 + "…"), (2, "OtherTool", "OtherTool")] + args = ('{"file_path": "' + "x" * 400)[:300] + "..." + assert lines == [f"INFO Tool call: file_read({args})", "INFO Tool call: OtherTool({})"] + + @pytest.mark.asyncio + async def test_turn_reply_falls_back_to_the_result_text(self, claude_config): + client = _ScriptedClient([_result_message(session_id="", result="only here")]) + backend = ClaudeAgentBackend(claude_config(oauth="x")) + with patch(_SDK_CLIENT, return_value=client): + result = await _turn(backend, _executor(backend.config)) + assert (result.text, result.session_id, result.input_tokens) == ("only here", None, 0) + + @pytest.mark.asyncio + async def test_one_shot_answer(self, claude_config): + from claude_agent_sdk import AssistantMessage, TextBlock + + backend = ClaudeAgentBackend(claude_config(oauth="x")) + client = _ScriptedClient([ + AssistantMessage(content=[TextBlock(text="a")], model="m"), + AssistantMessage(content=[TextBlock(text="b")], model="m"), + _result_message(result="ignored"), + ]) + with patch(_SDK_CLIENT, return_value=client): + assert await backend.run_one_shot(system_prompt="s", user_message="u") == "ab" + client = _ScriptedClient([_result_message(result="from result")]) + with patch(_SDK_CLIENT, return_value=client): + assert await backend.run_one_shot(system_prompt="s", user_message="u") == "from result" + + @pytest.mark.asyncio + async def test_one_shot_errors(self, claude_config): + from claude_agent_sdk import AssistantMessage, TextBlock + + backend = ClaudeAgentBackend(claude_config(oauth="x")) + client = _ScriptedClient([ + AssistantMessage(content=[TextBlock(text="E" * 300)], model="m", error="rate_limit"), + _result_message(is_error=True, subtype="error_during_execution"), + ]) + with patch(_SDK_CLIENT, return_value=client): + with pytest.raises(RuntimeError) as err: + await backend.run_one_shot(system_prompt="s", user_message="u") + assert str(err.value) == f"Claude one-shot failed (rate_limit): {'E' * 200}" + client = _ScriptedClient([_result_message(is_error=True, subtype="error_max_turns")]) + with patch(_SDK_CLIENT, return_value=client): + with pytest.raises(RuntimeError) as err: + await backend.run_one_shot(system_prompt="s", user_message="u") + assert str(err.value) == "Claude one-shot failed (error_max_turns): " diff --git a/tests/backends/test_claude_models.py b/tests/backends/test_claude_models.py index f76a242..73f1202 100644 --- a/tests/backends/test_claude_models.py +++ b/tests/backends/test_claude_models.py @@ -9,8 +9,8 @@ import httpx import pytest -from memclaw.backends import claude_models -from memclaw.backends.claude_models import fetch_models +from memclaw.backends.claude import models as claude_models +from memclaw.backends.claude.models import fetch_models # ──────────────────────────────────────────────────────────────────── @@ -60,7 +60,7 @@ async def _get(url, headers=None, params=None): ctx.__aenter__ = AsyncMock(return_value=client) ctx.__aexit__ = AsyncMock(return_value=None) - return patch("memclaw.backends.claude_models.httpx.AsyncClient", + return patch("memclaw.backends.claude.models.httpx.AsyncClient", MagicMock(return_value=ctx)) @@ -247,3 +247,12 @@ async def test_every_call_fetches_fresh(self): assert len(calls) == 2 assert calls[1]["headers"]["Authorization"] == "Bearer second-token" + + +class TestSdkEffort: + def test_known_levels_pass_through(self): + for level in claude_models.SDK_EFFORT_LEVELS: + assert claude_models.sdk_effort(level) == level + + def test_none_stays_none(self): + assert claude_models.sdk_effort(None) is None diff --git a/tests/backends/test_cursor.py b/tests/backends/test_cursor.py index 69644c4..ddbc091 100644 --- a/tests/backends/test_cursor.py +++ b/tests/backends/test_cursor.py @@ -20,13 +20,14 @@ from memclaw.backends.base import TurnRequest, TurnResult from memclaw.backends import REGISTRY, get_backend_class -from memclaw.backends.cursor import ( - CursorAgentBackend, - _agent_options, - _build_combined_prompt, - _build_user_message, +from memclaw.backends.cursor import CursorAgentBackend +from memclaw.backends.cursor.agents import ( + ChatAgent, + agent_options, + build_combined_prompt, + build_user_message, ) -from memclaw.backends.cursor_sdk_adapter import ( +from memclaw.backends.cursor.sdk_adapter import ( RunUsageTracker, accumulate_usage, assistant_message_text, @@ -36,7 +37,7 @@ record_interaction_usage, ) from memclaw.backends.mcp_bridge import HttpMcpServer -from memclaw.backends.cursor_hooks import cursor_hooks_installed +from memclaw.backends.cursor.hooks import cursor_hooks_installed from memclaw.config import ClaudeSettings, CursorSettings, MemclawConfig, OpenAISettings @@ -121,7 +122,7 @@ def test_status_rows_fall_back_to_default_model(self, tmp_path): class TestPromptBuilding: def test_agent_options_loads_project_setting_sources(self): - options = _agent_options( + options = agent_options( api_key="test", cwd="/tmp/memclaw", model="composer-2.5", @@ -146,7 +147,7 @@ def test_normalize_tool_call_strips_memclaw_prefix(self): assert args == {"file_path": "x.md"} def test_combined_prompt_includes_system_and_user(self): - prompt = _build_combined_prompt( + prompt = build_combined_prompt( system_prompt="You are Memclaw.", user_message="Hello", ) @@ -155,19 +156,19 @@ def test_combined_prompt_includes_system_and_user(self): assert "---" in prompt def test_follow_up_message_has_no_system_prompt(self): - message = _build_user_message( + message = build_user_message( system_prompt="", context="c", user_message="Hi", ) assert message == "c\n\nHi" def test_image_uses_sdk_image(self): - message = _build_user_message( + message = build_user_message( system_prompt="Sys", user_message="Look at this", image_b64="abc123", image_media_type="image/png", ) - assert message.text == _build_combined_prompt( + assert message.text == build_combined_prompt( system_prompt="Sys", user_message="Look at this", ) @@ -298,6 +299,88 @@ async def test_collect_run_result_reads_turn_ended_usage(self): assert result.output_tokens == 50 assert result.num_turns == 1 + @staticmethod + def _run(events, wait): + async def _events(): + for event in events: + yield event + + run = AsyncMock() + run.events = MagicMock(return_value=_events()) + run.wait = AsyncMock(return_value=wait) + return run + + @staticmethod + def _logs(): + from loguru import logger + + lines: list[str] = [] + sink = logger.add(lambda m: lines.append(f"{m.record['level'].name} {m.record['message']}")) + return lines, sink + + @pytest.mark.asyncio + async def test_collect_run_result_logs_and_counts(self): + from loguru import logger + + def _msg(**kw): + return SimpleNamespace(sdk_message=SimpleNamespace(**kw)) + + def _assistant(text): + return _msg(type="assistant", message=SimpleNamespace( + content=[SimpleNamespace(type="text", text=text)], + )) + + events = [ + SimpleNamespace(sdk_message=None), + _assistant("A long first answer"), + _msg(type="tool_call", status="running", name="memclaw_file_read", + args={"file_path": "x" * 400}, call_id="c1"), + _msg(type="tool_call", status="error", name="memclaw_file_read", + args=None, call_id="c1", result={"why": "nope"}), + _msg(type="tool_call", status="running", name="Shell", args=None, call_id=""), + _msg(type="tool_call", status="weird", name="memclaw_x", args=None, call_id="c3"), + _msg(type="tool_call", status="completed", name="memclaw_y", args={}, call_id="c4", + result=None), + _assistant(""), + _msg(type="other"), + ] + tracker = RunUsageTracker() + for _ in range(3): + tracker.on_delta(SimpleNamespace(type="turn-ended", usage={"output_tokens": 1})) + lines, sink = self._logs() + try: + result = await collect_run_result( + self._run(events, SimpleNamespace(result="short", num_turns=2)), + max_turns=2, usage_tracker=tracker, + ) + finally: + logger.remove(sink) + assert result.text == "A long first answer" + assert result.num_turns == 3 + assert result.output_tokens == 3 + assert lines == [ + "INFO Tool call: file_read(" + ('{"file_path": "' + "x" * 400)[:300] + "...)", + 'WARNING Tool file_read failed: {"why": "nope"}', + "INFO Tool call: Shell({})", + "WARNING Tool x unexpected status 'weird'", + "INFO Tool y completed: (ok)", + "WARNING Tool Shell started but never completed (call_id=Shell). " + "It may have been blocked by a Cursor hook or failed before MCP execution.", + "WARNING Cursor SDK reported 3 turns (Memclaw max_turns=2); " + "the SDK does not expose a turn cap — tighten prompts or hooks if needed.", + ] + + @pytest.mark.asyncio + async def test_collect_run_result_falls_back_to_wait_text(self): + result = await collect_run_result( + self._run([], SimpleNamespace(result="", num_turns=0)), max_turns=10, + ) + assert (result.text, result.num_turns) == ("", 1) + result = await collect_run_result( + self._run([], SimpleNamespace(output="from wait", num_turns=4)), max_turns=10, + ) + assert (result.text, result.num_turns) == ("from wait", 4) + def test_record_interaction_usage_falls_back_to_token_delta(self): totals = { "input_tokens": 0, @@ -356,7 +439,7 @@ def _make_client(*, create=None, resume=None, process=None): def _patched(backend, *clients): """Run *backend* against mock bridge clients (one per launch) and a stub MCP server.""" with patch.object( - backend, "_launch_client", new_callable=AsyncMock, side_effect=list(clients), + backend._bridge, "launch", new_callable=AsyncMock, side_effect=list(clients), ) as launch, patch.object( backend, "_ensure_mcp_server", new_callable=AsyncMock ), patch.object( @@ -434,7 +517,7 @@ async def test_launch_runs_bridge_in_memory_dir(self, tmp_path): "cursor_sdk.AsyncClient.launch_bridge", new_callable=AsyncMock, return_value=MagicMock(_owned_bridge=None), ) as launch: - await backend._launch_client() + await backend._bridge.launch() argv = launch.await_args.args[0] assert argv[:2] == ["/bin/sh", "-c"] assert argv[3] == backend._cwd @@ -611,7 +694,7 @@ async def test_shutdown_closes_agents_and_bridge(self, tmp_path): agent.close.assert_awaited_once() client.aclose.assert_awaited_once() stop_mcp.assert_awaited_once() - assert backend._client is None + assert backend._bridge.client is None @pytest.mark.asyncio async def test_run_turn_applies_cost_fallback(self, tmp_path): @@ -679,6 +762,31 @@ async def test_agent_start_starts_mcp_server(self, tmp_path, monkeypatch): mock_stop.assert_awaited_once() +class TestAgentStartHooks: + @staticmethod + async def _start(backend): + from loguru import logger + + lines: list[str] = [] + sink = logger.add(lambda m: lines.append(f"{m.record['level'].name} {m.record['message']}")) + try: + with patch.object(backend, "_ensure_mcp_server", new_callable=AsyncMock): + await backend.on_agent_start(MagicMock()) + finally: + logger.remove(sink) + return lines + + @pytest.mark.asyncio + async def test_installs_the_hooks_and_logs_their_status(self, tmp_path): + backend = _backend(tmp_path) + lines = await self._start(backend) + assert cursor_hooks_installed(backend.config.memory_dir) + assert lines == [ + "INFO Cursor tool-restriction hooks: ready (memclaw MCP provider='memclaw', " + "setting_sources=project)", + ] + + class TestBridgeRobustness: @pytest.mark.asyncio async def test_dead_bridge_is_relaunched_before_the_next_call(self, tmp_path): @@ -686,54 +794,52 @@ async def test_dead_bridge_is_relaunched_before_the_next_call(self, tmp_path): dead = _make_client(process=MagicMock(returncode=1)) fresh = _make_client() with patch.object( - backend, "_launch_client", new_callable=AsyncMock, side_effect=[dead, fresh], + backend._bridge, "launch", new_callable=AsyncMock, side_effect=[dead, fresh], ): - assert await backend._get_client() is dead - assert await backend._get_client() is fresh + assert await backend._bridge.get() is dead + assert await backend._bridge.get() is fresh dead.aclose.assert_awaited_once() @pytest.mark.asyncio async def test_running_bridge_is_reused(self, tmp_path): backend = _backend(tmp_path) alive = _make_client(process=MagicMock(returncode=None)) - with patch.object(backend, "_launch_client", new_callable=AsyncMock, side_effect=[alive]): - assert await backend._get_client() is alive - assert await backend._get_client() is alive + with patch.object(backend._bridge, "launch", new_callable=AsyncMock, side_effect=[alive]): + assert await backend._bridge.get() is alive + assert await backend._bridge.get() is alive def test_timeout_is_not_a_dead_bridge(self): - from memclaw.backends.cursor import _bridge_failed + from memclaw.backends.cursor.bridge import bridge_failed def raised_from(cause): exc = RuntimeError("run failed") exc.__cause__ = cause return exc - assert _bridge_failed(raised_from(httpx.ConnectError("refused"))) - assert not _bridge_failed(raised_from(httpx.ReadTimeout("slow"))) - assert not _bridge_failed(RuntimeError("agent error")) + assert bridge_failed(raised_from(httpx.ConnectError("refused"))) + assert not bridge_failed(raised_from(httpx.ReadTimeout("slow"))) + assert not bridge_failed(RuntimeError("agent error")) @pytest.mark.asyncio async def test_drain_survives_a_line_over_64_kib(self): - from memclaw.backends.cursor import _drain_stderr + from memclaw.backends.cursor.bridge import drain_stderr stream = asyncio.StreamReader() stream.feed_data(b"x" * 200_000 + b"\nok\n") stream.feed_eof() - await _drain_stderr(stream) # reads to EOF without raising + await drain_stderr(stream) # reads to EOF without raising assert stream.at_eof() @pytest.mark.asyncio async def test_shutdown_tolerates_a_session_added_meanwhile(self, tmp_path): - from memclaw.backends.cursor import _Session - backend = _backend(tmp_path) backend._mcp_server = MagicMock(stop=AsyncMock()) async def close_and_add(session): - backend._sessions.setdefault("late", _Session()) + backend._sessions.setdefault("late", ChatAgent()) - backend._sessions["a"] = _Session() - with patch.object(backend, "_close_agent", side_effect=close_and_add): + backend._sessions["a"] = ChatAgent() + with patch.object(ChatAgent, "close", autospec=True, side_effect=close_and_add): await backend.on_agent_shutdown() assert backend._sessions == {} diff --git a/tests/backends/test_cursor_hooks.py b/tests/backends/test_cursor_hooks.py index 3e2881b..cbdd0a0 100644 --- a/tests/backends/test_cursor_hooks.py +++ b/tests/backends/test_cursor_hooks.py @@ -9,7 +9,7 @@ import pytest -from memclaw.backends.cursor_hooks import ( +from memclaw.backends.cursor.hooks import ( cursor_hook_script_path, cursor_hooks_installed, cursor_hooks_json_path, diff --git a/tests/e2e/test_retrieval_e2e.py b/tests/e2e/test_retrieval_e2e.py index 4c4bcc1..102108f 100644 --- a/tests/e2e/test_retrieval_e2e.py +++ b/tests/e2e/test_retrieval_e2e.py @@ -8,7 +8,7 @@ from memclaw.agent import MemclawAgent from memclaw.memory import HybridSearch, MemoryIndex, MemoryStore from memclaw.openai_client import OpenAIClient -from memclaw.tools import ToolExecutor +from memclaw.tools import ToolContext, ToolExecutor from .conftest import days_ago, write_daily @@ -193,7 +193,7 @@ async def test_image_search_is_scoped_to_platform(vault): await index.store_platform_image("whatsapp", "wa-media-1", "A whiteboard with sprint planning notes") await index.store_platform_image("telegram", "tg-file-1", "A whiteboard with sprint planning sticky notes") found: list[dict] = [] - tools = ToolExecutor(vault, MemoryStore(vault), index, search, found, platform="telegram") + tools = ToolExecutor(ToolContext(vault, MemoryStore(vault), index, search, found, platform="telegram")) out = await tools.execute("image_search", {"query": "sprint planning whiteboard"}) assert "id 2 " in out and "id 1 " not in out await tools.execute("image_send", {"ids": [1, 2]}) @@ -206,7 +206,7 @@ async def test_image_search_is_scoped_to_platform(vault): async def test_file_write_markdown_is_searchable(vault): index = MemoryIndex(vault) search = HybridSearch(vault, index) - tools = ToolExecutor(vault, MemoryStore(vault), index, search, []) + tools = ToolExecutor(ToolContext(vault, MemoryStore(vault), index, search, [])) out = await tools.execute("file_write", { "file_path": "todos.md", "content": "# Todos\n\n- Renew passport before the Lisbon trip\n", }) @@ -219,7 +219,7 @@ async def test_file_write_markdown_is_searchable(vault): @pytest.mark.asyncio async def test_file_write_cannot_clobber_internal_files(vault): index = MemoryIndex(vault) - tools = ToolExecutor(vault, MemoryStore(vault), index, HybridSearch(vault, index), []) + tools = ToolExecutor(ToolContext(vault, MemoryStore(vault), index, HybridSearch(vault, index), [])) for target in ("memclaw.db", ".env", "sessions.json", "meta.json"): out = await tools.execute("file_write", {"file_path": target, "content": "oops"}) assert out.startswith("Blocked"), (target, out) diff --git a/tests/test_agent.py b/tests/test_agent.py index 55b69ec..f290b98 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -619,7 +619,7 @@ async def test_tool_calls_see_their_own_chat(self, cfg: MemclawConfig, fake_back async def run_turn(request, tool_executor): key = request.session_key await asyncio.sleep(0.05) # the other chat's message arrives meanwhile - seen[key] = tool_executor.chat_id + seen[key] = tool_executor.context.chat_id return TurnResult(text="ok", session_id=f"s-{key}") fake_backend.run_turn = run_turn diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 0000000..c91dc12 --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,270 @@ +"""The agent's tools, called through ToolExecutor: every tool's replies, +including the error and edge-case wording the agent sees.""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from memclaw.memory import SearchResult +from memclaw.tools import ToolContext, ToolExecutor + + +def _executor(config, *, platform="telegram", scheduler=None, chat_id="42", found_images=None): + store = MagicMock() + store.save.return_value = config.memory_dir / "memory" / "2026-01-01.md" + index = MagicMock() + index.index_file = AsyncMock() + index.store_platform_image = AsyncMock() + search = MagicMock() + search.search = AsyncMock(return_value=[]) + search.search_images = AsyncMock(return_value=[]) + executor = ToolExecutor(ToolContext( + config=config, store=store, index=index, search=search, + found_images=[] if found_images is None else found_images, + platform=platform, scheduler=scheduler, chat_id=chat_id, + )) + return executor, store, index, search + + +@pytest.fixture +def config(tmp_config): + return tmp_config + + +class TestDispatch: + @pytest.mark.asyncio + async def test_unknown_tool(self, config): + executor, *_ = _executor(config) + assert await executor.execute("nope", {}) == "Error: Unknown tool 'nope'" + + @pytest.mark.asyncio + async def test_a_failing_tool_is_reported_not_raised(self, config): + executor, *_ = _executor(config) + assert await executor.execute("memory_save", {}) == "Error executing memory_save: 'content'" + + +class TestMemoryTools: + @pytest.mark.asyncio + async def test_memory_save(self, config): + executor, store, index, _ = _executor(config) + out = await executor.execute( + "memory_save", {"content": "Max is a beagle", "entry_type": "fact", "tags": ["dog"]}, + ) + assert out == "Memory saved to 2026-01-01.md" + store.save.assert_called_once_with("Max is a beagle", entry_type="fact", tags=["dog"]) + index.index_file.assert_awaited_once_with(store.save.return_value) + + @pytest.mark.asyncio + async def test_memory_save_with_indexing_down(self, config): + executor, _, index, _ = _executor(config) + index.index_file.side_effect = RuntimeError("offline") + out = await executor.execute("memory_save", {"content": "x"}) + assert out == ( + "Memory saved to 2026-01-01.md" + " (search indexing is delayed; it will be searchable soon)" + ) + + @pytest.mark.asyncio + async def test_memory_search_formats_results(self, config): + executor, _, _, search = _executor(config) + search.search.return_value = [ + SearchResult(str(config.memory_file), 1, 2, " Likes tea \n", 0.912, "hybrid"), + SearchResult("/m/memory/2026-01-01.md", 3, 4, "Max is a beagle", 0.5, "vector"), + ] + out = await executor.execute("memory_search", {"query": "dog", "limit": 99}) + search.search.assert_awaited_once_with("dog", limit=25) + assert out == ( + "**[1]** (score: 0.91, source: permanent memory)\nLikes tea" + "\n\n---\n\n" + "**[2]** (score: 0.50, source: 2026-01-01)\nMax is a beagle" + ) + + @pytest.mark.asyncio + @pytest.mark.parametrize(("limit", "expected"), [(None, 10), ("x", 10), (0, 10), (-3, 1), (7, 7)]) + async def test_memory_search_limit(self, config, limit, expected): + executor, _, _, search = _executor(config) + out = await executor.execute("memory_search", {"query": "q", "limit": limit}) + assert out == "No matching memories found." + assert search.search.await_args.kwargs["limit"] == expected + + +class TestImageTools: + @pytest.mark.asyncio + async def test_image_save(self, config): + executor, store, index, _ = _executor(config, platform=None) + out = await executor.execute( + "image_save", {"description": "A cat " * 30, "media_ref": "f1", "caption": "Tom"}, + ) + assert out == f"Image saved: {('A cat ' * 30)[:100]}" + index.store_platform_image.assert_awaited_once_with( + platform="local", media_ref="f1", + description=f"Image: {'A cat ' * 30} Caption: Tom", caption="Tom", + ) + store.save.assert_called_once_with(f"Image: {'A cat ' * 30} Caption: Tom", entry_type="image") + + @pytest.mark.asyncio + async def test_image_search(self, config): + executor, _, _, search = _executor(config) + search.search_images.return_value = [ + {"id": 3, "score": 0.81234, "description": "word " * 100}, + ] + out = await executor.execute("image_search", {"query": "cat"}) + search.search_images.assert_awaited_once_with("cat", limit=5, platform="telegram") + description = " ".join(("word " * 100).split())[:300] + "…" + assert out == ( + "Closest stored images, best first (nothing sent yet):\n" + f"- id 3 (match 0.81): {description}" + "\nCall image_send with the ids of the ones the user asked for." + ) + + @pytest.mark.asyncio + async def test_image_search_nothing_found(self, config): + executor, *_ = _executor(config) + assert await executor.execute("image_search", {"query": "cat"}) == "No matching images found." + + @pytest.mark.asyncio + async def test_image_send(self, config): + found: list[dict] = [{"id": 1}] + executor, _, index, _ = _executor(config, found_images=found) + index.get_platform_images.return_value = [{"id": 1}, {"id": 2}] + out = await executor.execute("image_send", {"ids": ["1", 2, 5, 4]}) + index.get_platform_images.assert_called_once_with([1, 2, 5, 4], platform="telegram") + assert out == "Sending 2 image(s) with your reply. No stored image with id 4, 5." + assert found == [{"id": 1}, {"id": 2}] + + @pytest.mark.asyncio + async def test_image_send_nothing(self, config): + executor, _, index, _ = _executor(config) + index.get_platform_images.return_value = [] + assert await executor.execute("image_send", {}) == "Nothing to send." + + +class TestFileTools: + @pytest.mark.asyncio + async def test_update_instructions(self, config): + config.agent_file.write_text("# Rules\n") + executor, *_ = _executor(config) + out = await executor.execute("update_instructions", {"instruction": " Be brief \n"}) + assert out == "Instruction saved: Be brief" + assert config.agent_file.read_text() == "# Rules\n\n- Be brief\n" + + @pytest.mark.asyncio + async def test_file_write_and_read(self, config): + executor, _, index, _ = _executor(config) + index.is_indexable.return_value = False + target = config.memory_dir.resolve() / "lists" / "todo.txt" + assert await executor.execute( + "file_write", {"file_path": "lists/todo.txt", "content": "milk"}, + ) == f"File written: {target}" + index.index_file.assert_not_awaited() + assert await executor.execute("file_read", {"file_path": "lists/todo.txt"}) == "milk" + assert await executor.execute("file_read", {"file_path": "none.md"}) == ( + f"File not found: {config.memory_dir.resolve() / 'none.md'}" + ) + + @pytest.mark.asyncio + async def test_blocked_paths(self, config): + executor, *_ = _executor(config) + root = config.memory_dir.resolve() + assert await executor.execute("file_write", {"file_path": "/etc/x", "content": ""}) == ( + f"Blocked: path is outside {root} or is one of Memclaw's " + "internal files. Files must be under ~/.memclaw/" + ) + assert await executor.execute("file_read", {"file_path": "../x"}) == ( + f"Blocked: path is outside {root} or is one of Memclaw's internal files." + ) + assert await executor.execute("file_write", {"file_path": "MEMORY.md", "content": ""}) == ( + "Blocked: MEMORY.md and the daily notes in memory/ are maintained " + "by Memclaw. Use memory_save to add a memory." + ) + + +class TestReminderTools: + @pytest.mark.asyncio + async def test_needs_a_scheduler_and_a_chat(self, config): + executor, *_ = _executor(config, scheduler=None) + for tool in ("reminder_create", "reminder_list", "reminder_cancel"): + assert await executor.execute(tool, {}) == ( + "Reminders are only available when running in a messaging bot " + "(telegram/whatsapp/slack)." + ) + executor, *_ = _executor(config, scheduler=MagicMock(), chat_id=None) + assert await executor.execute("reminder_list", {}) == ( + "Reminders require a messaging context (missing platform/chat_id)." + ) + + @pytest.mark.asyncio + async def test_create_one_shot(self, config): + scheduler = MagicMock() + scheduler.create.return_value = 7 + executor, *_ = _executor(config, scheduler=scheduler) + out = await executor.execute( + "reminder_create", {"text": " call Alex ", "fire_at": "2026-04-13T21:30:00"}, + ) + assert out == "Reminder #7 scheduled for 2026-04-13T21:30." + scheduler.create.assert_called_once_with( + platform="telegram", chat_id="42", text="call Alex", + fire_at=datetime(2026, 4, 13, 21, 30), interval_seconds=None, + ) + + @pytest.mark.asyncio + async def test_create_converts_an_aware_time_to_local(self, config): + scheduler = MagicMock() + scheduler.create.return_value = 1 + executor, *_ = _executor(config, scheduler=scheduler) + await executor.execute("reminder_create", {"text": "t", "fire_at": "2026-04-13T21:30:00+00:00"}) + expected = datetime(2026, 4, 13, 21, 30, tzinfo=timezone.utc).astimezone().replace(tzinfo=None) + assert scheduler.create.call_args.kwargs["fire_at"] == expected + + @pytest.mark.asyncio + async def test_create_recurring(self, config): + scheduler = MagicMock() + scheduler.create.return_value = 2 + executor, *_ = _executor(config, scheduler=scheduler) + before = datetime.now() + out = await executor.execute("reminder_create", {"text": "water", "interval_seconds": 18000}) + fire_at = scheduler.create.call_args.kwargs["fire_at"] + assert before + timedelta(seconds=18000) <= fire_at <= datetime.now() + timedelta(seconds=18000) + assert out == ( + f"Reminder #2 scheduled for {fire_at.isoformat(timespec='minutes')} " + "and every 18000 seconds after." + ) + + @pytest.mark.asyncio + @pytest.mark.parametrize(("args", "expected"), [ + ({"text": "t", "fire_at": "soon"}, "Invalid fire_at: 'soon'. Use local ISO 8601."), + ({"text": "t"}, "Provide either fire_at or interval_seconds (or both)."), + ({"text": "t", "interval_seconds": 30}, "interval_seconds must be at least 60."), + ]) + async def test_create_rejects(self, config, args, expected): + scheduler = MagicMock() + executor, *_ = _executor(config, scheduler=scheduler) + assert await executor.execute("reminder_create", args) == expected + scheduler.create.assert_not_called() + + @pytest.mark.asyncio + async def test_list(self, config): + scheduler = MagicMock() + scheduler.list_for.return_value = [ + {"id": 1, "fire_at": "2026-04-13T21:30:00", "text": "call", "interval_seconds": None}, + {"id": 2, "fire_at": "2026-04-14T09:00:00", "text": "water", "interval_seconds": 3600}, + ] + executor, *_ = _executor(config, scheduler=scheduler) + assert await executor.execute("reminder_list", {}) == ( + "#1 at 2026-04-13T21:30:00: call\n#2 at 2026-04-14T09:00:00: water (every 3600s)" + ) + scheduler.list_for.assert_called_once_with("telegram", "42") + scheduler.list_for.return_value = [] + assert await executor.execute("reminder_list", {}) == "No pending reminders." + + @pytest.mark.asyncio + async def test_cancel(self, config): + scheduler = MagicMock() + scheduler.cancel.side_effect = [True, False] + executor, *_ = _executor(config, scheduler=scheduler) + assert await executor.execute("reminder_cancel", {"id": "3"}) == "Reminder #3 cancelled." + assert await executor.execute("reminder_cancel", {"id": 4}) == "No pending reminder #4." + scheduler.cancel.assert_called_with(4, platform="telegram", chat_id="42")