The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(buzz): preserve literal mentions and exact UUID targets
blunkjamie-dev1885a40ad3cc
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex c4114b3fe9b..cfc8ee1a732 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -186,6 +186,40 @@ _CHAT_KIND = 9# deliberately keeps the kind-9-only check: widening it there would let a# p-tagged forum post be reclassified as a DM and bypass mention gating._DISPATCH_KINDS = frozenset({_CHAT_KIND, 45001, 45003})+_UNRESOLVED_MENTION_ERROR_RE = re.compile(+ r"mention '@(?P<name>[^']+)' does not match a current channel member"+)+_BUZZ_PRESENTATION_MENTION_SEPARATOR = "\u200b"+++def _escape_unresolved_presentation_mention(content: str, error: str) -> Optional[str]:+ """Make one CLI-rejected ``@name`` token presentation-only.++ Buzz resolves whitespace-prefixed ``@name`` tokens into notification+ p-tags before signing or publishing. Ordinary prose such as a Hermes+ ``@session:...`` link can therefore fail mention preflight. Insert an+ invisible separator only after the rejected ``@`` so the rendered text+ remains readable while valid member mentions remain unchanged.++ Return ``None`` for unrelated errors or absent tokens. Callers retry at+ most once.+ """+ match = _UNRESOLVED_MENTION_ERROR_RE.search(error or "")+ if match is None:+ return None+ name = match.group("name")+ if not name:+ return None+ token = re.compile(+ rf"(?<!\S)@{re.escape(name)}(?=$|[^A-Za-z0-9._-])",+ re.IGNORECASE,+ )+ escaped, count = token.subn(+ lambda found: "@" + _BUZZ_PRESENTATION_MENTION_SEPARATOR + found.group(0)[1:],+ content,+ )+ return escaped if count else None+# How many events to request per poll / seed call._FETCH_LIMIT = 50# Bound on the per-channel de-dupe set (events, not bytes).@@ -860,6 +894,19 @@ class BuzzAdapter(BasePlatformAdapter):# ── Sending ───────────────────────────────────────────────────────────+ async def _run_message_send(self, args: List[str], content: str):+ """Run one send with a single unresolved-mention preflight retry."""+ code, out, err = await self._run_cli(args, input_text=content)+ if code == 0:+ return code, out, err+ escaped = _escape_unresolved_presentation_mention(content, err)+ if escaped is None:+ return code, out, err+ logger.info(+ "Buzz: retrying message after unresolved presentation-mention preflight"+ )+ return await self._run_cli(args, input_text=escaped)+async def send(self,chat_id: str,@@ -880,7 +927,7 @@ class BuzzAdapter(BasePlatformAdapter):)if reply_target and self._reply_to_mode != "off":args += ["--reply-to", str(reply_target)]- code, out, err = await self._run_cli(args, input_text=content)+ code, out, err = await self._run_message_send(args, content)if code != 0:return SendResult(success=False,@@ -1034,7 +1081,7 @@ class BuzzAdapter(BasePlatformAdapter):)if reply_target and self._reply_to_mode != "off":args += ["--reply-to", str(reply_target)]- code, out, err = await self._run_cli(args, input_text=caption or "")+ code, out, err = await self._run_message_send(args, caption or "")if code != 0:return SendResult(success=False, error=_cli_error_message(err, code), retryable=code == 2)try:@@ -2050,6 +2097,20 @@ async def _standalone_send(auth_tag=auth_tag,input_text=message,)+ if code != 0:+ escaped = _escape_unresolved_presentation_mention(message, err)+ if escaped is not None:+ logger.info(+ "Buzz: retrying standalone message after unresolved "+ "presentation-mention preflight"+ )+ code, out, err = await _exec_buzz(+ cli_path,+ args,+ relay_url=relay,+ private_key=private_key,+ input_text=escaped,+ )except asyncio.CancelledError:raiseexcept OSError as e:diff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.pyindex d6fb44672ac..46dd878b2cc 100644--- a/tests/gateway/test_buzz_adapter.py+++ b/tests/gateway/test_buzz_adapter.py@@ -1365,6 +1365,95 @@ class TestBuzzAdapterSend:args, _stdin = cli.calls[0]assert args[args.index("--reply-to") + 1] == "stable-root"+ @pytest.mark.asyncio+ async def test_send_retries_unresolved_presentation_mention_without_notifying(self):+ adapter = _make_adapter()+ cli = _ScriptedCli()+ cli.script(+ "messages",+ "send",+ "",+ code=1,+ stderr=(+ "mention '@session' does not match a current channel member; "+ "retry with --mention <pubkey>"+ ),+ )+ cli.script(+ "messages",+ "send",+ {"accepted": True, "event_id": "evt124", "message": ""},+ )+ adapter._run_cli = cli++ result = await adapter.send(+ CHANNEL,+ "Continue in @session:default/20260809_092321_24aa09.",+ )++ assert result.success is True+ assert result.message_id == "evt124"+ assert len(cli.calls) == 2+ assert cli.calls[0][1] == (+ "Continue in @session:default/20260809_092321_24aa09."+ )+ assert cli.calls[1][1] == (+ "Continue in @\u200bsession:default/20260809_092321_24aa09."+ )++ @pytest.mark.asyncio+ async def test_send_does_not_retry_unrelated_cli_failure(self):+ adapter = _make_adapter()+ cli = _ScriptedCli()+ cli.script(+ "messages",+ "send",+ "",+ code=1,+ stderr="relay unavailable",+ )+ adapter._run_cli = cli++ result = await adapter.send(CHANNEL, "hello @session")++ assert result.success is False+ assert len(cli.calls) == 1++ @pytest.mark.asyncio+ async def test_send_image_retries_unresolved_presentation_mention(self, tmp_path):+ img = tmp_path / "shot.png"+ img.write_bytes(b"\x89PNG fake")+ adapter = _make_adapter()+ cli = _ScriptedCli()+ cli.script(+ "messages",+ "send",+ "",+ code=1,+ stderr=(+ "mention '@session' does not match a current channel member; "+ "retry with --mention <pubkey>"+ ),+ )+ cli.script(+ "messages",+ "send",+ {"accepted": True, "event_id": "evt127", "message": ""},+ )+ adapter._run_cli = cli++ result = await adapter.send_image(+ CHANNEL,+ str(img),+ caption="See @session:default/example.",+ )++ assert result.success is True+ assert len(cli.calls) == 2+ assert cli.calls[0][1] == "See @session:default/example."+ assert cli.calls[1][1] == "See @\u200bsession:default/example."++# ── Thread anchoring ──────────────────────────────────────────────────────@@ -1706,6 +1795,59 @@ class TestStandaloneSend:assert captured["private_key"] == "nsec1x"assert captured["auth_tag"] == ""+ @pytest.mark.asyncio+ async def test_standalone_send_retries_unresolved_presentation_mention(+ self, monkeypatch, tmp_path+ ):+ from gateway.config import PlatformConfig++ fake_cli = tmp_path / "buzz"+ fake_cli.write_text("#!/bin/sh\n", encoding="utf-8")+ monkeypatch.setenv("BUZZ_RELAY_URL", "https://r")+ monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec1x")+ monkeypatch.setenv("BUZZ_CLI_PATH", str(fake_cli))+ sent = []++ async def fake_exec(+ cli_path,+ args,+ *,+ relay_url,+ private_key,+ input_text=None,+ timeout=30.0,+ ):+ sent.append(input_text)+ if len(sent) == 1:+ return (+ 1,+ "",+ "user_error: mention '@session' does not match a current "+ "channel member; retry with --mention <pubkey>",+ )+ return (+ 0,+ json.dumps(+ {"accepted": True, "event_id": "evt-standalone", "message": ""}+ ),+ "",+ )++ monkeypatch.setattr(_buzz_mod, "_exec_buzz", fake_exec)++ result = await _standalone_send(+ PlatformConfig(enabled=True, extra={}),+ CHANNEL,+ "See @session:default/example.",+ )++ assert result == {"success": True, "message_id": "evt-standalone"}+ assert sent == [+ "See @session:default/example.",+ "See @\u200bsession:default/example.",+ ]++# ── Editing and deleting (streaming) ──────────────────────────────────diff --git a/tests/tools/test_send_message_target_parse.py b/tests/tools/test_send_message_target_parse.pyindex d698070fa6e..8a1b7a44059 100644--- a/tests/tools/test_send_message_target_parse.py+++ b/tests/tools/test_send_message_target_parse.py@@ -29,6 +29,55 @@ def test_e164_target_still_requires_phone_platform() -> None:assert _parse_target_ref("matrix", "+15551234567")[2] is False+def test_buzz_uuid_target_is_explicit() -> None:+ chat_id, thread_id, is_explicit = _parse_target_ref(+ "buzz", "e74ae728-e68a-4f8b-b285-3f19ad2df1f8"+ )++ assert chat_id == "e74ae728-e68a-4f8b-b285-3f19ad2df1f8"+ assert thread_id is None+ assert is_explicit is True+++def test_send_message_routes_buzz_uuid_without_home_fallback() -> None:+ buzz = Platform("buzz")+ buzz_cfg = SimpleNamespace(enabled=True, token=None, extra={})+ config = SimpleNamespace(+ platforms={buzz: buzz_cfg},+ get_home_channel=lambda _platform: SimpleNamespace(+ chat_id="93b1a8c9-7093-4117-9db1-7199bacabd48"+ ),+ )++ with patch("gateway.config.load_gateway_config", return_value=config), \+ patch("tools.interrupt.is_interrupted", return_value=False), \+ patch("gateway.channel_directory.resolve_channel_name", side_effect=AssertionError("raw Buzz UUID should not resolve via directory")), \+ patch("model_tools._run_async", side_effect=_run_async_immediately), \+ patch("tools.send_message_tool._send_to_platform", new=AsyncMock(return_value={"success": True})) as send_mock, \+ patch("gateway.mirror.mirror_to_session", return_value=True):+ result = json.loads(+ send_message_tool(+ {+ "action": "send",+ "target": "buzz:e74ae728-e68a-4f8b-b285-3f19ad2df1f8",+ "message": "exact DM",+ }+ )+ )++ assert result["success"] is True+ assert "note" not in result+ send_mock.assert_awaited_once_with(+ buzz,+ buzz_cfg,+ "e74ae728-e68a-4f8b-b285-3f19ad2df1f8",+ "exact DM",+ thread_id=None,+ media_files=[],+ force_document=False,+ )++def test_send_message_routes_whatsapp_group_jid_without_home_fallback() -> None:whatsapp_cfg = SimpleNamespace(enabled=True, token=None, extra={"api_url": "http://bridge"})config = SimpleNamespace(diff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex 9d641239097..a43b2bc95bd 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -53,6 +53,12 @@ _WHATSAPP_JID_RE = re.compile(r"^\s*[\w-]+@(?:g\.us|s\.whatsapp\.net|lid|broadcast|newsletter)\s*$",re.IGNORECASE,)+# Buzz channels and DMs use native UUID identifiers. They are explicit+# targets and must never substitute the configured home channel.+_BUZZ_UUID_RE = re.compile(+ r"^\s*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\s*$",+ re.IGNORECASE,+)# Email addresses — a valid email like "[email protected]" should be treated as# an explicit target for the email platform, not fall through to channel-name# resolution which has no way to resolve a raw address.@@ -594,6 +600,8 @@ def _parse_target_ref(platform_name: str, target_ref: str):# through to the _PHONE_PLATFORMS handler below.if _WHATSAPP_JID_RE.fullmatch(target_ref):return target_ref.strip(), None, True+ if platform_name == "buzz" and _BUZZ_UUID_RE.fullmatch(target_ref):+ return target_ref.strip(), None, Truestripped_target = target_ref.strip()if platform_name == "signal" and stripped_target.startswith("group:"):group_id = stripped_target[len("group:"):].strip()