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(opencode): wait for async prompt startup

cyh9c503ba75b46
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 531b97140..d198b023f 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -242,7 +242,6 @@ def classify_auth_error(backend: str, error_text: str) -> bool:
"authentication",
"credential",
"api key",
- "provider",
"failed to send message: 401",
"failed to start async prompt: 401",
)
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 6af76caea..c0b715267 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -65,6 +65,9 @@ from .utils import resolve_opencode_model_id, resolve_opencode_reasoning_effort
logger = logging.getLogger(__name__)
_STEERING_SNAPSHOT_KEY = "opencode_native_steering"
_STATUS_RECONCILIATION_FAILURE_LIMIT = 3
+# OpenCode returns 204 after forking prompt work, before that worker necessarily
+# registers the session as busy.
+_ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS = 5.0
_RESTORED_IM_REGISTRATION_RETRY_DELAY_SECONDS = 0.25
_RESTORED_IM_PLATFORMS = {"slack", "discord", "telegram", "lark", "wechat"}
@@ -91,6 +94,8 @@ class _OpenCodeSteerState:
closing: bool = False
awaiting_after_message_ids: set[str] | None = None
awaiting_user_text: str | None = None
+ awaiting_start_confirmation_deadline: float | None = None
+ awaiting_active_status_observed: bool = False
idle_reconciliation_message: str = ""
restored: bool = False
reconcile_initial_status: bool = False
@@ -231,6 +236,12 @@ class _SteeringAwareOpenCodeServer:
)
)
+ def _clear_awaiting_reconciliation(self) -> None:
+ self._state.awaiting_after_message_ids = None
+ self._state.awaiting_user_text = None
+ self._state.awaiting_start_confirmation_deadline = None
+ self._state.awaiting_active_status_observed = False
+
def _terminal_reconciliation_failure(
self,
session_id: str,
@@ -305,8 +316,7 @@ class _SteeringAwareOpenCodeServer:
inserted_user_text=inserted_user_text,
)
):
- self._state.awaiting_after_message_ids = None
- self._state.awaiting_user_text = None
+ self._clear_awaiting_reconciliation()
self._state.reconcile_initial_status = False
self._state.closing = True
return messages
@@ -320,6 +330,17 @@ class _SteeringAwareOpenCodeServer:
else:
self._state.status_reconciliation_failures = 0
if status is not None and status.get("type") in {"busy", "retry"}:
+ if (
+ reconcile_insert
+ and inserted_user_text is not None
+ and self._inserted_user_index(
+ messages,
+ awaiting,
+ inserted_user_text,
+ )
+ >= 0
+ ):
+ self._state.awaiting_active_status_observed = True
if reconcile_initial_status and awaiting is None:
self._state.awaiting_after_message_ids = (
self._completed_assistant_boundary(messages)
@@ -348,9 +369,10 @@ class _SteeringAwareOpenCodeServer:
inserted_user_missing
and final_snapshot
and last_message_id in awaiting
+ and self._state.awaiting_start_confirmation_deadline
+ is None
):
- self._state.awaiting_after_message_ids = None
- self._state.awaiting_user_text = None
+ self._clear_awaiting_reconciliation()
self._state.closing = True
return messages
has_final_insert_result = (
@@ -361,38 +383,47 @@ class _SteeringAwareOpenCodeServer:
inserted_user_text=inserted_user_text,
)
)
- self._state.awaiting_after_message_ids = None
- self._state.awaiting_user_text = None
if has_final_insert_result:
+ self._clear_awaiting_reconciliation()
self._state.closing = True
return messages
- return self._terminal_reconciliation_failure(
- session_id,
- messages,
- name="NativeSessionEndedBeforeResult",
- message=self._idle_reconciliation_error_text(),
- )
- self._state.awaiting_after_message_ids = None
- self._state.awaiting_user_text = None
- if final_snapshot:
- self._state.closing = True
- elif (
- reconcile_initial_status
- and not self._has_final_assistant_after(
- messages,
- self._state.baseline_message_ids,
- )
- ):
- return self._terminal_reconciliation_failure(
- session_id,
- messages,
- name="NativeSessionEndedBeforeResult",
- message=self._idle_reconciliation_error_text(),
+ start_deadline = (
+ self._state.awaiting_start_confirmation_deadline
)
- return messages
+ if (
+ start_deadline is not None
+ and not self._state.awaiting_active_status_observed
+ and time.monotonic() < start_deadline
+ ):
+ wait_for_insert = True
+ else:
+ self._clear_awaiting_reconciliation()
+ return self._terminal_reconciliation_failure(
+ session_id,
+ messages,
+ name="NativeSessionEndedBeforeResult",
+ message=self._idle_reconciliation_error_text(),
+ )
+ else:
+ self._clear_awaiting_reconciliation()
+ if final_snapshot:
+ self._state.closing = True
+ elif (
+ reconcile_initial_status
+ and not self._has_final_assistant_after(
+ messages,
+ self._state.baseline_message_ids,
+ )
+ ):
+ return self._terminal_reconciliation_failure(
+ session_id,
+ messages,
+ name="NativeSessionEndedBeforeResult",
+ message=self._idle_reconciliation_error_text(),
+ )
+ return messages
else:
- self._state.awaiting_after_message_ids = None
- self._state.awaiting_user_text = None
+ self._clear_awaiting_reconciliation()
return messages
if wait_for_insert:
await asyncio.sleep(0.1)
@@ -1073,6 +1104,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
system=system_prompt_injection,
baseline_message_ids=set(baseline_message_ids),
awaiting_after_message_ids=set(baseline_message_ids),
+ awaiting_user_text=prompt_text,
+ awaiting_start_confirmation_deadline=(
+ time.monotonic()
+ + _ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS
+ ),
idle_reconciliation_message=self._idle_reconciliation_message(
model_dict,
reasoning_effort,
@@ -1353,9 +1389,16 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
except (asyncio.TimeoutError, TimeoutError, aiohttp.ClientConnectionError):
state.awaiting_after_message_ids = before_insert
state.awaiting_user_text = request.text
+ state.awaiting_start_confirmation_deadline = None
+ state.awaiting_active_status_observed = False
raise
state.awaiting_after_message_ids = before_insert
state.awaiting_user_text = request.text
+ state.awaiting_start_confirmation_deadline = (
+ time.monotonic()
+ + _ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS
+ )
+ state.awaiting_active_status_observed = False
except OpenCodePromptRejectedError as exc:
outcome = SteerOutcome.NOT_ACTIVE if exc.status == 404 else SteerOutcome.REFUSED
reason = "native_session_missing" if exc.status == 404 else "backend_refused"
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index b4254c0f2..f72c4fd18 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -2028,6 +2028,17 @@ class ClassifyAuthErrorTests(unittest.TestCase):
def test_opencode_credential_error_requires_reset(self):
self.assertTrue(classify_auth_error("opencode", "OpenCode error: missing provider credential"))
+ def test_opencode_provider_mentions_without_auth_evidence_are_ignored(self):
+ diagnostics = (
+ "NativeSessionEndedBeforeResult - OpenCode ended without a model reply. "
+ "Provider: openai; model: gpt-5.6-terra.",
+ "ProviderError - rate limited",
+ "Provider model is unavailable",
+ )
+ for diagnostic in diagnostics:
+ with self.subTest(diagnostic=diagnostic):
+ self.assertFalse(classify_auth_error("opencode", diagnostic))
+
class VerifyOpenCodeAuthListOutputTests(unittest.TestCase):
def test_target_provider_must_exist_in_output(self):
diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.py
index 5fdc75dd1..d1616c476 100644
--- a/tests/test_agent_steering.py
+++ b/tests/test_agent_steering.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import time
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -596,6 +597,11 @@ async def test_opencode_steers_existing_runner_without_abort_or_new_turn() -> No
receipt = await steer_active_turn(controller, "opencode", _steer_request(identity[1]))
assert receipt.outcome is SteerOutcome.ACCEPTED
+ state = agent._steering_states[primary.base_session_id]
+ assert state.awaiting_user_text == STEER_TEXT
+ assert state.awaiting_start_confirmation_deadline is not None
+ assert state.awaiting_start_confirmation_deadline > time.monotonic()
+ assert state.awaiting_active_status_observed is False
assert server.prompt_calls == [
{
"session_id": "opencode-session",
@@ -923,6 +929,10 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(
agent._active_requests[primary.base_session_id] = process_task
await poll_started.wait()
state = agent._steering_states[primary.base_session_id]
+ assert state.awaiting_user_text == primary.message
+ assert state.awaiting_start_confirmation_deadline is not None
+ assert state.awaiting_start_confirmation_deadline > time.monotonic()
+ assert state.awaiting_active_status_observed is False
target = ActiveSteerTarget(
runtime_key=primary.base_session_id,
logical_turn_id="logical-turn",
@@ -1424,6 +1434,101 @@ async def test_opencode_insert_reconciliation_survives_visible_user_until_idle()
await _cancel_tasks(gate_task)
+async def test_opencode_accepted_prompt_waits_for_delayed_busy_registration() -> None:
+ primary = _primary_request(backend="opencode")
+ gate_task = await _held_task()
+
+ class _DelayedStartServer(_OpenCodeServer):
+ async def list_messages(self, session_id: str, directory: str) -> list[dict]:
+ if self.list_calls == 3:
+ self.messages.append(
+ {
+ "info": {
+ "id": "follow-up-assistant",
+ "role": "assistant",
+ "time": {"completed": 2},
+ "finish": "stop",
+ },
+ "parts": [{"type": "text", "text": "answered"}],
+ }
+ )
+ return await super().list_messages(session_id, directory)
+
+ server = _DelayedStartServer(
+ messages=[
+ {
+ "info": {
+ "id": "primary-assistant",
+ "role": "assistant",
+ "time": {"completed": 1},
+ "finish": "stop",
+ },
+ "parts": [{"type": "text", "text": "primary"}],
+ },
+ {
+ "info": {"id": "follow-up-user", "role": "user"},
+ "parts": [{"type": "text", "text": "follow-up"}],
+ },
+ ],
+ status_responses=[None, {"type": "idle"}, {"type": "busy"}, {"type": "idle"}],
+ )
+ agent = _opencode_agent(primary, gate_task, server)
+ state = agent._steering_states[primary.base_session_id]
+ state.baseline_message_ids = {"primary-assistant"}
+ state.awaiting_after_message_ids = {"primary-assistant"}
+ state.awaiting_user_text = "follow-up"
+ state.awaiting_start_confirmation_deadline = time.monotonic() + 1
+ poll_server = _SteeringAwareOpenCodeServer(server, state)
+ try:
+ messages = await asyncio.wait_for(
+ poll_server.list_messages("opencode-session", primary.working_path),
+ timeout=1,
+ )
+
+ assert messages[-1]["info"]["id"] == "follow-up-assistant"
+ assert state.terminal_status_failure_messages is None
+ assert state.awaiting_after_message_ids is None
+ assert state.closing is True
+ assert server.list_calls == 4
+ finally:
+ await _cancel_tasks(gate_task)
+
+
+async def test_opencode_accepted_prompt_idle_start_timeout_is_terminal() -> None:
+ primary = _primary_request(backend="opencode")
+ gate_task = await _held_task()
+ server = _OpenCodeServer(
+ messages=[
+ {
+ "info": {"id": "follow-up-user", "role": "user"},
+ "parts": [{"type": "text", "text": "follow-up"}],
+ }
+ ],
+ status={"type": "idle"},
+ )
+ agent = _opencode_agent(primary, gate_task, server)
+ state = agent._steering_states[primary.base_session_id]
+ state.awaiting_after_message_ids = set()
+ state.awaiting_user_text = "follow-up"
+ state.awaiting_start_confirmation_deadline = time.monotonic() - 1
+ poll_server = _SteeringAwareOpenCodeServer(server, state)
+ try:
+ messages = await poll_server.list_messages(
+ "opencode-session",
+ primary.working_path,
+ )
+
+ assert messages[-1]["info"]["error"]["name"] == (
+ "NativeSessionEndedBeforeResult"
+ )
+ assert state.awaiting_after_message_ids is None
+ assert state.closing is True
+ finally:
+ await _cancel_tasks(gate_task)
+
+
@pytest.mark.anyio
async def test_opencode_requires_final_assistant_after_inserted_user() -> None:
primary = _primary_request(backend="opencode")