Skip to content

Your lightweight open-source personal agent.

fix(commands): keep slash-prefixed paths in normal chat

Xubin Ren7e00d6a944af
diff --git a/docs/chat-commands.md b/docs/chat-commands.md
index fc043c31f..82c539513 100644
--- a/docs/chat-commands.md
+++ b/docs/chat-commands.md
@@ -28,6 +28,21 @@ These commands work inside chat channels and interactive agent sessions:
| `/pairing revoke <channel> <user_id>` | Revoke a previously approved user on a specific channel |
| `/help` | Show available in-chat commands |
+## Commands and file paths
+
+The gateway treats a message as a command only when its first word matches a
+registered command name. Names are case-insensitive. Arguments must follow the
+command's supported form.
+
+Other text goes to the agent unchanged. This includes `/tmp`,
+`/home/user/project`, and `/Users/alice/report.md`. Unknown names such as `/neaw`
+also go to the agent; the gateway no longer returns a spelling suggestion.
+Use `/help` or the command menu to find a command.
+
+A path can have the same name as a command. For example, `/new` starts a new
+conversation. To discuss that directory, write `/new/` or `Look at /new`.
+Chat platforms can apply their own command rules before a message reaches the gateway.
+
## Pairing
When someone sends a DM to the bot and isn't on the allowlist — whether it's a new user or an existing user on a new channel — nanobot automatically replies with a **pairing code** (like `ABCD-EFGH`) that expires in 10 minutes. To grant them access:
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py
index fab573190..df18ea631 100644
--- a/nanobot/channels/websocket/tests/test_websocket_channel.py
+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py
@@ -477,7 +477,9 @@ async def test_temporary_chat_is_transient_and_discarded(bus, tmp_path) -> None:
@pytest.mark.asyncio
[email protected]("content", ["/goal private", "/trigger later", "/dream"])
[email protected]("content", [
+ "/goal private", "/trigger later", "/dream", "/NEW@nanobot", "/__shell pwd",
+])
async def test_temporary_chat_rejects_persistent_commands(bus, tmp_path, content) -> None:
sessions = SessionManager(tmp_path)
channel = WebSocketChannel(
@@ -503,6 +505,29 @@ async def test_temporary_chat_rejects_persistent_commands(bus, tmp_path, content
)
[email protected]("content", ["/tmp", "/new/file.txt", "/model@nanobot fast"])
+async def test_temporary_chat_accepts_paths_and_allowed_commands(bus, tmp_path, content) -> None:
+ sessions = SessionManager(tmp_path)
+ channel = WebSocketChannel(
+ {"enabled": True, "allowFrom": ["*"]}, bus,
+ gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
+ )
+ connection = AsyncMock()
+ connection.remote_address = ("127.0.0.1", 5000)
+ chat_id = await _new_temporary_chat(channel, connection)
+
+ await channel._dispatch_envelope(connection, "webui-client", {
+ "type": "message", "chat_id": chat_id, "content": content, "webui": True,
+ })
+
+ inbound = bus.publish_inbound.await_args.args[0]
+ assert inbound.content == content
+ assert inbound.require_existing_session is True
+ assert read_transcript_lines(inbound.session_key) == []
+ session = sessions.get_cached(inbound.session_key)
+ assert session is not None and not session.policy.persist
+
+
@pytest.mark.asyncio
async def test_disconnect_discards_temporary_chat(bus, tmp_path) -> None:
sessions = SessionManager(tmp_path)
diff --git a/nanobot/command/router.py b/nanobot/command/router.py
index 288e94f79..e48f54d49 100644
--- a/nanobot/command/router.py
+++ b/nanobot/command/router.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import re
from contextlib import AbstractContextManager
from dataclasses import dataclass, field
-from difflib import get_close_matches
from typing import TYPE_CHECKING, Any, Awaitable, Callable
from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -86,12 +85,21 @@ class CommandRouter:
def is_priority(self, text: str) -> bool:
return normalize_command_text(text).lower() in self._priority
+ def command_name(self, text: str) -> str | None:
+ """Return the registered command name, or None for ordinary chat text.
+
+ A leading slash alone is not command intent: absolute paths and other
+ slash-prefixed text must remain available to the agent.
+ """
+ parts = normalize_command_text(text).split(maxsplit=1)
+ return self._registered_commands().get(parts[0].lower()) if parts else None
+
def is_dispatchable_command(self, text: str) -> bool:
"""Check whether *text* should be handled by non-priority dispatch.
Exact priority commands are handled separately. Recognized non-priority
- commands and invalid slash commands are dispatched here so malformed
- commands can be rejected instead of reaching the LLM.
+ commands and malformed uses of registered commands are dispatched here
+ so argument errors can be rejected instead of reaching the LLM.
"""
cmd = normalize_command_text(text).lower()
if cmd in self._priority:
@@ -101,7 +109,7 @@ class CommandRouter:
for pfx, _ in self._prefix:
if cmd.startswith(pfx):
return True
- return cmd.startswith("/")
+ return self.command_name(text) is not None
async def dispatch_priority(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:
"""Dispatch a priority command. Called from run() without the lock."""
@@ -112,7 +120,7 @@ class CommandRouter:
return None
async def dispatch(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:
- """Try exact and prefix handlers, then reject invalid slash commands."""
+ """Try exact and prefix handlers, then validate registered commands."""
if ctx.msg.metadata.get("original_command"):
return None
ctx.raw = normalize_command_text(ctx.raw)
@@ -129,39 +137,25 @@ class CommandRouter:
return self._invalid_command_response(ctx)
def _invalid_command_response(self, ctx: CommandContext) -> OutboundMessage | None:
- if not ctx.raw.startswith("/"):
+ canonical = self.command_name(ctx.raw)
+ if canonical is None:
return None
entered = ctx.raw.split(maxsplit=1)[0]
- commands = self._registered_commands()
- canonical = commands.get(entered.lower())
- if canonical is not None:
- accepts_args = any(
- pfx.rstrip().lower() == entered.lower()
- for pfx, _ in self._prefix
+ accepts_args = any(
+ pfx.rstrip().lower() == entered.lower()
+ for pfx, _ in self._prefix
+ )
+ if accepts_args:
+ content = (
+ f'Invalid command "{entered}". '
+ 'Use "/help" to list available commands.'
)
- if accepts_args:
- content = (
- f'Invalid command "{entered}". '
- 'Use "/help" to list available commands.'
- )
- else:
- content = (
- f'Command "{canonical}" does not accept arguments. '
- f'Did you mean "{canonical}"?'
- )
else:
- matches = get_close_matches(entered.lower(), commands, n=1, cutoff=0.6)
- if matches:
- content = (
- f'Unknown command "{entered}". '
- f'Did you mean "{commands[matches[0]]}"?'
- )
- else:
- content = (
- f'Unknown command "{entered}". '
- 'Use "/help" to list available commands.'
- )
+ content = (
+ f'Command "{canonical}" does not accept arguments. '
+ f'Did you mean "{canonical}"?'
+ )
return OutboundMessage(
channel=ctx.msg.channel,
diff --git a/nanobot/webui/temporary_chats.py b/nanobot/webui/temporary_chats.py
index 9762dd557..377c472c1 100644
--- a/nanobot/webui/temporary_chats.py
+++ b/nanobot/webui/temporary_chats.py
@@ -13,6 +13,8 @@ from nanobot.bus.events import (
InboundMessage,
)
from nanobot.bus.queue import MessageBus
+from nanobot.command.builtin import register_builtin_commands
+from nanobot.command.router import CommandRouter
from nanobot.security.workspace_access import WorkspaceScope
from nanobot.session.manager import Session, SessionManager
from nanobot.webui.workspaces import WebUIWorkspaceController
@@ -62,6 +64,8 @@ class WebUITemporaryChats:
self._workspaces = workspaces
self._logger = logger
self._channel_name = channel_name
+ self._commands = CommandRouter()
+ register_builtin_commands(self._commands)
self._owners: dict[str, object] = {}
self._owner_chat_ids: dict[object, set[str]] = {}
# Keep active sessions alive if the bounded manager cache evicts them
@@ -119,8 +123,8 @@ class WebUITemporaryChats:
if session is None:
raise TemporaryChatError("temporary_chat_unavailable")
- command = content.strip().split(maxsplit=1)[0].lower() if content.strip() else ""
- if command.startswith("/") and command not in _TEMPORARY_CHAT_COMMANDS:
+ command = self._commands.command_name(content)
+ if command is not None and command not in _TEMPORARY_CHAT_COMMANDS:
raise TemporaryChatError("temporary_chat_command_rejected")
return TemporaryChatMessagePolicy(
diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py
index 316c69418..cd1c95953 100644
--- a/tests/agent/test_loop_save_turn.py
+++ b/tests/agent/test_loop_save_turn.py
@@ -290,7 +290,10 @@ async def test_new_with_bot_suffix_does_not_persist_command(tmp_path: Path) -> N
@pytest.mark.parametrize(
("content", "expected"),
[
- ("/neaw", 'Unknown command "/neaw". Did you mean "/new"?'),
+ (
+ "/stop now",
+ 'Command "/stop" does not accept arguments. Did you mean "/stop"?',
+ ),
(
"/status now",
'Command "/status" does not accept arguments. Did you mean "/status"?',
@@ -327,6 +330,32 @@ async def test_invalid_slash_command_is_rejected_without_calling_provider(
]
[email protected](("channel", "content"), [
+ ("websocket", "/tmp 看看这个目录"),
+ ("weixin", "/home/user/project"),
+ ("cli", "/new/file.txt"),
+])
+async def test_absolute_path_reaches_provider_as_chat(tmp_path, channel, content) -> None:
+ loop = _make_full_loop(tmp_path)
+ loop.provider.aclose = AsyncMock()
+ try:
+ response = await loop._process_message(InboundMessage(
+ channel=channel, sender_id="user", chat_id="path", content=content,
+ ))
+
+ assert response is not None and response.content == "Test title"
+ request = loop.provider.chat_stream_with_retry.await_args.kwargs
+ assert any(
+ message["role"] == "user" and content in message["content"]
+ for message in request["messages"]
+ )
+ session = loop.sessions.get_or_create(f"{channel}:path")
+ assert session.get_history()[0]["content"] == content
+ assert not session.messages[0].get("_command")
+ finally:
+ await loop.aclose()
+
+
def test_clean_generated_title_strips_reasoning_tags() -> None:
assert clean_generated_title("<think>reasoning</think> WebUI polish") == "WebUI polish"
assert clean_generated_title("Title: <think> The user said hello") == ""
diff --git a/tests/agent/test_session_inputs.py b/tests/agent/test_session_inputs.py
index fa331f6b8..0b3006211 100644
--- a/tests/agent/test_session_inputs.py
+++ b/tests/agent/test_session_inputs.py
@@ -98,3 +98,45 @@ async def test_session_message_text_is_not_dispatched_as_a_slash_command(
finally:
loop.stop()
await asyncio.wait_for(task, timeout=2)
+
+
+async def test_path_followup_reaches_running_turn(tmp_path: Path) -> None:
+ loop = _loop(tmp_path)
+ first_call = asyncio.Event()
+ release = asyncio.Event()
+ calls = []
+ path = "/home/user/project"
+
+ async def respond(**kwargs):
+ calls.append(str(kwargs["messages"]))
+ if len(calls) == 1:
+ first_call.set()
+ await release.wait()
+ return LLMResponse(content="Reviewed")
+
+ loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
+ run = asyncio.create_task(loop.run())
+ try:
+ await loop.bus.publish_inbound(InboundMessage(
+ channel="weixin", sender_id="user", chat_id="path", content="Review the project",
+ ))
+ await asyncio.wait_for(first_call.wait(), 3)
+ await loop.bus.publish_inbound(InboundMessage(
+ channel="weixin", sender_id="user", chat_id="path", content=path,
+ ))
+ async with asyncio.timeout(3):
+ while loop._pending_queues["weixin:path"].empty():
+ await asyncio.sleep(0)
+ release.set()
+ await asyncio.wait_for(asyncio.gather(*loop._active_tasks["weixin:path"]), 5)
+
+ assert len(calls) == 2
+ assert path in calls[1]
+ session = loop.sessions.get_or_create("weixin:path")
+ visible = [public_history_message(row) for row in session.messages]
+ assert any(row["content"] == path for row in visible)
+ assert not any(row.get("_command") for row in session.messages)
+ finally:
+ release.set()
+ loop.stop()
+ await asyncio.wait_for(run, 5)
diff --git a/tests/command/test_router_dispatchable.py b/tests/command/test_router_dispatchable.py
index a1eb53125..ed930d309 100644
--- a/tests/command/test_router_dispatchable.py
+++ b/tests/command/test_router_dispatchable.py
@@ -72,12 +72,13 @@ class TestIsDispatchableCommand:
assert router.is_dispatchable_command(" /new ")
assert router.is_dispatchable_command(" /pairing list ")
- def test_invalid_slash_commands_match_for_explicit_rejection(
+ def test_only_registered_commands_match_for_argument_validation(
self, router: CommandRouter,
) -> None:
- assert router.is_dispatchable_command("/unknown")
- assert router.is_dispatchable_command("/foo bar")
+ assert not router.is_dispatchable_command("/unknown")
+ assert not router.is_dispatchable_command("/foo bar")
assert router.is_dispatchable_command("/status now")
+ assert router.is_dispatchable_command("/STOP extra")
@pytest.mark.parametrize(
@@ -178,32 +179,24 @@ class TestMidTurnCommandDispatchedDirectly:
assert captured_args == ["hello world"]
@pytest.mark.asyncio
+ @pytest.mark.parametrize("content", [
+ "hello world", "/", "/tmp", "/tmp 看看这个目录", "/home/user/project",
+ "/Users/alice/report.md", "/new/file.txt", "/model/preset", "/neaw",
+ "/totally-unknown-command", "/tmp/file@new", "请看看 /home/user/project",
+ ])
async def test_non_command_returns_none(
self, router: CommandRouter, fake_loop: MagicMock, fake_msg: MagicMock,
+ content: str,
) -> None:
"""Regular text returns None from dispatch (not a command)."""
ctx = CommandContext(
msg=fake_msg, session=None,
- key="test:chat1", raw="hello world", loop=fake_loop,
+ key="test:chat1", raw=content, loop=fake_loop,
)
result = await router.dispatch(ctx)
assert result is None
-
- @pytest.mark.asyncio
- async def test_unknown_command_suggests_close_match(
- self, router: CommandRouter, fake_loop: MagicMock, fake_msg: MagicMock,
- ) -> None:
- fake_msg.content = "/neaw"
- ctx = CommandContext(
- msg=fake_msg, session=None,
- key="test:chat1", raw="/neaw", loop=fake_loop,
- )
-
- result = await router.dispatch(ctx)
-
- assert result is not None
- assert result.content == 'Unknown command "/neaw". Did you mean "/new"?'
- assert result.metadata["render_as"] == "text"
+ assert not router.is_dispatchable_command(content)
+ assert not router.is_priority(content)
@pytest.mark.asyncio
async def test_exact_command_with_arguments_suggests_valid_form(
@@ -222,25 +215,6 @@ class TestMidTurnCommandDispatchedDirectly:
'Command "/status" does not accept arguments. Did you mean "/status"?'
)
- @pytest.mark.asyncio
- async def test_unknown_command_without_close_match_points_to_help(
- self, router: CommandRouter, fake_loop: MagicMock, fake_msg: MagicMock,
- ) -> None:
- fake_msg.content = "/totally-unknown-command"
- ctx = CommandContext(
- msg=fake_msg, session=None,
- key="test:chat1", raw="/totally-unknown-command", loop=fake_loop,
- )
-
- result = await router.dispatch(ctx)
-
- assert result is not None
- assert result.content == (
- 'Unknown command "/totally-unknown-command". '
- 'Use "/help" to list available commands.'
- )
-
-
class TestPairingCommandDispatch:
"""Verify /pairing works via CommandRouter."""