Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

4.5 KB
Raw Blame
"""remember tool: the user says "remember X" → X is saved to Jarvis' MEMORY.md.

Every later conversation (voice, chat) shows it in its prompt.

The notebook lives in the Society lead's folder of the vault
(``society/jarvis/MEMORY.md``, see :mod:`dodaios.memory.learning.notebook`),
so the person can read and edit it in the app or in Obsidian. Without a
running notebook (a headless test, a boot that disabled learning) the fact
goes to the legacy core-memory file instead, so the request is never lost.

Risk tier: safe — only writes local files.
"""

from __future__ import annotations

import asyncio
from typing import Any

from dodaios.core.config import DATA_DIR
from dodaios.core.protocols import ExecutionContext, ToolResult


class RememberTool:
    name: str = "remember"
    risk_tier: str = "safe"
    description: str = (
        "Save something the user explicitly asked you to remember for future "
        "conversations into Dodaios' long-term MEMORY.md. Pass one self-contained "
        "sentence in the user's language that still makes sense later (resolve "
        "'this' or 'that'). Every later conversation sees it."
    )
    schema: dict[str, Any] = {
        "type": "object",
        "properties": {
            "fact": {
                "type": "string",
                "description": "What to remember, as one self-contained sentence.",
            },
            "category": {
                "type": "string",
                "description": "Optional label (e.g. 'preference', 'project'); "
                "used only by the legacy fallback store.",
                "default": "general",
            },
        },
        "required": ["fact"],
    }

    async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
        from dodaios.memory.learning.notebook import remember_explicitly

        fact = " ".join(str(args.get("fact") or "").split())
        if not fact:
            return ToolResult(success=False, output=None, error="fact is missing")
        said = str(getattr(ctx, "user_utterance", "") or "")
        vaulted = await self._into_vault(fact, said)
        if vaulted is not None:
            return vaulted
        try:
            change = await asyncio.to_thread(remember_explicitly, fact, evidence=said)
        except LookupError:  # no MEMORY.md notebook: use the legacy store
            return await self._legacy(fact, str(args.get("category") or "general").strip())
        except (ValueError, OSError) as exc:  # reported to the model as a failed save
            return ToolResult(success=False, output=None, error=f"not saved: {exc}")
        if change is None:
            return ToolResult(success=True, output=f"Already in MEMORY.md: {fact}")
        return ToolResult(success=True, output=f"Saved to MEMORY.md: {fact}")

    @staticmethod
    async def _into_vault(fact: str, said: str) -> ToolResult | None:
        """Save into the memory vault (ADR-0044); ``None`` while it is not running."""
        from dodaios.memory.vault import runtime as vault_runtime

        try:
            result = await asyncio.to_thread(vault_runtime.remember_explicitly, fact, evidence=said)
        except LookupError:  # no vault running: the caller falls back to the notebook
            return None
        except ValueError as exc:  # reported to the model as a failed save
            return ToolResult(success=False, output=None, error=f"not saved: {exc}")
        if result.action == "refused":
            return ToolResult(success=False, output=None, error="not saved: looks like a secret")
        if result.action == "existing":
            return ToolResult(success=True, output=f"Already in memory: {fact}")
        return ToolResult(success=True, output=f"Saved to memory: {fact}")

    @staticmethod
    async def _legacy(fact: str, category: str) -> ToolResult:
        from dodaios.memory import CORE_MEMORY_FILENAME, CoreMemory
        from dodaios.memory.learning.notebook import OWNER_ID
        from dodaios.memory.write_feedback import announce_write

        def _write() -> None:
            with announce_write(OWNER_ID, CORE_MEMORY_FILENAME, operation="add"):
                mem = CoreMemory.load(DATA_DIR / CORE_MEMORY_FILENAME)
                mem.add_fact(fact, category=category or "general")

        try:
            await asyncio.to_thread(_write)
        except Exception as exc:  # noqa: BLE001 — reported to the caller as a failed save
            return ToolResult(success=False, output=None, error=str(exc))
        return ToolResult(success=True, output=f"Remembered: [{category}] {fact}")