fix(commands): intercept non-priority commands during active turn
Non-priority slash commands (e.g. /new, /help, /dream-log) arriving while a session has an active LLM turn were silently queued into the pending injection buffer and later injected as raw user messages into the LLM conversation. This caused the model to respond to "/new" as plain text instead of executing the command. Root cause: the run() loop only checked priority commands (/stop, /restart, /status) before routing messages to the pending queue. All other command tiers (exact, prefix) bypassed command dispatch entirely. Changes: - Add CommandRouter.is_dispatchable_command() to match exact/prefix tiers, mirroring the existing is_priority() pattern. - In run(), intercept dispatchable commands before pending queue insertion and dispatch them directly via _dispatch_command_inline(). - Extract _cancel_active_tasks() from cmd_stop for reuse; cmd_new now cancels active tasks before clearing the session to prevent shared mutable state corruption from concurrent asyncio coroutines. - Update /new semantics: stops active task first, then clears session. - Update documentation in help text, docs, and Discord command list.
This commit is contained in:
+42
-4
@@ -345,6 +345,36 @@ class AgentLoop:
|
||||
|
||||
return format_tool_hints(tool_calls)
|
||||
|
||||
async def _dispatch_command_inline(
|
||||
self,
|
||||
msg: InboundMessage,
|
||||
key: str,
|
||||
raw: str,
|
||||
dispatch_fn: Callable[[CommandContext], Awaitable[OutboundMessage | None]],
|
||||
) -> None:
|
||||
"""Dispatch a command directly from the run() loop and publish the result."""
|
||||
ctx = CommandContext(msg=msg, session=None, key=key, raw=raw, loop=self)
|
||||
result = await dispatch_fn(ctx)
|
||||
if result:
|
||||
await self.bus.publish_outbound(result)
|
||||
else:
|
||||
logger.warning("Command '{}' matched but dispatch returned None", raw)
|
||||
|
||||
async def _cancel_active_tasks(self, key: str) -> int:
|
||||
"""Cancel and await all active tasks and subagents for *key*.
|
||||
|
||||
Returns the total number of cancelled tasks + subagents.
|
||||
"""
|
||||
tasks = self._active_tasks.pop(key, [])
|
||||
cancelled = sum(1 for t in tasks if not t.done() and t.cancel())
|
||||
for t in tasks:
|
||||
try:
|
||||
await t
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
sub_cancelled = await self.subagents.cancel_by_session(key)
|
||||
return cancelled + sub_cancelled
|
||||
|
||||
def _effective_session_key(self, msg: InboundMessage) -> str:
|
||||
"""Return the session key used for task routing and mid-turn injections."""
|
||||
if self._unified_session and not msg.session_key_override:
|
||||
@@ -478,16 +508,24 @@ class AgentLoop:
|
||||
|
||||
raw = msg.content.strip()
|
||||
if self.commands.is_priority(raw):
|
||||
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw=raw, loop=self)
|
||||
result = await self.commands.dispatch_priority(ctx)
|
||||
if result:
|
||||
await self.bus.publish_outbound(result)
|
||||
await self._dispatch_command_inline(
|
||||
msg, msg.session_key, raw,
|
||||
self.commands.dispatch_priority,
|
||||
)
|
||||
continue
|
||||
effective_key = self._effective_session_key(msg)
|
||||
# If this session already has an active pending queue (i.e. a task
|
||||
# is processing this session), route the message there for mid-turn
|
||||
# injection instead of creating a competing task.
|
||||
if effective_key in self._pending_queues:
|
||||
# Non-priority commands must not be queued for injection;
|
||||
# dispatch them directly (same pattern as priority commands).
|
||||
if self.commands.is_dispatchable_command(raw):
|
||||
await self._dispatch_command_inline(
|
||||
msg, effective_key, raw,
|
||||
self.commands.dispatch,
|
||||
)
|
||||
continue
|
||||
pending_msg = msg
|
||||
if effective_key != msg.session_key:
|
||||
pending_msg = dataclasses.replace(
|
||||
|
||||
@@ -135,7 +135,7 @@ if DISCORD_AVAILABLE:
|
||||
|
||||
def _register_app_commands(self) -> None:
|
||||
commands = (
|
||||
("new", "Start a new conversation", "/new"),
|
||||
("new", "Stop current task and start a new conversation", "/new"),
|
||||
("stop", "Stop the current task", "/stop"),
|
||||
("restart", "Restart the bot", "/restart"),
|
||||
("status", "Show bot status", "/status"),
|
||||
|
||||
@@ -17,15 +17,7 @@ async def cmd_stop(ctx: CommandContext) -> OutboundMessage:
|
||||
"""Cancel all active tasks and subagents for the session."""
|
||||
loop = ctx.loop
|
||||
msg = ctx.msg
|
||||
tasks = loop._active_tasks.pop(msg.session_key, [])
|
||||
cancelled = sum(1 for t in tasks if not t.done() and t.cancel())
|
||||
for t in tasks:
|
||||
try:
|
||||
await t
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
sub_cancelled = await loop.subagents.cancel_by_session(msg.session_key)
|
||||
total = cancelled + sub_cancelled
|
||||
total = await loop._cancel_active_tasks(msg.session_key)
|
||||
content = f"Stopped {total} task(s)." if total else "No active task to stop."
|
||||
return OutboundMessage(
|
||||
channel=msg.channel, chat_id=msg.chat_id, content=content,
|
||||
@@ -100,8 +92,9 @@ async def cmd_status(ctx: CommandContext) -> OutboundMessage:
|
||||
|
||||
|
||||
async def cmd_new(ctx: CommandContext) -> OutboundMessage:
|
||||
"""Start a fresh session."""
|
||||
"""Stop active task and start a fresh session."""
|
||||
loop = ctx.loop
|
||||
await loop._cancel_active_tasks(ctx.key)
|
||||
session = ctx.session or loop.sessions.get_or_create(ctx.key)
|
||||
snapshot = session.messages[session.last_consolidated:]
|
||||
session.clear()
|
||||
@@ -327,7 +320,7 @@ def build_help_text() -> str:
|
||||
"""Build canonical help text shared across channels."""
|
||||
lines = [
|
||||
"🐈 nanobot commands:",
|
||||
"/new — Start a new conversation",
|
||||
"/new — Stop current task and start a new conversation",
|
||||
"/stop — Stop the current task",
|
||||
"/restart — Restart the bot",
|
||||
"/status — Show bot status",
|
||||
|
||||
@@ -57,6 +57,20 @@ class CommandRouter:
|
||||
def is_priority(self, text: str) -> bool:
|
||||
return text.strip().lower() in self._priority
|
||||
|
||||
def is_dispatchable_command(self, text: str) -> bool:
|
||||
"""Check whether *text* matches any non-priority command tier (exact or prefix).
|
||||
|
||||
Does NOT check priority or interceptor tiers.
|
||||
If this returns True, ``dispatch()`` is guaranteed to match a handler.
|
||||
"""
|
||||
cmd = text.strip().lower()
|
||||
if cmd in self._exact:
|
||||
return True
|
||||
for pfx, _ in self._prefix:
|
||||
if cmd.startswith(pfx):
|
||||
return True
|
||||
return False
|
||||
|
||||
async def dispatch_priority(self, ctx: CommandContext) -> OutboundMessage | None:
|
||||
"""Dispatch a priority command. Called from run() without the lock."""
|
||||
handler = self._priority.get(ctx.raw.lower())
|
||||
|
||||
Reference in New Issue
Block a user