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(codex): bound resume retries and protect shared transports (#2053)
Call White8bf3311be3fd
diff --git a/core/session_turns.py b/core/session_turns.pyindex 6c659dea9..9c2bc076c 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -210,6 +210,7 @@ SCHEDULED_TARGET_AGENT_KEY = "scheduled_target_agent_name"_NON_RESTORABLE_RUNTIME_BACKENDS = frozenset({"claude", "codex"})_MAX_AUTOMATIC_UNKNOWN_START_REPLAYS = 1+_MAX_PREWRITE_START_ATTEMPTS = 3_UNKNOWN_START_REPLAY_INSTRUCTION = ("[Avibe recovery: this request may have been delivered before restart. ""Before any irreversible action, check whether the work is already complete.]\n\n"@@ -4601,6 +4602,7 @@ class SessionTurnManager:replayed_unknown_start = Falseunknown_start_exhausted = Falseunknown_start_run_ids: list[str] = []+ requeued_input = Falseforced_retire_ids = retire_unwritten_delivery_ids or set()start_deferred = Falselinked_activation_deferred = False@@ -4735,6 +4737,16 @@ class SessionTurnManager:)elif outcome == "not_written":for initial in initial_batch:+ receipt = {"kind": evidence_kind, **(evidence or {})}+ if (+ evidence_kind == "definitive_prewrite_failure"+ and receipt.get("reason") == SETTLED_BY_NO_TERMINAL_RESULT+ and delivery_store.consecutive_prewrite_start_failures(initial) + 1+ >= _MAX_PREWRITE_START_ATTEMPTS+ ):+ # Batch membership does not transfer one input's+ # exhausted retry budget to newer inputs.+ receipt["requires_explicit_retry"] = Trueretire_unwritten = str(initial["id"]) in forced_retire_idsowned_run_terminal = Falserun_ids = (@@ -4777,12 +4789,13 @@ class SessionTurnManager:),next_state=next_state,next_priority="p3",- receipt={"kind": evidence_kind, **(evidence or {})},+ receipt=receipt,)if definitive is None:raise RuntimeError("terminal no-write evidence lost a Delivery batch CAS")+ requeued_input = requeued_input or next_state == "queued"else:accepted = delivery_store.materialize_start_acceptance(conn,@@ -5054,6 +5067,8 @@ class SessionTurnManager:if materialized_id:self._publish_materialized_delivery(materialized_id)if result.get("changed"):+ if requeued_input:+ self._publish_queue_update(session_id)self._publish_terminal_inbox_update(session_id)if status_changed and projected_status is not None:from core.inbox_events import busdiff --git a/docs/plans/2026-09-19-codex-resume-retry.md b/docs/plans/2026-09-19-codex-resume-retry.mdnew file mode 100644index 000000000..7f90317d7--- /dev/null+++ b/docs/plans/2026-09-19-codex-resume-retry.md@@ -0,0 +1,154 @@+# Codex resume and bounded pre-write recovery++Issue: #2049.++## Problem and evidence++A large `thread/resume` response exceeds the stdio reader's 128 MiB line+limit. The reader loses the oversized-response cause, all pending requests+receive an ordinary connection error, and adapter retries restart a shared+per-working-directory process. The shared Delivery owner then repeatedly+requeues the same unwritten input.++A hermetic probe with Codex 0.154.0, the production Avibe transport, and a+loopback Responses fixture produced 17 real turns and a 427,901,977-byte+rollout. Default resume failed at the existing line limit. Resuming the same+thread with `excludeTurns: true` returned 1,937 bytes. Separate checks proved+that the next model request retained the old context, configuration refresh+still worked, stored history remained readable, and another thread could run+on the same process.++## Contract++1. Both Codex resume producers request `excludeTurns: true`. Avibe consumes+ the response identity and configuration, not its historical `thread.turns`.+ This does not truncate stored or model-visible history.+2. A stdio line-limit failure retains a typed oversized-response cause. It is+ not classified as a reconnectable failure. A definitive pre-write resume+ failure uses the existing `requires_explicit_retry` receipt contract.+3. The shared Delivery/Turn settlement owner permits at most three automatic+ startup attempts ending in `definitive_prewrite_failure/no_terminal_result`+ per Delivery before requiring explicit recovery. Batch membership never+ transfers an older input's exhausted budget to newer inputs. Concurrency+ refusal and native acceptance/unknown-start recovery keep their existing policies.+4. Inputs requiring recovery remain queued with the same Delivery ID,+ snapshot, attachments, and FIFO position. Timer drains and restart recovery+ cannot replay them. The existing failure-notice Retry action and Send now+ can retry them. Validated failure-notice Retry resets the bounded budget;+ Send now grants one attempt and does not replenish an exhausted budget.+ Any definitively unwritten Send now attempt preserves an existing hold,+ regardless of its failure kind; only validated failure-notice Retry resets it.+ The budget derives from server-owned delivery history, not process memory+ or caller metadata.+ The shared read payload projects `requires_explicit_retry` and `retry_reason`+ from this receipt, for CLI queue inspection and the existing Web queue strip.+ These fields never authorize dispatch; the claim owner rereads the history.+ Requeuing publishes the existing `queue.updated` event after commit so live+ clients receive this projection without a reload.+5. Failure-triggered Codex transport replacement uses the existing durable+ ownership and live-turn checks. A still-live shared process cannot be+ replaced while another accepted turn or protected activity owns it.+ Replacement of a definitively dead process retains the existing narrower+ ownership policy. A blocked replacement preserves session bookkeeping.+ The adapter registers the complete durable Session binding before transport+ acquisition or resume, including on the first turn after controller restart.++## Boundaries and intentional non-changes++- `modules/agents/codex/transport.py` owns framing and transport error identity.+- `modules/agents/codex/agent.py` owns Codex resume and process replacement.+- `core/native_dispatch_phase.py`, `core/session_turns.py`, and+ `storage/message_deliveries.py` own proof of no write, durable settlement,+ and the retry budget.+- Existing Retry/Send now admission remains the recovery interface. No new+ queue state, schema migration, retry scheduler, or parallel queue is added.+ The existing recovery cadence remains; this change bounds attempts rather+ than introducing a second exponential-backoff scheduler.+- The 128 MiB reader limit remains a resource boundary. Other oversized+ protocol messages fail visibly; this change does not add an unbounded parser.+- Accepted or ambiguous native work is not blindly replayed after process+ death: tools may already have produced side effects. Adapter-local recovery+ requires explicit pre-write evidence, not merely a reconnectable exception.+- No workstation service restart, remote regression, deployment, or merge is+ part of this implementation authorization.++## Validation++- Codex adapter tests cover both resume paths, permanent failure identity,+ bounded reconnect behavior, and shared-process ownership.+- Transport tests reproduce a line overrun and distinguish it from normal EOF.+- Real-storage Delivery tests cover budget exhaustion across manager restarts,+ explicit recovery with original inputs, batch/FIFO preservation, and+ unchanged transient refusal/accepted/unknown policies.+- Reuse the isolated native Codex/loopback model harness to verify that the+ production adapter's excluded history still reaches the next model request.+- Run focused Python suites and changed-file Ruff checks; require current-head+ Codex review, zero unresolved threads, and the complete GitHub CI workflow.++### Local results++- 611 focused Python tests and 50 subtests passed, including the retry FSM,+ shared runtime ownership, CLI, UI stream, and message-delivery scenarios.+- All 9 isolated native Codex contracts passed with 0.154.0. The new excluded+ resume contract also passed against the official 0.153.2 binary: both resume+ paths returned the expected model/effort, omitted turns, retained the old+ non-ASCII input in the next model request, and preserved readable history.+- 4,661 UI tests passed; UI production build, lint baseline, theme validation,+ test typechecking, and changed-file Ruff passed.+- No real model service, user Codex home, or credentials were used by the native+ contracts. Full browser/IM operation against a deployed local Incus instance+ remains a post-merge opt-in; the running workstation service was untouched.++### Review follow-up++The review of `805cfbc3b` is the first findings-bearing head (four threads,+three root-cause classes: durable retry bookkeeping, runtime enrollment, and+live projection). The orchestrator verified the full inventory and+approved narrow contract-preserving corrections:++- Per-input accounting: independently exhaust each Delivery in a mixed-age batch.+- Runtime enrollment: produce the durable binding before any ownership-gated replacement.+- Hold transition closure: a non-spending concurrency refusal cannot release an existing hold.+- Live projection: publish the committed requeue through the existing queue event.++Each was reproduced by a failing regression before correction. The tests use+the real session-manager ownership target, mixed-age SQLite delivery batches,+repeated manual retries/refusals, and a separate database connection observing+the queue event after commit. The failing CI prompt-baseline fixture also now+supplies real prewrite evidence and an explicit successful-replacement result.+After these corrections, the expanded run passed 758 Python tests and 52+subtests, including all 9 native Codex contracts. Changed-file Ruff also passed.++### Circuit-breaker diagnosis after the second reviewed head++The orchestrator fetched the complete review inventory before editing:+`805cfbc3b` has four findings (all resolved); `6e58847eb` has one open finding,+comment `4052408717`. Durable retry bookkeeping therefore appears on two+findings-bearing heads and trips the review-loop breaker. Runtime enrollment+and live projection have no new findings. The exact-head `lint` inventory+contains one run, `35425310211`; its six Python shards passed and the remaining+UI check was still running at diagnosis.++Inspection of the previous diff and its real-SQLite consuming test confirms+that the refusal-only history traversal encoded one error type instead of the+one-shot authorization boundary. A permanent hold followed by Send now and an+ordinary no-write failure drops the hold even though no Retry event occurred.+Changing error classes must not implicitly authorize more dispatches.++Scope decision: generalize the existing receipt reader to traverse completed+`not_written` starts, independently of receipt kind/reason, while keeping a+current claim/open and accepted/unknown/restart outcomes as boundaries. A+validated `backend_failure_retry` event still releases the hold. Do not alter+budget accounting, settlement ownership, native recovery policy, or the schema.+Exercise held and unheld inputs, repeated explicit no-write attempts (including+exact native-start absence), Retry reset, and accepted/unknown boundaries.+This is a narrow, reversible correction of the shipped contract, not a new+state machine or a reason to add another failure-specific exception.++The expanded transition tests failed in five combinations before the fix:+permanent hold followed by an ordinary failure, and either hold followed by a+different transient failure or exact native-start absence. After correction,+457 shared-delivery/retry/CLI/ownership tests and 309 Codex tests passed (766+total, plus 52 subtests), including all 9 isolated native Codex contracts.+Changed-file Ruff and whitespace checks passed. The sole previous-head `lint`+run subsequently completed successfully; new-head review and CI remain required.diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex ca2a1ba32..8d22305a6 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -26,7 +26,11 @@ from core.managed_skills import (managed_skill_environment,managed_skill_project_base,)-from core.native_dispatch_phase import mark_backend_dispatch_attempted+from core.native_dispatch_phase import (+ backend_dispatch_attempted,+ mark_backend_dispatch_attempted,+ mark_prewrite_recovery_required,+)from core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.prompt_registry import prompt_textfrom core.services.agent_steering import (@@ -54,7 +58,7 @@ from modules.agents.base import AgentRequest, BaseAgentfrom modules.agents.subagent_router import SubagentDefinition, load_codex_subagentfrom modules.agents.codex.event_handler import CodexEventHandlerfrom modules.agents.codex.session import CodexSessionManager-from modules.agents.codex.transport import CodexRPCError, CodexTransport+from modules.agents.codex.transport import CodexResponseTooLargeError, CodexRPCError, CodexTransportfrom modules.agents.codex.turn_state import CodexTurnRegistryfrom vibe.codex_config import LEGACY_MANAGED_PROVIDER_IDS, MANAGED_PROVIDER_IDfrom vibe.i18n import t as i18n_t@@ -405,6 +409,12 @@ class CodexAgent(BaseAgent):async with self._session_locks[request.base_session_id]:launch = Nonetry:+ # Register a complete durable binding before any transport+ # acquisition or resume can fail and require ownership checks.+ self.ensure_agent_session_id(request)+ self._session_mgr.set_session_key(request.base_session_id, request.session_key)+ self._session_mgr.set_cwd(request.base_session_id, request.working_path)+ self._bind_runtime_agent_session_id(request)if getattr(self.controller, "model_hub_runtime", None) is not None:from modules.agents.model_hub import bind_launch, resolve_model_hub_launch@@ -455,9 +465,6 @@ class CodexAgent(BaseAgent):self._event_handler._release_stream_turn(request.context)return- # Resolve after queued turns, then bind this session to the runtime.- self._session_mgr.set_session_key(request.base_session_id, request.session_key)- self._session_mgr.set_cwd(request.base_session_id, request.working_path)self._touch_transport_activity(request.working_path)await self._delete_ack(request)@@ -469,7 +476,6 @@ class CodexAgent(BaseAgent):thread_id = self._session_mgr.get_thread_id(request.base_session_id)if not thread_id:- self.ensure_agent_session_id(request)developer_instructions = await self._build_thread_developer_instructions(request)prompt_rendered = Truethread_id = await self._start_or_resume_thread(@@ -506,7 +512,6 @@ class CodexAgent(BaseAgent):# Render once at the actual Turn boundary. Besides keeping the# payload byte-stable, this avoids repeating Memory admission# side effects while the same request refreshes and starts.- self.ensure_agent_session_id(request)if not prompt_rendered:developer_instructions = await self._build_thread_developer_instructions(request)prompt_rendered = True@@ -527,36 +532,39 @@ class CodexAgent(BaseAgent):# Safety net: if the thread is stale (e.g. Codex server-side# expiry, or the proactive invalidation in _get_or_create_transport# was bypassed by a race), invalidate and retry once.- if self._is_recoverable_transport_error(e):+ if (+ self._is_recoverable_transport_error(e)+ and backend_dispatch_attempted(request.context) is False+ ):logger.warning("Recoverable Codex transport failure for session %s, restarting transport and retrying: %s",request.base_session_id,e,)- await self._drop_transport_after_failure(request.working_path, transport, request)- try:- if launch is None:- transport = await self._get_or_create_transport(request.working_path)- else:- transport = await self._get_or_create_transport(request.working_path, launch)- self._touch_transport_activity(request.working_path)- if not prompt_rendered:- self.ensure_agent_session_id(request)- developer_instructions = await self._build_thread_developer_instructions(request)- prompt_rendered = True- thread_id = await self._start_or_resume_thread(- transport, request, developer_instructions=developer_instructions- )- self._bind_runtime_agent_session_id(request)- await self._start_turn(- transport,- request,- thread_id,- developer_instructions=developer_instructions,- )- return # retry succeeded- except Exception as retry_err:- e = retry_err # fall through to normal error handling+ if await self._drop_transport_after_failure(request.working_path, transport, request):+ try:+ if launch is None:+ transport = await self._get_or_create_transport(request.working_path)+ else:+ transport = await self._get_or_create_transport(request.working_path, launch)+ self._touch_transport_activity(request.working_path)+ if not prompt_rendered:+ self.ensure_agent_session_id(request)+ developer_instructions = await self._build_thread_developer_instructions(request)+ prompt_rendered = True+ thread_id = await self._start_or_resume_thread(+ transport, request, developer_instructions=developer_instructions+ )+ self._bind_runtime_agent_session_id(request)+ await self._start_turn(+ transport,+ request,+ thread_id,+ developer_instructions=developer_instructions,+ )+ return # retry succeeded+ except Exception as retry_err:+ e = retry_err # fall through to normal error handling# FAIL LOUD on a server-side "thread not found": the conversation is# gone, so surface the error instead of silently clearing the@@ -564,6 +572,8 @@ class CodexAgent(BaseAgent):# The mapping is kept so the failure is consistent until the user# explicitly starts a new session (product decision: no silent# fallbacks).+ if isinstance(e, (CodexResumeUnavailableError, CodexResponseTooLargeError)):+ mark_prewrite_recovery_required(request.context, "codex_resume_unavailable")self._turn_registry.clear_pending_turn_start(request.base_session_id, request)logger.error("Error in Codex handle_message: %s", e, exc_info=True)await self._record_model_hub_native_failure(request.context, str(e))@@ -1017,6 +1027,12 @@ class CodexAgent(BaseAgent):setter(request.base_session_id, session_id)def _error_display_text(self, error: BaseException) -> str:+ if isinstance(error, CodexResponseTooLargeError):+ language = str(+ getattr(getattr(self.controller, "config", None), "language", "en")+ or "en"+ )+ return f"❌ {i18n_t('error.codexResponseTooLarge', language, limitMiB=error.limit // (1024 * 1024))}"if isinstance(error, CodexPromptRefreshUnavailableError):language = str(getattr(getattr(self.controller, "config", None), "language", "en")@@ -1581,6 +1597,8 @@ class CodexAgent(BaseAgent):# ------------------------------------------------------------------def _is_recoverable_transport_error(self, error: Exception) -> bool:+ if isinstance(error, CodexResponseTooLargeError):+ return Falseif isinstance(error, (ConnectionError, TimeoutError)):return True@@ -1599,12 +1617,27 @@ class CodexAgent(BaseAgent):))+ async def _transport_replacement_is_safe(self, cwd: str, transport: CodexTransport) -> bool:+ """Recheck durable ownership and live turns inside retirement."""+ ownership = await self._runtime_ownership_snapshot_for_cwd_async(cwd)+ dead = self._transport_alive(transport) is False+ blocked = getattr(+ ownership,+ "blocks_dead_transport_replacement" if dead else "blocks_transport_replacement",+ True,+ )+ return bool(+ ownership is not None+ and not blocked+ and (dead or not self._has_active_turns_for_cwd(cwd))+ )+async def _drop_transport_after_failure(self,cwd: str,transport: CodexTransport,request: AgentRequest,- ) -> None:+ ) -> bool:"""Remove a broken app-server and clear stale in-memory request state."""lock = self._transport_locks.setdefault(cwd, asyncio.Lock())async with lock:@@ -1615,6 +1648,7 @@ class CodexAgent(BaseAgent):detached = await self._stop_and_detach_transport_generation(cwd,transport,+ final_predicate=lambda: self._transport_replacement_is_safe(cwd, transport),)except Exception as exc:logger.warning(@@ -1622,9 +1656,10 @@ class CodexAgent(BaseAgent):cwd,exc,)- return+ return Falseif not detached:- return+ logger.warning("Codex failure recovery cannot replace an owned transport for cwd=%s", cwd)+ return Falseelif current is None:identity = self._transport_activation_identity(transport)registry = getattr(getattr(self, "controller", None), "runtime_activation", None)@@ -1633,7 +1668,7 @@ class CodexAgent(BaseAgent):"Refusing to stop an untracked current Codex generation for cwd=%s",cwd,)- return+ return Falsetry:await transport.stop()except Exception as exc:@@ -1642,7 +1677,7 @@ class CodexAgent(BaseAgent):cwd,exc,)- return+ return Falseelse:identity = self._transport_activation_identity(transport)registry = getattr(@@ -1657,7 +1692,7 @@ class CodexAgent(BaseAgent):"Refusing to stop a replaced but still-current Codex generation for cwd=%s",cwd,)- return+ return Falsetry:await transport.stop()except Exception as exc:@@ -1666,7 +1701,7 @@ class CodexAgent(BaseAgent):cwd,exc,)- return+ return Falseif should_invalidate_cwd_sessions:for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):@@ -1679,6 +1714,7 @@ class CodexAgent(BaseAgent):self._session_mgr.invalidate_thread(request.base_session_id)self._clear_thread_developer_instructions(request.base_session_id)self._turn_registry.clear_session(request.base_session_id)+ return Trueasync def _get_or_create_transport(self,@@ -1697,10 +1733,6 @@ class CodexAgent(BaseAgent):async with self._transport_locks[cwd], AsyncExitStack() as catalog_pins:# Double-check after acquiring lockexisting = self._transports.get(cwd)- existing_dead = bool(- existing is not None- and self._transport_alive(existing) is False- )desired_fingerprint = launch.fingerprint if launch is not None else "direct"existing_fingerprint = getattr(existing, "runtime_fingerprint", "direct")runtime_changed = existing_fingerprint != desired_fingerprint@@ -1756,32 +1788,10 @@ class CodexAgent(BaseAgent):# Stop stale transport if anyif existing:- async def replacement_is_safe() -> bool:- ownership = (- await self._runtime_ownership_snapshot_for_cwd_async(cwd)- )- replacement_blocked = getattr(- ownership,- (- "blocks_dead_transport_replacement"- if existing_dead- else "blocks_transport_replacement"- ),- True,- )- return bool(- ownership is not None- and not replacement_blocked- and (- existing_dead- or not self._has_active_turns_for_cwd(cwd)- )- )-detached = await self._stop_and_detach_transport_generation(cwd,existing,- final_predicate=replacement_is_safe,+ final_predicate=lambda: self._transport_replacement_is_safe(cwd, existing),)if not detached:raise RuntimeError(@@ -2402,6 +2412,7 @@ class CodexAgent(BaseAgent):self.bind_agent_session_id(request, persisted)resume_params: Dict[str, Any] = {"threadId": persisted,+ "excludeTurns": True,}if developer_instructions:resume_params["developerInstructions"] = await self._native_thread_prompt(@@ -2445,7 +2456,7 @@ class CodexAgent(BaseAgent):if isinstance(thread_obj, dict):thread_id = thread_obj.get("id", "")except Exception as e:- if isinstance(e, CodexPromptRefreshUnavailableError):+ if isinstance(e, (CodexPromptRefreshUnavailableError, CodexResponseTooLargeError)):raiseif self._is_recoverable_transport_error(e):# Transient: reconnect the SAME thread (handled by the outer@@ -2726,6 +2737,7 @@ class CodexAgent(BaseAgent):if len(resume_params) == 1:return+ resume_params["excludeTurns"] = Trueawait transport.send_request("thread/resume",resume_params,diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.pyindex 6953adaf9..d7a8803ef 100644--- a/modules/agents/codex/transport.py+++ b/modules/agents/codex/transport.py@@ -87,6 +87,14 @@ class CodexRPCError(RuntimeError):return self.code in {-32600, -32601, -32602}+class CodexResponseTooLargeError(RuntimeError):+ """The shared stdout reader cannot accept a protocol frame of this size."""++ def __init__(self, limit: int = STREAM_BUFFER_LIMIT) -> None:+ self.limit = limit+ super().__init__(f"Codex app-server response exceeds the {limit}-byte stdout line limit")++class CodexTransport:"""Manages a persistent ``codex app-server`` subprocess.@@ -433,12 +441,14 @@ class CodexTransport:async def _reader_loop(self) -> None:"""Read stdout line-by-line and dispatch JSON-RPC messages."""assert self._process and self._process.stdout+ failure: Exception = ConnectionError("Codex app-server stdout closed")try:while True:try:raw = await self._process.stdout.readline()except (asyncio.LimitOverrunError, ValueError) as err:logger.error("Codex stdout buffer error: %s", err)+ failure = CodexResponseTooLargeError()breakif not raw:break # EOF@@ -461,7 +471,7 @@ class CodexTransport:# Process ended — fail pending futuresfor fut in self._pending.values():if not fut.done():- fut.set_exception(ConnectionError("Codex app-server stdout closed"))+ fut.set_exception(failure)self._pending.clear()async def _dispatch(self, msg: dict[str, Any]) -> None:diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex 74008ec39..49c96bc02 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -359,17 +359,56 @@ def failure_retry_state(delivery: dict[str, Any]) -> str:return state-def requires_explicit_start_retry(delivery: dict[str, Any]) -> bool:- """An unwritten permanent failure stays queued until its owner retries it."""+def explicit_start_retry_receipt(delivery: dict[str, Any]) -> dict[str, Any] | None:+ """Read the durable hold, never caller-supplied Message metadata."""+ completed_no_write = Falsefor event in reversed(_history(delivery.get("delivery_history_json"))["events"]):if event.get("kind") == FAILURE_RETRY_HISTORY_KIND:- return False+ return Noneif event.get("kind") == "start":- return (+ receipt = event.get("receipt") or {}+ if (event.get("outcome") == "not_written"- and (event.get("receipt") or {}).get("requires_explicit_retry") is True- )- return False+ and receipt.get("requires_explicit_retry") is True+ ):+ return dict(receipt)+ if event.get("outcome") == "not_written":+ # Send now grants one attempt, not permission to clear a hold.+ # A different no-write failure must preserve that boundary too.+ completed_no_write = True+ continue+ if completed_no_write and event.get("outcome") in {"claimed", "opened"}:+ continue+ return None+ return None+++def requires_explicit_start_retry(delivery: dict[str, Any]) -> bool:+ """An unwritten permanent failure stays queued until its owner retries it."""+ return explicit_start_retry_receipt(delivery) is not None+++def consecutive_prewrite_start_failures(delivery: dict[str, Any]) -> int:+ """Count startup failures since Retry, without charging concurrency refusal."""+ count = 0+ for event in reversed(_history(delivery.get("delivery_history_json"))["events"]):+ if event.get("kind") == FAILURE_RETRY_HISTORY_KIND:+ break+ if event.get("kind") != "start":+ continue+ if event.get("outcome") in {"claimed", "opened"}:+ continue+ receipt = event.get("receipt") or {}+ if receipt.get("reason") == "refused_concurrent_turn":+ continue+ if (+ event.get("outcome") != "not_written"+ or receipt.get("kind") != "definitive_prewrite_failure"+ or receipt.get("reason") != "no_terminal_result"+ ):+ break+ count += 1+ return countdef active_turn(conn: Connection, session_id: str) -> dict[str, Any] | None:@@ -457,6 +496,7 @@ def _delivery_payload_from_snapshot() -> dict[str, Any]:content = _json_object(snapshot.get("content_json"))metadata = _json_object(snapshot.get("metadata_json"))+ retry_receipt = explicit_start_retry_receipt(row) if row.get("state") == "queued" else Nonereturn {"id": row["id"],"delivery_id": row["id"],@@ -485,6 +525,8 @@ def _delivery_payload_from_snapshot("dispatch_text": row.get("dispatch_text") or "","priority": row.get("priority"),"state": row.get("state"),+ "requires_explicit_retry": retry_receipt is not None,+ "retry_reason": retry_receipt.get("reason") if retry_receipt is not None else None,"created_at": row.get("submitted_at"),"submitted_at": row.get("submitted_at"),"updated_at": row.get("updated_at"),diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 8e2c1ada9..d13c0c5f8 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -14,6 +14,30 @@ status_legend:manual: currently validated only by human regressiongap: not covered yetscenarios:+ - id: MESSAGE-DELIVERY-031+ name: Bounded prewrite retry retains FIFO input across restart until explicit recovery+ status: covered+ kind: recovery+ layer: contract+ test: tests/test_session_delivery_fsm.py::test_prewrite_retry_budget_survives_restart_and_preserves_original_input+ - id: MESSAGE-DELIVERY-032+ name: Oversized Codex stdout frames preserve a non-reconnectable failure cause+ status: covered+ kind: regression+ layer: contract+ test: tests/test_codex_transport.py::CodexTransportHealthTests::test_oversized_stdout_fails_all_pending_requests_with_typed_cause+ - id: MESSAGE-DELIVERY-033+ name: Failure recovery cannot replace a Codex process owned by a live neighbour+ status: covered+ kind: concurrency+ layer: contract+ test: tests/test_codex_agent.py::CodexAgentHandleMessageTests::test_failure_replacement_respects_live_durable_and_unknown_ownership+ - id: MESSAGE-DELIVERY-034+ name: Excluded Codex resume responses preserve stored history and next-turn model context+ status: partial+ kind: regression+ layer: contract+ test: tests/test_codex_prompt_delivery_contract.py::test_excluded_resume_preserves_native_history_and_model_settings- id: MESSAGE-DELIVERY-001name: Scheduled result finalizes its delivery anchorstatus: covereddiff --git a/tests/scenarios/message_delivery/observations.yaml b/tests/scenarios/message_delivery/observations.yamlindex a77fe1614..fbd5dd260 100644--- a/tests/scenarios/message_delivery/observations.yaml+++ b/tests/scenarios/message_delivery/observations.yaml@@ -1,6 +1,23 @@version: 1capability: message_deliveryobservations:+ - id: OBS-MESSAGE-DELIVERY-009+ source: issue_2049_and_hermetic_native_reproduction+ related_scenarios:+ - MESSAGE-DELIVERY-031+ - MESSAGE-DELIVERY-032+ - MESSAGE-DELIVERY-033+ - MESSAGE-DELIVERY-034+ summary: Large Codex resume responses caused unlimited prewrite retries and collateral shared-process restarts.+ previous_assumption: A no-write receipt proved that another automatic retry would succeed and every connection error justified process replacement.+ observed_behavior: Resume exceeded the 128 MiB stdout frame limit, lost its failure identity, and repeatedly restarted other accepted turns in the same cwd.+ required_updates:+ - exclude unused response turns without truncating stored or model-visible context+ - retain typed framing failures and hold definite resume failures for explicit recovery+ - bound generic prewrite attempts using durable history and preserve original queued input+ - do not spend or reset that budget on concurrency refusal+ - gate failure replacement on existing durable ownership and forbid ambiguous input replay+ - project the existing explicit-retry hold to CLI and the Web queue strip- id: OBS-MESSAGE-DELIVERY-008source: user_feedback_and_read_only_runtime_diagnosisrelated_scenarios:diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 8724eb83e..383bc02ba 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -18,7 +18,14 @@ from core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.runtime_activation import RuntimeActivationRegistryfrom core.runtime_ownership import RuntimeTargetOwnershipSnapshot, SessionRuntimeDispositionfrom modules.agents.base import BaseAgent as RealBaseAgent-from modules.agents.codex.transport import CodexRPCError+from modules.agents.codex.transport import CodexResponseTooLargeError, CodexRPCError+from modules.agents.codex.session import CodexSessionManager as RealCodexSessionManager+from core.native_dispatch_phase import (+ DISPATCH_PHASE_ATTEMPTING,+ DISPATCH_PHASE_PREWRITE,+ prewrite_failure_evidence,+ set_dispatch_phase,+)_AGENT_PATH = Path(__file__).resolve().parents[1] / "modules/agents/codex/agent.py"@@ -44,11 +51,12 @@ class _BaseAgent:def ensure_agent_session_id(self, request, *, session_anchor=None):anchor = session_anchor or request.base_session_id- ensure = getattr(self.sessions, "ensure_agent_session_id", None)+ sessions = getattr(self, "sessions", None)+ ensure = getattr(sessions, "ensure_agent_session_id", None)if callable(ensure):session_id = ensure(request.session_key, self.name, anchor)else:- getter = getattr(self.sessions, "get_agent_session_row_id", None)+ getter = getattr(sessions, "get_agent_session_row_id", None)session_id = getter(request.session_key, anchor, self.name) if callable(getter) else Noneif session_id:request.context.platform_specific["agent_session_id"] = session_id@@ -102,6 +110,7 @@ setattr(_session_module, "CodexSessionManager", object)_transport_module = types.ModuleType("modules.agents.codex.transport")setattr(_transport_module, "CodexTransport", object)setattr(_transport_module, "CodexRPCError", CodexRPCError)+setattr(_transport_module, "CodexResponseTooLargeError", CodexResponseTooLargeError)_turn_state_module = types.ModuleType("modules.agents.codex.turn_state")setattr(_turn_state_module, "CodexTurnRegistry", object)@@ -1582,12 +1591,13 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):request = SimpleNamespace(base_session_id="session-1",working_path="/tmp/work",- context=object(),+ context=SimpleNamespace(platform_specific={}),session_key="settings-1",ack_message_id=None,)+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)- bad_transport = SimpleNamespace(stop=AsyncMock())+ bad_transport = SimpleNamespace(stop=AsyncMock(), is_alive=False)fresh_transport = SimpleNamespace()invalidated = []session_mgr = SimpleNamespace(@@ -1611,6 +1621,9 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._transports = {"/tmp/work": bad_transport}agent._transport_locks = {"/tmp/work": asyncio.Lock()}agent._transport_last_activity = {"/tmp/work": 1.0}+ agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(+ return_value=SimpleNamespace(blocks_dead_transport_replacement=False)+ )agent._session_mgr = session_mgragent.sessions = sessionsagent._get_or_create_transport = AsyncMock(side_effect=[bad_transport, fresh_transport])@@ -1650,14 +1663,16 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):request = SimpleNamespace(base_session_id="session-1",working_path="/tmp/work",- context=object(),+ context=SimpleNamespace(platform_specific={}),session_key="settings-1",ack_message_id=None,)+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)bad_transport = SimpleNamespace(send_request=AsyncMock(side_effect=ConnectionError("Codex app-server transport is not available")),stop=AsyncMock(),+ is_alive=False,)fresh_transport = SimpleNamespace()agent._session_locks = {}@@ -1672,6 +1687,9 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._transports = {"/tmp/work": bad_transport}agent._transport_locks = {"/tmp/work": asyncio.Lock()}agent._transport_last_activity = {"/tmp/work": 1.0}+ agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(+ return_value=SimpleNamespace(blocks_dead_transport_replacement=False)+ )agent._session_mgr = SimpleNamespace(set_session_key=Mock(),set_cwd=Mock(),@@ -1700,6 +1718,65 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._start_thread.assert_not_awaited()agent.controller.emit_agent_message.assert_not_awaited()+ async def test_cold_resume_failure_binds_session_before_ownership_checks(self):+ for incomplete_prior_binding in (False, True):+ with self.subTest(incomplete_prior_binding=incomplete_prior_binding):+ agent = object.__new__(CodexAgent)+ request = SimpleNamespace(+ base_session_id="session-1", working_path="/tmp/work",+ context=SimpleNamespace(platform_specific={}),+ session_key="settings-1", ack_message_id=None,+ )+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)+ bad = SimpleNamespace(stop=AsyncMock(), is_alive=False)+ fresh = SimpleNamespace(is_alive=True)+ agent._session_locks = {}+ agent._transport_locks = {}+ agent._transports = {request.working_path: bad}+ agent._transport_last_activity = {}+ agent._session_mgr = RealCodexSessionManager()+ if incomplete_prior_binding:+ agent._session_mgr.set_session_key("session-1", "settings-1")+ agent._session_mgr.set_cwd("session-1", request.working_path)+ agent.sessions = SimpleNamespace(+ ensure_agent_session_id=Mock(return_value="ses-durable"),+ )+ agent._turn_registry = _HandleMessageTurnRegistry(active_turn=None)+ agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())+ agent._delete_ack = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent._touch_transport_activity = Mock()+ agent._build_thread_developer_instructions = AsyncMock(return_value="prompt")+ agent._start_or_resume_thread = AsyncMock(+ side_effect=[ConnectionError("stdout closed"), "thread-restored"],+ )+ agent._start_turn = AsyncMock()++ def snapshot(target):+ self.assertEqual([binding.session_id for binding in target.bindings], ["ses-durable"])+ return SimpleNamespace(blocks_dead_transport_replacement=False)++ agent.controller = SimpleNamespace(+ emit_agent_message=AsyncMock(),+ runtime_ownership=SimpleNamespace(snapshot=Mock(side_effect=snapshot)),+ )++ async def get_transport(_cwd):+ # Both initial acquisition and failure recovery must see a+ # complete producer-side binding, not a mocked predicate.+ target = agent._runtime_ownership_target_for_cwd(request.working_path)+ self.assertIsNotNone(target)+ self.assertEqual([binding.session_id for binding in target.bindings], ["ses-durable"])+ return agent._transports.get(request.working_path, fresh)++ agent._get_or_create_transport = AsyncMock(side_effect=get_transport)+ await agent.handle_message(request)+ bad.stop.assert_awaited_once()+ agent.controller.runtime_ownership.snapshot.assert_called_once()+ self.assertEqual(agent._get_or_create_transport.await_count, 2)+ agent._start_turn.assert_awaited_once()+ agent.controller.emit_agent_message.assert_not_awaited()+async def test_drop_transport_after_failure_keeps_other_sessions_when_transport_was_replaced(self):agent = object.__new__(CodexAgent)request = SimpleNamespace(base_session_id="session-1")@@ -1740,7 +1817,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):request = SimpleNamespace(base_session_id="session-1")activation = RuntimeActivationRegistry()observed_current = []- transport = SimpleNamespace()+ transport = SimpleNamespace(is_alive=False)async def stop_transport():observed_current.append(activation.is_current(identity))@@ -1750,6 +1827,9 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._transport_locks = {"/tmp/work": asyncio.Lock()}agent._transport_last_activity = {"/tmp/work": 1.0}agent._transport_cwd_inodes = {"/tmp/work": 1}+ agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(+ return_value=SimpleNamespace(blocks_dead_transport_replacement=False)+ )agent._session_mgr = SimpleNamespace(sessions_for_cwd=Mock(return_value=["session-1"]),invalidate_thread=Mock(),@@ -1778,6 +1858,117 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._start_thread.assert_not_awaited()+ async def test_permanent_resume_failure_holds_only_proven_unwritten_input(self):+ for error in (+ CodexResponseTooLargeError(), _MODULE.CodexResumeUnavailableError("thread-old"),+ TimeoutError("no start acknowledgement"),+ ):+ for phase in (DISPATCH_PHASE_PREWRITE, DISPATCH_PHASE_ATTEMPTING, None):+ with self.subTest(error=type(error).__name__, phase=phase):+ agent = object.__new__(CodexAgent)+ context = SimpleNamespace(platform_specific={})+ if phase:+ set_dispatch_phase(context, phase)+ request = SimpleNamespace(+ base_session_id="session-1", working_path="/tmp/work",+ context=context, session_key="settings-1", ack_message_id=None,+ )+ transport = SimpleNamespace(stop=AsyncMock())+ agent.controller = SimpleNamespace(+ config=SimpleNamespace(language="en"), emit_agent_message=AsyncMock(),+ )+ agent.sessions = SimpleNamespace()+ agent._session_locks = {}+ agent._turn_registry = _HandleMessageTurnRegistry(active_turn=None)+ agent._session_mgr = SimpleNamespace(+ set_session_key=Mock(), set_cwd=Mock(), get_thread_id=Mock(return_value=None),+ )+ agent._get_or_create_transport = AsyncMock(return_value=transport)+ agent._touch_transport_activity = Mock()+ agent._delete_ack = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())+ agent._build_thread_developer_instructions = AsyncMock(return_value="prompt")+ agent._start_or_resume_thread = AsyncMock(side_effect=error)+ agent._start_turn = AsyncMock()+ agent._drop_transport_after_failure = AsyncMock(return_value=False)++ await agent.handle_message(request)++ agent._get_or_create_transport.assert_awaited_once()+ if isinstance(error, TimeoutError) and phase == DISPATCH_PHASE_PREWRITE:+ agent._drop_transport_after_failure.assert_awaited_once()+ else:+ agent._drop_transport_after_failure.assert_not_awaited()+ agent._start_turn.assert_not_awaited()+ transport.stop.assert_not_awaited()+ self.assertEqual(+ prewrite_failure_evidence(context),+ {"reason": "codex_resume_unavailable", "requires_explicit_retry": True}+ if phase == DISPATCH_PHASE_PREWRITE and not isinstance(error, TimeoutError) else {},+ )+ self.assertTrue(agent.controller.emit_agent_message.await_args.kwargs["is_error"])++ async def test_failure_replacement_respects_live_durable_and_unknown_ownership(self):+ """MESSAGE-DELIVERY-033: one failed resume cannot kill a live neighbour."""+ for live, blocked, active, allowed in (+ (True, False, True, False), # In-memory active/pending neighbour.+ (True, True, False, False), # Durable owner without local registry.+ (True, None, False, False), # Unreadable ownership fails closed.+ (False, True, False, False), # Dead process still has protected work.+ (False, False, True, True), # Dead process can be reclaimed.+ (True, False, False, True), # Idle process can be reclaimed.+ ):+ with self.subTest(live=live, blocked=blocked, active=active):+ agent = object.__new__(CodexAgent)+ activation = RuntimeActivationRegistry()+ transport = SimpleNamespace(stop=AsyncMock(), is_alive=live)+ agent.controller = SimpleNamespace(runtime_activation=activation)+ agent._transports = {"/tmp/work": transport}+ agent._transport_locks = {}+ agent._transport_last_activity = {"/tmp/work": 1.0}+ agent._session_mgr = SimpleNamespace(+ sessions_for_cwd=Mock(return_value=["failed", "neighbour"]),+ invalidate_thread=Mock(),+ )+ agent._turn_registry = SimpleNamespace(clear_session=Mock())+ agent._has_active_turns_for_cwd = Mock(return_value=active)+ agent._runtime_ownership_snapshot_for_cwd_async = AsyncMock(+ return_value=None if blocked is None else SimpleNamespace(+ blocks_transport_replacement=blocked,+ blocks_dead_transport_replacement=blocked,+ )+ )+ identity = agent._attach_transport_activation("/tmp/work", transport)+ result = await agent._drop_transport_after_failure(+ "/tmp/work", transport, SimpleNamespace(base_session_id="failed"),+ )+ self.assertIs(result, allowed)+ if allowed:+ transport.stop.assert_awaited_once()+ self.assertNotIn("/tmp/work", agent._transports)+ else:+ transport.stop.assert_not_awaited()+ agent._session_mgr.invalidate_thread.assert_not_called()+ agent._turn_registry.clear_session.assert_not_called()+ self.assertIs(agent._transports["/tmp/work"], transport)+ self.assertTrue(activation.is_current(identity))++ async def test_start_or_resume_preserves_oversized_response_identity(self):+ agent = object.__new__(CodexAgent)+ agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-old"))+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent._build_thread_developer_instructions = AsyncMock(return_value=None)+ agent._start_thread = AsyncMock()+ error = CodexResponseTooLargeError()+ transport = SimpleNamespace(send_request=AsyncMock(side_effect=error))+ request = SimpleNamespace(session_key="settings-1", base_session_id="session-1")+ with self.assertRaises(CodexResponseTooLargeError) as caught:+ await agent._start_or_resume_thread(transport, request)+ self.assertIs(caught.exception, error)+ self.assertFalse(agent._is_recoverable_transport_error(error))+ agent._start_thread.assert_not_awaited()+def test_find_request_does_not_bootstrap_turn_completed_for_pending_turn(self):agent = object.__new__(CodexAgent)agent._session_mgr = _StubSessionManager()@@ -2106,6 +2297,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):method, params = transport.send_request.await_args_list[2].argsself.assertEqual(method, "thread/resume")self.assertEqual(params["threadId"], "thread-existing")+ self.assertIs(params["excludeTurns"], True)self.assertNotIn("developerInstructions", params)async def test_resume_thread_rebinds_managed_provider_when_thread_id_matches_config(self):@@ -3564,6 +3756,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):method, params = transport.send_request.await_args.argsself.assertEqual(method, "thread/resume")self.assertEqual(params["threadId"], "thread-existing")+ self.assertIs(params["excludeTurns"], True)self.assertNotIn("modelProvider", params)self.assertNotIn("developerInstructions", params)diff --git a/tests/test_codex_native_prompt_baseline.py b/tests/test_codex_native_prompt_baseline.pyindex 5ff3e5f65..6e6552f87 100644--- a/tests/test_codex_native_prompt_baseline.py+++ b/tests/test_codex_native_prompt_baseline.py@@ -180,6 +180,8 @@ async def test_fork_sets_target_baseline_but_inherits_source_history_identity():@pytest.mark.parametrize("prompt", [PROMPT_A, None, ""])@pytest.mark.parametrize("recover", [False, True])async def test_dispatch_renders_once_even_for_empty_prompt_and_transport_recovery(prompt, recover):+ from core.native_dispatch_phase import DISPATCH_PHASE_PREWRITE, set_dispatch_phase+agent = _agent({})request = _request()agent._session_locks = {}@@ -193,7 +195,7 @@ async def test_dispatch_renders_once_even_for_empty_prompt_and_transport_recovertransport = _transport()fresh = _transport()agent._get_or_create_transport = AsyncMock(side_effect=[transport, fresh])- agent._drop_transport_after_failure = AsyncMock()+ agent._drop_transport_after_failure = AsyncMock(return_value=True)agent._refresh_thread_developer_instructions_if_needed = AsyncMock()agent._bind_runtime_agent_session_id = Mock()agent._build_thread_developer_instructions = AsyncMock(return_value=prompt)@@ -202,6 +204,7 @@ async def test_dispatch_renders_once_even_for_empty_prompt_and_transport_recoverif recover else ["thread-contract"])agent._start_turn = AsyncMock()+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)await agent.handle_message(request)agent._build_thread_developer_instructions.assert_awaited_once_with(request)assert agent._start_or_resume_thread.await_args_list == [diff --git a/tests/test_codex_prompt_delivery_contract.py b/tests/test_codex_prompt_delivery_contract.pyindex f5fffd0d6..368e88a10 100644--- a/tests/test_codex_prompt_delivery_contract.py+++ b/tests/test_codex_prompt_delivery_contract.py@@ -227,6 +227,54 @@ def _request(tmp_path):)+async def test_excluded_resume_preserves_native_history_and_model_settings(tmp_path):+ """MESSAGE-DELIVERY-034: response omission is not model-context truncation."""+ async with _native_server(tmp_path) as harness:+ marker = {}+ agent = _agent(marker)+ request = _request(tmp_path)+ old_text = "原始上下文:保留编号 EXCLUDE-TURNS-2049 🧪"+ agent._build_input = Mock(return_value=[{"type": "text", "text": old_text, "text_elements": []}])+ thread_id = await agent._start_or_resume_thread(+ harness.native, request, developer_instructions="Keep context.",+ )+ await agent._start_turn(harness.native, request, thread_id, developer_instructions="Keep context.")+ await harness.finish_turn()+ native = await harness.restart()++ # Exercise both production resume producers and inspect their real responses.+ agent = _agent(marker)+ resumes = []+ send_request = native.send_request++ async def capture(method, params=None, **kwargs):+ response = await send_request(method, params, **kwargs)+ if method == "thread/resume":+ resumes.append((params, response))+ return response++ native.send_request = capture+ assert await agent._start_or_resume_thread(+ native, request, developer_instructions="Keep context.",+ ) == thread_id+ assert agent._thread_model_settings["contract"] == (thread_id, MODEL, "high")+ agent._caller_env_for_request = Mock(return_value={"AVIBE_CONTRACT": "更新"})+ await agent._refresh_thread_developer_instructions_if_needed(native, request, thread_id)+ assert len(resumes) == 2+ for params, response in resumes:+ assert params["excludeTurns"] is True+ assert response["thread"]["id"] == thread_id+ assert not response["thread"].get("turns")+ assert response["model"] == MODEL+ assert response["reasoningEffort"] == "high"+ await agent._start_turn(native, request, thread_id, developer_instructions="Keep context.")+ await harness.finish_turn()+ assert old_text in json.dumps(harness.requests[-1]["input"], ensure_ascii=False)+ history = await native.send_request("thread/read", {"threadId": thread_id, "includeTurns": True})+ assert len(history["thread"]["turns"]) == 2++@pytest.mark.asyncioasync def test_production_agent_instructions_are_last_in_native_baseline_and_overlay(tmp_path, monkeypatch):monkeypatch.setattr("core.managed_skills.resolve_skills", lambda *_args, **_kwargs: [])diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.pyindex fac61bb17..b4b4eff87 100644--- a/tests/test_codex_transport.py+++ b/tests/test_codex_transport.py@@ -10,6 +10,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from modules.agents.codex.transport import (AVIBE_APP_SERVER_CONFIG_OVERRIDES,CodexRPCError,+ CodexResponseTooLargeError,CodexTransport,STREAM_BUFFER_LIMIT,)@@ -24,6 +25,34 @@ def _forced_config_args() -> tuple[str, ...]:class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):+ async def test_oversized_stdout_fails_all_pending_requests_with_typed_cause(self):+ """MESSAGE-DELIVERY-032: preserve framing failure instead of retryable EOF."""+ transport = CodexTransport(binary="codex", cwd="/tmp")+ stdout = asyncio.StreamReader(limit=64)+ stdout.feed_data(b'{"result":"' + b"x" * 100 + b'"}\n')+ transport._process = SimpleNamespace(stdout=stdout, returncode=None)+ pending = [asyncio.get_running_loop().create_future() for _ in range(2)]+ transport._pending = dict(enumerate(pending))+ transport._reader_task = asyncio.create_task(transport._reader_loop())+ await transport._reader_task+ for future in pending:+ with self.assertRaises(CodexResponseTooLargeError) as caught:+ await future+ self.assertNotIsInstance(caught.exception, ConnectionError)+ self.assertFalse(transport.is_alive)+ self.assertEqual(transport._pending, {})++ async def test_normal_stdout_eof_remains_a_connection_error(self):+ transport = CodexTransport(binary="codex", cwd="/tmp")+ stdout = asyncio.StreamReader()+ stdout.feed_eof()+ transport._process = SimpleNamespace(stdout=stdout, returncode=None)+ pending = asyncio.get_running_loop().create_future()+ transport._pending[1] = pending+ await transport._reader_loop()+ with self.assertRaisesRegex(ConnectionError, "stdout closed"):+ await pending+async def test_rpc_errors_preserve_protocol_rejection_identity(self):transport = CodexTransport(binary="codex", cwd="/tmp")for code in (-32600, -32601, -32602, -32603, -32000):diff --git a/tests/test_session_cli.py b/tests/test_session_cli.pyindex 5edb340fe..875604792 100644--- a/tests/test_session_cli.py+++ b/tests/test_session_cli.py@@ -459,6 +459,38 @@ def test_queue_list_is_paginated_in_fifo_order_and_exposes_run_identity(assert page2["pagination"]["has_more"] is False+def test_queue_list_reports_server_owned_explicit_retry_hold(monkeypatch, tmp_path, capsys):+ from core.session_turns import SessionTurnManager+ from tests.test_session_delivery_fsm import _Controller++ engine = _setup(monkeypatch, tmp_path)+ scope_id = _seed(engine, "sesaaa")+ manager = SessionTurnManager(_Controller())+ manager._engine = engine+ with engine.begin() as conn:+ payload = message_deliveries.enqueue_queued(+ conn, scope_id=scope_id, session_id="sesaaa", text="保留附件",+ metadata={"requires_explicit_retry": True, "retry_reason": "caller spoof"},+ )+ _, before = _run(cli.cmd_session_queue_list, ["session", "queue", "list", "sesaaa"], capsys)+ assert before["queued"][0]["requires_explicit_retry"] is False+ assert before["queued"][0]["retry_reason"] is None+ for _ in range(3):+ turn_id = message_deliveries.new_turn_id()+ with engine.begin() as conn:+ delivery = message_deliveries.get_delivery(conn, payload["id"])+ message_deliveries.claim_start_batch(+ conn, turn_id=turn_id, session_id="sesaaa", backend="claude",+ deliveries=[delivery], dispatch_text="保留附件",+ )+ manager._settle_durable_prewrite_failure(turn_id, outcome="no_terminal_result")+ code, result = _run(cli.cmd_session_queue_list, ["session", "queue", "list", "sesaaa"], capsys)+ assert code == 0+ assert result["queued"][0]["id"] == payload["id"]+ assert result["queued"][0]["requires_explicit_retry"] is True+ assert result["queued"][0]["retry_reason"] == "no_terminal_result"++def test_queue_remove_deletes_only_the_named_session_row_and_notifies_web(monkeypatch,tmp_path,diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 6f030b66c..a5e45a8ff 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -5721,6 +5721,275 @@ def test_definite_handler_prewrite_exit_requeues_through_terminal_boundary(assert turn["settled_by"] == "no_terminal_result"[email protected]("retry", ["failure_notice", "send_now"])+async def test_prewrite_retry_budget_survives_restart_and_preserves_original_input(managers, retry, monkeypatch):+ """MESSAGE-DELIVERY-031: bounded failures retain FIFO input until explicit retry."""+ from tests.backend_failure_retry_helpers import reserve_failure_retry++ manager, restarted, engine, engine_b, starts = managers+ admitted = await manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm", priority="p3", content="请继续检查附件 🧪",+ content_json={"attachments": [{"name": "报告.pdf", "url": "fixture://report"}]},+ ),+ context=_context(),+ )+ original = _row(engine, admitted.delivery_id)["snapshot_json"]+ queue_events = []++ def observe_committed_queue(event, payload):+ if event == "queue.updated":+ assert payload == {"session_id": "ses_fsm"}+ # A second connection proves the notification follows commit.+ with engine_b.connect() as conn:+ row = delivery_store.get_delivery(conn, admitted.delivery_id)+ queue_events.append(delivery_store.public_delivery_payload(row))++ monkeypatch.setattr("core.inbox_events.bus.publish", observe_committed_queue)+ for attempt in range(1, 4):+ assert len(starts) == attempt+ queue_events.clear()+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT)+ retained = _row(engine, admitted.delivery_id)+ assert retained["state"] == "queued"+ assert retained["snapshot_json"] == original+ assert delivery_store.requires_explicit_start_retry(retained) is (attempt == 3)+ public = delivery_store.public_delivery_payload(retained)+ assert public["requires_explicit_retry"] is (attempt == 3)+ assert public["retry_reason"] == (SETTLED_BY_NO_TERMINAL_RESULT if attempt == 3 else None)+ assert queue_events[-1]["state"] == "queued"+ assert queue_events[-1]["requires_explicit_retry"] is (attempt == 3)+ before_duplicate_settle = len(queue_events)+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT)+ assert len(queue_events) == before_duplicate_settle+ await restarted.recover_durable_delivery_state("ses_fsm")+ for _ in range(3):+ assert not await manager.drain_delivery_queue("ses_fsm")+ await restarted.recover_durable_delivery_state("ses_fsm")+ assert len(starts) == 3+ assert _row(engine, admitted.delivery_id) == retained++ if retry == "failure_notice":+ with engine.begin() as conn:+ notice = messages_service.append(+ conn, session_id="ses_fsm", scope_id=None, platform="avibe",+ author="agent", source="agent", message_type="notify", text="Startup failed",+ metadata={+ "event": "backend_failure", "backend": "codex",+ "turn_id": starts[-1][0], "failure_id": f"turn:{starts[-1][0]}",+ },+ )+ reserved = reserve_failure_retry(conn, notice)+ assert reserved["id"] == admitted.delivery_id+ result = await restarted.deliver(+ DeliveryRequest(+ session_id="ses_fsm", priority="p3", content="must not replace original",+ delivery_id=admitted.delivery_id,+ ),+ context=_context(),+ )+ assert result.state == "claimed"+ else:+ result = await restarted.send_now("ses_fsm", expected_delivery_id=admitted.delivery_id)+ assert result["status"] == "claimed"+ assert len(starts) == 4+ assert starts[-1][1] == starts[0][1]+ assert _row(engine, admitted.delivery_id)["snapshot_json"] == original+ assert not delivery_store.public_delivery_payload(_row(engine, admitted.delivery_id))["requires_explicit_retry"]++ # Retry replenishes the budget; Send now grants only one extra attempt.+ for attempt in range(3 if retry == "failure_notice" else 1):+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT)+ await restarted.recover_durable_delivery_state("ses_fsm")+ assert len(starts) == (6 if retry == "failure_notice" else 4)+ assert delivery_store.requires_explicit_start_retry(_row(engine, admitted.delivery_id))+ successor = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="后续输入"),+ context=_context(),+ )+ assert successor.state == "queued"+ assert not await restarted.drain_delivery_queue("ses_fsm")+ assert _row(engine, admitted.delivery_id)["snapshot_json"] == original+++async def test_concurrent_start_refusal_does_not_spend_or_reset_prewrite_budget(managers):+ manager, restarted, engine, _other, starts = managers+ admitted = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="keep waiting"),+ context=_context(),+ )+ for outcome in (+ SETTLED_BY_NO_TERMINAL_RESULT,+ *["refused_concurrent_turn"] * 4,+ SETTLED_BY_NO_TERMINAL_RESULT,+ SETTLED_BY_NO_TERMINAL_RESULT,+ ):+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=outcome)+ await restarted.recover_durable_delivery_state("ses_fsm")+ assert len(starts) == 7+ retained = _row(engine, admitted.delivery_id)+ assert delivery_store.consecutive_prewrite_start_failures(retained) == 3+ assert delivery_store.requires_explicit_start_retry(retained)+++async def test_prewrite_batched_retry_budget_is_per_input(managers):+ manager, restarted, engine, _other, starts = managers+ older = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="older"),+ context=_context(),+ )+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT)+ await restarted.recover_durable_delivery_state("ses_fsm")+ newer = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="新输入"),+ context=_context(),+ )+ snapshot = _row(engine, newer.delivery_id)["snapshot_json"]+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT)+ await restarted.recover_durable_delivery_state("ses_fsm")+ assert len(starts) == 3+ assert _row(engine, older.delivery_id)["turn_id"] == _row(engine, newer.delivery_id)["turn_id"]+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT)+ assert delivery_store.requires_explicit_start_retry(_row(engine, older.delivery_id))+ assert not delivery_store.requires_explicit_start_retry(_row(engine, newer.delivery_id))+ assert delivery_store.consecutive_prewrite_start_failures(_row(engine, newer.delivery_id)) == 1+ assert not await restarted.drain_delivery_queue("ses_fsm")+ with engine.begin() as conn:+ assert delivery_store.retire_queued(conn, "ses_fsm", older.delivery_id)+ assert await restarted.drain_delivery_queue("ses_fsm")+ assert len(starts) == 4+ assert starts[-1][1] == "新输入"+ assert _row(engine, newer.delivery_id)["snapshot_json"] == snapshot++[email protected]("permanent", [False, True])+ "outcome",+ [+ "refused_concurrent_turn",+ SETTLED_BY_NO_TERMINAL_RESULT,+ "transient_start_failure",+ "native_start_attempt_absent",+ ],+)+async def test_send_now_no_write_preserves_existing_retry_hold(managers, permanent, outcome):+ """MESSAGE-DELIVERY-031: changing failure classes never resets a one-shot hold."""+ from tests.backend_failure_retry_helpers import reserve_failure_retry++ manager, restarted, engine, _other, starts = managers+ admitted = await manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm", priority="p3", content="仍然保留",+ content_json={"attachments": [{"name": "报告.pdf", "url": "fixture://report"}]},+ ),+ context=_context(),+ )+ original = _row(engine, admitted.delivery_id)["snapshot_json"]+ reason = "codex_resume_unavailable" if permanent else SETTLED_BY_NO_TERMINAL_RESULT+ for _ in range(1 if permanent else 3):+ manager._settle_durable_prewrite_failure(+ starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT,+ failure_evidence={"reason": reason, "requires_explicit_retry": True} if permanent else None,+ )+ await restarted.recover_durable_delivery_state("ses_fsm")+ for _ in range(2):+ assert delivery_store.requires_explicit_start_retry(_row(engine, admitted.delivery_id))+ result = await manager.send_now("ses_fsm", expected_delivery_id=admitted.delivery_id)+ assert result["status"] == "claimed"+ assert not delivery_store.requires_explicit_start_retry(_row(engine, admitted.delivery_id))+ if outcome == "native_start_attempt_absent":+ with engine.connect() as conn:+ turn = delivery_store.get_turn(conn, starts[-1][0])+ assert manager.reconcile_start_attempt_not_written(+ turn["id"], turn["start_attempt_id"], backend="codex",+ )+ else:+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=outcome)+ retained = _row(engine, admitted.delivery_id)+ assert retained["state"] == "queued"+ assert retained["snapshot_json"] == original+ held = delivery_store.public_delivery_payload(retained)+ assert held["requires_explicit_retry"] is True+ assert held["retry_reason"] == reason+ count = len(starts)+ assert not await manager.drain_delivery_queue("ses_fsm")+ await restarted.recover_durable_delivery_state("ses_fsm")+ assert len(starts) == count+ assert _row(engine, admitted.delivery_id) == retained++ # Only the validated failure-notice action releases the retained hold.+ with engine.begin() as conn:+ notice = messages_service.append(+ conn, session_id="ses_fsm", scope_id=None, platform="avibe",+ author="agent", source="agent", message_type="notify", text="Startup failed",+ metadata={+ "event": "backend_failure", "backend": "codex",+ "turn_id": starts[-1][0], "failure_id": f"turn:{starts[-1][0]}",+ },+ )+ reserved = reserve_failure_retry(conn, notice)+ assert reserved["id"] == admitted.delivery_id+ assert not delivery_store.requires_explicit_start_retry(reserved)+ assert delivery_store.consecutive_prewrite_start_failures(reserved) == 0+ count = len(starts)+ assert await restarted.drain_delivery_queue("ses_fsm")+ for attempt in range(1, 4):+ assert len(starts) == count + attempt+ manager._settle_durable_prewrite_failure(starts[-1][0], outcome=SETTLED_BY_NO_TERMINAL_RESULT)+ assert delivery_store.requires_explicit_start_retry(_row(engine, admitted.delivery_id)) is (attempt == 3)+ await restarted.recover_durable_delivery_state("ses_fsm")+ assert len(starts) == count + 3+ assert _row(engine, admitted.delivery_id)["snapshot_json"] == original+ assert all(text == starts[0][1] for _, text in starts)++[email protected]("outcome", ["accepted", "unknown"])+async def test_send_now_written_or_ambiguous_attempt_does_not_restore_prewrite_hold(managers, outcome):+ manager, _restarted, engine, _other, starts = managers+ admitted = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="只执行一次"),+ context=_context(),+ )+ manager._settle_durable_prewrite_failure(+ admitted.turn_id, outcome=SETTLED_BY_NO_TERMINAL_RESULT,+ failure_evidence={"reason": "codex_resume_unavailable", "requires_explicit_retry": True},+ )+ result = await manager.send_now("ses_fsm", expected_delivery_id=admitted.delivery_id)+ assert result["status"] == "claimed"+ turn_id = starts[-1][0]+ if outcome == "accepted":+ context = _context()+ context.platform_specific["turn_token"] = turn_id+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"+ manager.on_native_start(+ context, backend="codex", runtime_key=f"runtime-key-{turn_id}",+ runtime_turn_id=f"runtime-{turn_id}",+ )+ assert not manager._settle_durable_prewrite_failure(+ turn_id, outcome=SETTLED_BY_NO_TERMINAL_RESULT,+ )["changed"]+ else:+ released = manager._reconcile_durable_runner_release(+ turn_id, cancelled=False, failed=True, prewrite_refused=False,+ definitive_prewrite_exit=False, settled_by=None, terminal_is_error=True,+ )+ assert released["defer_queue_resume"] is True+ with engine.connect() as conn:+ turn = delivery_store.get_turn(conn, turn_id)+ assert turn["start_receipt_outcome"] == outcome+ row = _row(engine, admitted.delivery_id)+ assert row["state"] == ("accepted" if outcome == "accepted" else "claimed")+ assert not delivery_store.requires_explicit_start_retry(row)+ assert not delivery_store.public_delivery_payload(row)["requires_explicit_retry"]+ assert not await manager.drain_delivery_queue("ses_fsm")+ assert len(starts) == 2++def test_definite_handler_prewrite_exception_requeues_through_terminal_boundary(managers,monkeypatch,diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex dd52e5da9..b8434ccf1 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -3357,18 +3357,20 @@ export const QueueStrip: React.FC<{}> = ({ queue, onRemove, onRecall, onSendNow }) => {const { t } = useTranslation();if (queue.length === 0) return null;+ const retryRequired = queue.some((item) => item.requires_explicit_retry === true);return (<div className="shrink-0 px-4 md:px-8"><div className="mx-auto w-full max-w-[1080px] rounded-xl border border-cyan/25 bg-cyan/[0.04] p-2"><div className="flex items-center justify-between px-1 pb-1.5"><span className="inline-flex items-center gap-1.5 font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-cyan-ink"><Clock className="size-3" />- {t('chat.queue.title', { count: queue.length })}+ {t(retryRequired ? 'chat.queue.retryRequired' : 'chat.queue.title', { count: queue.length })}</span><Button type="button" variant="ghost" size="sm" onClick={onSendNow} className="h-6 px-2 text-[11px] text-cyan-ink">{t('chat.queue.sendNow')}</Button></div>+ {retryRequired && <p className="px-1 pb-1.5 text-[11px] text-muted">{t('chat.queue.retryHint')}</p>}<divdata-queue-batch="true"className="flex max-h-32 flex-col overflow-y-auto rounded-lg bg-surface-2"diff --git a/ui/src/components/workbench/ChatQueueRow.test.tsx b/ui/src/components/workbench/ChatQueueRow.test.tsxindex 95b138d82..42de12aae 100644--- a/ui/src/components/workbench/ChatQueueRow.test.tsx+++ b/ui/src/components/workbench/ChatQueueRow.test.tsx@@ -120,6 +120,34 @@ const chips = () => [...document.querySelectorAll('[data-queue-attachment^="fileconst more = () => [...document.querySelectorAll('[data-queue-attachment-more="true"]')] as HTMLElement[];describe('QueueStrip — compatible queued messages read as one batch', () => {+ it('MESSAGE-DELIVERY-031: shows the server-owned retry hold and preserves Send now', () => {+ const onSendNow = vi.fn();+ const items = [queued({+ text: '请继续检查附件', content: {}, requires_explicit_retry: true,+ retry_reason: 'no_terminal_result',+ })];+ const view = render(+ <I18nextProvider i18n={i18n}>+ <QueueStrip queue={items} onRemove={vi.fn()} onRecall={vi.fn()} onSendNow={onSendNow} />+ </I18nextProvider>,+ );+ expect(screen.getByText('Retry needed · 1')).toBeTruthy();+ expect(screen.getByText(/Automatic startup retries stopped/)).toBeTruthy();+ expect(screen.getByText('请继续检查附件')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Send now' }));+ expect(onSendNow).toHaveBeenCalledTimes(1);+ view.rerender(+ <I18nextProvider i18n={i18n}>+ <QueueStrip+ queue={[{ ...items[0], requires_explicit_retry: false, metadata: { requires_explicit_retry: true } }]}+ onRemove={vi.fn()} onRecall={vi.fn()} onSendNow={onSendNow}+ />+ </I18nextProvider>,+ );+ expect(screen.queryByText(/Automatic startup retries stopped/)).toBeNull();+ expect(screen.getByText('Queued · 1')).toBeTruthy();+ });+it('uses one shared bubble and reveals each original row boundary on hover or focus', () => {const html = wrap(<QueueStripdiff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex d9d2159da..d5d4a37bf 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1316,6 +1316,9 @@ export type WorkbenchMessage = {parent_native_message_id: string | null;// Server-owned read projection. Durable Message rows never carry this field.projection?: 'claimed_delivery' | null;+ // Server-owned queued Delivery recovery projection, not Message metadata.+ requires_explicit_retry?: boolean;+ retry_reason?: string | null;text: string;content: Record<string, unknown>;metadata: Record<string, unknown>;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 6b32fc40a..1777fcfc6 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4343,6 +4343,8 @@},"queue": {"title": "Queued · {{count}}",+ "retryRequired": "Retry needed · {{count}}",+ "retryHint": "Automatic startup retries stopped after failure. Your input is retained. Resolve the error, then use Send now or Retry on the failure notice.","sendNow": "Send now","recall": "Recall to input","remove": "Remove from queue",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex aab16126c..cd131a876 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4342,6 +4342,8 @@"opDelete": "删除"},"queue": {+ "retryRequired": "等待手动重试 · {{count}}",+ "retryHint": "启动失败,自动重试已停止,原输入已保留。排查错误后,点击“立即发送”或失败提示上的“重试”。","title": "排队中 · {{count}}","sendNow": "立即发送","recall": "撤回到输入框",diff --git a/vibe/cli.py b/vibe/cli.pyindex 9a695eced..1b6e1e0fa 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -8016,6 +8016,8 @@ def _session_queue_row(row: dict, *, position: int) -> dict:"author": row.get("author"),"source": row.get("source"),"run_id": _queued_agent_run_id(row),+ "requires_explicit_retry": row.get("requires_explicit_retry") is True,+ "retry_reason": row.get("retry_reason"),}diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 1f71999f5..56d700605 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -414,6 +414,7 @@"claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Restore the original session in its original working directory, then explicitly retry the pending input; or start a new conversation from the current directory.","sessionGeneric": "An error occurred: {error}","codexPromptRefreshUnavailable": "Codex could not confirm that it can safely refresh Avibe's instructions for this existing session. Check or update Codex, then retry this turn.",+ "codexResponseTooLarge": "Codex returned a response larger than {limitMiB} MiB, so this connection cannot continue. Check or update Codex before retrying.","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.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex a34193765..49dfacb8d 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -414,6 +414,7 @@"claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请在原工作目录恢复原会话,再手动重试待发送的输入;也可以在当前目录开始一个新会话。","sessionGeneric": "发生错误:{error}","codexPromptRefreshUnavailable": "Codex 无法确认能否安全刷新此现有会话的 Avibe 指令。请检查或升级 Codex 后重试本回合。",+ "codexResponseTooLarge": "Codex 返回的响应超过 {limitMiB} MiB,此连接无法继续。请检查或升级 Codex 后重试。","opencodeModelHubOverlayRequired": "OpenCode 仍在准备 Gateway 模式,请稍后重试。","opencodePolicyRefreshPending": "OpenCode 仍在完成已有回合,暂时无法按 Avibe 当前的 Skill 策略重启。请在该回合结束后重试。","opencodeRuntimeConfigInvalid": "OpenCode 无法启动,因为 OPENCODE_CONFIG_CONTENT 无效。请修正运行时配置后重试。",