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(session): optional markers (wrap=False) + idle-based completion
smixsda9176a14210
diff --git a/src/d_brain/services/claude_session.py b/src/d_brain/services/claude_session.pyindex bf45e76..a3460c8 100644--- a/src/d_brain/services/claude_session.py+++ b/src/d_brain/services/claude_session.py@@ -36,6 +36,8 @@ from d_brain.services.tmux_parse import (classify_state,extract_reply,is_complete,+ is_idle,+ strip_chrome,)logger = logging.getLogger(__name__)@@ -296,9 +298,13 @@ class ClaudeSession:self._tmux("paste-buffer", "-t", self._target, "-b", buf, "-d")self._sleep(self._paste_settle)- def _send_prompt(self, prompt: str, rid: str) -> None:+ def _send_prompt(self, prompt: str, rid: str, *, wrap: bool = True) -> None:# Markers are written INLINE (mid-sentence) so the input echo never# forms a line-anchored pair; only the model's answer does.+ if not wrap:+ self._send_text(prompt)+ self._send_enter()+ returnpayload = (f"{prompt}\n\n"f"When done, wrap your ENTIRE reply between a line containing only "@@ -315,6 +321,7 @@ class ClaudeSession:*,timeout: float = DEFAULT_TIMEOUT,request_id: str | None = None,+ wrap: bool = True,) -> AskResult:"""Send a prompt, return the model's reply (or a non-ok status).@@ -323,6 +330,12 @@ class ClaudeSession:logged-out short-circuit, a frozen pane (stall) is interrupted, and ahard timeout returns a timeout status. request_id is for logging only;the marker rid is always freshly generated to avoid stale answers.++ wrap=True (default) appends the marker instruction and extracts the+ reply between the marker pair — the reliable path for model turns.+ wrap=False types the prompt verbatim; completion is the pane sitting+ idle for two consecutive polls and the reply is the chrome-stripped+ pane text (best effort, may include the input echo)."""rid = self._rid_factory()log_id = request_id or rid@@ -342,11 +355,12 @@ class ClaudeSession:return AskResult("logged_out")self._inflight.write_text(f"{log_id}\n{self._clock()}\n")- self._send_prompt(prompt, rid)+ self._send_prompt(prompt, rid, wrap=wrap)last_live = self._liveness_fn()last_change = self._clock()deadline = self._clock() + timeout+ idle_streak = 0while self._clock() < deadline:cap = self._capture()state = classify_state(cap)@@ -356,9 +370,17 @@ class ClaudeSession:if state == PaneState.LOGGED_OUT:self._inflight.unlink(missing_ok=True)return AskResult("logged_out")- if is_complete(cap, rid):- self._inflight.unlink(missing_ok=True)- return AskResult("ok", reply=extract_reply(cap, rid))+ if wrap:+ if is_complete(cap, rid):+ self._inflight.unlink(missing_ok=True)+ return AskResult("ok", reply=extract_reply(cap, rid))+ elif is_idle(cap):+ idle_streak += 1+ if idle_streak >= 2:+ self._inflight.unlink(missing_ok=True)+ return AskResult("ok", reply=strip_chrome(cap))+ else:+ idle_streak = 0live = self._liveness_fn()if live != last_live:diff --git a/src/d_brain/services/tmux_parse.py b/src/d_brain/services/tmux_parse.pyindex d2fccee..c5829f5 100644--- a/src/d_brain/services/tmux_parse.py+++ b/src/d_brain/services/tmux_parse.py@@ -119,12 +119,37 @@ _STARTING_RE = re.compile(r"Claude Code v\d", re.I)# bypass footer is ALWAYS on screen under --dangerously-skip-permissions and# must never be used as an idle signal by itself._WORKING_RE = re.compile(r"esc to interrupt")+# Idle = a BARE ❯ on its own line (empty input). A menu selector ("❯ 1. Yes…")+# has text after the chevron and must NOT count — otherwise a turn stuck on an+# approval/menu prompt would be mistaken for completion (wrap=False).+_IDLE_BARE_RE = re.compile(r"(?m)^\s*❯\s*$")def _chrome(text: str) -> str:return "\n".join(text.splitlines()[-_CHROME_LINES:])+_CHROME_LINE_RE = re.compile(+ r"^\s*❯?\s*$" # empty / bare idle prompt+ r"|^\s*─+\s*$" # box rule+ r"|bypass permissions on" # always-present footer+ r"|esc to interrupt" # working spinner hint+ r"|^\s*⏵⏵" # footer arrows+ r"|^\s{2}\S.* \| .* \| " # status line: " name | model | path"+)+++def strip_chrome(text: str) -> str:+ """Best-effort body of a non-marker turn: drop TUI chrome lines.++ Used for ``wrap=False`` turns where no marker pair exists; the result may+ still contain the input echo — callers treat it as informational text,+ not a structured reply.+ """+ kept = [ln for ln in text.splitlines() if not _CHROME_LINE_RE.search(ln)]+ return "\n".join(kept).strip()++def is_idle(text: str) -> bool:"""True iff the session sits at an idle input prompt (no active turn).@@ -138,7 +163,7 @@ def is_idle(text: str) -> bool:chrome = _chrome(text)if _WORKING_RE.search(chrome):return False- return bool(_IDLE_RE.search(chrome))+ return bool(_IDLE_BARE_RE.search(chrome))def classify_state(text: str) -> PaneState:diff --git a/tests/test_claude_session.py b/tests/test_claude_session.pyindex dd25d0c..1c1196f 100644--- a/tests/test_claude_session.py+++ b/tests/test_claude_session.py@@ -301,3 +301,55 @@ def test_kill_sends_kill_session(tmp_path, clock):assert "kill-session" in fake.sent_subcommands()+++# ── optional markers (wrap=False) + idle-based completion ──────────────────+++class FakeTmuxText(FakeTmux):+ """FakeTmux that also records text streamed to load-buffer."""++ def __init__(self, *args, **kwargs) -> None:+ super().__init__(*args, **kwargs)+ self.texts: list[str] = []++ def __call__(self, args, **kwargs): # noqa: ANN001+ if kwargs.get("input") is not None:+ self.texts.append(kwargs["input"])+ return super().__call__(args, **kwargs)+++def test_ask_wrap_false_does_not_append_marker_instruction(tmp_path, clock):+ fake = FakeTmuxText([READY, THINKING, "ответ\n" + READY, "ответ\n" + READY], exists=True)+ (tmp_path / ".dbrain").mkdir()+ (tmp_path / ".dbrain" / "ready").touch()+ s = make_session(tmp_path, fake, clock)+ s.ask("/clear", timeout=30, wrap=False)+ assert fake.texts, "prompt was not streamed to the pane"+ assert "<<<R:" not in fake.texts[0]+ assert "When done" not in fake.texts[0]+++def test_ask_wrap_false_completes_on_idle(tmp_path, clock):+ fake = FakeTmuxText(+ [READY, THINKING, THINKING, "ответ модели\n" + READY, "ответ модели\n" + READY],+ exists=True,+ )+ (tmp_path / ".dbrain").mkdir()+ (tmp_path / ".dbrain" / "ready").touch()+ s = make_session(tmp_path, fake, clock)+ res = s.ask("сделай дело", timeout=30, wrap=False)+ assert res.ok, res+ assert "ответ модели" in (res.reply or "")+ assert "bypass permissions" not in (res.reply or "")+++def test_ask_wrap_true_still_appends_markers(tmp_path, clock):+ rid = "rid00001"+ fake = FakeTmuxText([READY, _complete(rid)], exists=True)+ (tmp_path / ".dbrain").mkdir()+ (tmp_path / ".dbrain" / "ready").touch()+ s = make_session(tmp_path, fake, clock)+ res = s.ask("ping", timeout=30)+ assert res.ok and res.reply == "PONG"+ assert fake.texts and f"<<<R:{rid}>>>" in fake.texts[0]diff --git a/tests/test_tmux_parse.py b/tests/test_tmux_parse.pyindex a137f5c..e1d5e14 100644--- a/tests/test_tmux_parse.py+++ b/tests/test_tmux_parse.py@@ -340,3 +340,17 @@ def test_is_idle_false_on_empty_pane():from d_brain.services.tmux_parse import is_idleassert not is_idle("")+++def test_is_idle_false_on_menu_selector():+ """An interactive menu's selector (`❯ 1. Yes …`) is NOT an idle prompt —+ only a bare ❯ (empty input line) counts. Guards wrap=False completion+ against approval/menu prompts."""+ from d_brain.services.tmux_parse import is_idle++ pane = (+ "Do you approve this plan?\n"+ " ❯ 1. Yes, proceed\n 2. No, keep planning\n"+ " ⏵⏵ bypass permissions on (shift+tab to cycle)\n"+ )+ assert not is_idle(pane)