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(opencode): wait for directory bootstrap before a turn's first request (#2305)
Call Whiteaaf1018e02b4
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex cb79ad0a9..18b756400 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -92,6 +92,7 @@ from .poll_loop import (restored_session_key_from_poll_info,)from .server import (+ OpenCodeDirectoryBootstrapTimeoutError,OpenCodeManagedPolicyRefreshPendingError,OpenCodeModelHubOverlayRequiredError,OpenCodePromptRejectedError,@@ -1065,6 +1066,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):localized_key = "error.opencodePolicyRefreshPending"elif isinstance(error, OpenCodeRuntimeConfigInvalidError):localized_key = "error.opencodeRuntimeConfigInvalid"+ elif isinstance(error, OpenCodeDirectoryBootstrapTimeoutError):+ localized_key = "error.opencodeDirectoryBootstrapTimeout"if localized_key is not None:language = str(getattr(getattr(self.controller, "config", None), "language", "en")@@ -1361,6 +1364,12 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await server.ensure_running()caller_context_binding_path = _caller_context_path_for_server(server)activation_identity = self._attach_server_activation(server)+ await self._session_manager.ensure_working_dir(request.working_path)+ # A healthy server may still be bootstrapping this directory (about+ # a minute on a fresh host). Waiting here, before the ack is deleted,+ # keeps the turn visibly in progress and leaves session creation to+ # its ordinary request timeout.+ await server.ensure_directory_ready(request.working_path)except asyncio.CancelledError:await self._finish_prestart_cancellation(request,@@ -1392,7 +1401,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):try:await self._delete_ack(request)- await self._session_manager.ensure_working_dir(request.working_path)except BaseException as error:if isinstance(error, asyncio.CancelledError):await self._finish_prestart_cancellation(diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex d321c335e..11c037d7a 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -52,6 +52,14 @@ DEFAULT_OPENCODE_HOST = "127.0.0.1"# A cold OpenCode process can take more than 15 seconds to load on a busy or# freshly provisioned host. This is a startup ceiling, not a request timeout.SERVER_START_TIMEOUT = 60+# ``/global/health`` only proves the process is serving. OpenCode bootstraps a+# per-directory instance on that directory's first request, and with any plugin+# configured (Avibe always installs one) the bootstrap waits for OpenCode's own+# npm install into each config directory that has no ``node_modules`` yet: about+# a minute on a fresh host. The bootstrap keeps running inside OpenCode if the+# client gives up, so a later request joins it. This is a readiness ceiling, not+# a request timeout.+DIRECTORY_BOOTSTRAP_TIMEOUT = 300OPENCODE_LOG_TAIL_BYTES = 2_000_000MODEL_HUB_OVERLAY_DRAIN_TIMEOUT_SECONDS = 30.0_USE_CURRENT_CALLER_CONTEXT_PATH = object()@@ -229,6 +237,10 @@ class OpenCodeModelHubOverlayRequiredError(RuntimeError):"""Hub mode cannot launch OpenCode until its owner configures an overlay."""+class OpenCodeDirectoryBootstrapTimeoutError(RuntimeError):+ """OpenCode is still bootstrapping a directory after the readiness ceiling."""++class OpenCodeServerManager:"""Manages a singleton OpenCode server process shared across all working directories."""@@ -2138,6 +2150,28 @@ class OpenCodeServerManager:# Let it continue running so the next vibe-remote instance can adopt it.logger.info("OpenCode server left running for next vibe-remote instance to adopt")+ async def ensure_directory_ready(self, directory: str) -> None:+ """Wait until OpenCode has bootstrapped its instance for ``directory``.++ Any directory-scoped request waits for that bootstrap; an idempotent read+ takes the wait so no request with side effects can time out halfway.+ """+ async with self._request_scope():+ session = await self._get_http_session()+ try:+ async with session.get(+ f"{self.base_url}/path",+ headers={"x-opencode-directory": _percent_encode_path(directory)},+ timeout=aiohttp.ClientTimeout(total=DIRECTORY_BOOTSTRAP_TIMEOUT),+ ) as resp:+ if resp.status != 200:+ text = await resp.text()+ raise RuntimeError(f"OpenCode could not prepare {directory}: {resp.status} {text}")+ except asyncio.TimeoutError as exc:+ raise OpenCodeDirectoryBootstrapTimeoutError(+ f"OpenCode did not finish preparing {directory} within {DIRECTORY_BOOTSTRAP_TIMEOUT}s"+ ) from exc+async def create_session(self, directory: str, title: Optional[str] = None) -> Dict[str, Any]:async with self._request_scope():session = await self._get_http_session()diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex 33b87007b..5bff6528d 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -1316,6 +1316,9 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanuasync def ensure_running(self):return None+ async def ensure_directory_ready(self, directory):+ return None+async def list_messages(self, session_id, directory):return []@@ -1455,6 +1458,9 @@ async def test_opencode_ambiguous_start_failure_preserves_recovery_poll(async def ensure_running(self):return None+ async def ensure_directory_ready(self, directory):+ return None+async def list_messages(self, session_id, directory):return []@@ -2947,6 +2953,9 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(async def ensure_running(self):return None+ async def ensure_directory_ready(self, directory):+ return None+async def list_messages(self, session_id, directory):return [{"info": {"id": "primary-user", "role": "user"}, "parts": []}]diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 475f7f58b..d301b7d60 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -1089,6 +1089,9 @@ def test_opencode_fork_prompt_marks_target_session_id_authoritative():async def ensure_running(self):return None+ async def ensure_directory_ready(self, directory):+ return None+async def list_messages(self, session_id, directory):return []@@ -1290,6 +1293,9 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(async def ensure_running(self):return None+ async def ensure_directory_ready(self, directory):+ return None+async def list_messages(self, session_id, directory):return []@@ -3910,6 +3916,9 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, casync def ensure_running(self):return None+ async def ensure_directory_ready(self, directory):+ return None+async def list_messages(self, session_id, directory):return []diff --git a/tests/test_opencode_directory_bootstrap.py b/tests/test_opencode_directory_bootstrap.pynew file mode 100644index 000000000..8dc5585ba--- /dev/null+++ b/tests/test_opencode_directory_bootstrap.py@@ -0,0 +1,161 @@+"""A healthy OpenCode server can still be bootstrapping the turn's directory.++OpenCode answers ``/global/health`` as soon as it serves, but bootstraps a+per-directory instance on that directory's first request. On a fresh host the+bootstrap waits for OpenCode's own npm install and outlasts Avibe's ordinary+request timeout, so a first turn must wait for it instead of failing.+"""++from __future__ import annotations++import asyncio+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++from aiohttp import web++import modules.agents.opencode.server as server_module+from modules.agents.base import AgentRequest+from modules.agents.opencode.agent import OpenCodeAgent+from modules.agents.opencode.server import OpenCodeServerManager+from modules.agents.opencode.session import OpenCodeSessionManager+from modules.im import MessageContext++REQUEST_TIMEOUT_SECONDS = 1+++@asynccontextmanager+async def _cold_opencode(bootstrap_seconds: float):+ """Serve OpenCode's cold-start contract over real HTTP.++ Health answers at once. Every directory-scoped request waits for that+ directory's one-time bootstrap, which keeps running when a client gives up.+ """++ bootstraps: dict[str, asyncio.Task] = {}+ created_sessions: list[str] = []++ async def bootstrapped(request: web.Request) -> None:+ directory = request.headers["x-opencode-directory"]+ if directory not in bootstraps:+ bootstraps[directory] = asyncio.ensure_future(asyncio.sleep(bootstrap_seconds))+ await asyncio.shield(bootstraps[directory])++ async def health(_request: web.Request) -> web.Response:+ return web.json_response({"healthy": True, "version": "1.18.18"})++ async def path(request: web.Request) -> web.Response:+ await bootstrapped(request)+ return web.json_response({"directory": request.headers["x-opencode-directory"]})++ async def create_session(request: web.Request) -> web.Response:+ await bootstrapped(request)+ session_id = f"ses_cold_{len(created_sessions) + 1}"+ created_sessions.append(session_id)+ return web.json_response({"id": session_id})++ async def abort_session(request: web.Request) -> web.Response:+ await bootstrapped(request)+ return web.json_response(True)++ app = web.Application()+ app.router.add_get("/global/health", health)+ app.router.add_get("/path", path)+ app.router.add_post("/session", create_session)+ app.router.add_post("/session/{session_id}/abort", abort_session)+ runner = web.AppRunner(app, handler_cancellation=True)+ await runner.setup()+ try:+ await web.TCPSite(runner, "127.0.0.1", 0).start()+ yield runner.addresses[0][1], created_sessions+ finally:+ for task in bootstraps.values():+ task.cancel()+ await runner.cleanup()+++async def _first_turn(tmp_path, port: int, monkeypatch):+ """Run a fresh thread's first turn up to the point it would prompt."""++ reached_prompt: list[tuple[str, str, str] | None] = []+ failures: list[str] = []++ async def emit_backend_failure(_controller, _context, _backend, _error, *, display_text, request):+ failures.append(display_text)++ monkeypatch.setattr("modules.agents.opencode.agent.emit_backend_failure", emit_backend_failure)++ server = OpenCodeServerManager(port=port, request_timeout_seconds=REQUEST_TIMEOUT_SECONDS)+ # The process is up and healthy; its lifecycle is not what this covers.+ server.ensure_running = AsyncMock(return_value=server.base_url)++ agent = object.__new__(OpenCodeAgent)+ sessions = SimpleNamespace(+ get_agent_session_id=Mock(return_value=None),+ ensure_agent_session_id=Mock(return_value="sesavibe01"),+ bind_agent_session=Mock(return_value="sesavibe01"),+ remove_active_poll=Mock(),+ )+ agent.sessions = sessions+ agent._session_manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")++ def stop_before_prompt(_context):+ reached_prompt.append(agent._session_manager.get_request_session(request.base_session_id))+ raise RuntimeError("test boundary before the prompt")++ agent.controller = SimpleNamespace(+ config=SimpleNamespace(language="en", platform="slack"),+ get_opencode_overrides=stop_before_prompt,+ )+ agent.config = agent.controller.config+ agent._get_server = AsyncMock(return_value=server)+ agent._delete_ack = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent.record_model_hub_native_failure = AsyncMock()+ agent._steering_states = {}++ working_path = str(tmp_path / "workspace")+ request = AgentRequest(+ context=MessageContext(user_id="U1", channel_id="C1", platform="slack", platform_specific={}),+ message="hello",+ user_message="hello",+ working_path=working_path,+ base_session_id="base-1",+ composite_session_id=f"base-1:{working_path}",+ session_key="slack::channel::C1",+ )+ try:+ await agent._process_message(request)+ finally:+ await server.close_http_session()+ return working_path, reached_prompt, failures+++def test_first_turn_waits_for_directory_bootstrap_longer_than_request_timeout(tmp_path, monkeypatch) -> None:+ async def scenario():+ async with _cold_opencode(bootstrap_seconds=REQUEST_TIMEOUT_SECONDS + 1) as (port, created_sessions):+ working_path, reached_prompt, failures = await _first_turn(tmp_path, port, monkeypatch)+ return working_path, reached_prompt, failures, created_sessions++ working_path, reached_prompt, failures, created_sessions = asyncio.run(scenario())++ assert reached_prompt == [("ses_cold_1", working_path, "slack::channel::C1")]+ assert created_sessions == ["ses_cold_1"]+ assert failures == ["OpenCode request failed: RuntimeError: test boundary before the prompt"]+++def test_bootstrap_past_the_readiness_ceiling_reports_first_time_setup(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(server_module, "DIRECTORY_BOOTSTRAP_TIMEOUT", REQUEST_TIMEOUT_SECONDS, raising=False)++ async def scenario():+ async with _cold_opencode(bootstrap_seconds=REQUEST_TIMEOUT_SECONDS + 2) as (port, created_sessions):+ _working_path, reached_prompt, failures = await _first_turn(tmp_path, port, monkeypatch)+ return reached_prompt, failures, created_sessions++ reached_prompt, failures, created_sessions = asyncio.run(scenario())++ assert reached_prompt == []+ assert created_sessions == []+ assert failures == ["❌ OpenCode is still finishing its first-time setup. Send your message again shortly."]+diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.pyindex 10eeb476e..411a568fb 100644--- a/tests/test_opencode_stop_receipt.py+++ b/tests/test_opencode_stop_receipt.py@@ -333,6 +333,9 @@ class _StubOpenCodeServer:self.start_entered.set()await asyncio.Event().wait()+ async def ensure_directory_ready(self, _directory):+ return None+async def list_messages(self, **_kwargs):return []diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 132196771..7f35320c5 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -442,6 +442,7 @@"opencodeModelHubOverlayRequired": "OpenCode is still preparing for Gateway mode. Retry in a moment.","opencodePolicyRefreshPending": "OpenCode is still finishing an existing turn and cannot restart with Avibe's current Skill policy yet. Retry after that turn finishes.","opencodeRuntimeConfigInvalid": "OpenCode could not start because OPENCODE_CONFIG_CONTENT is invalid. Fix the runtime configuration and retry.",+ "opencodeDirectoryBootstrapTimeout": "OpenCode is still finishing its first-time setup. Send your message again shortly.","resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?","resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it.","fileAttachmentUploadFailedWithLink": "⚠️ I could not deliver {filename} as a WeChat file. You can download it from Avibe after signing in if prompted:\n{url}",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 5c33d0545..e8bb965b2 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -442,6 +442,7 @@"opencodeModelHubOverlayRequired": "OpenCode 仍在准备 Gateway 模式,请稍后重试。","opencodePolicyRefreshPending": "OpenCode 仍在完成已有回合,暂时无法按 Avibe 当前的 Skill 策略重启。请在该回合结束后重试。","opencodeRuntimeConfigInvalid": "OpenCode 无法启动,因为 OPENCODE_CONFIG_CONTENT 无效。请修正运行时配置后重试。",+ "opencodeDirectoryBootstrapTimeout": "OpenCode 仍在完成首次准备,请稍后重新发送消息。","resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?","resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。","fileAttachmentUploadFailedWithLink": "⚠️ {filename} 没能作为微信文件直接发送。你可以通过 Avibe 下载;如提示登录,请先登录:\n{url}",