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): refresh caller env for reused shells (#725)
Call White516008b27aa6
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 8b84d3f02..5336d5201 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -5,10 +5,12 @@ from __future__ import annotationsimport asyncioimport loggingimport os+import shleximport timefrom pathlib import Pathfrom typing import Any, Dict, Optional+from config import pathsfrom config.v2_config import (DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS,DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,@@ -32,6 +34,7 @@ from vibe.codex_config import LEGACY_MANAGED_PROVIDER_IDS, MANAGED_PROVIDER_IDlogger = logging.getLogger(__name__)_CODEX_MANAGED_PROVIDER_IDS = frozenset((MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS))+CODEX_CALLER_ENV_DIR = "codex-caller-env"class CodexResumeUnavailableError(RuntimeError):@@ -732,10 +735,39 @@ class CodexAgent(BaseAgent):context = getattr(request, "context", None)return caller_env_for_platform_payload(getattr(context, "platform_specific", None))+ def _caller_env_script_path(self, request: AgentRequest) -> Path:+ caller_env = self._caller_env_for_request(request)+ session_key = (+ str(getattr(request, "base_session_id", "") or "").strip()+ or caller_env.get("AVIBE_SESSION_ID")+ or "session"+ )+ safe_session_id = "".join(+ ch if ch.isalnum() or ch in ("-", "_", ".") else "_"+ for ch in session_key+ )+ return paths.get_runtime_dir() / CODEX_CALLER_ENV_DIR / f"{safe_session_id}.sh"++ def _write_caller_env_script(self, request: AgentRequest) -> Path | None:+ env = self._caller_env_for_request(request)+ if not env:+ return None+ script_path = self._caller_env_script_path(request)+ script_path.parent.mkdir(parents=True, exist_ok=True)+ lines = ["# Generated by Avibe. Sourced by Codex shell commands.\n"]+ for key, value in sorted(env.items()):+ lines.append(f"export {key}={shlex.quote(value)}\n")+ tmp_path = script_path.with_suffix(script_path.suffix + ".tmp")+ tmp_path.write_text("".join(lines), encoding="utf-8")+ tmp_path.replace(script_path)+ return script_path+def _inject_caller_env_config(self, params: Dict[str, Any], request: AgentRequest) -> None:env = self._caller_env_for_request(request)if not env:return+ env_script_path = self._caller_env_script_path(request)+ env = {**env, "BASH_ENV": str(env_script_path)}config = dict(params.get("config") or {})shell_policy = dict(config.get("shell_environment_policy") or {})set_env = dict(shell_policy.get("set") or {})@@ -1265,6 +1297,7 @@ class CodexAgent(BaseAgent):if effective_effort:turn_params["effort"] = effective_effort+ self._write_caller_env_script(request)self._turn_registry.begin_turn_start(request, thread_id)event_handler = getattr(self, "_event_handler", None)snapshot_generated_images = getattr(diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex fd3f8fca8..68fd0dbf4 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -2,6 +2,7 @@ import asyncioimport importlib.utilimport osimport sys+import tempfileimport typesimport unittestfrom pathlib import Path@@ -1110,6 +1111,38 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(set_env["AVIBE_CALLER_SOURCE"], "agent_run")self.assertEqual(set_env["AVIBE_CALLER_BACKEND"], "codex")self.assertEqual(set_env["AVIBE_NATIVE_SESSION_ID"], "thread-parent")+ self.assertTrue(set_env["BASH_ENV"].endswith("/codex-caller-env/ses-parent.sh"))++ def test_write_caller_env_script_refreshes_reused_thread_run_id(self):+ agent = object.__new__(CodexAgent)+ request = SimpleNamespace(+ base_session_id="session-1",+ context=SimpleNamespace(+ platform_specific={+ "task_execution_id": "run-one",+ "task_trigger_kind": "agent_run",+ "agent_session_target": {+ "id": "ses-parent",+ "agent_backend": "codex",+ "native_session_id": "thread-parent",+ },+ },+ ),+ )++ with tempfile.TemporaryDirectory() as tmpdir:+ with patch("config.paths.get_runtime_dir", return_value=Path(tmpdir)):+ script_path = agent._write_caller_env_script(request)+ self.assertIsNotNone(script_path)+ first = script_path.read_text()+ request.context.platform_specific["task_execution_id"] = "run-two"+ second_path = agent._write_caller_env_script(request)+ second = second_path.read_text()++ self.assertIn("export AVIBE_RUN_ID=run-one", first)+ self.assertIn("export AVIBE_SESSION_ID=ses-parent", first)+ self.assertIn("export AVIBE_RUN_ID=run-two", second)+ self.assertNotIn("export AVIBE_RUN_ID=run-one", second)async def test_start_thread_requests_danger_full_access(self):agent = object.__new__(CodexAgent)@@ -2619,6 +2652,53 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):)agent.controller.get_codex_overrides.assert_not_called()+ async def test_start_turn_writes_current_caller_env_script_for_reused_threads(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ context=SimpleNamespace(+ platform="slack",+ platform_specific={+ "task_execution_id": "run-two",+ "task_trigger_kind": "agent_run",+ "agent_session_target": {+ "id": "sesk8m4q2p7x",+ "agent_backend": "codex",+ "native_session_id": "thread-existing",+ },+ },+ ),+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ )+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-2"}}))++ with tempfile.TemporaryDirectory() as tmpdir:+ with patch("config.paths.get_runtime_dir", return_value=Path(tmpdir)):+ await agent._start_turn(transport, request, "thread-existing")+ env_script = Path(tmpdir) / "codex-caller-env" / "session-1.sh"+ script_text = env_script.read_text()++ params = transport.send_request.await_args.args[1]+ self.assertNotIn("config", params)+ self.assertIn("export AVIBE_SESSION_ID=sesk8m4q2p7x", script_text)+ self.assertIn("export AVIBE_RUN_ID=run-two", script_text)+ self.assertIn("export AVIBE_CALLER_SOURCE=agent_run", script_text)+ self.assertIn("export AVIBE_CALLER_BACKEND=codex", script_text)+ self.assertIn("export AVIBE_NATIVE_SESSION_ID=thread-existing", script_text)+async def test_start_turn_uses_controller_codex_overrides(self):agent = object.__new__(CodexAgent)agent.settings_manager = SimpleNamespace(