Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(claude): raise sdk json buffer size

cyhhao5a9782901cec
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index ab43004b3..11b23c6ad 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -13,7 +13,12 @@ import uuid
from dataclasses import dataclass
from typing import Any, Optional
-from modules.claude_sdk_compat import CLAUDE_SDK_AVAILABLE, ClaudeAgentOptions, ClaudeSDKClient
+from modules.claude_sdk_compat import (
+ CLAUDE_SDK_AVAILABLE,
+ CLAUDE_SDK_MAX_BUFFER_SIZE,
+ ClaudeAgentOptions,
+ ClaudeSDKClient,
+)
from modules.im import InlineButton, InlineKeyboard, MessageContext
from vibe.i18n import t as i18n_t
from vibe.opencode_config import remove_opencode_provider_api_key
@@ -647,6 +652,7 @@ class AgentAuthService:
"cwd": working_path,
"env": claude_env,
"setting_sources": ["user", "project", "local"],
+ "max_buffer_size": CLAUDE_SDK_MAX_BUFFER_SIZE,
}
permission_mode = getattr(getattr(self.controller.config, "claude", None), "permission_mode", None)
if permission_mode:
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index ea53d025b..e5644f6dd 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -8,7 +8,11 @@ import time
from typing import Optional, Dict, Any, Tuple
from uuid import uuid4
from modules.im import MessageContext
-from modules.claude_sdk_compat import ClaudeSDKClient, ClaudeAgentOptions
+from modules.claude_sdk_compat import (
+ CLAUDE_SDK_MAX_BUFFER_SIZE,
+ ClaudeAgentOptions,
+ ClaudeSDKClient,
+)
from modules.agents.native_sessions.base import build_resume_preview
from .base import BaseHandler
@@ -553,6 +557,7 @@ class SessionHandler(BaseHandler):
"disallowed_tools": ["AskUserQuestion"],
"env": claude_env, # Pass Anthropic/Claude env vars
"stderr": _capture_claude_stderr,
+ "max_buffer_size": CLAUDE_SDK_MAX_BUFFER_SIZE,
}
cli_path_override = self._get_claude_cli_path_override()
if cli_path_override:
@@ -887,6 +892,8 @@ class SessionHandler(BaseHandler):
context,
self._get_formatter(context).format_error(self._t("error.sessionReset")),
)
+ # TODO: Consider treating Claude SDK oversized JSON buffer failures as
+ # broken sessions once the recovery behavior is validated in production.
elif "Session is broken" in error_msg or "Connection closed" in error_msg or "Connection lost" in error_msg:
logger.error(f"Session {composite_key} is broken - cleaning up")
await self.cleanup_session(composite_key)
diff --git a/main.py b/main.py
index 847383210..29cd90af3 100644
--- a/main.py
+++ b/main.py
@@ -39,19 +39,25 @@ def apply_claude_sdk_patches():
"""Apply runtime patches for third-party SDK limits."""
logger = logging.getLogger(__name__)
try:
+ from modules.claude_sdk_compat import CLAUDE_SDK_MAX_BUFFER_SIZE
from claude_agent_sdk._internal.transport import subprocess_cli
except Exception as exc:
logger.warning(f"Claude SDK patch skipped: {exc}")
return
- buffer_size = 16 * 1024 * 1024
- previous = getattr(subprocess_cli, "_MAX_BUFFER_SIZE", None)
- subprocess_cli._MAX_BUFFER_SIZE = buffer_size
- if previous != buffer_size:
+ patched = []
+ for attr in ("_DEFAULT_MAX_BUFFER_SIZE", "_MAX_BUFFER_SIZE"):
+ if not hasattr(subprocess_cli, attr):
+ continue
+ previous = getattr(subprocess_cli, attr)
+ setattr(subprocess_cli, attr, CLAUDE_SDK_MAX_BUFFER_SIZE)
+ if previous != CLAUDE_SDK_MAX_BUFFER_SIZE:
+ patched.append(f"{attr} from {previous} to {CLAUDE_SDK_MAX_BUFFER_SIZE} bytes")
+
+ if patched:
logger.info(
- "Patched claude_agent_sdk _MAX_BUFFER_SIZE from %s to %s bytes",
- previous,
- buffer_size,
+ "Patched claude_agent_sdk buffer limits: %s",
+ ", ".join(patched),
)
diff --git a/modules/claude_client.py b/modules/claude_client.py
index 09ed7d8b9..204688a89 100644
--- a/modules/claude_client.py
+++ b/modules/claude_client.py
@@ -2,6 +2,7 @@ import logging
import os
from typing import Optional, Callable
from modules.claude_sdk_compat import (
+ CLAUDE_SDK_MAX_BUFFER_SIZE,
ClaudeAgentOptions,
SystemMessage,
AssistantMessage,
@@ -26,6 +27,7 @@ class ClaudeClient:
permission_mode=config.permission_mode, # type: ignore[arg-type]
cwd=config.cwd,
system_prompt=config.system_prompt,
+ max_buffer_size=CLAUDE_SDK_MAX_BUFFER_SIZE,
) # type: ignore[arg-type]
def format_message(
diff --git a/modules/claude_sdk_compat.py b/modules/claude_sdk_compat.py
index 6dc8c4d7d..8c35c1747 100644
--- a/modules/claude_sdk_compat.py
+++ b/modules/claude_sdk_compat.py
@@ -6,6 +6,14 @@ import logging
logger = logging.getLogger(__name__)
+CLAUDE_SDK_MAX_BUFFER_SIZE = 16 * 1024 * 1024
+CLAUDE_SDK_BUFFER_ERROR_TEXT = "JSON message exceeded maximum buffer size"
+
+
+def is_claude_sdk_buffer_error(error: object) -> bool:
+ """Return True when Claude SDK failed on a single oversized JSON message."""
+ return CLAUDE_SDK_BUFFER_ERROR_TEXT in str(error)
+
try:
from claude_agent_sdk import ( # type: ignore[import-not-found]
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index ac5ae98fe..c628f8d7b 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -15,6 +15,7 @@ from core.agent_auth_service import (
classify_auth_error,
verify_opencode_auth_list_output,
)
+from modules.claude_sdk_compat import CLAUDE_SDK_MAX_BUFFER_SIZE
from modules.im import MessageContext
@@ -878,6 +879,33 @@ class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):
controller.agent_service.agents["claude"].refresh_auth_state.assert_awaited_once()
service._refresh_opencode_server.assert_awaited_once()
+ async def test_create_claude_control_client_sets_large_sdk_buffer(self):
+ controller = _StubController()
+ service = AgentAuthService(controller)
+ context = MessageContext(user_id="U1", channel_id="C1")
+ captured = {}
+
+ class _StubClaudeAgentOptions:
+ def __init__(self, **kwargs):
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self):
+ captured["connected"] = True
+
+ with (
+ patch("core.agent_auth_service.ClaudeAgentOptions", _StubClaudeAgentOptions),
+ patch("core.agent_auth_service.ClaudeSDKClient", _StubClaudeSDKClient),
+ ):
+ await service._create_claude_control_client(context)
+
+ self.assertTrue(captured["connected"])
+ self.assertEqual(captured["options"].max_buffer_size, CLAUDE_SDK_MAX_BUFFER_SIZE)
+
async def test_verify_login_reports_opencode_segmentation_fault(self):
controller = _StubController()
service = AgentAuthService(controller)
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 0cdb4da74..4dd29f2db 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -14,6 +14,7 @@ import core.handlers.session_handler as session_handler_module
from config.v2_compat import to_app_config
from config.v2_config import AgentsConfig, ClaudeConfig, RuntimeConfig, SlackConfig, V2Config
from core.handlers.session_handler import SessionHandler
+from modules.claude_sdk_compat import CLAUDE_SDK_MAX_BUFFER_SIZE
from modules.im import MessageContext
@@ -134,6 +135,7 @@ def test_session_handler_passes_configured_claude_cli_path(monkeypatch, tmp_path
assert captured["connected"] is True
assert captured["options"].cli_path == "/usr/local/bin/claude-proxy"
+ assert captured["options"].max_buffer_size == CLAUDE_SDK_MAX_BUFFER_SIZE
assert controller.claude_sessions[f"slack_C123:{tmp_path}"] is client
assert getattr(client, "_vibe_runtime_base_session_id") == "slack_C123"
assert getattr(client, "_vibe_runtime_session_key") == f"slack_C123:{tmp_path}"
diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.py
index 62080b378..ce4337a1c 100644
--- a/tests/test_session_handler_base_id.py
+++ b/tests/test_session_handler_base_id.py
@@ -345,3 +345,29 @@ def test_claude_session_not_found_error_is_reported_without_cleanup() -> None:
assert message.startswith("ERR:Claude Code could not find the historical session")
assert "11111111-1111-1111-1111-111111111111" in message
assert "/tmp/other" in message
+
+
+def test_claude_sdk_buffer_error_is_reported_without_cleanup_for_now() -> None:
+ controller = _Controller(platform="slack", dm_threads=False)
+ controller.im_client = _FakeIM()
+ handler = SessionHandler(controller)
+ cleanup_calls = []
+
+ async def _cleanup_session(composite_key: str) -> None:
+ cleanup_calls.append(composite_key)
+
+ handler.cleanup_session = _cleanup_session
+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")
+
+ asyncio.run(
+ handler.handle_session_error(
+ "slack_C123:/tmp/workdir",
+ context,
+ RuntimeError("Failed to decode JSON: JSON message exceeded maximum buffer size of 1048576 bytes"),
+ )
+ )
+
+ assert cleanup_calls == []
+ assert len(controller.im_client.sent_messages) == 1
+ _, message = controller.im_client.sent_messages[0]
+ assert "JSON message exceeded maximum buffer size" in message