An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.
Python ai-agentsai-automationclaudeclaude-codeebbinghausknowledge-graphllmmemory-systemobsidianpersonal-assistantpkmproductivitypythonsecond-braintelegram-botvoice-assistant
feat(chat): slash commands split by behavior, not by leading slash
smixs671f203d4a8b
diff --git a/src/d_brain/bot/handlers/chat.py b/src/d_brain/bot/handlers/chat.pyindex 98796d9..2f08a87 100644--- a/src/d_brain/bot/handlers/chat.py+++ b/src/d_brain/bot/handlers/chat.py@@ -33,9 +33,28 @@ router.message.filter(F.chat.type == ChatType.PRIVATE)MAX_RESPONSE_LENGTH = 4096+# Slash commands split by BEHAVIOR, not by the leading "/":+# - control: client-side Claude Code commands — no model turn, fire-and-forget+# - tui: interactive full-screen UIs — undrivable through a typed pane+# - everything else (incl. /skill-name) is a normal model turn → marker path+_CONTROL = {"/clear", "/compact", "/model"}+_TUI_ONLY = {"/agents", "/config", "/login"}+_manager: ChatSessionManager | None = None+def classify_command(text: str) -> str:+ """'control' | 'tui' | 'turn' for an incoming chat text."""+ if not text.startswith("/"):+ return "turn"+ head = text.split(maxsplit=1)[0]+ if head in _CONTROL:+ return "control"+ if head in _TUI_ONLY:+ return "tui"+ return "turn"++def _get_manager() -> ChatSessionManager:"""Lazy-init ChatSessionManager singleton."""global _manager # noqa: PLW0603@@ -45,6 +64,24 @@ def _get_manager() -> ChatSessionManager:return _manager+async def _dispatch_text(bot: Bot, chat_id: int, user_id: int, text: str) -> None:+ """Route a text by behavior: control → fire-and-forget; tui → hint;+ normal turn (incl. /skill-name) → session via the marker path."""+ kind = classify_command(text)+ if kind == "control":+ await _get_manager().send_control(text)+ await bot.send_message(chat_id, f"⌨️ <code>{html.escape(text)}</code> отправлена в сессию.")+ return+ if kind == "tui":+ await bot.send_message(+ chat_id,+ "Эта команда открывает интерактивный интерфейс — доступно только "+ "через <code>dbrain attach</code> на сервере.",+ )+ return+ await _process_and_reply(bot, chat_id, user_id, text)++async def _process_and_reply(bot: Bot, chat_id: int, user_id: int, prompt: str) -> None:"""Send the prompt to the shared session and deliver the reply."""typing_task = asyncio.create_task(_typing_loop(bot, chat_id))@@ -188,9 +225,14 @@ async def handle_chat_voice(message: Message, bot: Bot) -> None:await message.answer(f"Error: {e}")[email protected](F.text, lambda m: not m.text.startswith("/"))[email protected](F.text)async def handle_chat_text(message: Message, bot: Bot) -> None:- """Handle text messages in private chat (excluding commands)."""+ """Handle text messages in private chat.++ Bot-level commands (/start, /help, …) are intercepted by routers+ registered earlier; anything that reaches here — including Claude Code+ slash commands and /skill-name invocations — is dispatched by behavior.+ """if not message.text or not message.from_user:return@@ -210,4 +252,4 @@ async def handle_chat_text(message: Message, bot: Bot) -> None:msg_id=message.message_id,)- await _process_and_reply(bot, message.chat.id, message.from_user.id, message.text)+ await _dispatch_text(bot, message.chat.id, message.from_user.id, message.text)diff --git a/src/d_brain/services/chat_session.py b/src/d_brain/services/chat_session.pyindex 26be1bf..49fdd14 100644--- a/src/d_brain/services/chat_session.py+++ b/src/d_brain/services/chat_session.py@@ -50,6 +50,11 @@ class ChatSessionManager:logger.warning("session ask for user %d returned %s", user_id, res.status)return _STATUS_MESSAGES.get(res.status, _STATUS_MESSAGES["error"])+ async def send_control(self, text: str) -> None:+ """Fire-and-forget a client-side Claude Code command into the session."""+ async with get_ask_lock():+ await asyncio.to_thread(self._session.send_control, text)+def reset(self, user_id: int) -> None:"""Clear the live session context (durable data in files is kept)."""self._session.clear()diff --git a/src/d_brain/services/claude_session.py b/src/d_brain/services/claude_session.pyindex a3460c8..5efc343 100644--- a/src/d_brain/services/claude_session.py+++ b/src/d_brain/services/claude_session.py@@ -278,13 +278,21 @@ class ClaudeSession:self._ready_flag.unlink(missing_ok=True)self._inflight.unlink(missing_ok=True)- def clear(self) -> None:- """Manual recovery only (durable-state-first: no scheduled clear)."""+ def send_control(self, text: str) -> None:+ """Type a client-side Claude Code command verbatim, fire-and-forget.++ Control commands (/clear, /model, …) produce no model turn and thus+ no marker pair — there is nothing to extract, so don't wait.+ """with self._locked() as got:if got:- self._send_text("/clear")+ self._send_text(text)self._send_enter()+ def clear(self) -> None:+ """Manual recovery only (durable-state-first: no scheduled clear)."""+ self.send_control("/clear")+# ── sending ──────────────────────────────────────────────────────def _send_text(self, text: str) -> None:diff --git a/tests/test_chat_handler.py b/tests/test_chat_handler.pyindex 65039c0..8abe6db 100644--- a/tests/test_chat_handler.py+++ b/tests/test_chat_handler.py@@ -45,3 +45,63 @@ def test_no_debounce_infrastructure_left():for name in ("DEBOUNCE_SECONDS", "DebounceBuffer", "_add_to_buffer", "_debounce_flush", "_buffers"):assert not hasattr(chat, name), f"zombie debounce symbol: {name}"+++# ── slash commands split by BEHAVIOR, not by leading "/" ───────────────────+++def test_classify_command_skill_is_normal_turn():+ from d_brain.bot.handlers.chat import classify_command++ assert classify_command("/vault-note сохрани мысль") == "turn"+ assert classify_command("привет, как дела?") == "turn"+++def test_classify_command_control_is_fire_and_forget():+ from d_brain.bot.handlers.chat import classify_command++ assert classify_command("/clear") == "control"+ assert classify_command("/model sonnet") == "control"+++def test_classify_command_tui_is_unsupported():+ from d_brain.bot.handlers.chat import classify_command++ assert classify_command("/agents") == "tui"+ assert classify_command("/config") == "tui"+ assert classify_command("/login") == "tui"+++def test_control_command_dispatches_fire_and_forget(monkeypatch):+ from d_brain.bot.handlers import chat++ class Mgr(FakeManager):+ def __init__(self):+ super().__init__()+ self.controls: list[str] = []++ async def send_control(self, text: str) -> None:+ self.controls.append(text)++ mgr = Mgr()+ monkeypatch.setattr(chat, "_get_manager", lambda: mgr)+ bot = FakeBot()++ asyncio.run(chat._dispatch_text(bot, chat_id=10, user_id=1, text="/clear"))++ assert mgr.controls == ["/clear"]+ assert mgr.sent == [] # no marker turn started+ assert bot.messages # got an acknowledgement+++def test_tui_command_rejected_with_hint(monkeypatch):+ from d_brain.bot.handlers import chat++ mgr = FakeManager()+ monkeypatch.setattr(chat, "_get_manager", lambda: mgr)+ bot = FakeBot()++ asyncio.run(chat._dispatch_text(bot, chat_id=10, user_id=1, text="/agents"))++ assert mgr.sent == []+ assert bot.messages and "attach" in bot.messages[0][1]