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): stop rejected prompt delivery loops (#1186)

Call Whitee99616aebddf
diff --git a/core/session_turns.py b/core/session_turns.py
index 1ce0305e6..9944bdae8 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -3754,6 +3754,46 @@ class SessionTurnManager:
)
return bool(result.get("changed"))
+ def settle_start_attempt_invalid_input(
+ self,
+ turn_id: str,
+ attempt_id: str,
+ *,
+ backend: str,
+ ) -> bool:
+ """Retire a start batch rejected permanently before any native write."""
+
+ if not turn_id or not attempt_id:
+ return False
+ with self._sqlite_engine().connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ if turn is None or turn.get("start_attempt_id") != attempt_id:
+ return False
+ session_id = str(turn["session_id"])
+ delivery_ids = {
+ str(row["id"])
+ for row in delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ }
+ if not delivery_ids:
+ return False
+ result = self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="adapter_start_invalid_input",
+ evidence_kind="native_start_invalid_input",
+ evidence={"backend": backend, "attempt_id": attempt_id},
+ expected_start_attempt_id=attempt_id,
+ retire_unwritten_delivery_ids=delivery_ids,
+ )
+ if result.get("changed"):
+ self._publish_queue_update(session_id)
+ if not result.get("preserve_queue"):
+ asyncio.create_task(
+ self._resume_after_native_terminal(session_id, turn_id),
+ name=f"durable-terminal-resume:{session_id}",
+ )
+ return bool(result.get("changed"))
+
def _settle_durable_prewrite_failure(
self,
turn_id: str,
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 71106837c..6af76caea 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -53,7 +53,12 @@ from .caller_context import bind_session as bind_caller_context_session
from .client_manager import OpenCodeClientManager
from .message_processor import OpenCodeMessageProcessorMixin
from .poll_loop import OpenCodePollLoop, restored_platform_from_poll_info, restored_session_key_from_poll_info
-from .server import OpenCodePromptRejectedError, OpenCodeServerManager
+from .server import (
+ OpenCodePromptRejectedError,
+ OpenCodeServerManager,
+ native_message_id_for_attempt,
+ native_message_ids_for_attempt,
+)
from .session import OpenCodeResumeUnavailableError, OpenCodeSessionManager
from .utils import resolve_opencode_model_id, resolve_opencode_reasoning_effort
@@ -1041,13 +1046,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
session_id=session_id,
directory=request.working_path,
text=prompt_text,
- message_id=str(
- (request.context.platform_specific or {}).get(
- "delivery_start_attempt_id"
- )
- or ""
- )
- or None,
+ message_id=(
+ native_message_id_for_attempt(start_attempt_id)
+ if start_attempt_id
+ else None
+ ),
agent=agent_to_use,
model=model_dict,
reasoning_effort=reasoning_effort,
@@ -1141,26 +1144,42 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
poll_can_be_removed = not (logical_turn_id and start_attempt_id)
if logical_turn_id and start_attempt_id:
- reconcile = getattr(
- getattr(self.controller, "session_turns", None),
- "reconcile_start_attempt_not_written",
- None,
- )
- if callable(reconcile):
- try:
- poll_can_be_removed = bool(
- reconcile(
- logical_turn_id,
- start_attempt_id,
- backend=self.name,
- )
+ session_turns = getattr(self.controller, "session_turns", None)
+ try:
+ if e.is_permanent_input_rejection:
+ settle_invalid = getattr(
+ session_turns,
+ "settle_start_attempt_invalid_input",
+ None,
)
- except Exception:
- logger.exception(
- "Failed to persist definitive rejected OpenCode start "
- "for Turn=%s; preserving its active poll",
- logical_turn_id,
+ if callable(settle_invalid):
+ poll_can_be_removed = bool(
+ settle_invalid(
+ logical_turn_id,
+ start_attempt_id,
+ backend=self.name,
+ )
+ )
+ else:
+ reconcile = getattr(
+ session_turns,
+ "reconcile_start_attempt_not_written",
+ None,
)
+ if callable(reconcile):
+ poll_can_be_removed = bool(
+ reconcile(
+ logical_turn_id,
+ start_attempt_id,
+ backend=self.name,
+ )
+ )
+ except Exception:
+ logger.exception(
+ "Failed to persist definitive rejected OpenCode start "
+ "for Turn=%s; preserving its active poll",
+ logical_turn_id,
+ )
await self._remove_ack_reaction(request)
if session_id and poll_can_be_removed:
@@ -1323,7 +1342,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"tools": {"question": False},
}
if request.attempt_id:
- prompt_kwargs["message_id"] = request.attempt_id
+ prompt_kwargs["message_id"] = native_message_id_for_attempt(
+ request.attempt_id
+ )
await server.prompt_async(
**prompt_kwargs,
)
@@ -1420,35 +1441,40 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
reason="runtime_unavailable",
backend=self.name,
)
- try:
- message = await server.get_message(
- native_session_id,
- request.attempt_id,
- directory,
- )
- except Exception as exc: # noqa: BLE001 - absence is not negative proof
- return steer_result(
- SteerOutcome.UNKNOWN,
- reason="attempt_evidence_unavailable",
- backend=self.name,
- diagnostic=str(exc),
- )
- info = message.get("info") if isinstance(message, dict) else None
- if (
- isinstance(info, dict)
- and str(info.get("id") or "") == request.attempt_id
- and info.get("role") == "user"
- ):
- return steer_result(
- SteerOutcome.ACCEPTED,
- reason="native_message_found",
- backend=self.name,
- native_message_id=request.attempt_id,
- )
+ diagnostics: list[str] = []
+ observed_evidence = False
+ for native_message_id in native_message_ids_for_attempt(request.attempt_id):
+ try:
+ message = await server.get_message(
+ native_session_id,
+ native_message_id,
+ directory,
+ )
+ except Exception as exc: # noqa: BLE001 - absence is not negative proof
+ diagnostics.append(str(exc))
+ continue
+ observed_evidence = True
+ info = message.get("info") if isinstance(message, dict) else None
+ if (
+ isinstance(info, dict)
+ and str(info.get("id") or "") == native_message_id
+ and info.get("role") == "user"
+ ):
+ return steer_result(
+ SteerOutcome.ACCEPTED,
+ reason="native_message_found",
+ backend=self.name,
+ native_message_id=native_message_id,
+ )
return steer_result(
SteerOutcome.UNKNOWN,
- reason="untrusted_attempt_evidence",
+ reason=(
+ "untrusted_attempt_evidence"
+ if observed_evidence
+ else "attempt_evidence_unavailable"
+ ),
backend=self.name,
+ diagnostic="; ".join(diagnostics),
)
async def handle_stop(self, request: AgentRequest) -> bool:
@@ -1627,11 +1653,14 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
verification_unknown = True
baseline_message_ids = set(poll_info.baseline_message_ids)
+ start_attempt_message_ids = set(
+ native_message_ids_for_attempt(start_attempt_id)
+ )
start_attempt_found = any(
- start_attempt_id
+ start_attempt_message_ids
and message.get("info", {}).get("role") == "user"
and str(message.get("info", {}).get("id") or "")
- == start_attempt_id
+ in start_attempt_message_ids
for message in messages
)
has_in_progress = False
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 46593215e..da74d31d2 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -59,6 +59,28 @@ def _percent_encode_path(path: str) -> str:
return _url_quote(path, safe="/")
+def native_message_id_for_attempt(attempt_id: str) -> str:
+ """Map one durable attempt identity into OpenCode's message namespace."""
+
+ value = str(attempt_id or "").strip()
+ if not value.startswith("atm") or len(value) == 3:
+ raise ValueError("OpenCode prompt attempt identity must start with 'atm'")
+ return f"msg{value[3:]}"
+
+
+def native_message_ids_for_attempt(attempt_id: str) -> tuple[str, ...]:
+ """Return current and legacy native identities for exact evidence reads."""
+
+ value = str(attempt_id or "").strip()
+ if not value:
+ return ()
+ try:
+ current = native_message_id_for_attempt(value)
+ except ValueError:
+ return (value,)
+ return (current, value) if current != value else (value,)
+
+
class OpenCodePromptRejectedError(RuntimeError):
"""Definitive HTTP rejection from OpenCode's async prompt endpoint."""
@@ -67,6 +89,10 @@ class OpenCodePromptRejectedError(RuntimeError):
self.response_text = response_text
super().__init__(f"Failed to start async prompt: {status} {response_text}")
+ @property
+ def is_permanent_input_rejection(self) -> bool:
+ return self.status == 400
+
class OpenCodeServerManager:
"""Manages a singleton OpenCode server process shared across all working directories."""
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index c6bf4443f..66004bb57 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -128,6 +128,12 @@ scenarios:
kind: lifecycle
layer: scenario
test: tests/scenarios/message_delivery/test_message_delivery_scenarios.py::test_background_session_scenario_stays_silent_including_its_prompt
+ - id: MESSAGE-DELIVERY-020
+ name: Permanent native start rejection retires one Delivery and unblocks FIFO
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_permanent_start_rejection_retires_delivery_without_retry
- id: MESSAGE-DELIVERY-101
name: Unresolved fallback-capable delivery fences only later FIFO submissions
status: covered
diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.py
index 999bd9ba7..5fdc75dd1 100644
--- a/tests/test_agent_steering.py
+++ b/tests/test_agent_steering.py
@@ -638,7 +638,7 @@ async def test_opencode_reconciles_exact_native_attempt_without_resteering() ->
),
)
assert receipt.outcome is SteerOutcome.ACCEPTED
- assert server.prompt_calls[0]["message_id"] == attempt_id
+ assert server.prompt_calls[0]["message_id"] == "msg_exact_restart_evidence"
reconciled = await reconcile_steer_attempt(
controller,
@@ -652,12 +652,45 @@ async def test_opencode_reconciles_exact_native_attempt_without_resteering() ->
)
assert reconciled.outcome is SteerOutcome.ACCEPTED
- assert reconciled.details["native_message_id"] == attempt_id
+ assert reconciled.details["native_message_id"] == "msg_exact_restart_evidence"
assert len(server.prompt_calls) == 1
finally:
await _cancel_tasks(gate_task)
+async def test_opencode_reconciles_legacy_native_attempt_without_resteering() -> None:
+ primary = _primary_request(backend="opencode")
+ gate_task = await _held_task()
+ attempt_id = "atm_legacy_restart_evidence"
+ server = _OpenCodeServer(
+ messages=[
+ {"info": {"id": attempt_id, "role": "user"}, "parts": []},
+ ]
+ )
+ agent = _opencode_agent(primary, gate_task, server)
+ controller = _controller_with_active_gate(agent, primary, gate_task)
+ try:
+ identity = active_steer_identity(controller, "opencode", "avibe-session")
+ assert identity is not None
+ reconciled = await reconcile_steer_attempt(
+ controller,
+ "opencode",
+ SteerReconcileRequest(
+ target_session_id="avibe-session",
+ expected_logical_turn_id=identity[0],
+ expected_native_turn_id=identity[1],
+ attempt_id=attempt_id,
+ ),
+ )
+
+ assert reconciled.outcome is SteerOutcome.ACCEPTED
+ assert reconciled.details["native_message_id"] == attempt_id
+ assert server.prompt_calls == []
+ finally:
+ await _cancel_tasks(gate_task)
+
+
@pytest.mark.anyio
async def test_opencode_stop_waits_for_in_flight_steering_write() -> None:
primary = _primary_request(backend="opencode")
@@ -914,9 +947,11 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(
@pytest.mark.anyio
[email protected]("status", [400, 409])
@pytest.mark.parametrize("reconciliation_fails", [False, True])
async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanup(
monkeypatch,
+ status: int,
reconciliation_fails: bool,
) -> None:
primary = _primary_request(backend="opencode")
@@ -932,7 +967,7 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanu
async def prompt_async(self, **kwargs):
events.append("prompt")
- raise OpenCodePromptRejectedError(409, "prompt refused")
+ raise OpenCodePromptRejectedError(status, "prompt refused")
async def abort_session(self, session_id, directory):
events.append("abort")
@@ -982,6 +1017,12 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanu
raise RuntimeError("storage unavailable")
return True
+ def settle_start_attempt_invalid_input(turn_id, attempt_id, *, backend):
+ events.append(f"invalid:{turn_id}:{attempt_id}:{backend}")
+ if reconciliation_fails:
+ raise RuntimeError("storage unavailable")
+ return True
+
server = _Server()
controller = SimpleNamespace(
config=SimpleNamespace(
@@ -1001,6 +1042,7 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanu
get_opencode_overrides=lambda context: (None, None, None),
session_turns=SimpleNamespace(
reconcile_start_attempt_not_written=reconcile_start_attempt_not_written,
+ settle_start_attempt_invalid_input=settle_start_attempt_invalid_input,
),
)
agent = object.__new__(OpenCodeAgent)
@@ -1033,10 +1075,15 @@ async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanu
await agent._process_message(primary)
+ expected_reconciliation = (
+ "invalid:logical-turn:atm-start:opencode"
+ if status == 400
+ else "reconcile:logical-turn:atm-start:opencode"
+ )
assert events[:3] == [
"persist_poll",
"prompt",
- "reconcile:logical-turn:atm-start:opencode",
+ expected_reconciliation,
]
assert "abort" not in events
assert ("remove_poll" in events) is not reconciliation_fails
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 6f5957372..e66ee5cc3 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -831,7 +831,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
assert calls[0]["tools"] == {"question": False}
assert calls[0]["model"] == {"providerID": "openai", "modelID": "gpt-5.4"}
assert calls[0]["reasoning_effort"] == "high"
- assert calls[0]["message_id"] == "atm_initial_start"
+ assert calls[0]["message_id"] == "msg_initial_start"
assert recovery_order[:2] == ["poll", "prompt"]
steering_snapshot = active_polls[0]["processing_indicator"]["opencode_native_steering"]
assert steering_snapshot["system"] == calls[0]["system"]
diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.py
index c1089ae48..ff3d3c90a 100644
--- a/tests/test_opencode_restore_polls.py
+++ b/tests/test_opencode_restore_polls.py
@@ -17,6 +17,8 @@ import sys
from pathlib import Path
from types import SimpleNamespace
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config.v2_sessions import ActivePollInfo # noqa: E402
@@ -336,7 +338,7 @@ def test_restore_preserves_durable_poll_when_verification_is_temporarily_unavail
)
poll.processing_indicator = {
"platform": "avibe",
- "delivery_start_attempt_id": "attempt-unknown",
+ "delivery_start_attempt_id": "atm-unknown",
"opencode_native_steering": {
"target_session_id": "ses_wb",
"logical_turn_id": "turn-unknown",
@@ -363,7 +365,18 @@ def test_restore_preserves_durable_poll_when_verification_is_temporarily_unavail
assert removed == []
-def test_restore_rebuilds_completed_exact_start_attempt() -> None:
+ ("attempt_id", "native_message_id"),
+ [
+ ("atm-start", "msg-start"),
+ ("atm-start", "atm-start"),
+ ("legacy-start", "legacy-start"),
+ ],
+)
+def test_restore_rebuilds_completed_exact_start_attempt(
+ attempt_id: str,
+ native_message_id: str,
+) -> None:
poll = _make_poll(
platform="avibe",
base_session_id="ses_wb",
@@ -371,7 +384,7 @@ def test_restore_rebuilds_completed_exact_start_attempt() -> None:
)
poll.processing_indicator = {
"platform": "avibe",
- "delivery_start_attempt_id": "atm-start",
+ "delivery_start_attempt_id": attempt_id,
"opencode_native_steering": {
"target_session_id": "ses_wb",
"logical_turn_id": "logical-start",
@@ -379,7 +392,7 @@ def test_restore_rebuilds_completed_exact_start_attempt() -> None:
}
agent, _, removed, _ = _build_agent({"oc-1": poll})
agent._test_server.messages = [
- {"info": {"id": "atm-start", "role": "user", "time": {}}},
+ {"info": {"id": native_message_id, "role": "user", "time": {}}},
{
"info": {
"id": "assistant-done",
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 6d1646ae8..e90df52d4 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -469,7 +469,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
body = fake_session.posts[0]["json"]
self.assertEqual(body["tools"], {"question": False})
- async def test_prompt_async_uses_durable_attempt_as_native_message_id(self):
+ async def test_prompt_async_uses_opencode_native_message_id(self):
manager = OpenCodeServerManager(binary="opencode", port=4096)
fake_session = _FakeSession()
@@ -482,12 +482,28 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
session_id="ses-1",
directory="/tmp/work",
text="hello",
- message_id="atm_exact_evidence",
+ message_id="msg_exact_evidence",
)
self.assertEqual(
fake_session.posts[0]["json"]["messageID"],
- "atm_exact_evidence",
+ "msg_exact_evidence",
+ )
+
+ def test_durable_attempt_maps_to_opencode_message_namespace(self):
+ self.assertEqual(
+ SERVER_MODULE.native_message_id_for_attempt("atm_exact_evidence"),
+ "msg_exact_evidence",
+ )
+
+ def test_attempt_evidence_accepts_current_and_legacy_native_ids(self):
+ self.assertEqual(
+ SERVER_MODULE.native_message_ids_for_attempt("atm_exact_evidence"),
+ ("msg_exact_evidence", "atm_exact_evidence"),
+ )
+ self.assertEqual(
+ SERVER_MODULE.native_message_ids_for_attempt("legacy-evidence"),
+ ("legacy-evidence",),
)
async def test_prompt_async_exposes_definitive_http_rejection(self):
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 86a1812ca..4924b02cf 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -2573,6 +2573,44 @@ def test_exact_missing_start_attempt_requeues_only_its_own_delivery(managers) ->
assert terminal["terminal_outcome"] == "not_written"
+async def test_permanent_start_rejection_retires_delivery_without_retry(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ admitted = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="invalid payload"),
+ context=_context(),
+ )
+ following = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="continue FIFO"),
+ context=_context(),
+ )
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, str(admitted.turn_id))
+ assert turn is not None
+ attempt_id = str(turn["start_attempt_id"])
+
+ assert manager.settle_start_attempt_invalid_input(
+ str(admitted.turn_id),
+ attempt_id,
+ backend="opencode",
+ )
+ delivery = _row(engine, str(admitted.delivery_id))
+ assert delivery["state"] == "retired"
+ history = json.loads(delivery["delivery_history_json"])["events"]
+ assert history[-1]["outcome"] == "invalid_input"
+ assert _row(engine, str(following.delivery_id))["state"] == "queued"
+ assert len(starts) == 1
+ with engine.connect() as conn:
+ terminal = delivery_store.get_turn(conn, str(admitted.turn_id))
+ assert delivery_store.claimable_fifo_head(conn, "ses_fsm") is not None
+ assert terminal is not None
+ assert terminal["terminal_outcome"] == "not_written"
+
+ await asyncio.sleep(0)
+ assert _row(engine, str(following.delivery_id))["state"] == "claimed"
+ assert starts[-1][1] == "continue FIFO"
+
+
def test_pre_dispatch_hydration_failure_is_definitively_recoverable(managers) -> None:
first, restarted, engine, _engine_b, starts = managers