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(codex): report a CLI that cannot start and reach the loopback gateway through proxies (#2452)

Call White11619a2e48ea
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 5a96db257..7394be93b 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -48,6 +48,7 @@ from modules.agents.opencode.utils import (
resolve_opencode_reasoning_effort,
)
from modules.im import InlineButton, InlineKeyboard, MessageContext
+from vibe.codex_launch_failure import CLI_NOT_FOUND, CodexLaunchError
from vibe.i18n import t as i18n_t
from vibe.opencode_config import remove_opencode_provider_api_key
@@ -3064,6 +3065,16 @@ class AgentAuthService:
return result
except FileNotFoundError:
return {"ok": False, "error": "cli_not_found", "detail": binary}
+ except CodexLaunchError as err:
+ # The CLI never started; its recognized cause explains the failure.
+ if err.cause == CLI_NOT_FOUND:
+ return {"ok": False, "error": "cli_not_found", "detail": binary}
+ return {
+ "ok": False,
+ "error": "spawn_failed",
+ "detail": str(err),
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
except Exception as err: # noqa: BLE001
detail = str(err).strip()
if "no such file or directory" in detail.lower() or "claude code not found" in detail.lower():
diff --git a/core/watch_worker.py b/core/watch_worker.py
index 1acf1d7b4..2e2e673da 100644
--- a/core/watch_worker.py
+++ b/core/watch_worker.py
@@ -26,6 +26,14 @@ class WatchWorkerProtocolError(ValueError):
self.code = code
+class _CommandSpawnError(Exception):
+ """The operating system refused to start the requested command."""
+
+ def __init__(self, error: OSError):
+ super().__init__(str(error))
+ self.os_errno = error.errno if isinstance(error.errno, int) else None
+
+
def encode_watch_worker_spec(
*,
command: list[str],
@@ -39,10 +47,17 @@ def encode_watch_worker_spec(
return json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode("ascii")
-def encode_watch_worker_error(code: str, detail: str | None = None) -> str:
- payload = {"code": code}
+def encode_watch_worker_error(
+ code: str,
+ detail: str | None = None,
+ *,
+ spawn_errno: int | None = None,
+) -> str:
+ payload: dict[str, Any] = {"code": code}
if detail:
payload["detail"] = detail
+ if spawn_errno is not None:
+ payload["spawnErrno"] = spawn_errno
return WATCH_WORKER_ERROR_PREFIX + json.dumps(
payload,
ensure_ascii=True,
@@ -50,19 +65,37 @@ def encode_watch_worker_error(code: str, detail: str | None = None) -> str:
)
-def decode_watch_worker_error(stderr: str) -> tuple[str, str | None] | None:
+def _watch_worker_error_payload(stderr: str) -> dict[str, Any] | None:
if not stderr.startswith(WATCH_WORKER_ERROR_PREFIX):
return None
try:
payload = json.loads(stderr[len(WATCH_WORKER_ERROR_PREFIX) :].strip())
except (json.JSONDecodeError, UnicodeDecodeError):
- return ("supervisorFailed", None)
- if not isinstance(payload, dict) or not isinstance(payload.get("code"), str):
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+
+def decode_watch_worker_error(stderr: str) -> tuple[str, str | None] | None:
+ payload = _watch_worker_error_payload(stderr)
+ if payload is None:
+ return None
+ if not isinstance(payload.get("code"), str):
return ("supervisorFailed", None)
detail = payload.get("detail")
return payload["code"], detail if isinstance(detail, str) else None
+def decode_watch_worker_spawn_errno(stderr: str) -> int | None:
+ """The OS error number that stopped the worker from starting its command.
+
+ Structured, so a caller can tell a missing executable from one it may not
+ run without reading the platform's wording of either.
+ """
+
+ code = (_watch_worker_error_payload(stderr) or {}).get("spawnErrno")
+ return code if type(code) is int else None
+
+
#: The leaf i18n key per handshake failure the worker can report. The PROTOCOL is one
#: thing whichever lane spawned the supervisor, but the SENTENCE is not: the same
#: failure has to read as "watch worker" to somebody managing a watch and as "command"
@@ -310,14 +343,17 @@ def _run_watch_worker() -> int:
try:
popen_args: Any = shell_command if shell_command is not None else command
- process = subprocess.Popen(
- popen_args,
- shell=shell_command is not None,
- env=child_env,
- stdin=subprocess.DEVNULL,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
+ try:
+ process = subprocess.Popen(
+ popen_args,
+ shell=shell_command is not None,
+ env=child_env,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ except OSError as exc:
+ raise _CommandSpawnError(exc) from exc
if process.stdout is None or process.stderr is None:
raise RuntimeError("watch worker output pipes are unavailable")
@@ -352,6 +388,15 @@ def main() -> int:
except WatchWorkerProtocolError as exc:
print(encode_watch_worker_error(exc.code), file=sys.stderr, flush=True)
return 1
+ except _CommandSpawnError as exc:
+ print(
+ encode_watch_worker_error(
+ "supervisorFailed", str(exc), spawn_errno=exc.os_errno
+ ),
+ file=sys.stderr,
+ flush=True,
+ )
+ return 1
except Exception as exc:
print(
encode_watch_worker_error("supervisorFailed", str(exc)),
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 28bc0e3ef..5b3e36189 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -83,6 +83,7 @@ from vibe.codex_config import (
MANAGED_PROVIDER_ID,
codex_credential_identity,
)
+from vibe.codex_launch_failure import CodexLaunchError
from vibe.desktop_backends import desktop_backend_subprocess_environment
from vibe.i18n import t as i18n_t
from vibe.message_identity import is_input_turn
@@ -682,18 +683,6 @@ class CodexAgent(BaseAgent):
binding = await self._acquire_generation(request.working_path, launch, inputs=inputs)
bindings.append(binding)
await self._move_session_to(binding.generation, request)
- except FileNotFoundError:
- await emit_backend_failure(
- self.controller,
- request.context,
- self.name,
- "Codex CLI not found",
- display_text="❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",
- request=request,
- )
- await self._remove_ack_reaction(request)
- self._event_handler._release_stream_turn(request.context)
- return
except Exception as e:
from modules.agents.model_hub import launch_refusal_copy
@@ -713,6 +702,12 @@ class CodexAgent(BaseAgent):
display_text = (
f"❌ {i18n_t('error.agentRuntimeRetired', language, agent=i18n_t('backend.codex', language))}"
)
+ elif isinstance(e, CodexLaunchError):
+ # Not a source failure: no Hub cooldown. Every retry fails the
+ # same way until the CLI is repaired, so hold the unwritten
+ # input for an explicit retry after the repair.
+ mark_prewrite_recovery_required(request.context, e.retry_reason)
+ display_text = f"❌ {i18n_t(e.copy_key, language)}"
elif isinstance(e, CodexModelHubCatalogUnavailableError):
await self._record_model_hub_native_failure(request.context, str(e))
display_text = f"❌ {i18n_t('modelHub.errors.codex_catalog_unavailable', language)}"
@@ -1611,6 +1606,9 @@ class CodexAgent(BaseAgent):
# result must still release its pin after the caller leaves.
preparation.add_done_callback(self._discard_model_hub_catalog)
raise
+ except CodexLaunchError:
+ # The binary itself cannot start; the turn reports that cause.
+ raise
except Exception as exc:
raise CodexModelHubCatalogUnavailableError(
"Codex Model Hub catalog preparation failed"
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index 931ea9886..a60c247c7 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -8,12 +8,19 @@ import logging
import os
import signal
from asyncio.subprocess import Process
+from collections import deque
from contextlib import nullcontext
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Mapping, Optional
+from core.os_errors import local_os_errno
from core.process_diagnostics import log_process_snapshot, process_identity
from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
from vibe.codex_config import format_toml_basic_string
+from vibe.codex_launch_failure import (
+ CodexLaunchError,
+ launch_failure_from_errno,
+ launch_failure_from_stderr,
+)
logger = logging.getLogger(__name__)
@@ -21,6 +28,9 @@ if TYPE_CHECKING:
from vibe.backend_model_catalog import CodexHubCatalog
STREAM_BUFFER_LIMIT = 128 * 1024 * 1024 # 128 MB
+# Enough of a launcher's last words to say why it exited before ``initialize``.
+_STDERR_TAIL_LINES = 64
+_LAUNCH_EXIT_GRACE_SECONDS = 2.0
# Avibe owns the user-facing surface, durable automation, and agent delegation.
@@ -131,6 +141,8 @@ class CodexTransport:
self.supports_turn_collaboration_mode = False
self._reader_task: Optional[asyncio.Task[None]] = None
self._stderr_task: Optional[asyncio.Task[None]] = None
+ # Read only to recognize a launch that cannot start; never reported.
+ self._stderr_tail: deque[str] = deque(maxlen=_STDERR_TAIL_LINES)
# Callbacks
self._notification_cb: Optional[Callable[[str, dict[str, Any]], Awaitable[None]]] = None
@@ -163,6 +175,7 @@ class CodexTransport:
raise RuntimeError("A stopped Codex Hub transport needs a newly prepared catalog")
self._closed_event.clear()
+ self._stderr_tail.clear()
cmd = (
[self._binary, "--dangerously-bypass-approvals-and-sandbox"]
+ ["app-server"]
@@ -203,6 +216,11 @@ class CodexTransport:
self._process = await spawn
await self.stop()
raise
+ except OSError as exc:
+ cause = launch_failure_from_errno(local_os_errno(exc))
+ if cause is None:
+ raise
+ raise CodexLaunchError(cause) from exc
if catalog is not None:
self._catalog_exit_task = asyncio.create_task(
self._release_catalog_on_exit(self._process, catalog)
@@ -257,12 +275,38 @@ class CodexTransport:
logger.info("Codex app-server handshake cancelled, cleaning up")
else:
logger.exception("Codex app-server handshake failed, cleaning up")
+ cause = None
try:
- await self.stop()
- except Exception:
- logger.exception("Failed to clean up Codex app-server after handshake failure")
+ if isinstance(exc, ConnectionError):
+ cause = await self._exited_launch_failure()
+ finally:
+ try:
+ await self.stop()
+ except Exception:
+ logger.exception("Failed to clean up Codex app-server after handshake failure")
+ if cause is not None:
+ raise CodexLaunchError(cause) from exc
raise
+ async def _exited_launch_failure(self) -> str | None:
+ """Why a process that ended before answering ``initialize`` cannot start.
+
+ Only a process that has exited explains its own failure; an app-server
+ still running lost its connection for another reason.
+ """
+ proc, stderr_task = self._process, self._stderr_task
+ if proc is None or stderr_task is None:
+ return None
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=_LAUNCH_EXIT_GRACE_SECONDS)
+ # The launcher's last words are complete once its stderr closes.
+ await asyncio.wait_for(asyncio.shield(stderr_task), timeout=_LAUNCH_EXIT_GRACE_SECONDS)
+ except asyncio.TimeoutError:
+ return None
+ if proc.returncode == 0:
+ return None
+ return launch_failure_from_stderr("\n".join(self._stderr_tail))
+
async def stop(self) -> None:
"""Gracefully shut down the app-server process."""
self._initialized = False
@@ -555,6 +599,7 @@ class CodexTransport:
if not line:
break
decoded = line.decode(errors="ignore").rstrip()
+ self._stderr_tail.append(decoded[:2000])
logger.info("Codex stderr: %s", decoded[:2000])
except asyncio.CancelledError:
return
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index c87fe085a..043061b98 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import hashlib
+import ipaddress
import json
import os
import re
@@ -11,6 +12,7 @@ import shutil
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Callable, Literal, Mapping, Optional, cast
+from urllib.parse import urlsplit
from config import paths
from config.atomic_io import write_atomic
@@ -421,6 +423,43 @@ def build_claude_hub_env(
return result
+def _loopback_proxy_exemption(gateway_base_url: str) -> str | None:
+ """The ``NO_PROXY`` entry naming a loopback gateway, or None for any other host."""
+
+ host = (urlsplit(gateway_base_url).hostname or "").lower()
+ if host == "localhost":
+ return host
+ try:
+ address = ipaddress.ip_address(host)
+ except ValueError:
+ return None
+ return str(address) if address.is_loopback else None
+
+
+def _exempt_loopback_gateway_from_proxies(env: dict[str, str], gateway_base_url: str) -> None:
+ """Let the CLI reach the gateway on this machine without a proxy.
+
+ Codex sends loopback requests through ``HTTP(S)_PROXY`` and through the
+ macOS system proxy, whose exception list it does not read, so a turn's
+ gateway request can end at a proxy that cannot reach it (the reported 502).
+ ``NO_PROXY`` is the exemption Codex honors. The gateway host joins each
+ exemption list the child already has, or a new ``NO_PROXY``; every other
+ entry and proxy setting stays as it was.
+ """
+
+ entry = _loopback_proxy_exemption(gateway_base_url)
+ if entry is None:
+ return
+ # Readers disagree on which spelling wins, and a present but empty value
+ # still wins for Codex, so each list the child has is extended on its own.
+ names = [name for name in ("NO_PROXY", "no_proxy") if name in env] or ["NO_PROXY"]
+ for name in names:
+ entries = [item.strip() for item in env.get(name, "").split(",") if item.strip()]
+ if "*" in entries or entry in (item.lower() for item in entries):
+ continue
+ env[name] = ",".join([*entries, entry])
+
+
def build_codex_hub_launch(
base_args: list[str],
base_env: dict[str, str],
@@ -438,6 +477,7 @@ def build_codex_hub_launch(
for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE", "CODEX_API_KEY"):
env.pop(key, None)
env["AVIBE_MODEL_HUB_TOKEN"] = launch.gateway_token
+ _exempt_loopback_gateway_from_proxies(env, launch.gateway_base_url)
provider = "avibe_model_hub"
gateway_v1 = f"{launch.gateway_base_url.rstrip('/')}/v1"
overrides = [
diff --git a/tests/e2e/test_codex_launch_failures.py b/tests/e2e/test_codex_launch_failures.py
new file mode 100644
index 000000000..11b76204c
--- /dev/null
+++ b/tests/e2e/test_codex_launch_failures.py
@@ -0,0 +1,56 @@
+"""MH-CODEX-LAUNCH-003: the installed Codex launcher's own failure is recognized.
+
+A disposable copy of the installed npm launcher without its platform package is
+an incomplete install, the state a failed or interrupted npm update leaves. The
+installed CLI is only read. Through the real supervisor and transport, Avibe
+must name the repair cause instead of an error that suggests a retry, whichever
+launcher version is installed.
+"""
+
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+import pytest
+
+from modules.agents.codex.transport import CodexTransport
+from vibe import backend_model_catalog
+from vibe.codex_launch_failure import INSTALL_INCOMPLETE, CodexLaunchError
+
+pytestmark = pytest.mark.e2e_model_hub
+
+
+def incomplete_codex(tmp_path) -> str:
+ binary = shutil.which("codex")
+ if binary is None or shutil.which("node") is None:
+ pytest.skip("The npm Codex launcher and Node.js are unavailable")
+ launcher = Path(binary).resolve()
+ package = launcher.parent.parent
+ if launcher.name != "codex.js" or not (package / "package.json").is_file():
+ pytest.skip("The installed Codex is not the npm launcher")
+ copy = tmp_path / "lib" / "node_modules" / "@openai" / "codex"
+ (copy / "bin").mkdir(parents=True)
+ shutil.copy2(package / "package.json", copy / "package.json")
+ shutil.copy2(launcher, copy / "bin" / "codex.js")
+ entry = tmp_path / "bin" / "codex"
+ entry.parent.mkdir()
+ entry.symlink_to(copy / "bin" / "codex.js")
+ return str(entry)
+
+
+def test_incomplete_install_stops_the_catalog_export_with_its_cause(incomplete_codex):
+ with pytest.raises(CodexLaunchError) as raised:
+ backend_model_catalog._export_codex_bundled_catalog(incomplete_codex)
+
+ assert raised.value.cause == INSTALL_INCOMPLETE
+
+
+async def test_incomplete_install_stops_the_app_server_with_its_cause(incomplete_codex, tmp_path):
+ transport = CodexTransport(binary=incomplete_codex, cwd=str(tmp_path / "work"))
+
+ with pytest.raises(CodexLaunchError) as raised:
+ await transport.start()
+
+ assert raised.value.cause == INSTALL_INCOMPLETE
diff --git a/tests/e2e/test_model_hub_backend_settings.py b/tests/e2e/test_model_hub_backend_settings.py
index 692154f2f..847615158 100644
--- a/tests/e2e/test_model_hub_backend_settings.py
+++ b/tests/e2e/test_model_hub_backend_settings.py
@@ -6,7 +6,9 @@ import asyncio
import json
import os
import shutil
+import socketserver
import subprocess
+import threading
import time
from pathlib import Path
from types import SimpleNamespace
@@ -16,10 +18,15 @@ import pytest
from config.v2_config import ModelHubBackendModelConfig, ModelHubMenuConfig
from core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL
-from modules.agents.model_hub import ModelHubRuntimeRouter
+from modules.agents.codex.transport import CodexTransport
+from modules.agents.model_hub import ModelHubLaunch, ModelHubRuntimeRouter, build_codex_hub_launch
from modules.agents.opencode.caller_context import PLUGIN_FILENAME, PLUGIN_SOURCE
from tests.e2e.drivers.model_hub_app import ModelHubTestApp
from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
+from tests.e2e.test_model_hub_catalog_consumer import (
+ codex_catalog_runtime, # noqa: F401 -- fixture dependency
+ rejected_external_proxy, # noqa: F401 -- fixture dependency
+)
from tests.e2e.test_model_hub_routing import _request_credential
from tests.e2e.test_model_hub_runtime import _install_engine, _local_engine_manifest
from tests.e2e.test_model_hub_sources import SYNTHETIC_API_KEY, _configure_protocol, _create_source
@@ -31,6 +38,7 @@ from tests.scenario_harness.model_hub import (
service_for,
source,
)
+from vibe.backend_model_catalog import _codex_hub_catalog_bytes
from vibe.opencode_config import managed_opencode_runtime_config_content
@@ -196,3 +204,104 @@ def test_opencode_native_settings_cannot_change_hub_transport(tmp_path, options_
assert all(_request_credential(item) == token for item in captured), [item["headers"] for item in captured]
assert all(item["body"]["model"] == model for item in captured)
assert native_settings.read_text() == native_payload
+
+
+_PROXY_NAMES = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy")
+
+
+class _ProxyTrap(socketserver.ThreadingTCPServer):
+ """A loopback proxy that records each request line and answers 502."""
+
+ allow_reuse_address = True
+ daemon_threads = True
+
+ def __init__(self):
+ self.lines: list[str] = []
+ super().__init__(("127.0.0.1", 0), _ProxyTrapHandler)
+
+ @property
+ def url(self) -> str:
+ return f"http://127.0.0.1:{self.server_address[1]}"
+
+ def __enter__(self):
+ threading.Thread(target=self.serve_forever, daemon=True).start()
+ return self
+
+ def __exit__(self, *exc_info):
+ self.shutdown()
+ self.server_close()
+
+
+class _ProxyTrapHandler(socketserver.StreamRequestHandler):
+ def handle(self):
+ self.server.lines.append(self.rfile.readline(4096).decode("latin-1").strip())
+ while self.rfile.readline(65536) not in (b"\r\n", b"\n", b""):
+ pass
+ self.wfile.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+
+
+async def _hub_turn(binary, runtime, env, catalog_path, gateway, *, exempt):
+ """One Hub turn on the real app-server; returns its terminal status."""
+ launch = ModelHubLaunch(
+ backend="codex", channel="hub", requested_model="proxy-probe", target_model="upstream-alias",
+ runtime_model="proxy-probe", gateway_base_url=gateway.url, gateway_token="isolated-proxy-fixture",
+ )
+ args, launch_env = build_codex_hub_launch([], env, launch, model_catalog_path=catalog_path)
+ if not exempt:
+ # The launch as it was before the gateway joined the exemptions.
+ launch_env = {key: value for key, value in launch_env.items() if key.upper() != "NO_PROXY"}
+ transport = CodexTransport(binary=binary, cwd=str(runtime.home), runtime_args=args, runtime_env=launch_env)
+ completed: asyncio.Queue = asyncio.Queue()
+
+ async def notify(method, params):
+ if method == "turn/completed":
+ await completed.put(params["turn"]["status"])
+
+ transport.on_notification(notify)
+ try:
+ await transport.start()
+ thread = await transport.send_request(
+ "thread/start", {"model": "proxy-probe", "cwd": str(runtime.home), "approvalPolicy": "never", "ephemeral": True},
+ )
+ await transport.send_request(
+ "turn/start", {"threadId": thread["thread"]["id"], "input": [{"type": "text", "text": "Reply with ready."}]},
+ )
+ return await asyncio.wait_for(completed.get(), timeout=60)
+ finally:
+ await transport.stop()
+
+
+def test_mh_codex_launch_002_configured_proxies_cannot_divert_the_loopback_gateway(codex_catalog_runtime):
+ """MH-CODEX-LAUNCH-002: a Hub turn reaches the gateway on this machine despite configured proxies.
+
+ Codex sends loopback requests through any proxy it is given and does not
+ read the macOS proxy exception list. Every proxy variable points at a
+ recording trap and nothing is exempt beforehand, so only the launch's own
+ exemption keeps the gateway request off the trap. The same launch without
+ it is caught by the trap, so the trap is proved to intercept.
+ """
+ binary, runtime, raw_catalog = codex_catalog_runtime
+ Path(runtime.env["CODEX_HOME"], "config.toml").write_text('cli_auth_credentials_store = "file"\n')
+ catalog_path = runtime.home / "proxy-models.json"
+ catalog_path.write_bytes(_codex_hub_catalog_bytes(
+ raw_catalog, [ModelHubBackendModelConfig(id="proxy-probe", context_window=128_000).to_payload()],
+ ))
+ with _ProxyTrap() as trap, MockLLMUpstream() as gateway:
+ gateway.configure(protocol="openai_responses")
+ env = {key: value for key, value in runtime.env.items() if key.upper() != "NO_PROXY"}
+ env.update(dict.fromkeys(_PROXY_NAMES, trap.url))
+
+ status = asyncio.run(_hub_turn(binary, runtime, env, catalog_path, gateway, exempt=True))
+
+ assert status == "completed"
+ assert "/v1/responses" in [item["path"] for item in gateway.requests()]
+ assert trap.lines == []
+
+ gateway.reset_requests()
+ status = asyncio.run(_hub_turn(binary, runtime, env, catalog_path, gateway, exempt=False))
+
+ assert status == "failed"
+ assert gateway.requests() == []
+ assert trap.lines and all(
+ line == f"POST {gateway.url}/v1/responses HTTP/1.1" for line in trap.lines
+ ), trap.lines
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 4ed6a2882..6cbee59bb 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -66,6 +66,7 @@ capabilities:
- tests/test_model_hub_routing_modes.py
- tests/test_model_hub_transport_leases.py
- tests/test_model_hub_injection.py
+ - tests/test_codex_launch_failure.py
- tests/test_model_hub_runtime.py
- tests/test_model_hub_inference_wait.py
- tests/test_model_hub_retry_advice.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index f3bce1e7b..60fd55abd 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -10,6 +10,7 @@ capability:
- tests/test_model_hub_resolution.py
- tests/test_model_hub_background_discovery.py
- tests/test_model_hub_injection.py
+ - tests/test_codex_launch_failure.py
- tests/test_codex_request_routing.py
- tests/test_model_hub_runtime.py
- tests/test_model_hub_inference_wait.py
@@ -514,6 +515,25 @@ scenarios:
kind: injection
layer: e2e
test: tests/e2e/test_model_hub_backend_settings.py::test_codex_native_provider_settings_cannot_change_hub_egress
+ - id: MH-CODEX-LAUNCH-002
+ name: A Codex Hub turn reaches the gateway on this machine when proxies are configured, and every other proxy setting is kept
+ status: covered
+ kind: injection
+ layer: e2e
+ test: tests/e2e/test_model_hub_backend_settings.py::test_mh_codex_launch_002_configured_proxies_cannot_divert_the_loopback_gateway
+ related_tests:
+ - tests/test_model_hub_injection.py::test_codex_hub_launch_bypasses_proxies_only_for_its_loopback_gateway
+ - id: MH-CODEX-LAUNCH-003
+ name: A Codex CLI that cannot start ends the turn with repair guidance and holds its input for an explicit retry; once repaired, the same Session continues
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_codex_launch_failure.py::test_a_codex_cli_that_cannot_start_holds_the_input_for_a_repair
+ related_tests:
+ - tests/test_codex_launch_failure.py::test_recognizes_only_launch_failures_it_has_evidence_for
+ - tests/test_codex_runtime_generations.py::test_a_session_whose_cli_could_not_start_resumes_its_thread_once_repaired
+ - tests/test_session_delivery_fsm.py::test_send_now_no_write_preserves_existing_retry_hold
+ - tests/e2e/test_codex_launch_failures.py::test_incomplete_install_stops_the_catalog_export_with_its_cause
- id: MH-OPENCODE-LAUNCH-001
name: Native OpenCode settings preserve the exact Hub provider transport and authentication
status: covered
diff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.py
index 7174f1931..40f65bdf4 100644
--- a/tests/test_backend_model_catalog.py
+++ b/tests/test_backend_model_catalog.py
@@ -594,7 +594,6 @@ def test_codex_hub_catalog_export_uses_stable_supervisor(monkeypatch):
)
assert captured["timeout_seconds"] == backend_model_catalog.CODEX_HUB_CATALOG_TIMEOUT_SECONDS
assert captured["max_output_bytes"] == backend_model_catalog.CODEX_HUB_CATALOG_MAX_BYTES
- assert captured["discard_stderr"] is True
def test_codex_hub_catalog_export_survives_deleted_service_cwd(monkeypatch, tmp_path):
@@ -639,6 +638,7 @@ def test_codex_hub_catalog_export_survives_deleted_service_cwd(monkeypatch, tmp_
)
def test_codex_hub_catalog_export_rejects_supervised_failures(monkeypatch, result, message):
result.stdout = ""
+ result.stderr = ""
async def run(**_kwargs):
return result
diff --git a/tests/test_codex_launch_failure.py b/tests/test_codex_launch_failure.py
new file mode 100644
index 000000000..d60613f71
--- /dev/null
+++ b/tests/test_codex_launch_failure.py
@@ -0,0 +1,239 @@
+"""MH-CODEX-LAUNCH-003: a Codex CLI that cannot start asks for a repair, not a retry.
+
+The launcher captures are real stderr from the published npm launchers
+(@openai/codex 0.121.0 and 0.162.1) in disposable incomplete installs, with
+only the machine-specific prefix replaced. The Codex captures are the CLI's
+own failures, which keep their ordinary handling. Every process below is real:
+the export runs through the stable supervisor and the app-server through its
+transport, so recognition is proved where Avibe actually observes the failure.
+"""
+
+from __future__ import annotations
+
+import os
+from unittest.mock import AsyncMock
+
+import pytest
+
+from core.native_dispatch_phase import (
+ DISPATCH_PHASE_PREWRITE,
+ prewrite_failure_evidence,
+ set_dispatch_phase,
+)
+from modules.agents.codex.transport import CodexTransport
+from tests.test_codex_runtime_generations import _Router, _agent, _launch, _request
+from vibe import backend_model_catalog
+from vibe.codex_launch_failure import (
+ CLI_NOT_FOUND,
+ INSTALL_INCOMPLETE,
+ PERMISSION_DENIED,
+ CodexLaunchError,
+ launch_failure_from_stderr,
+)
+from vibe.i18n import t as i18n_t
+
+pytestmark = pytest.mark.skipif(os.name == "nt", reason="POSIX launcher fixtures")
+
+PREFIX = "/opt/codex-fixture/lib/node_modules/@openai/codex"
+NATIVE_0_121 = f"{PREFIX}/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/codex/codex"
+NATIVE_0_162 = f"{PREFIX}/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex"
+
+
+def _node_spawn_failure(native: str, code: str, errno: int) -> str:
+ return f"""\
+Error: spawn {native} {code}
+ at ChildProcess._handle.onexit (node:internal/child_process:285:19)
+ at onErrorNT (node:internal/child_process:483:16)
+ at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {{
+ errno: -{errno},
+ code: '{code}',
+ syscall: 'spawn {native}',
+ path: '{native}',
+ spawnargs: [ 'debug', 'models', '--bundled', '-c', 'model_catalog_json=null' ]
+}}
+"""
+
+
+# 0.121.0, platform package present, native executable missing.
+NATIVE_MISSING_0_121 = _node_spawn_failure(NATIVE_0_121, "ENOENT", 2)
+# 0.162.1, native executable present but not executable.
+NATIVE_NOT_EXECUTABLE_0_162 = _node_spawn_failure(NATIVE_0_162, "EACCES", 13)
+# 0.121.0, platform package missing.
+PLATFORM_MISSING_0_121 = f"""\
+file://{PREFIX}/bin/codex.js:100
+ throw new Error(
+ ^
+
+Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest
+ at file://{PREFIX}/bin/codex.js:100:11
+ at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
+ at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:647:26)
+ at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)
+
+Node.js v22.18.0
+"""
+# 0.162.1, platform package or its native executable missing.
+NATIVE_MISSING_0_162 = f"""\
+file://{PREFIX}/bin/codex.js:107
+ throw new Error(
+ ^
+
+Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest
+ at findCodexExecutable (file://{PREFIX}/bin/codex.js:107:9)
+ at file://{PREFIX}/bin/codex.js:112:20
+ at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
+ at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:647:26)
+ at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)
+
+Node.js v22.18.0
+"""
+# Codex 0.162.1's own failures: a missing catalog file, and a usage error.
+CODEX_MISSING_FILE = "Error: No such file or directory (os error 2)\n"
+CODEX_USAGE = """\
+error: unexpected argument '--unknown-flag' found
+
+Usage: codex debug models --bundled
+
+For more information, try '--help'.
+"""
+# The launcher's interpreter is not on PATH (exit 127).
+NODE_MISSING = "env: node: No such file or directory\n"
+
+# Stands for anything a process prints: it must never leave recognition.
+SENTINEL = "printed-only-to-stderr-5c1e"
+
+
+ ("stderr", "cause"),
+ [
+ (NATIVE_MISSING_0_121, INSTALL_INCOMPLETE),
+ (PLATFORM_MISSING_0_121, INSTALL_INCOMPLETE),
+ (NATIVE_MISSING_0_162, INSTALL_INCOMPLETE),
+ (NATIVE_MISSING_0_162.replace("\n", "\r\n"), INSTALL_INCOMPLETE),
+ (NATIVE_NOT_EXECUTABLE_0_162, PERMISSION_DENIED),
+ (CODEX_MISSING_FILE, None),
+ (CODEX_USAGE, None),
+ (NODE_MISSING, None),
+ ("Error: ENOENT: no such file or directory, open '/opt/codex-fixture/config.toml'\n", None),
+ ("", None),
+ ],
+)
+def test_recognizes_only_launch_failures_it_has_evidence_for(stderr, cause):
+ """MH-CODEX-LAUNCH-003: only the launcher's own reports name a repair cause."""
+
+ assert launch_failure_from_stderr(stderr) == cause
+
+
+def _replaying_cli(tmp_path, stderr: str, *, code: int = 1) -> str:
+ """An executable that fails the way a captured launch did."""
+
+ script = tmp_path / "codex"
+ script.write_text(f"#!/bin/sh\ncat >&2 <<'CAPTURE'\n{stderr}{SENTINEL}\nCAPTURE\nexit {code}\n")
+ script.chmod(0o755)
+ return str(script)
+
+
+def _missing_cli(tmp_path) -> str:
+ return str(tmp_path / "absent" / "codex")
+
+
+def _unexecutable_cli(tmp_path) -> str:
+ script = tmp_path / "codex"
+ script.write_text("#!/bin/sh\nexit 0\n")
+ script.chmod(0o644)
+ return str(script)
+
+
+UNRUNNABLE = [
+ pytest.param(lambda path: _replaying_cli(path, NATIVE_MISSING_0_162), INSTALL_INCOMPLETE, id="platform-missing"),
+ pytest.param(lambda path: _replaying_cli(path, NATIVE_MISSING_0_121), INSTALL_INCOMPLETE, id="native-missing"),
+ pytest.param(
+ lambda path: _replaying_cli(path, NATIVE_NOT_EXECUTABLE_0_162), PERMISSION_DENIED, id="native-not-executable",
+ ),
+ pytest.param(_missing_cli, CLI_NOT_FOUND, id="cli-missing"),
+ pytest.param(_unexecutable_cli, PERMISSION_DENIED, id="cli-not-executable"),
+]
+ORDINARY = [
+ pytest.param(CODEX_MISSING_FILE, 1, id="codex-error"),
+ pytest.param(CODEX_USAGE, 2, id="codex-usage"),
+ pytest.param(NODE_MISSING, 127, id="node-missing"),
+]
+
+
[email protected](("make_cli", "cause"), UNRUNNABLE)
+def test_catalog_export_reports_why_codex_cannot_start(tmp_path, make_cli, cause):
+ """MH-CODEX-LAUNCH-003: the supervised export names the cause, never the output."""
+
+ with pytest.raises(CodexLaunchError) as raised:
+ backend_model_catalog._export_codex_bundled_catalog(make_cli(tmp_path))
+
+ assert raised.value.cause == cause
+ assert SENTINEL not in repr(raised.value) and str(tmp_path) not in str(raised.value)
+ assert raised.value.__cause__ is None and raised.value.__context__ is None
+
+
[email protected](("stderr", "code"), ORDINARY)
+def test_catalog_export_keeps_other_failures_retryable(tmp_path, stderr, code):
+ with pytest.raises(RuntimeError, match="could not export its bundled model catalog") as raised:
+ backend_model_catalog._export_codex_bundled_catalog(_replaying_cli(tmp_path, stderr, code=code))
+
+ assert not isinstance(raised.value, CodexLaunchError)
+ assert SENTINEL not in repr(raised.value)
+
+
[email protected](("make_cli", "cause"), UNRUNNABLE)
+async def test_app_server_start_reports_why_codex_cannot_start(tmp_path, make_cli, cause):
+ """MH-CODEX-LAUNCH-003: an app-server that cannot start names its cause."""
+
+ transport = CodexTransport(binary=make_cli(tmp_path), cwd=str(tmp_path / "work"))
+
+ with pytest.raises(CodexLaunchError) as raised:
+ await transport.start()
+
+ assert raised.value.cause == cause
+ assert SENTINEL not in str(raised.value)
+ assert not transport.is_alive
+
+
[email protected](("stderr", "code"), ORDINARY)
+async def test_app_server_start_keeps_other_failures(tmp_path, stderr, code):
+ transport = CodexTransport(binary=_replaying_cli(tmp_path, stderr, code=code), cwd=str(tmp_path / "work"))
+
+ with pytest.raises(ConnectionError):
+ await transport.start()
+
+
[email protected]("channel", ["hub", "direct"])
[email protected](("make_cli", "cause"), UNRUNNABLE)
+async def test_a_codex_cli_that_cannot_start_holds_the_input_for_a_repair(tmp_path, channel, make_cli, cause):
+ """MH-CODEX-LAUNCH-003: the turn asks for a repair and keeps its input for an explicit retry.
+
+ A Hub turn fails while exporting the catalog; a direct turn while starting
+ the app-server. Neither may tell the user to just retry, start a Hub
+ cooldown, or leave a generation behind for the next turn.
+ """
+
+ router = _Router()
+ router.launches["model-a"] = _launch("model-a", channel, token="hub-token")
+ agent, cwd = _agent(tmp_path, router=router)
+ agent.codex_config.binary = make_cli(tmp_path)
+ agent.controller.emit_agent_message = AsyncMock(return_value="notice-1")
+ request = _request(cwd, "s1")
+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)
+
+ await agent.handle_message(request)
+
+ assert prewrite_failure_evidence(request.context) == {
+ "reason": f"codex_cli_{cause}",
+ "requires_explicit_retry": True,
+ }
+ notify = agent.controller.emit_agent_message.await_args_list[0]
+ assert notify.args[1:3] == ("notify", f"❌ {i18n_t(CodexLaunchError(cause).copy_key, 'en')}")
+ result = agent.controller.emit_agent_message.await_args_list[-1]
+ assert result.args[1] == "result" and result.kwargs["is_error"] is True
+ assert SENTINEL not in repr(agent.controller.emit_agent_message.await_args_list)
+ agent._record_model_hub_native_failure.assert_not_awaited()
+ assert agent._units[cwd].current is None
diff --git a/tests/test_codex_runtime_generations.py b/tests/test_codex_runtime_generations.py
index 06ac7d03e..49ecfb82e 100644
--- a/tests/test_codex_runtime_generations.py
+++ b/tests/test_codex_runtime_generations.py
@@ -14,7 +14,7 @@ from unittest.mock import AsyncMock, Mock
import pytest
import modules.agents.codex.agent as codex_agent_module
-from core.native_dispatch_phase import DISPATCH_PHASE_PREWRITE, set_dispatch_phase
+from core.native_dispatch_phase import DISPATCH_PHASE_PREWRITE, prewrite_failure_evidence, set_dispatch_phase
from core.handlers.model_hub.provenance import BoundedProvenanceStore, TurnCorrelationRegistry
from core.runtime_activation import RuntimeActivationRegistry
from core.session_activities import SessionActivityRegistry
@@ -27,6 +27,7 @@ from modules.agents.model_hub import ModelHubLaunch
from modules.agents.runtime_generations import RuntimeUnitStopping
from modules.agents.service import AgentService
from tests.codex_generation_support import init_generation_state
+from vibe.codex_launch_failure import INSTALL_INCOMPLETE, CodexLaunchError
from vibe.i18n import t as i18n_t
@@ -1097,6 +1098,52 @@ async def test_runtime_gen_016_hub_scope_is_revoked_only_with_the_last_hub_gener
assert router.retired == [router.scopes[0]]
+async def test_a_session_whose_cli_could_not_start_resumes_its_thread_once_repaired(tmp_path):
+ """MH-CODEX-LAUNCH-003: a repaired CLI continues the same Session and Codex thread.
+
+ The process that ran the Session's thread has exited, and the next start
+ finds the CLI broken. That input waits for an explicit retry and the Session
+ keeps its thread binding; after the repair, the retried input resumes the
+ same thread on a new process instead of opening a new conversation.
+ """
+ agent, cwd = _agent(tmp_path)
+ agent.controller.emit_agent_message = AsyncMock(return_value="notice-1")
+ await agent.handle_message(_request(cwd, "s1"))
+ first = _server_for(agent, "s1")
+ thread_id = agent._session_mgr.get_thread_id("s1")
+ await first.complete(thread_id)
+ first.close_reader()
+ first.exit()
+
+ async def broken_cli(server):
+ server._process.exit(1)
+ raise CodexLaunchError(INSTALL_INCOMPLETE)
+
+ FakeAppServer.on_start = broken_cli
+ held = _request(cwd, "s1")
+ set_dispatch_phase(held.context, DISPATCH_PHASE_PREWRITE)
+ await asyncio.wait_for(agent.handle_message(held), 1)
+
+ assert prewrite_failure_evidence(held.context) == {
+ "reason": "codex_cli_install_incomplete",
+ "requires_explicit_retry": True,
+ }
+ assert agent._turn_registry.get_active_turn("s1") is None
+ agent.sessions.clear_agent_session_mapping.assert_not_called()
+
+ FakeAppServer.on_start = None
+ retried = _request(cwd, "s1")
+ await asyncio.wait_for(agent.handle_message(retried), 1)
+
+ repaired = _server_for(agent, "s1")
+ assert repaired not in FakeAppServer.started[:2] and repaired.alive
+ opened = [(method, params.get("threadId")) for method, params in repaired.requests if method.startswith("thread/")]
+ assert opened == [("thread/resume", thread_id)]
+ assert agent._session_mgr.get_thread_id("s1") == thread_id
+ assert agent._turn_registry.get_active_turn("s1")
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("cancelled_on", ["first-attempt", "retry"])
async def test_runtime_gen_010_a_cancelled_admission_never_pins_its_generation(tmp_path, fake_app_servers, cancelled_on):
diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.py
index 7d8853a86..7be06246e 100644
--- a/tests/test_model_hub_injection.py
+++ b/tests/test_model_hub_injection.py
@@ -356,7 +356,54 @@ def test_codex_hub_launch_uses_responses_wire_api_and_ephemeral_token(tmp_path):
assert "model_providers.avibe_model_hub.request_max_retries=0" in args
assert "features.unbounded_connection_retries=false" in args
assert not any("stream_max_retries" in arg for arg in args)
- assert env == {"AVIBE_MODEL_HUB_TOKEN": "local-test-token"}
+ assert env == {"AVIBE_MODEL_HUB_TOKEN": "local-test-token", "NO_PROXY": "127.0.0.1"}
+
+
+PROXY = {"HTTPS_PROXY": "http://proxy.example:8080", "http_proxy": "http://proxy.example:8080"}
+
+
+ ("gateway", "inherited", "expected"),
+ [
+ # Neither spelling present: one new list naming only the gateway host.
+ ("http://127.0.0.1:15220", {}, {"NO_PROXY": "127.0.0.1"}),
+ ("http://[::1]:15220", {}, {"NO_PROXY": "::1"}),
+ ("http://localhost:15220", {}, {"NO_PROXY": "localhost"}),
+ # Each spelling present is extended on its own; none is added or dropped.
+ (
+ "http://127.0.0.1:15220",
+ {"no_proxy": "corp.example, .internal"},
+ {"no_proxy": "corp.example,.internal,127.0.0.1"},
+ ),
+ (
+ "http://127.0.0.1:15220",
+ {"NO_PROXY": "corp.example", "no_proxy": "10.0.0.0/8"},
+ {"NO_PROXY": "corp.example,127.0.0.1", "no_proxy": "10.0.0.0/8,127.0.0.1"},
+ ),
+ # Present but empty still wins for Codex over the other spelling.
+ (
+ "http://127.0.0.1:15220",
+ {"NO_PROXY": "", "no_proxy": "corp.example"},
+ {"NO_PROXY": "127.0.0.1", "no_proxy": "corp.example,127.0.0.1"},
+ ),
+ # Already exempt, or everything is: left exactly as it was.
+ ("http://127.0.0.1:15220", {"NO_PROXY": "*"}, {"NO_PROXY": "*"}),
+ ("http://LOCALHOST:15220", {"no_proxy": "LocalHost"}, {"no_proxy": "LocalHost"}),
+ # A gateway elsewhere keeps the proxy that reaches it.
+ ("http://10.0.0.5:15220", {}, {}),
+ ("https://gateway.example", {"NO_PROXY": "corp.example"}, {"NO_PROXY": "corp.example"}),
+ ],
+)
+def test_codex_hub_launch_bypasses_proxies_only_for_its_loopback_gateway(tmp_path, gateway, inherited, expected):
+ """MH-CODEX-LAUNCH-002: only the loopback gateway joins the child's proxy exemptions."""
+
+ launch = hub_launch(backend="codex", gateway_base_url=gateway)
+ base_env = {**PROXY, **inherited, "PATH": "/bin"}
+
+ _args, env = build_codex_hub_launch([], base_env, launch, model_catalog_path=tmp_path / "models.json")
+
+ assert env == {**PROXY, **expected, "PATH": "/bin", "AVIBE_MODEL_HUB_TOKEN": "local-test-token"}
+ assert base_env == {**PROXY, **inherited, "PATH": "/bin"}
def test_codex_hub_launch_requires_provider_safe_catalog():
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 21910e399..d7a29c52c 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -31,6 +31,7 @@ from modules.agents.opencode.message_processor import (
extract_opencode_response_text,
is_empty_terminal_opencode_message,
)
+from vibe.codex_launch_failure import CLI_NOT_FOUND, INSTALL_INCOMPLETE, CodexLaunchError
from vibe.claude_config import (
MANAGED_ENV_VALUES,
clear_claude_oauth_credentials_files,
@@ -1490,17 +1491,26 @@ def test_test_web_auth_rejects_unsupported_backend(service: AgentAuthService) ->
assert _run(service.test_web_auth("gemini")) == {"ok": False, "error": "unsupported_backend"}
-def test_test_web_auth_surfaces_cli_not_found(
- service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+ ("failure", "error", "detail"),
+ [
+ (FileNotFoundError("no such cli"), "cli_not_found", "/usr/bin/echo"),
+ # What the app-server transport raises when the CLI cannot start.
+ (CodexLaunchError(CLI_NOT_FOUND), "cli_not_found", "/usr/bin/echo"),
+ (CodexLaunchError(INSTALL_INCOMPLETE), "spawn_failed", "Codex CLI installation is incomplete"),
+ ],
+)
+def test_test_web_auth_surfaces_a_cli_that_cannot_start(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch, failure, error, detail
) -> None:
monkeypatch.setattr(
service,
"_run_codex_agent_probe",
- AsyncMock(side_effect=FileNotFoundError("no such cli")),
+ AsyncMock(side_effect=failure),
)
result = _run(service.test_web_auth("codex"))
assert result["ok"] is False
- assert result["error"] == "cli_not_found"
+ assert (result["error"], result["detail"]) == (error, detail)
def test_claude_probe_timeout_bounds_disconnect_and_reaps_process(
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
index 378fb8dae..e680dcbdf 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -27,6 +27,7 @@ from vibe.claude_model_catalog import (
load_catalog_models,
)
from vibe.codex_config import get_codex_home
+from vibe.codex_launch_failure import CodexLaunchError, launch_failure_from_stderr
if TYPE_CHECKING:
from storage.lock import MigrationFileLock
@@ -507,7 +508,6 @@ def _export_codex_bundled_catalog(
max_output_bytes=CODEX_HUB_CATALOG_MAX_BYTES,
extra_env=env,
remove_env=removed_env,
- discard_stderr=True,
)
)
if result.timed_out:
@@ -515,6 +515,11 @@ def _export_codex_bundled_catalog(
if result.stdout_truncated:
raise RuntimeError("Codex bundled model catalog exceeded the safety limit")
if result.exit_code != 0:
+ # Stderr is read only to recognize a CLI that cannot start; it never
+ # reaches an error message, a log, or the user.
+ cause = launch_failure_from_stderr(result.stderr)
+ if cause is not None:
+ raise CodexLaunchError(cause)
raise RuntimeError("Codex could not export its bundled model catalog")
return result.stdout.encode()
diff --git a/vibe/codex_launch_failure.py b/vibe/codex_launch_failure.py
new file mode 100644
index 000000000..73ffb2af6
--- /dev/null
+++ b/vibe/codex_launch_failure.py
@@ -0,0 +1,90 @@
+"""Why the configured Codex CLI cannot start: a closed set of repair causes.
+
+Avibe starts the configured Codex executable for the Model Hub catalog export
+and for every app-server. When that executable cannot run, each later turn
+fails the same way, so the turn needs a repair, not a retry. Recognition reads
+only what the failed launch produced: the operating system's error for the
+exec, or the published npm launcher's report that its platform package or
+native executable is missing or not executable. Callers receive a cause, never
+the process output. Anything else stays unrecognized and keeps its own handling.
+"""
+
+from __future__ import annotations
+
+import errno
+import re
+
+from core.watch_worker import decode_watch_worker_spawn_errno
+
+CLI_NOT_FOUND = "cli_not_found"
+INSTALL_INCOMPLETE = "install_incomplete"
+PERMISSION_DENIED = "permission_denied"
+
+_COPY_KEYS = {
+ CLI_NOT_FOUND: "error.codexCliNotFound",
+ INSTALL_INCOMPLETE: "error.codexCliInstallIncomplete",
+ PERMISSION_DENIED: "error.codexCliPermissionDenied",
+}
+_DIAGNOSTICS = {
+ CLI_NOT_FOUND: "Codex CLI executable was not found",
+ INSTALL_INCOMPLETE: "Codex CLI installation is incomplete",
+ PERMISSION_DENIED: "Codex CLI is not permitted to run",
+}
+
+# The npm launcher's own report that its platform package, or in newer
+# launchers its native executable, is missing (seen from 0.121.0 to 0.162.1).
+_MISSING_PLATFORM_PACKAGE = re.compile(
+ r"^Error: Missing optional dependency @openai/codex-\S+", re.MULTILINE
+)
+# Node's report when an older launcher spawns a native executable that is
+# missing, or any launcher one that is not executable.
+_NATIVE_SPAWN_FAILURE = re.compile(
+ r"^Error: spawn .+ (?P<code>ENOENT|EACCES)$", re.MULTILINE
+)
+
+
+class CodexLaunchError(RuntimeError):
+ """The configured Codex CLI cannot start until it is repaired."""
+
+ def __init__(self, cause: str) -> None:
+ if cause not in _COPY_KEYS:
+ raise ValueError(f"Unknown Codex launch failure: {cause}")
+ self.cause = cause
+ super().__init__(_DIAGNOSTICS[cause])
+
+ @property
+ def copy_key(self) -> str:
+ """The localized repair instruction for this cause."""
+
+ return _COPY_KEYS[self.cause]
+
+ @property
+ def retry_reason(self) -> str:
+ """The durable reason an unwritten input waits for an explicit retry."""
+
+ return f"codex_cli_{self.cause}"
+
+
+def launch_failure_from_errno(code: int | None) -> str | None:
+ """The cause of an exec the operating system refused, by error number."""
+
+ if code == errno.ENOENT:
+ return CLI_NOT_FOUND
+ if code == errno.EACCES:
+ return PERMISSION_DENIED
+ return None
+
+
+def launch_failure_from_stderr(stderr: str) -> str | None:
+ """The cause a failed launch reported on stderr; the text is not retained."""
+
+ spawn_errno = decode_watch_worker_spawn_errno(stderr)
+ if spawn_errno is not None:
+ return launch_failure_from_errno(spawn_errno)
+ text = stderr.replace("\r\n", "\n")
+ if _MISSING_PLATFORM_PACKAGE.search(text):
+ return INSTALL_INCOMPLETE
+ spawn = _NATIVE_SPAWN_FAILURE.search(text)
+ if spawn is None:
+ return None
+ return INSTALL_INCOMPLETE if spawn.group("code") == "ENOENT" else PERMISSION_DENIED
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index fa3e923a2..80913b38b 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -441,6 +441,9 @@
"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.",
"codexForkBoundaryUnavailable": "Codex could not determine a safe history boundary for this fork. Wait for the source turn to finish, then retry. If the problem persists, check or update Codex.",
"codexThreadReleaseUnavailable": "Codex could not move this conversation off the app-server it last ran on, because that process is still holding it. Retry this input once the work still running there finishes.",
+ "codexCliInstallIncomplete": "Codex could not start because its installation is incomplete: part of the Codex CLI is missing. Retrying alone will not fix this. Reinstall Codex, then retry this input.",
+ "codexCliPermissionDenied": "Codex could not start because the system did not allow the Codex CLI to run. Retrying alone will not fix this. Make the Codex CLI executable or reinstall Codex, then retry this input.",
+ "codexCliNotFound": "Codex could not start because its CLI was not found. Install Codex or set its CLI path on the Backends page in Settings, then retry this input.",
"agentRuntimeRetired": "{agent} was turned off, or Avibe is stopping, so this message was not started. Send it again once {agent} is enabled.",
"codexResponseTooLarge": "Codex returned a response larger than {limitMiB} MiB, so this connection cannot continue. Check or update Codex before retrying.",
"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.json
index ac285de05..1ddf358a7 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -441,6 +441,9 @@
"codexPromptRefreshUnavailable": "Codex 无法确认能否安全刷新此现有会话的 Avibe 指令。请检查或升级 Codex 后重试本回合。",
"codexForkBoundaryUnavailable": "Codex 无法确定此次分叉的安全历史边界。请等待源会话当前回合结束后重试;如果问题持续,请检查或升级 Codex。",
"codexThreadReleaseUnavailable": "Codex 无法把这个会话从它上次运行的 app-server 进程上移走,因为该进程仍占用着它。请等那里仍在运行的工作结束后重试这条输入。",
+ "codexCliInstallIncomplete": "Codex 安装不完整,缺少 Codex CLI 的部分文件,因此无法启动。仅重试无法解决。请重新安装 Codex,然后重试这条输入。",
+ "codexCliPermissionDenied": "系统不允许运行 Codex CLI,因此 Codex 无法启动。仅重试无法解决。请让 Codex CLI 可以执行,或重新安装 Codex,然后重试这条输入。",
+ "codexCliNotFound": "找不到 Codex CLI,因此 Codex 无法启动。请在设置的“后端”页面安装 Codex 或设置其 CLI 路径,然后重试这条输入。",
"agentRuntimeRetired": "{agent} 已关闭或 Avibe 正在停止,这条消息没有开始执行。请在 {agent} 启用后重新发送。",
"codexResponseTooLarge": "Codex 返回的响应超过 {limitMiB} MiB,此连接无法继续。请检查或升级 Codex 后重试。",
"opencodeRuntimeConfigInvalid": "OpenCode 无法启动,因为 OPENCODE_CONFIG_CONTENT 无效。请修正运行时配置后重试。",