Skip to content

Your lightweight open-source personal agent.

refactor(agent): move internal prompts into packaged templates

Xubin Renc3b4ebae53f8
diff --cc nanobot/agent/memory.py
index c83b0a98e,3fbc651c9..62de34bba
--- a/nanobot/agent/memory.py
+++ b/nanobot/agent/memory.py
@@@ -11,8 -12,11 +12,12 @@@ from typing import TYPE_CHECKING, Any,
from loguru import logger
+from nanobot.utils.prompt_templates import render_template
- from nanobot.utils.helpers import ensure_dir, estimate_message_tokens, estimate_prompt_tokens_chain
+ from nanobot.utils.helpers import ensure_dir, estimate_message_tokens, estimate_prompt_tokens_chain, strip_think
+
+ from nanobot.agent.runner import AgentRunSpec, AgentRunner
+ from nanobot.agent.tools.registry import ToolRegistry
+ from nanobot.utils.gitstore import GitStore
if TYPE_CHECKING:
from nanobot.providers.base import LLMProvider
@@@ -112,106 -325,10 +326,10 @@@ class MemoryStore
)
return "\n".join(lines)
- async def consolidate(
- self,
- messages: list[dict],
- provider: LLMProvider,
- model: str,
- ) -> bool:
- """Consolidate the provided message chunk into MEMORY.md + HISTORY.md."""
- if not messages:
- return True
-
- current_memory = self.read_long_term()
- prompt = render_template(
- "agent/memory_consolidate.md",
- part="user",
- current_memory=current_memory or "(empty)",
- conversation=self._format_messages(messages),
- )
-
- chat_messages = [
- {"role": "system", "content": render_template("agent/memory_consolidate.md", part="system")},
- {"role": "user", "content": prompt},
- ]
-
- try:
- forced = {"type": "function", "function": {"name": "save_memory"}}
- response = await provider.chat_with_retry(
- messages=chat_messages,
- tools=_SAVE_MEMORY_TOOL,
- model=model,
- tool_choice=forced,
- )
-
- if response.finish_reason == "error" and _is_tool_choice_unsupported(
- response.content
- ):
- logger.warning("Forced tool_choice unsupported, retrying with auto")
- response = await provider.chat_with_retry(
- messages=chat_messages,
- tools=_SAVE_MEMORY_TOOL,
- model=model,
- tool_choice="auto",
- )
-
- if not response.has_tool_calls:
- logger.warning(
- "Memory consolidation: LLM did not call save_memory "
- "(finish_reason={}, content_len={}, content_preview={})",
- response.finish_reason,
- len(response.content or ""),
- (response.content or "")[:200],
- )
- return self._fail_or_raw_archive(messages)
-
- args = _normalize_save_memory_args(response.tool_calls[0].arguments)
- if args is None:
- logger.warning("Memory consolidation: unexpected save_memory arguments")
- return self._fail_or_raw_archive(messages)
-
- if "history_entry" not in args or "memory_update" not in args:
- logger.warning("Memory consolidation: save_memory payload missing required fields")
- return self._fail_or_raw_archive(messages)
-
- entry = args["history_entry"]
- update = args["memory_update"]
-
- if entry is None or update is None:
- logger.warning("Memory consolidation: save_memory payload contains null required fields")
- return self._fail_or_raw_archive(messages)
-
- entry = _ensure_text(entry).strip()
- if not entry:
- logger.warning("Memory consolidation: history_entry is empty after normalization")
- return self._fail_or_raw_archive(messages)
-
- self.append_history(entry)
- update = _ensure_text(update)
- if update != current_memory:
- self.write_long_term(update)
-
- self._consecutive_failures = 0
- logger.info("Memory consolidation done for {} messages", len(messages))
- return True
- except Exception:
- logger.exception("Memory consolidation failed")
- return self._fail_or_raw_archive(messages)
-
- def _fail_or_raw_archive(self, messages: list[dict]) -> bool:
- """Increment failure count; after threshold, raw-archive messages and return True."""
- self._consecutive_failures += 1
- if self._consecutive_failures < self._MAX_FAILURES_BEFORE_RAW_ARCHIVE:
- return False
- self._raw_archive(messages)
- self._consecutive_failures = 0
- return True
-
- def _raw_archive(self, messages: list[dict]) -> None:
- """Fallback: dump raw messages to HISTORY.md without LLM summarization."""
- ts = datetime.now().strftime("%Y-%m-%d %H:%M")
+ def raw_archive(self, messages: list[dict]) -> None:
- """Fallback: dump raw messages to HISTORY.md without LLM summarization."""
++ """Fallback: dump raw messages to history.jsonl without LLM summarization."""
self.append_history(
- f"[{ts}] [RAW] {len(messages)} messages\n"
+ f"[RAW] {len(messages)} messages\n"
f"{self._format_messages(messages)}"
)
logger.warning(
@@@ -219,8 -336,14 +337,14 @@@
)
- class MemoryConsolidator:
- """Owns consolidation policy, locking, and session offset updates."""
+
+ # ---------------------------------------------------------------------------
+ # Consolidator — lightweight token-budget triggered consolidation
+ # ---------------------------------------------------------------------------
+
+
+ class Consolidator:
- """Lightweight consolidation: summarizes evicted messages, appends to HISTORY.md."""
++ """Lightweight consolidation: summarizes evicted messages into history.jsonl."""
_MAX_CONSOLIDATION_ROUNDS = 5
@@@ -294,14 -415,50 +416,37 @@@
self._get_tool_definitions(),
)
- async def archive_messages(self, messages: list[dict[str, object]]) -> bool:
- """Archive messages with guaranteed persistence (retries until raw-dump fallback)."""
+ async def archive(self, messages: list[dict]) -> bool:
- """Summarize messages via LLM and append to HISTORY.md.
++ """Summarize messages via LLM and append to history.jsonl.
+
+ Returns True on success (or degraded success), False if nothing to do.
+ """
if not messages:
+ return False
+ try:
+ formatted = MemoryStore._format_messages(messages)
+ response = await self.provider.chat_with_retry(
+ model=self.model,
+ messages=[
+ {
+ "role": "system",
- "content": (
- "Extract key facts from this conversation. "
- "Only output items matching these categories, skip everything else:\n"
- "- User facts: personal info, preferences, stated opinions, habits\n"
- "- Decisions: choices made, conclusions reached\n"
- "- Solutions: working approaches discovered through trial and error, "
- "especially non-obvious methods that succeeded after failed attempts\n"
- "- Events: plans, deadlines, notable occurrences\n"
- "- Preferences: communication style, tool preferences\n\n"
- "Priority: user corrections and preferences > solutions > decisions > events > environment facts. "
- "The most valuable memory prevents the user from having to repeat themselves.\n\n"
- "Skip: code patterns derivable from source, git history, "
- "or anything already captured in existing memory.\n\n"
- "Output as concise bullet points, one fact per line. "
- "No preamble, no commentary.\n"
- "If nothing noteworthy happened, output: (nothing)"
++ "content": render_template(
++ "agent/consolidator_archive.md",
++ strip=True,
+ ),
+ },
+ {"role": "user", "content": formatted},
+ ],
+ tools=None,
+ tool_choice=None,
+ )
+ summary = response.content or "[no summary]"
+ self.store.append_history(summary)
+ return True
+ except Exception:
+ logger.warning("Consolidation LLM call failed, raw-dumping to history")
+ self.store.raw_archive(messages)
return True
- for _ in range(self.store._MAX_FAILURES_BEFORE_RAW_ARCHIVE):
- if await self.consolidate_messages(messages):
- return True
- return True
async def maybe_consolidate_by_tokens(self, session: Session) -> None:
"""Loop: archive old messages until prompt fits within safe budget.
@@@ -364,3 -521,186 +509,163 @@@
estimated, source = self.estimate_session_prompt_tokens(session)
if estimated <= 0:
return
+
+
+ # ---------------------------------------------------------------------------
+ # Dream — heavyweight cron-scheduled memory consolidation
+ # ---------------------------------------------------------------------------
+
+
+ class Dream:
- """Two-phase memory processor: analyze HISTORY.md, then edit files via AgentRunner.
++ """Two-phase memory processor: analyze history.jsonl, then edit files via AgentRunner.
+
+ Phase 1 produces an analysis summary (plain LLM call).
+ Phase 2 delegates to AgentRunner with read_file / edit_file tools so the
+ LLM can make targeted, incremental edits instead of replacing entire files.
+ """
+
- _PHASE1_SYSTEM = (
- "Compare conversation history against current memory files. "
- "Output one line per finding:\n"
- "[FILE] atomic fact or change description\n\n"
- "Files: USER (identity, preferences, habits), "
- "SOUL (bot behavior, tone), "
- "MEMORY (knowledge, project context, tool patterns)\n\n"
- "Rules:\n"
- "- Only new or conflicting information — skip duplicates and ephemera\n"
- "- Prefer atomic facts: \"has a cat named Luna\" not \"discussed pet care\"\n"
- "- Corrections: [USER] location is Tokyo, not Osaka\n"
- "- Also capture confirmed approaches: if the user validated a non-obvious choice, note it\n\n"
- "If nothing needs updating: [SKIP] no new information"
- )
-
- _PHASE2_SYSTEM = (
- "Update memory files based on the analysis below.\n\n"
- "## Quality standards\n"
- "- Every line must carry standalone value — no filler\n"
- "- Concise bullet points under clear headers\n"
- "- Remove outdated or contradicted information\n\n"
- "## Editing\n"
- "- File contents provided below — edit directly, no read_file needed\n"
- "- Batch changes to the same file into one edit_file call\n"
- "- Surgical edits only — never rewrite entire files\n"
- "- Do NOT overwrite correct entries — only add, update, or remove\n"
- "- If nothing to update, stop without calling tools"
- )
-
+ def __init__(
+ self,
+ store: MemoryStore,
+ provider: LLMProvider,
+ model: str,
+ max_batch_size: int = 20,
+ max_iterations: int = 10,
+ max_tool_result_chars: int = 16_000,
+ ):
+ self.store = store
+ self.provider = provider
+ self.model = model
+ self.max_batch_size = max_batch_size
+ self.max_iterations = max_iterations
+ self.max_tool_result_chars = max_tool_result_chars
+ self._runner = AgentRunner(provider)
+ self._tools = self._build_tools()
+
+ # -- tool registry -------------------------------------------------------
+
+ def _build_tools(self) -> ToolRegistry:
+ """Build a minimal tool registry for the Dream agent."""
+ from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool
+
+ tools = ToolRegistry()
+ workspace = self.store.workspace
+ tools.register(ReadFileTool(workspace=workspace, allowed_dir=workspace))
+ tools.register(EditFileTool(workspace=workspace, allowed_dir=workspace))
+ return tools
+
+ # -- main entry ----------------------------------------------------------
+
+ async def run(self) -> bool:
+ """Process unprocessed history entries. Returns True if work was done."""
+ last_cursor = self.store.get_last_dream_cursor()
+ entries = self.store.read_unprocessed_history(since_cursor=last_cursor)
+ if not entries:
+ return False
+
+ batch = entries[: self.max_batch_size]
+ logger.info(
+ "Dream: processing {} entries (cursor {}→{}), batch={}",
+ len(entries), last_cursor, batch[-1]["cursor"], len(batch),
+ )
+
+ # Build history text for LLM
+ history_text = "\n".join(
+ f"[{e['timestamp']}] {e['content']}" for e in batch
+ )
+
+ # Current file contents
+ current_memory = self.store.read_memory() or "(empty)"
+ current_soul = self.store.read_soul() or "(empty)"
+ current_user = self.store.read_user() or "(empty)"
+ file_context = (
+ f"## Current MEMORY.md\n{current_memory}\n\n"
+ f"## Current SOUL.md\n{current_soul}\n\n"
+ f"## Current USER.md\n{current_user}"
+ )
+
+ # Phase 1: Analyze
+ phase1_prompt = (
+ f"## Conversation History\n{history_text}\n\n{file_context}"
+ )
+
+ try:
+ phase1_response = await self.provider.chat_with_retry(
+ model=self.model,
+ messages=[
- {"role": "system", "content": self._PHASE1_SYSTEM},
++ {
++ "role": "system",
++ "content": render_template("agent/dream_phase1.md", strip=True),
++ },
+ {"role": "user", "content": phase1_prompt},
+ ],
+ tools=None,
+ tool_choice=None,
+ )
+ analysis = phase1_response.content or ""
+ logger.debug("Dream Phase 1 complete ({} chars)", len(analysis))
+ except Exception:
+ logger.exception("Dream Phase 1 failed")
+ return False
+
+ # Phase 2: Delegate to AgentRunner with read_file / edit_file
+ phase2_prompt = f"## Analysis Result\n{analysis}\n\n{file_context}"
+
+ tools = self._tools
+ messages: list[dict[str, Any]] = [
- {"role": "system", "content": self._PHASE2_SYSTEM},
++ {
++ "role": "system",
++ "content": render_template("agent/dream_phase2.md", strip=True),
++ },
+ {"role": "user", "content": phase2_prompt},
+ ]
+
+ try:
+ result = await self._runner.run(AgentRunSpec(
+ initial_messages=messages,
+ tools=tools,
+ model=self.model,
+ max_iterations=self.max_iterations,
+ max_tool_result_chars=self.max_tool_result_chars,
+ fail_on_tool_error=True,
+ ))
+ logger.debug(
+ "Dream Phase 2 complete: stop_reason={}, tool_events={}",
+ result.stop_reason, len(result.tool_events),
+ )
+ except Exception:
+ logger.exception("Dream Phase 2 failed")
+ result = None
+
+ # Build changelog from tool events
+ changelog: list[str] = []
+ if result and result.tool_events:
+ for event in result.tool_events:
+ if event["status"] == "ok":
+ changelog.append(f"{event['name']}: {event['detail']}")
+
+ # Advance cursor — always, to avoid re-processing Phase 1
+ new_cursor = batch[-1]["cursor"]
+ self.store.set_last_dream_cursor(new_cursor)
+ self.store.compact_history()
+
+ if result and result.stop_reason == "completed":
+ logger.info(
+ "Dream done: {} change(s), cursor advanced to {}",
+ len(changelog), new_cursor,
+ )
+ else:
+ reason = result.stop_reason if result else "exception"
+ logger.warning(
+ "Dream incomplete ({}): cursor advanced to {}",
+ reason, new_cursor,
+ )
+
+ # Git auto-commit (only when there are actual changes)
+ if changelog and self.store.git.is_initialized():
+ ts = batch[-1]["timestamp"]
+ sha = self.store.git.auto_commit(f"dream: {ts}, {len(changelog)} change(s)")
+ if sha:
+ logger.info("Dream commit: {}", sha)
+
+ return True
diff --cc nanobot/templates/agent/consolidator_archive.md
index 000000000,000000000..5073f4f44
new file mode 100644
--- /dev/null
+++ b/nanobot/templates/agent/consolidator_archive.md
@@@ -1,0 -1,0 +1,13 @@@
++Extract key facts from this conversation. Only output items matching these categories, skip everything else:
++- User facts: personal info, preferences, stated opinions, habits
++- Decisions: choices made, conclusions reached
++- Solutions: working approaches discovered through trial and error, especially non-obvious methods that succeeded after failed attempts
++- Events: plans, deadlines, notable occurrences
++- Preferences: communication style, tool preferences
++
++Priority: user corrections and preferences > solutions > decisions > events > environment facts. The most valuable memory prevents the user from having to repeat themselves.
++
++Skip: code patterns derivable from source, git history, or anything already captured in existing memory.
++
++Output as concise bullet points, one fact per line. No preamble, no commentary.
++If nothing noteworthy happened, output: (nothing)
diff --cc nanobot/templates/agent/dream_phase1.md
index 000000000,000000000..2476468c8
new file mode 100644
--- /dev/null
+++ b/nanobot/templates/agent/dream_phase1.md
@@@ -1,0 -1,0 +1,13 @@@
++Compare conversation history against current memory files.
++Output one line per finding:
++[FILE] atomic fact or change description
++
++Files: USER (identity, preferences, habits), SOUL (bot behavior, tone), MEMORY (knowledge, project context, tool patterns)
++
++Rules:
++- Only new or conflicting information — skip duplicates and ephemera
++- Prefer atomic facts: "has a cat named Luna" not "discussed pet care"
++- Corrections: [USER] location is Tokyo, not Osaka
++- Also capture confirmed approaches: if the user validated a non-obvious choice, note it
++
++If nothing needs updating: [SKIP] no new information
diff --cc nanobot/templates/agent/dream_phase2.md
index 000000000,000000000..4547e8fa2
new file mode 100644
--- /dev/null
+++ b/nanobot/templates/agent/dream_phase2.md
@@@ -1,0 -1,0 +1,13 @@@
++Update memory files based on the analysis below.
++
++## Quality standards
++- Every line must carry standalone value — no filler
++- Concise bullet points under clear headers
++- Remove outdated or contradicted information
++
++## Editing
++- File contents provided below — edit directly, no read_file needed
++- Batch changes to the same file into one edit_file call
++- Surgical edits only — never rewrite entire files
++- Do NOT overwrite correct entries — only add, update, or remove
++- If nothing to update, stop without calling tools
diff --cc nanobot/templates/agent/identity.md
index bd3d922ba,000000000..db54bd17a
mode 100644,000000..100644
--- a/nanobot/templates/agent/identity.md
+++ b/nanobot/templates/agent/identity.md
@@@ -1,25 -1,0 +1,25 @@@
+# nanobot 🐈
+
+You are nanobot, a helpful AI assistant.
+
+## Runtime
+{{ runtime }}
+
+## Workspace
+Your workspace is at: {{ workspace_path }}
- - Long-term memory: {{ workspace_path }}/memory/MEMORY.md (write important facts here)
- - History log: {{ workspace_path }}/memory/HISTORY.md (grep-searchable). Each entry starts with [YYYY-MM-DD HH:MM].
++- Long-term memory: {{ workspace_path }}/memory/MEMORY.md (automatically managed by Dream — do not edit directly)
++- History log: {{ workspace_path }}/memory/history.jsonl (append-only JSONL, not grep-searchable).
+- Custom skills: {{ workspace_path }}/skills/{% raw %}{skill-name}{% endraw %}/SKILL.md
+
+{{ platform_policy }}
+
+## nanobot Guidelines
+- State intent before tool calls, but NEVER predict or claim results before receiving them.
+- Before modifying a file, read it first. Do not assume files or directories exist.
+- After writing or editing a file, re-read it if accuracy matters.
+- If a tool call fails, analyze the error before retrying with a different approach.
+- Ask for clarification when the request is ambiguous.
+{% include 'agent/_snippets/untrusted_content.md' %}
+
+Reply directly with text for conversations. Only use the 'message' tool to send to a specific chat channel.
+IMPORTANT: To send files (images, documents, audio, video) to the user, you MUST call the 'message' tool with the 'media' parameter. Do NOT use read_file to "send" a file — reading a file only shows its content to you, it does NOT deliver the file to the user. Example: message(content="Here is the file", media=["/path/to/file.png"])
diff --cc pyproject.toml
index 0e64cdfd4,a00cf6bc6..ae87c7beb
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -48,7 -48,7 +48,8 @@@ dependencies =
"chardet>=3.0.2,<6.0.0",
"openai>=2.8.0",
"tiktoken>=0.12.0,<1.0.0",
+ "jinja2>=3.1.0,<4.0.0",
+ "dulwich>=0.22.0,<1.0.0",
]
[project.optional-dependencies]
diff --cc tests/agent/test_context_prompt_cache.py
index 4484e5ed0,4484e5ed0..6da34648b
--- a/tests/agent/test_context_prompt_cache.py
+++ b/tests/agent/test_context_prompt_cache.py
@@@ -47,6 -47,6 +47,19 @@@ def test_system_prompt_stays_stable_whe
assert prompt1 == prompt2
++def test_system_prompt_reflects_current_dream_memory_contract(tmp_path) -> None:
++ workspace = _make_workspace(tmp_path)
++ builder = ContextBuilder(workspace)
++
++ prompt = builder.build_system_prompt()
++
++ assert "memory/history.jsonl" in prompt
++ assert "automatically managed by Dream" in prompt
++ assert "do not edit directly" in prompt
++ assert "memory/HISTORY.md" not in prompt
++ assert "write important facts here" not in prompt
++
++
def test_runtime_context_is_separate_untrusted_user_message(tmp_path) -> None:
"""Runtime metadata should be merged with the user message."""
workspace = _make_workspace(tmp_path)