Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(claude): surface safety fallback notifications (#861)
Call Whiteda47b1a958b4
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 95af2bd23..13ba2b2ba 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -558,15 +558,22 @@ class ClaudeAgent(BaseAgent):message_type = self._detect_message_type(message)formatter = self._get_formatter(context)+ is_model_refusal_fallback = self._is_model_refusal_fallback_message(message)+ model_refusal_fallback_notice = (+ self._parse_model_refusal_fallback_notice(message)+ if is_model_refusal_fallback+ else None+ )# Unsolicited backend output (a background-task completion or# a ScheduleWakeup re-invoked the agent inside this SDK# process) reaches this long-lived receiver with no Avibe turn# open. Open an agent-initiated turn so the reply is persisted# + delivered + notified instead of dropped by the outbound- # active-turn guard. Content messages only — system/user- # frames never carry a user-facing reply.- if message_type in ("assistant", "result"):+ # active-turn guard. An actionable refusal-fallback frame is+ # the one user-facing system exception: it belongs to the+ # replacement run and must use that run's turn.+ if message_type in ("assistant", "result") or model_refusal_fallback_notice is not None:await self._maybe_begin_agent_initiated_turn(context,composite_key,@@ -697,6 +704,26 @@ class ClaudeAgent(BaseAgent):continue+ # Match the structured subtype instead of relying only on the+ # current SDK's generic SystemMessage class. A future SDK may+ # promote this event to a dedicated typed message.+ if is_model_refusal_fallback:+ if model_refusal_fallback_notice is None:+ logger.debug("Ignoring non-actionable Claude refusal fallback for %s", composite_key)+ continue+ if not self._has_pending_requests(composite_key):+ logger.info(+ "Dropping Claude refusal fallback for %s without an active turn",+ composite_key,+ )+ continue+ await self._handle_model_refusal_fallback(+ context,+ composite_key,+ model_refusal_fallback_notice,+ )+ continue+if message_type == "system":formatted_message = self.claude_client.format_message(message,@@ -1321,6 +1348,71 @@ class ClaudeAgent(BaseAgent):parts.append(self._get_formatter(context).escape_special_chars(text))return "\n\n".join(parts).strip()+ @staticmethod+ def _is_model_refusal_fallback_message(message) -> bool:+ return (getattr(message, "subtype", "") or "").strip().lower() == "model_refusal_fallback"++ @staticmethod+ def _parse_model_refusal_fallback_notice(message) -> Optional[tuple[str, str, str]]:+ data = getattr(message, "data", None)+ if not isinstance(data, dict):+ return None++ direction = str(data.get("direction") or "").strip().lower()+ if direction and direction != "retry":+ return None++ original_value = data.get("original_model") or data.get("originalModel") or ""+ fallback_value = data.get("fallback_model") or data.get("fallbackModel") or ""+ original_model = " ".join(str(original_value).split())[:160]+ fallback_model = " ".join(str(fallback_value).split())[:160]+ provider_content = str(data.get("content") or "").strip()+ if not provider_content and not (original_model and fallback_model):+ return None+ return original_model, fallback_model, provider_content++ async def _handle_model_refusal_fallback(+ self,+ context: MessageContext,+ composite_key: str,+ notice: tuple[str, str, str],+ ) -> None:+ """Surface Claude's structured safety fallback without ending the turn."""+ # Claude Code can write this marker after the fallback assistant row. Do+ # not infer retraction order from the marker alone: the result path may+ # still need that assistant text when ResultMessage.result is empty.+ pending_requests = self._pending_requests.get(composite_key) or []+ self._adopt_pending_turn_token(context, pending_requests[0] if pending_requests else None)++ original_model, fallback_model, provider_content = notice++ text = ""+ translator = getattr(self.session_handler, "_t", None) or getattr(self.controller, "_t", None)+ if callable(translator) and original_model and fallback_model:+ text = translator(+ "status.claudeRefusalFallback",+ originalModel=original_model,+ fallbackModel=fallback_model,+ )+ if not text:+ text = provider_content+ if not text:+ logger.warning("Claude refusal fallback for %s had no displayable content", composite_key)+ return++ logger.info(+ "Claude safety fallback for session %s: %s -> %s",+ composite_key,+ original_model or "<unknown>",+ fallback_model or "<unknown>",+ )+ await self.controller.emit_agent_message(+ context,+ "notify",+ text,+ parse_mode="markdown",+ )+async def _handle_auth_failure_result(self,context: MessageContext,diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.pyindex 0ff9264be..100d358a1 100644--- a/tests/test_claude_agent_initiated_turn.py+++ b/tests/test_claude_agent_initiated_turn.py@@ -70,6 +70,23 @@ def _one_result_client():return _Client()+def _fallback_client(data):+ class ModelRefusalFallbackMessage:+ subtype = "model_refusal_fallback"++ def __init__(self):+ self.data = data++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield ModelRefusalFallbackMessage()++ return _iterate()++ return _Client()++def _build_agent(*, running_calls=None, mark_idle_calls=None, active_calls=None):mark_idle_calls = mark_idle_calls if mark_idle_calls is not None else []controller = SimpleNamespace(@@ -217,6 +234,79 @@ class BeginAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):+ async def test_non_actionable_fallback_does_not_open_agent_initiated_turn(self):+ active_calls: list[str] = []+ agent, service = _build_agent(active_calls=active_calls)+ composite_key = "session-fallback:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "OLD",+ "agent_session_id": "sess-fallback",+ },+ )++ await agent._receive_messages(+ _fallback_client(+ {+ "direction": "declined",+ "original_model": "claude-fable-5",+ "fallback_model": "claude-opus-4-8",+ }+ ),+ "session-fallback",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ gate = service._get_turn_gate(composite_key)+ self.assertFalse(gate.lock.locked())+ self.assertEqual(gate.token, "")+ self.assertFalse(agent._has_pending_requests(composite_key))+ self.assertEqual(active_calls, [])+ agent.controller.emit_agent_message.assert_not_awaited()++ async def test_fallback_notice_is_dropped_when_agent_initiated_turn_is_contended(self):+ agent, service = _build_agent()+ composite_key = "session-fallback:/tmp/work"+ gate = service._get_turn_gate(composite_key)+ await gate.lock.acquire()+ gate.token = "USER-TURN"+ gate.backend = "claude"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "OLD",+ "agent_session_id": "sess-fallback",+ },+ )+ try:+ await agent._receive_messages(+ _fallback_client(+ {+ "originalModel": "claude-fable-5",+ "fallbackModel": "claude-opus-4-8",+ }+ ),+ "session-fallback",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )+ finally:+ gate.lock.release()++ self.assertEqual(gate.token, "USER-TURN")+ self.assertFalse(agent._has_pending_requests(composite_key))+ agent.controller.emit_agent_message.assert_not_awaited()+async def test_unsolicited_reply_is_delivered_not_dropped(self):running_calls: list = []mark_idle_calls: list[str] = []diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 3be1e2dba..211071cc0 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -10,6 +10,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from modules.agents.base import BaseAgentfrom modules.agents.claude_agent import ClaudeAgentfrom modules.agents.service import AgentService+from modules.claude_sdk_compat import TextBlockclass _StubSessions:@@ -1362,6 +1363,135 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._native_session_ids[composite_key], "session-sdk")controller.emit_agent_message.assert_not_awaited()+ async def test_receive_legacy_refusal_fallback_notifies_without_dropping_replacement_text(self):+ controller = _StubController()+ controller._get_session_key = lambda _context: "avibe::project::p1"+ controller.im_client.formatter = SimpleNamespace(+ escape_special_chars=lambda text: text,+ format_assistant_message=lambda parts: "\n\n".join(parts),+ )+ controller.session_handler = SimpleNamespace(+ capture_session_id=lambda *_args, **_kwargs: None,+ mark_session_idle=lambda _key: None,+ _t=lambda key, **kwargs: (+ (+ "Claude's safety checks triggered for this request. "+ f"It switched from {kwargs['originalModel']} to {kwargs['fallbackModel']} and retried. "+ f"This session will continue on {kwargs['fallbackModel']}."+ )+ if key == "status.claudeRefusalFallback"+ else key+ ),+ )+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={+ "turn_token": "stale-turn",+ "agent_runtime_turn_token": "stale-runtime",+ },+ )+ pending_context = SimpleNamespace(+ platform_specific={+ "turn_token": "current-turn",+ "agent_runtime_turn_key": "session-1:/tmp/work",+ "agent_runtime_turn_token": "current-runtime",+ }+ )+ pending_request = SimpleNamespace(context=pending_context)+ composite_key = "session-1:/tmp/work"+ agent._pending_requests[composite_key] = [pending_request]++ emitted = []++ async def _emit(message_context, message_type, text, **kwargs):+ emitted.append(+ (+ message_type,+ text,+ kwargs,+ dict(message_context.platform_specific),+ )+ )++ controller.emit_agent_message = AsyncMock(side_effect=_emit)+ replacement_block = TextBlock.__new__(TextBlock)+ replacement_block.text = "replacement answer"+ replacement_message = type(+ "AssistantMessage",+ (),+ {+ "content": [replacement_block],+ "model": "claude-opus-4-8",+ "usage": None,+ "error": None,+ },+ )()+ fallback_message = type(+ "ModelRefusalFallbackMessage",+ (),+ {+ "subtype": "model_refusal_fallback",+ "data": {+ "trigger": "refusal",+ "originalModel": "claude-fable-5[1m]",+ "fallbackModel": "claude-opus-4-8",+ },+ },+ )()+ result_message = type(+ "ResultMessage",+ (),+ {"subtype": "success", "result": None, "duration_ms": 1},+ )()++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield replacement_message+ yield fallback_message+ yield result_message++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-1",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ self.assertEqual(+ emitted,+ [+ (+ "notify",+ "Claude's safety checks triggered for this request. It switched from claude-fable-5[1m] "+ "to claude-opus-4-8 and retried. This session will continue on "+ "claude-opus-4-8.",+ {"parse_mode": "markdown"},+ {+ "turn_token": "current-turn",+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "current-runtime",+ },+ )+ ],+ )+ self.assertNotIn(composite_key, agent._pending_assistant_message)+ self.assertNotIn(composite_key, agent._last_assistant_text)+ agent.emit_result_message.assert_awaited_once_with(+ context,+ "replacement answer",+ subtype="success",+ duration_ms=1,+ parse_mode="markdown",+ request=pending_request,+ )+async def test_init_message_binds_native_session_to_existing_agent_session(self):controller = _StubController()binds = []diff --git a/tests/test_claude_sdk_compat.py b/tests/test_claude_sdk_compat.pyindex e44ba2dbe..503b8d46e 100644--- a/tests/test_claude_sdk_compat.py+++ b/tests/test_claude_sdk_compat.py@@ -52,6 +52,50 @@ def test_receive_messages_skips_unknown_types_returning_none():assert messages == []+@requires_claude_sdk+ "payload",+ [+ pytest.param(+ {+ "type": "system",+ "subtype": "model_refusal_fallback",+ "trigger": "refusal",+ "direction": "retry",+ "original_model": "claude-fable-5",+ "fallback_model": "claude-opus-4-8",+ "request_id": "req_test",+ "api_refusal_category": "cyber",+ "content": "Fable 5 safeguards flagged this request. Switched to Opus 4.8.",+ "uuid": "msg_test",+ "session_id": "session_test",+ },+ id="sdk",+ ),+ pytest.param(+ {+ "type": "system",+ "subtype": "model_refusal_fallback",+ "level": "warning",+ "trigger": "refusal",+ "originalModel": "claude-fable-5[1m]",+ "fallbackModel": "claude-opus-4-8",+ "apiRefusalCategory": None,+ "apiRefusalExplanation": None,+ },+ id="legacy-transcript",+ ),+ ],+)+def test_receive_messages_preserves_model_refusal_fallback_payload(payload):+ messages = asyncio.run(_collect_messages([payload]))++ assert len(messages) == 1+ assert isinstance(messages[0], compat.SystemMessage)+ assert messages[0].subtype == "model_refusal_fallback"+ assert messages[0].data == payload++def test_missing_sdk_permission_allow_fallback_is_non_throwing(monkeypatch):original_import = builtins.__import__diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 62236326e..cadf90fb7 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -4,6 +4,7 @@"done": "done","stopped": "stopped","failed": "failed",+ "claudeRefusalFallback": "Claude's safety checks triggered for this request. It switched from {originalModel} to {fallbackModel} and retried. This session will continue on {fallbackModel}.","steps": "{count} st","tokens": "{count} tok"},diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 28523f1c3..b987412e0 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -4,6 +4,7 @@"done": "完成","stopped": "已终止","failed": "失败",+ "claudeRefusalFallback": "本次请求触发了 Claude 的安全检查,已从 {originalModel} 切换到 {fallbackModel} 并重试。本会话后续将继续使用 {fallbackModel}。","steps": "{count} 步","tokens": "{count} tok"},