Skip to content

Your lightweight open-source personal agent.

refactor(command): declare session queue policy at registration (#6170)

chengyongru67742b288057
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index f21ec6ffa..48bd286c7 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -52,7 +52,7 @@ from nanobot.bus.outbound_events import (
)
from nanobot.bus.queue import MessageBus
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
-from nanobot.command.router import command_text, normalize_command_text
+from nanobot.command.router import command_text
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
from nanobot.llm_usage.context import source_from_request
@@ -785,8 +785,7 @@ class AgentLoop:
dispatch_fn: Callable[[CommandContext], Awaitable[InboundMessage | OutboundMessage | None]],
) -> None:
"""Dispatch a command directly from the run() loop and publish the result."""
- if normalize_command_text(raw).lower() == "/compact":
- # Compaction must wait for the active turn to commit its session.
+ if self.commands.requires_session_queue(raw):
self._enqueue_session_message(msg)
return
@@ -803,10 +802,8 @@ class AgentLoop:
result = await dispatch_fn(ctx)
if isinstance(result, InboundMessage):
self._enqueue_session_message(result)
- elif result:
+ elif result is not None:
await self.bus.publish_outbound(result)
- else:
- logger.warning("Command '{}' matched but dispatch returned None", raw)
# A shell command may run for up to the configured exec timeout. Keep
# the inbound consumer responsive when it runs beside an active turn.
@@ -1532,7 +1529,7 @@ class AgentLoop:
coordinator.complete(msg, error=error)
if (
msg.channel != "system"
- and normalize_command_text(msg.content).lower() == "/compact"
+ and self.commands.requires_session_queue(command_text(msg))
):
delivery = self.turn_delivery_factory.unrouted(msg, session_key)
await delivery.complete(None, publish_completion=True)
@@ -1646,7 +1643,7 @@ class AgentLoop:
if not turn_continuation.internal_continuation_pending(msg.metadata):
await delivery.idle()
except asyncio.CancelledError:
- if not completion_published and normalize_command_text(msg.content).lower() == "/compact":
+ if not completion_published and self.commands.requires_session_queue(command_text(msg)):
await delivery.complete(None, publish_completion=True)
raise
finally:
@@ -2034,14 +2031,13 @@ class AgentLoop:
is_user_turn=is_user_turn,
turn_scopes=ctx.turn_scopes,
)
+ command_matched = self.commands.command_name(raw) is not None
result = await self.commands.dispatch(cmd_ctx)
if isinstance(result, InboundMessage):
ctx.msg = result
result = None
+ command_matched = False
ctx.turn_scopes.append(GoalInputScope(ctx.msg))
- if cmd_ctx.raw.lower() == "/compact":
- # Compaction reports through events, not an archiveable command reply.
- return True
if result is not None:
ctx.outbound = result
# Shortcut commands skip BUILD and SAVE, so we must persist the
@@ -2066,7 +2062,7 @@ class AgentLoop:
attributes=ctx.attributes,
)
return True
- return False
+ return command_matched
async def _build_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session()
diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.py
index 43df46e2f..c2f985990 100644
--- a/nanobot/command/builtin.py
+++ b/nanobot/command/builtin.py
@@ -1070,7 +1070,7 @@ def register_builtin_commands(router: CommandRouter) -> None:
router.priority("/restart", cmd_restart)
router.priority("/status", cmd_status)
router.exact("/new", cmd_new)
- router.exact("/compact", cmd_compact)
+ router.exact("/compact", cmd_compact, session_queue=True)
router.exact("/status", cmd_status)
router.exact("/model", cmd_model)
router.prefix("/model ", cmd_model)
diff --git a/nanobot/command/router.py b/nanobot/command/router.py
index e48f54d49..cd880a52d 100644
--- a/nanobot/command/router.py
+++ b/nanobot/command/router.py
@@ -71,12 +71,17 @@ class CommandRouter:
self._priority: dict[str, Handler] = {}
self._exact: dict[str, Handler] = {}
self._prefix: list[tuple[str, Handler]] = []
+ self._session_commands: set[str] = set()
def priority(self, cmd: str, handler: Handler) -> None:
self._priority[cmd] = handler
- def exact(self, cmd: str, handler: Handler) -> None:
+ def exact(self, cmd: str, handler: Handler, *, session_queue: bool = False) -> None:
self._exact[cmd] = handler
+ if session_queue:
+ self._session_commands.add(cmd)
+ else:
+ self._session_commands.discard(cmd)
def prefix(self, pfx: str, handler: Handler) -> None:
self._prefix.append((pfx, handler))
@@ -85,6 +90,11 @@ class CommandRouter:
def is_priority(self, text: str) -> bool:
return normalize_command_text(text).lower() in self._priority
+ def requires_session_queue(self, text: str) -> bool:
+ """Whether an exact command must run on the session worker."""
+ cmd = normalize_command_text(text).lower()
+ return cmd in self._session_commands and cmd not in self._priority
+
def command_name(self, text: str) -> str | None:
"""Return the registered command name, or None for ordinary chat text.
diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.py
index a6cc36e21..03a974e7a 100644
--- a/tests/command/test_compact_command.py
+++ b/tests/command/test_compact_command.py
@@ -12,7 +12,7 @@ from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import TurnCompleted
-from nanobot.command.builtin import cmd_stop
+from nanobot.command.builtin import cmd_compact, cmd_stop
from nanobot.command.router import CommandContext
from nanobot.providers.base import GenerationSettings, LLMResponse, ProviderConversationState
from nanobot.runtime_context import public_history_message
@@ -38,6 +38,7 @@ async def loop(tmp_path):
context_window_tokens=128_000,
)
loop.tools.get_definitions = MagicMock(return_value=[])
+ loop.commands.exact("/summarize", cmd_compact, session_queue=True)
try:
yield loop
finally:
@@ -45,7 +46,7 @@ async def loop(tmp_path):
@pytest.mark.asyncio
[email protected]("command", ["/compact", " /COMPACT@nanobot "])
[email protected]("command", ["/compact", " /COMPACT@nanobot ", "/summarize"])
async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command) -> None:
bus = loop.bus
session = loop.sessions.get_or_create("cli:test")
@@ -191,10 +192,11 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
@pytest.mark.asyncio
-async def test_compact_during_active_turn_waits_for_the_session_lock(loop) -> None:
[email protected]("command", ["/COMPACT@nanobot", "/summarize"])
+async def test_compact_during_active_turn_waits_for_the_session_lock(loop, command) -> None:
key = "websocket:test"
msg = InboundMessage(
- channel="websocket", sender_id="user", chat_id="test", content="/COMPACT@nanobot",
+ channel="websocket", sender_id="user", chat_id="test", content=command,
)
lock = loop._get_session_lock(key)
async with lock:
@@ -216,10 +218,11 @@ async def test_compact_during_active_turn_waits_for_the_session_lock(loop) -> No
@pytest.mark.asyncio
-async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loop) -> None:
[email protected]("command", ["/compact", "/summarize"])
+async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loop, command) -> None:
key = "websocket:test"
msg = InboundMessage(
- channel="websocket", sender_id="user", chat_id="test", content="/compact",
+ channel="websocket", sender_id="user", chat_id="test", content=command,
metadata={"webui_turn_id": "queued-compact"},
)
completions = []
@@ -235,7 +238,8 @@ async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loo
@pytest.mark.asyncio
-async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop) -> None:
[email protected]("command_text", ["/compact", "/summarize"])
+async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop, command_text) -> None:
key = "cli:test"
started = asyncio.Event()
release = asyncio.Event()
@@ -267,7 +271,7 @@ async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop) -> None:
loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="before compaction",
))
- command = InboundMessage(channel="cli", sender_id="u", chat_id="test", content="/compact")
+ command = InboundMessage(channel="cli", sender_id="u", chat_id="test", content=command_text)
await loop._dispatch_command_inline(command, key, command.content, loop.commands.dispatch)
loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="after compaction",
@@ -283,7 +287,7 @@ async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop) -> None:
assert [public_history_message(message)["content"] for message in compacted_history if message["role"] == "user"] == [
"initial question", "before compaction",
]
- assert all("/compact" != message.get("content") for request in requests for message in request)
+ assert all(command_text != message.get("content") for request in requests for message in request)
assert "after compaction" in str(requests[-1])
events = [loop.bus.outbound.get_nowait().event for _ in range(loop.bus.outbound_size)]
assert [event.phase for event in events if isinstance(event, ContextCompactionEvent)] == [
@@ -292,7 +296,8 @@ async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop) -> None:
@pytest.mark.asyncio
-async def test_stop_completes_compact_queued_behind_an_active_turn(loop) -> None:
[email protected]("command_text", ["/compact", "/summarize"])
+async def test_stop_completes_compact_queued_behind_an_active_turn(loop, command_text) -> None:
key = "websocket:test"
started = asyncio.Event()
@@ -309,7 +314,7 @@ async def test_stop_completes_compact_queued_behind_an_active_turn(loop) -> None
task = next(iter(loop._active_tasks[key]))
await asyncio.wait_for(started.wait(), timeout=5)
command = InboundMessage(
- channel="websocket", sender_id="u", chat_id="test", content="/compact",
+ channel="websocket", sender_id="u", chat_id="test", content=command_text,
metadata={"webui_turn_id": "queued-compact"},
)
await loop._dispatch_command_inline(command, key, command.content, loop.commands.dispatch)
@@ -323,7 +328,8 @@ async def test_stop_completes_compact_queued_behind_an_active_turn(loop) -> None
@pytest.mark.asyncio
-async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:
[email protected]("command", ["/compact", "/summarize"])
+async def test_stop_finishes_inflight_compaction_as_cancelled(loop, command) -> None:
key = "websocket:test"
session = loop.sessions.get_or_create(key)
session.add_message("user", "important question")
@@ -339,7 +345,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:
completions = []
loop.bus.subscribe(completions.append, TurnCompleted)
msg = InboundMessage(
- channel="websocket", sender_id="user", chat_id="test", content="/compact",
+ channel="websocket", sender_id="user", chat_id="test", content=command,
metadata={"webui_turn_id": "compact-turn"},
)
loop._enqueue_session_message(msg)