Skip to content

Your lightweight open-source personal agent.

fix(loop): resolve conflicts with main and improve /new handler

Re-bin1cfcc647b727
diff --cc nanobot/agent/loop.py
index 06ab1f759,7b9317ccc..5762fa91d
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@@ -1,12 -1,13 +1,13 @@@
"""Agent loop: the core processing engine."""
+ from __future__ import annotations
+
import asyncio
- from contextlib import AsyncExitStack
import json
- import json_repair
- from pathlib import Path
import re
- from typing import Any, Awaitable, Callable
+ from contextlib import AsyncExitStack
+ from pathlib import Path
-from typing import TYPE_CHECKING, Awaitable, Callable
++from typing import TYPE_CHECKING, Any, Awaitable, Callable
from loguru import logger
@@@ -88,21 -93,15 +93,17 @@@ class AgentLoop
self._mcp_servers = mcp_servers or {}
self._mcp_stack: AsyncExitStack | None = None
self._mcp_connected = False
+ self._mcp_connecting = False
self._consolidating: set[str] = set() # Session keys with consolidation in progress
+ self._consolidation_tasks: set[asyncio.Task] = set() # Strong refs to in-flight tasks
+ self._consolidation_locks: dict[str, asyncio.Lock] = {}
self._register_default_tools()
-
+
def _register_default_tools(self) -> None:
"""Register the default set of tools."""
- # File tools (workspace for relative paths, restrict if configured)
allowed_dir = self.workspace if self.restrict_to_workspace else None
- self.tools.register(ReadFileTool(workspace=self.workspace, allowed_dir=allowed_dir))
- self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir))
- self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir))
- self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir))
-
- # Shell tool
+ for cls in (ReadFileTool, WriteFileTool, EditFileTool, ListDirTool):
+ self.tools.register(cls(workspace=self.workspace, allowed_dir=allowed_dir))
self.tools.register(ExecTool(
working_dir=str(self.workspace),
timeout=self.exec_config.timeout,
@@@ -286,103 -270,74 +272,108 @@@
self._running = False
logger.info("Agent loop stopping")
+ def _get_consolidation_lock(self, session_key: str) -> asyncio.Lock:
+ lock = self._consolidation_locks.get(session_key)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._consolidation_locks[session_key] = lock
+ return lock
+
+ def _prune_consolidation_lock(self, session_key: str, lock: asyncio.Lock) -> None:
- """Drop unused per-session lock entries to avoid unbounded growth."""
- waiters = getattr(lock, "_waiters", None)
- has_waiters = bool(waiters)
- if lock.locked() or has_waiters:
- return
- self._consolidation_locks.pop(session_key, None)
-
++ """Drop lock entry if no longer in use."""
++ if not lock.locked():
++ self._consolidation_locks.pop(session_key, None)
++
async def _process_message(
self,
msg: InboundMessage,
session_key: str | None = None,
on_progress: Callable[[str], Awaitable[None]] | None = None,
) -> OutboundMessage | None:
- """
- Process a single inbound message.
-
- Args:
- msg: The inbound message to process.
- session_key: Override session key (used by process_direct).
- on_progress: Optional callback for intermediate output (defaults to bus publish).
-
- Returns:
- The response message, or None if no response needed.
- """
- # System messages route back via chat_id ("channel:chat_id")
+ """Process a single inbound message and return the response."""
+ # System messages: parse origin from chat_id ("channel:chat_id")
if msg.channel == "system":
- return await self._process_system_message(msg)
-
+ channel, chat_id = (msg.chat_id.split(":", 1) if ":" in msg.chat_id
+ else ("cli", msg.chat_id))
+ logger.info("Processing system message from {}", msg.sender_id)
+ key = f"{channel}:{chat_id}"
+ session = self.sessions.get_or_create(key)
+ self._set_tool_context(channel, chat_id, msg.metadata.get("message_id"))
+ messages = self.context.build_messages(
+ history=session.get_history(max_messages=self.memory_window),
+ current_message=msg.content, channel=channel, chat_id=chat_id,
+ )
+ final_content, _ = await self._run_agent_loop(messages)
+ session.add_message("user", f"[System: {msg.sender_id}] {msg.content}")
+ session.add_message("assistant", final_content or "Background task completed.")
+ self.sessions.save(session)
+ return OutboundMessage(channel=channel, chat_id=chat_id,
+ content=final_content or "Background task completed.")
+
preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content
logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview)
-
+
key = session_key or msg.session_key
session = self.sessions.get_or_create(key)
-
- # Handle slash commands
+
+ # Slash commands
cmd = msg.content.strip().lower()
if cmd == "/new":
- messages_to_archive = session.messages.copy()
+ lock = self._get_consolidation_lock(session.key)
- messages_to_archive: list[dict[str, Any]] = []
++ self._consolidating.add(session.key)
+ try:
+ async with lock:
- messages_to_archive = session.messages[session.last_consolidated :].copy()
- temp_session = Session(key=session.key)
- temp_session.messages = messages_to_archive
- archived = await self._consolidate_memory(temp_session, archive_all=True)
- except Exception as e:
- logger.error("/new archival failed for {}: {}", session.key, e)
- return OutboundMessage(
- channel=msg.channel,
- chat_id=msg.chat_id,
- content="Could not start a new session because memory archival failed. Please try again.",
- )
-
- if messages_to_archive and not archived:
++ snapshot = session.messages[session.last_consolidated:]
++ if snapshot:
++ temp = Session(key=session.key)
++ temp.messages = list(snapshot)
++ if not await self._consolidate_memory(temp, archive_all=True):
++ return OutboundMessage(
++ channel=msg.channel, chat_id=msg.chat_id,
++ content="Memory archival failed, session not cleared. Please try again.",
++ )
++ except Exception:
++ logger.exception("/new archival failed for {}", session.key)
+ return OutboundMessage(
- channel=msg.channel,
- chat_id=msg.chat_id,
- content="Could not start a new session because memory archival failed. Please try again.",
++ channel=msg.channel, chat_id=msg.chat_id,
++ content="Memory archival failed, session not cleared. Please try again.",
+ )
++ finally:
++ self._consolidating.discard(session.key)
++ self._prune_consolidation_lock(session.key, lock)
+
session.clear()
self.sessions.save(session)
self.sessions.invalidate(session.key)
- self._prune_consolidation_lock(session.key, lock)
-
- async def _consolidate_and_cleanup():
- temp = Session(key=session.key)
- temp.messages = messages_to_archive
- await self._consolidate_memory(temp, archive_all=True)
-
- asyncio.create_task(_consolidate_and_cleanup())
return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id,
-- content="New session started. Memory consolidation in progress.")
++ content="New session started.")
if cmd == "/help":
return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id,
content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands")
-
+
if len(session.messages) > self.memory_window and session.key not in self._consolidating:
self._consolidating.add(session.key)
+ lock = self._get_consolidation_lock(session.key)
async def _consolidate_and_unlock():
try:
- await self._consolidate_memory(session)
+ async with lock:
+ await self._consolidate_memory(session)
finally:
self._consolidating.discard(session.key)
+ self._prune_consolidation_lock(session.key, lock)
+ _task = asyncio.current_task()
+ if _task is not None:
+ self._consolidation_tasks.discard(_task)
- asyncio.create_task(_consolidate_and_unlock())
+ _task = asyncio.create_task(_consolidate_and_unlock())
+ self._consolidation_tasks.add(_task)
self._set_tool_context(msg.channel, msg.chat_id, msg.metadata.get("message_id"))
+ if message_tool := self.tools.get("message"):
+ if isinstance(message_tool, MessageTool):
+ message_tool.start_turn()
+
initial_messages = self.context.build_messages(
history=session.get_history(max_messages=self.memory_window),
current_message=msg.content,
@@@ -411,157 -366,22 +402,22 @@@
session.add_message("assistant", final_content,
tools_used=tools_used if tools_used else None)
self.sessions.save(session)
-
- return OutboundMessage(
- channel=msg.channel,
- chat_id=msg.chat_id,
- content=final_content,
- metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts)
- )
-
- async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None:
- """
- Process a system message (e.g., subagent announce).
-
- The chat_id field contains "original_channel:original_chat_id" to route
- the response back to the correct destination.
- """
- logger.info("Processing system message from {}", msg.sender_id)
-
- # Parse origin from chat_id (format: "channel:chat_id")
- if ":" in msg.chat_id:
- parts = msg.chat_id.split(":", 1)
- origin_channel = parts[0]
- origin_chat_id = parts[1]
- else:
- # Fallback
- origin_channel = "cli"
- origin_chat_id = msg.chat_id
-
- session_key = f"{origin_channel}:{origin_chat_id}"
- session = self.sessions.get_or_create(session_key)
- self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id"))
- initial_messages = self.context.build_messages(
- history=session.get_history(max_messages=self.memory_window),
- current_message=msg.content,
- channel=origin_channel,
- chat_id=origin_chat_id,
- )
- final_content, _ = await self._run_agent_loop(initial_messages)
- if final_content is None:
- final_content = "Background task completed."
-
- session.add_message("user", f"[System: {msg.sender_id}] {msg.content}")
- session.add_message("assistant", final_content)
- self.sessions.save(session)
-
+ if message_tool := self.tools.get("message"):
+ if isinstance(message_tool, MessageTool) and message_tool._sent_in_turn:
+ return None
+
return OutboundMessage(
- channel=origin_channel,
- chat_id=origin_chat_id,
- content=final_content
+ channel=msg.channel, chat_id=msg.chat_id, content=final_content,
+ metadata=msg.metadata or {},
)
-
- async def _consolidate_memory(self, session, archive_all: bool = False) -> bool:
- """Consolidate old messages into MEMORY.md + HISTORY.md.
-
- Args:
- archive_all: If True, clear all messages and reset session (for /new command).
- If False, only write to files without modifying session.
- """
- memory = self.context.memory
-
- if archive_all:
- old_messages = session.messages
- keep_count = 0
- logger.info("Memory consolidation (archive_all): {} total messages archived", len(session.messages))
- else:
- keep_count = self.memory_window // 2
- if len(session.messages) <= keep_count:
- logger.debug("Session {}: No consolidation needed (messages={}, keep={})", session.key, len(session.messages), keep_count)
- return True
-
- messages_to_process = len(session.messages) - session.last_consolidated
- if messages_to_process <= 0:
- logger.debug("Session {}: No new messages to consolidate (last_consolidated={}, total={})", session.key, session.last_consolidated, len(session.messages))
- return True
-
- old_messages = session.messages[session.last_consolidated:-keep_count]
- if not old_messages:
- return True
- logger.info("Memory consolidation started: {} total, {} new to consolidate, {} keep", len(session.messages), len(old_messages), keep_count)
-
- lines = []
- for m in old_messages:
- if not m.get("content"):
- continue
- tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else ""
- lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}")
- conversation = "\n".join(lines)
- current_memory = memory.read_long_term()
-
- prompt = f"""You are a memory consolidation agent. Process this conversation and return a JSON object with exactly two keys:
-
- 1. "history_entry": A paragraph (2-5 sentences) summarizing the key events/decisions/topics. Start with a timestamp like [YYYY-MM-DD HH:MM]. Include enough detail to be useful when found by grep search later.
-
- 2. "memory_update": The updated long-term memory content. Add any new facts: user location, preferences, personal info, habits, project context, technical decisions, tools/services used. If nothing new, return the existing content unchanged.
-
- ## Current Long-term Memory
- {current_memory or "(empty)"}
-
- ## Conversation to Process
- {conversation}
-
- **IMPORTANT**: Both values MUST be strings, not objects or arrays.
-
- Example:
- {{
- "history_entry": "[2026-02-14 22:50] User asked about...",
- "memory_update": "- Host: HARRYBOOK-T14P\n- Name: Nado"
- }}
-
- Respond with ONLY valid JSON, no markdown fences."""
- try:
- response = await self.provider.chat(
- messages=[
- {"role": "system", "content": "You are a memory consolidation agent. Respond only with valid JSON."},
- {"role": "user", "content": prompt},
- ],
- model=self.model,
- )
- text = (response.content or "").strip()
- if not text:
- logger.warning("Memory consolidation: LLM returned empty response, skipping")
- return False
- if text.startswith("```"):
- text = text.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
- result = json_repair.loads(text)
- if not isinstance(result, dict):
- logger.warning("Memory consolidation: unexpected response type, skipping. Response: {}", text[:200])
- return False
-
- if entry := result.get("history_entry"):
- # Defensive: ensure entry is a string (LLM may return dict)
- if not isinstance(entry, str):
- entry = json.dumps(entry, ensure_ascii=False)
- memory.append_history(entry)
- if update := result.get("memory_update"):
- # Defensive: ensure update is a string
- if not isinstance(update, str):
- update = json.dumps(update, ensure_ascii=False)
- if update != current_memory:
- memory.write_long_term(update)
-
- if archive_all:
- session.last_consolidated = 0
- else:
- session.last_consolidated = len(session.messages) - keep_count
- logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated)
- return True
- except Exception as e:
- logger.error("Memory consolidation failed: {}", e)
- return False
- async def _consolidate_memory(self, session, archive_all: bool = False) -> None:
- """Delegate to MemoryStore.consolidate()."""
- await MemoryStore(self.workspace).consolidate(
++ async def _consolidate_memory(self, session, archive_all: bool = False) -> bool:
++ """Delegate to MemoryStore.consolidate(). Returns True on success."""
++ return await MemoryStore(self.workspace).consolidate(
+ session, self.provider, self.model,
+ archive_all=archive_all, memory_window=self.memory_window,
+ )
async def process_direct(
self,
diff --cc nanobot/agent/memory.py
index 29477c4b9,51abd8f17..cdbc49f38
--- a/nanobot/agent/memory.py
+++ b/nanobot/agent/memory.py
@@@ -28,3 -65,74 +65,79 @@@ class MemoryStore
def get_memory_context(self) -> str:
long_term = self.read_long_term()
return f"## Long-term Memory\n{long_term}" if long_term else ""
+
+ async def consolidate(
+ self,
+ session: Session,
+ provider: LLMProvider,
+ model: str,
+ *,
+ archive_all: bool = False,
+ memory_window: int = 50,
- ) -> None:
- """Consolidate old messages into MEMORY.md + HISTORY.md via LLM tool call."""
++ ) -> bool:
++ """Consolidate old messages into MEMORY.md + HISTORY.md via LLM tool call.
++
++ Returns True on success (including no-op), False on failure.
++ """
+ if archive_all:
+ old_messages = session.messages
+ keep_count = 0
+ logger.info("Memory consolidation (archive_all): {} messages", len(session.messages))
+ else:
+ keep_count = memory_window // 2
+ if len(session.messages) <= keep_count:
- return
++ return True
+ if len(session.messages) - session.last_consolidated <= 0:
- return
++ return True
+ old_messages = session.messages[session.last_consolidated:-keep_count]
+ if not old_messages:
- return
++ return True
+ logger.info("Memory consolidation: {} to consolidate, {} keep", len(old_messages), keep_count)
+
+ lines = []
+ for m in old_messages:
+ if not m.get("content"):
+ continue
+ tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else ""
+ lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}")
+
+ current_memory = self.read_long_term()
+ prompt = f"""Process this conversation and call the save_memory tool with your consolidation.
+
+ ## Current Long-term Memory
+ {current_memory or "(empty)"}
+
+ ## Conversation to Process
+ {chr(10).join(lines)}"""
+
+ try:
+ response = await provider.chat(
+ messages=[
+ {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."},
+ {"role": "user", "content": prompt},
+ ],
+ tools=_SAVE_MEMORY_TOOL,
+ model=model,
+ )
+
+ if not response.has_tool_calls:
+ logger.warning("Memory consolidation: LLM did not call save_memory, skipping")
- return
++ return False
+
+ args = response.tool_calls[0].arguments
+ if entry := args.get("history_entry"):
+ if not isinstance(entry, str):
+ entry = json.dumps(entry, ensure_ascii=False)
+ self.append_history(entry)
+ if update := args.get("memory_update"):
+ if not isinstance(update, str):
+ update = json.dumps(update, ensure_ascii=False)
+ if update != current_memory:
+ self.write_long_term(update)
+
+ session.last_consolidated = 0 if archive_all else len(session.messages) - keep_count
+ logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated)
- except Exception as e:
- logger.error("Memory consolidation failed: {}", e)
++ return True
++ except Exception:
++ logger.exception("Memory consolidation failed")
++ return False