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

* refactor(command): distinguish handled commands without replies

* refactor(command): declare session queue scheduling at registration
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-12 13:38:14 +08:00
1 parent 61fa3aa83c
commit 67742b2880
4 files changed
+39 -27

No files matched your search

+8 -12
View File
@@ -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()
+1 -1
View File
@@ -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)
+11 -1
View File
@@ -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.