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
feat(codex): refactor to persistent app-server mode with JSON-RPC 2.0
cyh87b609508250
diff --git a/docs/plans/codex-app-server-refactor.md b/docs/plans/codex-app-server-refactor.mdnew file mode 100644index 000000000..b590fcb9d--- /dev/null+++ b/docs/plans/codex-app-server-refactor.md@@ -0,0 +1,282 @@+# Codex App-Server Refactor Plan++## Background++The current Codex agent (`modules/agents/codex_agent.py`) launches a **new subprocess per message** via `codex exec --json`. When a new message arrives while one is in-flight, the old process group is SIGKILLed and a fresh process is started. This means:++- **No true message insertion**: cannot send a follow-up message into an active session+- **No graceful interruption**: SIGKILL loses all context+- **Session resume is fragile**: `codex exec resume <id>` starts a new process each time++Codex CLI v0.77+ provides an `app-server` mode — a persistent subprocess communicating via **JSON-RPC 2.0 over stdio**. This is the same pattern used by the Claude agent (persistent subprocess + stdin/stdout) but with a standardized JSON-RPC protocol.++## Goal++Replace the one-shot `codex exec` subprocess model with a persistent `codex app-server` process, enabling:++1. **True message insertion** — send `turn/start` into an active thread without killing the process+2. **Graceful interruption** — `turn/interrupt` instead of SIGKILL+3. **Session context preservation** — one persistent process per working directory, threads managed by Codex internally+4. **Streaming events** — real-time `item/agentMessage/delta`, `item/commandExecution/outputDelta` notifications++## Protocol Summary (JSON-RPC 2.0 over stdio)++### Lifecycle+1. Launch: `codex app-server` (persistent, reads JSON-RPC from stdin, writes to stdout)+2. Client sends `initialize` request with `clientInfo`+3. Server responds with capabilities+4. Client sends `initialized` notification+5. Client sends `thread/start` to create a new thread (returns `threadId`)+6. Client sends `turn/start` with `threadId` + `input` to begin a turn+7. Server streams notifications: `turn/started`, `item/started`, `item/agentMessage/delta`, `item/completed`, `turn/completed`+8. Server may send `item/commandExecution/requestApproval` or `item/fileChange/requestApproval` — client must respond with approval+9. For follow-up messages: send another `turn/start` on the same `threadId`+10. For interruption: send `turn/interrupt` with `threadId` + `turnId`+11. For session resume across process restarts: `thread/resume` with `threadId`++### Key Types++**UserInput** (for `turn/start` input array):+- `{"type": "text", "text": "..."}` — text message+- `{"type": "image", "url": "..."}` — image URL+- `{"type": "localImage", "path": "..."}` — local image file++**ThreadStartParams**: `{approvalPolicy?, cwd?, model?, sandbox?, baseInstructions?, config?}`+**TurnStartParams**: `{threadId, input[], model?, effort?, approvalPolicy?, cwd?, sandboxPolicy?}`+**TurnInterruptParams**: `{threadId, turnId}`++**Server Notifications** (key ones):+- `thread/started` → `{threadId}`+- `turn/started` → `{threadId, turnId}`+- `turn/completed` → `{threadId, turnId, ...}`+- `item/started` → `{threadId, turnId, itemId, itemType}`+- `item/completed` → `{threadId, turnId, item: {type, ...}}`+- `item/agentMessage/delta` → `{threadId, turnId, itemId, delta}` (streaming text)+- `item/commandExecution/outputDelta` → `{threadId, turnId, itemId, delta}`+- `item/reasoning/summaryTextDelta` → `{threadId, turnId, itemId, delta}`+- `error` → `{threadId, turnId, error, willRetry}`++**Server Requests** (need client response):+- `item/commandExecution/requestApproval` → `{threadId, turnId, itemId}` — auto-approve+- `item/fileChange/requestApproval` → `{threadId, turnId, itemId}` — auto-approve++## Architecture++### New Files++```+modules/agents/codex/+ __init__.py # re-exports CodexAgent+ transport.py # CodexTransport: process lifecycle + JSON-RPC I/O+ session.py # Thread/turn state management per Slack thread+ event_handler.py # Maps server notifications → Slack messages+ agent.py # CodexAgent: orchestrates transport + session + events+```++### Existing File Changes+- `modules/agents/codex_agent.py` — delete (replaced by `codex/agent.py`)+- `modules/agents/registry.py` — update import path+- `config/v2_compat.py` — no changes needed (binary path still used)++### Class Design++#### CodexTransport (`transport.py`)++Manages the persistent `codex app-server` subprocess.++```python+class CodexTransport:+ """Manages a persistent codex app-server subprocess with JSON-RPC 2.0 communication."""++ def __init__(self, binary: str, cwd: str, extra_args: list[str]):+ self._binary = binary+ self._cwd = cwd+ self._extra_args = extra_args+ self._process: Optional[Process] = None+ self._request_id: int = 0+ self._pending: dict[int, asyncio.Future] = {} # id → Future for RPC responses+ self._write_lock = asyncio.Lock()+ self._initialized = False++ async def start(self) -> None:+ """Launch app-server, perform initialize handshake."""++ async def stop(self) -> None:+ """Graceful shutdown: close stdin, wait, then SIGTERM/SIGKILL."""++ async def send_request(self, method: str, params: dict) -> dict:+ """Send JSON-RPC request and await response."""++ async def send_notification(self, method: str, params: dict | None = None) -> None:+ """Send JSON-RPC notification (no response expected)."""++ async def _reader_loop(self) -> None:+ """Read stdout line-by-line, dispatch responses and notifications."""++ def on_notification(self, callback: Callable[[str, dict], Awaitable[None]]) -> None:+ """Register notification handler."""++ def on_server_request(self, callback: Callable[[int, str, dict], Awaitable[dict]]) -> None:+ """Register server request handler (for approval requests)."""++ @property+ def is_alive(self) -> bool: ...+```++#### CodexSessionManager (`session.py`)++Maps Slack thread → Codex thread/turn IDs.++```python+class CodexSessionManager:+ """Maps vibe-remote session keys to Codex thread/turn state."""++ def __init__(self):+ self._threads: dict[str, str] = {} # base_session_id → threadId+ self._active_turns: dict[str, str] = {} # base_session_id → turnId+ self._transport_map: dict[str, str] = {} # base_session_id → transport_key++ def get_thread_id(self, base_session_id: str) -> Optional[str]: ...+ def set_thread_id(self, base_session_id: str, thread_id: str) -> None: ...+ def get_active_turn(self, base_session_id: str) -> Optional[str]: ...+ def set_active_turn(self, base_session_id: str, turn_id: str) -> None: ...+ def clear_active_turn(self, base_session_id: str) -> None: ...+ def clear(self, base_session_id: str) -> None: ...+```++#### CodexEventHandler (`event_handler.py`)++Translates server notifications into `emit_agent_message` calls.++```python+class CodexEventHandler:+ """Handles codex app-server notifications and maps them to Slack messages."""++ def __init__(self, agent: 'CodexAgent'):+ self._agent = agent+ self._pending_text: dict[str, str] = {} # turnId → accumulated text+ self._message_buffers: dict[str, str] = {} # itemId → text delta buffer++ async def handle_notification(self, method: str, params: dict, request: AgentRequest) -> None:+ """Dispatch a server notification to the appropriate handler."""++ async def _on_turn_started(self, params: dict, request: AgentRequest) -> None: ...+ async def _on_turn_completed(self, params: dict, request: AgentRequest) -> None: ...+ async def _on_item_completed(self, params: dict, request: AgentRequest) -> None: ...+ async def _on_agent_message_delta(self, params: dict, request: AgentRequest) -> None: ...+ async def _on_command_output_delta(self, params: dict, request: AgentRequest) -> None: ...+ async def _on_reasoning_delta(self, params: dict, request: AgentRequest) -> None: ...+ async def _on_error(self, params: dict, request: AgentRequest) -> None: ...+```++#### CodexAgent (`agent.py`)++Replaces `codex_agent.py`, orchestrates the above components.++```python+class CodexAgent(BaseAgent):+ name = "codex"++ def __init__(self, controller, codex_config):+ super().__init__(controller)+ self._config = codex_config+ self._transports: dict[str, CodexTransport] = {} # cwd → transport+ self._session_mgr = CodexSessionManager()+ self._event_handlers: dict[str, CodexEventHandler] = {}+ self._active_requests: dict[str, AgentRequest] = {} # base_session_id → request++ async def handle_message(self, request: AgentRequest) -> None:+ """+ 1. Get or create transport for request.working_path+ 2. Get or create thread (thread/start or thread/resume)+ 3. If turn is active: turn/interrupt first, then turn/start+ 4. Send turn/start with user's message+ 5. Notifications flow through event_handler → Slack+ """++ async def handle_stop(self, request: AgentRequest) -> bool:+ """Send turn/interrupt for the active turn."""++ async def clear_sessions(self, settings_key: str) -> int:+ """Archive threads, stop transports scoped to settings_key."""++ async def _get_or_create_transport(self, cwd: str) -> CodexTransport:+ """Lazy-start a transport for the given working directory."""++ async def _handle_approval(self, request_id: int, method: str, params: dict) -> dict:+ """Auto-approve all command/file approval requests."""+```++## Key Design Decisions++### 1. One Transport Per Working Directory+Since `codex app-server` is scoped to a `cwd`, we maintain one persistent process per unique working directory. Multiple Slack threads in the same channel share the transport but have separate Codex threads.++### 2. Auto-Approve All Requests+Like the current `--dangerously-bypass-approvals-and-sandbox` flag, we auto-approve all `item/commandExecution/requestApproval` and `item/fileChange/requestApproval` server requests by responding with `{"approved": true}`.++### 3. Message Insertion via turn/interrupt + turn/start+When a new message arrives while a turn is active:+1. Send `turn/interrupt` for the active turn+2. Wait for `turn/completed` (with interrupted status)+3. Send new `turn/start` with the new message++This is graceful — Codex preserves the conversation context, unlike SIGKILL.++### 4. Thread Resume on Process Restart+If the transport crashes or is restarted, we use `thread/resume` with the stored `threadId` to restore conversation state.++### 5. Event-Driven Slack Messages+Map notifications directly:+- `item/completed` (type=agent_message) → `emit_agent_message("assistant", ...)`+- `item/completed` (type=command_execution) → `emit_agent_message("toolcall", ...)`+- `item/completed` (type=reasoning) → `emit_agent_message("assistant", "🧠 ...")`+- `turn/completed` → `emit_result_message(...)` (final result)+- `error` → `emit_agent_message("notify", "❌ ...")`+- `thread/started` → `emit_agent_message("system", ...)` (init message)++### 6. Pending Message Pattern (same as current)+Keep the "pending assistant message" pattern: buffer the last `agent_message` item, emit previous ones immediately, emit the last one as the result message on `turn/completed`.++## Implementation Order++### Phase 1: Transport Layer+- [ ] Create `modules/agents/codex/__init__.py`+- [ ] Implement `CodexTransport` in `transport.py`+ - Process lifecycle (start, stop, crash detection)+ - JSON-RPC request/response correlation+ - Notification dispatch+ - Server request handling (approval auto-approve)+ - Stderr monitoring++### Phase 2: Session Management+- [ ] Implement `CodexSessionManager` in `session.py`+ - Thread ID mapping+ - Active turn tracking+ - Integration with `settings_manager` for persistence++### Phase 3: Event Handler+- [ ] Implement `CodexEventHandler` in `event_handler.py`+ - Notification dispatching+ - Agent message buffering (pending pattern)+ - Tool call formatting+ - Reasoning display+ - Error handling++### Phase 4: Agent Orchestration+- [ ] Implement `CodexAgent` in `codex/agent.py`+ - `handle_message`: transport → thread → turn flow+ - `handle_stop`: turn/interrupt+ - `clear_sessions`: thread/archive + transport cleanup+ - Approval request auto-approve+ - Thread resume on transport restart+- [ ] Update `modules/agents/registry.py` import+- [ ] Delete old `modules/agents/codex_agent.py`++### Phase 5: Testing & Polish+- [ ] Manual E2E test: start bot, send message, verify response+- [ ] Test message insertion (send second message while first is running)+- [ ] Test /stop (graceful interruption)+- [ ] Test /clear (session cleanup)+- [ ] Test transport crash recovery+- [ ] Lint check (ruff)diff --git a/modules/agents/__init__.py b/modules/agents/__init__.pyindex 1a3a1ef54..d9aadf8a6 100644--- a/modules/agents/__init__.py+++ b/modules/agents/__init__.py@@ -2,7 +2,7 @@ from typing import Optionalfrom .base import BaseAgent, AgentRequest, AgentMessagefrom .claude_agent import ClaudeAgent-from .codex_agent import CodexAgent+from .codex import CodexAgentfrom .opencode import OpenCodeAgentfrom .service import AgentServicediff --git a/modules/agents/codex/__init__.py b/modules/agents/codex/__init__.pynew file mode 100644index 000000000..20edd084e--- /dev/null+++ b/modules/agents/codex/__init__.py@@ -0,0 +1,5 @@+"""Codex agent package — persistent app-server mode."""++from .agent import CodexAgent++__all__ = ["CodexAgent"]diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pynew file mode 100644index 000000000..a261f5df0--- /dev/null+++ b/modules/agents/codex/agent.py@@ -0,0 +1,350 @@+"""Codex agent — persistent app-server mode with JSON-RPC 2.0 transport."""++from __future__ import annotations++import asyncio+import logging+import os+from typing import Any, Dict, Optional++from modules.agents.base import AgentRequest, BaseAgent+from modules.agents.codex.event_handler import CodexEventHandler+from modules.agents.codex.session import CodexSessionManager+from modules.agents.codex.transport import CodexTransport++logger = logging.getLogger(__name__)+++class CodexAgent(BaseAgent):+ """Codex CLI integration via persistent ``codex app-server`` subprocess.++ One transport (subprocess) is maintained per unique working directory.+ Multiple Slack threads in the same channel share a transport but each+ gets its own Codex thread.+ """++ name = "codex"++ def __init__(self, controller: Any, codex_config: Any) -> None:+ super().__init__(controller)+ self.codex_config = codex_config++ # cwd → CodexTransport (one persistent process per working dir)+ self._transports: Dict[str, CodexTransport] = {}+ self._transport_locks: Dict[str, asyncio.Lock] = {}++ self._session_mgr = CodexSessionManager()+ self._event_handler = CodexEventHandler(self)++ # base_session_id → active AgentRequest (for routing notifications)+ self._active_requests: Dict[str, AgentRequest] = {}+ # Track which base_sessions have emitted the init system message+ self._initialized_sessions: set[str] = set()++ # ------------------------------------------------------------------+ # BaseAgent interface+ # ------------------------------------------------------------------++ async def handle_message(self, request: AgentRequest) -> None:+ """Process a user message by routing it through app-server.++ Flow:+ 1. Get or create transport for the working directory+ 2. Get or create a Codex thread for this Slack thread+ 3. If a turn is active → interrupt it first+ 4. Start a new turn with the user's message+ """+ try:+ transport = await self._get_or_create_transport(request.working_path)+ except FileNotFoundError:+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ "❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",+ )+ await self._remove_ack_reaction(request)+ return+ except Exception as e:+ logger.error("Failed to start Codex transport: %s", e, exc_info=True)+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ f"❌ Failed to start Codex CLI: {e}",+ )+ await self._remove_ack_reaction(request)+ return++ # Store the active request so notifications can route to the right context+ self._active_requests[request.base_session_id] = request++ await self._delete_ack(request)++ try:+ # Get or create thread+ thread_id = self._session_mgr.get_thread_id(request.base_session_id)++ if not thread_id:+ thread_id = await self._start_thread(transport, request)++ # If a turn is active, interrupt it first+ active_turn = self._session_mgr.get_active_turn(request.base_session_id)+ if active_turn:+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ "⚠️ Interrupting previous Codex task...",+ )+ try:+ await transport.send_request(+ "turn/interrupt",+ {"threadId": thread_id, "turnId": active_turn},+ )+ # Clear pending text for the interrupted turn+ self._event_handler.clear_pending(active_turn)+ self._session_mgr.clear_active_turn(request.base_session_id)+ except Exception as e:+ logger.warning("Failed to interrupt turn %s: %s", active_turn, e)++ # Build input items+ input_items = self._build_input(request)++ # Read channel-level configuration overrides+ channel_settings = self.settings_manager.get_channel_settings(request.context.channel_id)+ routing = channel_settings.routing if channel_settings else None+ effective_model = (routing.codex_model if routing else None) or self.codex_config.default_model+ effective_effort = routing.codex_reasoning_effort if routing else None++ # Start a new turn+ turn_params: Dict[str, Any] = {+ "threadId": thread_id,+ "input": input_items,+ }+ if effective_model:+ turn_params["model"] = effective_model+ if effective_effort:+ turn_params["effort"] = effective_effort++ resp = await transport.send_request("turn/start", turn_params)+ turn_id = resp.get("turnId", "")+ if turn_id:+ self._session_mgr.set_active_turn(request.base_session_id, turn_id)+ logger.info(+ "Codex turn started: thread=%s turn=%s session=%s",+ thread_id,+ turn_id,+ request.composite_session_id,+ )++ except Exception as e:+ logger.error("Error in Codex handle_message: %s", e, exc_info=True)+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ f"❌ Codex error: {e}",+ )+ await self._remove_ack_reaction(request)++ async def handle_stop(self, request: AgentRequest) -> bool:+ """Gracefully interrupt the active turn."""+ thread_id = self._session_mgr.get_thread_id(request.base_session_id)+ turn_id = self._session_mgr.get_active_turn(request.base_session_id)++ if not thread_id or not turn_id:+ return False++ transport = self._transports.get(request.working_path)+ if not transport or not transport.is_alive:+ return False++ try:+ await transport.send_request(+ "turn/interrupt",+ {"threadId": thread_id, "turnId": turn_id},+ )+ self._event_handler.clear_pending(turn_id)+ self._session_mgr.clear_active_turn(request.base_session_id)+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ "🛑 Terminated Codex execution.",+ )+ logger.info("Codex turn %s interrupted via /stop", turn_id)+ return True+ except Exception as e:+ logger.error("Failed to interrupt Codex turn: %s", e)+ return False++ async def clear_sessions(self, settings_key: str) -> int:+ """Clear all sessions and optionally stop transports."""+ self.settings_manager.clear_agent_sessions(settings_key, self.name)++ count = self._session_mgr.clear_all()++ # Stop all transports — they'll be recreated on next message+ for cwd, transport in list(self._transports.items()):+ try:+ await transport.stop()+ except Exception as e:+ logger.warning("Error stopping transport for %s: %s", cwd, e)+ self._transports.clear()+ self._transport_locks.clear()+ self._active_requests.clear()+ self._initialized_sessions.clear()++ return count++ # ------------------------------------------------------------------+ # Transport management+ # ------------------------------------------------------------------++ async def _get_or_create_transport(self, cwd: str) -> CodexTransport:+ """Return an initialized transport for the given working directory."""+ existing = self._transports.get(cwd)+ if existing and existing.is_initialized:+ return existing++ # Serialize creation per cwd+ if cwd not in self._transport_locks:+ self._transport_locks[cwd] = asyncio.Lock()++ async with self._transport_locks[cwd]:+ # Double-check after acquiring lock+ existing = self._transports.get(cwd)+ if existing and existing.is_initialized:+ return existing++ # Stop stale transport if any+ if existing:+ await existing.stop()++ transport = CodexTransport(+ binary=self.codex_config.binary,+ cwd=cwd,+ extra_args=list(self.codex_config.extra_args),+ )++ # Wire up callbacks+ transport.on_notification(self._on_notification)+ transport.on_server_request(self._on_server_request)++ await transport.start()+ self._transports[cwd] = transport+ return transport++ # ------------------------------------------------------------------+ # Thread management+ # ------------------------------------------------------------------++ async def _start_thread(+ self,+ transport: CodexTransport,+ request: AgentRequest,+ ) -> str:+ """Create a new Codex thread and return its threadId."""+ params: Dict[str, Any] = {+ "cwd": request.working_path,+ "approvalPolicy": "never",+ "sandbox": "danger-full-access",+ }++ resp = await transport.send_request("thread/start", params)+ thread_id = resp.get("threadId", "")+ if not thread_id:+ raise RuntimeError("Codex thread/start returned no threadId")++ self._session_mgr.set_thread_id(request.base_session_id, thread_id)+ return thread_id++ # ------------------------------------------------------------------+ # Input building+ # ------------------------------------------------------------------++ def _build_input(self, request: AgentRequest) -> list[Dict[str, Any]]:+ """Convert AgentRequest into Codex UserInput items."""+ items: list[Dict[str, Any]] = []++ # Text input+ message = request.message+ if request.files:+ # Append file info like Claude agent does+ file_lines = ["", "[User Attachments]"]+ for attachment in request.files:+ if not attachment.local_path:+ continue+ is_image = (attachment.mimetype or "").startswith("image/")+ if is_image:+ # Send as localImage input+ items.append(+ {+ "type": "localImage",+ "path": attachment.local_path,+ }+ )+ else:+ size_str = f", {attachment.size} bytes" if attachment.size else ""+ file_lines.append(f"- File: {attachment.local_path} ({attachment.mimetype}{size_str})")+ if len(file_lines) > 2:+ message = f"{message}\n" + "\n".join(file_lines)++ if message:+ items.insert(0, {"type": "text", "text": message})++ return items++ # ------------------------------------------------------------------+ # Callback handlers (wired to transport)+ # ------------------------------------------------------------------++ async def _on_notification(self, method: str, params: Dict[str, Any]) -> None:+ """Route a server notification to the event handler."""+ # Find the active request by threadId+ thread_id = params.get("threadId", "")+ request = self._find_request_for_thread(thread_id)+ if not request:+ logger.debug(+ "No active request for Codex notification %s (thread=%s)",+ method,+ thread_id,+ )+ return++ await self._event_handler.handle_notification(method, params, request)++ async def _on_server_request(+ self,+ req_id: int | str,+ method: str,+ params: Dict[str, Any],+ ) -> Dict[str, Any]:+ """Handle server requests — auto-approve all."""+ if method in (+ "item/commandExecution/requestApproval",+ "item/fileChange/requestApproval",+ ):+ logger.info("Auto-approving Codex %s (item=%s)", method, params.get("itemId"))+ return {"approved": True}++ logger.warning("Unknown Codex server request: %s", method)+ return {"approved": True}++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------++ def _find_request_for_thread(self, thread_id: str) -> Optional[AgentRequest]:+ """Look up the active AgentRequest for a given Codex threadId."""+ for base_id, request in self._active_requests.items():+ stored_thread = self._session_mgr.get_thread_id(base_id)+ if stored_thread == thread_id:+ return request+ return None++ async def _delete_ack(self, request: AgentRequest) -> None:+ ack_id = request.ack_message_id+ if ack_id and hasattr(self.im_client, "delete_message"):+ try:+ await self.im_client.delete_message(request.context.channel_id, ack_id)+ except Exception as err:+ logger.debug("Could not delete ack message: %s", err)+ finally:+ request.ack_message_id = Nonediff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pynew file mode 100644index 000000000..53ce4d7bf--- /dev/null+++ b/modules/agents/codex/event_handler.py@@ -0,0 +1,238 @@+"""Translates Codex app-server notifications into vibe-remote agent messages."""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING, Any, Optional, Tuple++if TYPE_CHECKING:+ from modules.agents.base import AgentRequest++logger = logging.getLogger(__name__)+++class CodexEventHandler:+ """Maps codex app-server server notifications to ``emit_agent_message`` calls.++ Maintains a *pending assistant message* buffer so that intermediate+ ``agent_message`` items are emitted immediately while the final one is held+ back until ``turn/completed`` and emitted as the result message.+ """++ def __init__(self, agent: Any) -> None:+ self._agent = agent+ # turnId → (accumulated_text, parse_mode)+ self._pending_assistant: dict[str, Tuple[str, Optional[str]]] = {}++ # ------------------------------------------------------------------+ # Public entry point+ # ------------------------------------------------------------------++ async def handle_notification(+ self,+ method: str,+ params: dict[str, Any],+ request: AgentRequest,+ ) -> None:+ handler = self._DISPATCH.get(method)+ if handler:+ await handler(self, params, request)+ else:+ logger.debug("Unhandled Codex notification: %s", method)++ # ------------------------------------------------------------------+ # Notification handlers+ # ------------------------------------------------------------------++ async def _on_thread_started(self, params: dict[str, Any], request: AgentRequest) -> None:+ thread_id = params.get("threadId", "")+ if thread_id:+ self._agent._session_mgr.set_thread_id(request.base_session_id, thread_id)+ # Persist thread_id in settings_manager for /clear resume+ self._agent.settings_manager.set_agent_session_mapping(+ request.settings_key,+ self._agent.name,+ request.base_session_id,+ thread_id,+ )++ system_text = self._agent.im_client.formatter.format_system_message(+ request.working_path,+ "init",+ thread_id,+ )+ await self._agent.controller.emit_agent_message(+ request.context,+ "system",+ system_text,+ parse_mode="markdown",+ )++ async def _on_turn_started(self, params: dict[str, Any], request: AgentRequest) -> None:+ turn_id = params.get("turnId", "")+ if turn_id:+ self._agent._session_mgr.set_active_turn(request.base_session_id, turn_id)+ logger.info(+ "Codex turn started: thread=%s turn=%s",+ params.get("threadId"),+ turn_id,+ )++ async def _on_turn_completed(self, params: dict[str, Any], request: AgentRequest) -> None:+ turn_id = params.get("turnId", "")+ self._agent._session_mgr.clear_active_turn(request.base_session_id)++ pending = self._pending_assistant.pop(turn_id, None)+ if pending:+ pending_text, pending_parse_mode = pending+ await self._agent.emit_result_message(+ request.context,+ pending_text,+ subtype="success",+ started_at=request.started_at,+ parse_mode=pending_parse_mode or "markdown",+ request=request,+ )+ else:+ await self._agent.emit_result_message(+ request.context,+ None,+ subtype="success",+ started_at=request.started_at,+ parse_mode="markdown",+ request=request,+ )++ async def _on_item_completed(self, params: dict[str, Any], request: AgentRequest) -> None:+ item = params.get("item", {})+ item_type = item.get("type")+ turn_id = params.get("turnId", "")++ if item_type == "agent_message":+ text = ""+ # Extract text from content array+ for content in item.get("content", []):+ if isinstance(content, dict) and content.get("type") == "Text":+ text += content.get("text", "")+ # Fallback to top-level text field+ if not text:+ text = item.get("text", "")+ if text:+ # Emit previous pending message as assistant, buffer this one+ prev = self._pending_assistant.get(turn_id)+ if prev:+ prev_text, prev_pm = prev+ await self._agent.controller.emit_agent_message(+ request.context,+ "assistant",+ prev_text,+ parse_mode=prev_pm or "markdown",+ )+ self._pending_assistant[turn_id] = (text, "markdown")++ elif item_type == "command_execution":+ command = item.get("command", "")+ status = item.get("status", "")+ exit_code = item.get("exitCode")+ output = item.get("output", "")+ if command:+ toolcall = self._agent.im_client.formatter.format_toolcall(+ "bash",+ {+ "command": command,+ "status": status,+ "exit_code": exit_code,+ "output": output[:500] if output else "",+ },+ )+ await self._agent.controller.emit_agent_message(+ request.context,+ "toolcall",+ toolcall,+ parse_mode="markdown",+ )++ elif item_type == "file_change":+ file_path = item.get("filePath", "")+ change_type = item.get("changeType", "")+ if file_path:+ toolcall = self._agent.im_client.formatter.format_toolcall(+ "file_change",+ {"file": file_path, "type": change_type},+ )+ await self._agent.controller.emit_agent_message(+ request.context,+ "toolcall",+ toolcall,+ parse_mode="markdown",+ )++ elif item_type == "reasoning":+ text = item.get("text", "")+ # Try extracting from summary array+ if not text:+ for summary in item.get("summary", []):+ if isinstance(summary, dict):+ text += summary.get("text", "")+ if text:+ await self._agent.controller.emit_agent_message(+ request.context,+ "assistant",+ f"_🧠 {text}_",+ parse_mode="markdown",+ )++ async def _on_error(self, params: dict[str, Any], request: AgentRequest) -> None:+ error = params.get("error", {})+ message = error.get("message", "Unknown error") if isinstance(error, dict) else str(error)+ will_retry = params.get("willRetry", False)+ suffix = " (will retry)" if will_retry else ""+ await self._agent.controller.emit_agent_message(+ request.context,+ "notify",+ f"❌ Codex error: {message}{suffix}",+ )++ async def _on_agent_message_delta(self, params: dict[str, Any], request: AgentRequest) -> None:+ # Streaming delta — currently we accumulate at item/completed level,+ # but we could implement progressive Slack message updates here.+ pass++ async def _on_command_output_delta(self, params: dict[str, Any], request: AgentRequest) -> None:+ # Streaming command output — could implement live output display.+ pass++ async def _on_reasoning_delta(self, params: dict[str, Any], request: AgentRequest) -> None:+ # Streaming reasoning — currently handled at item/completed level.+ pass++ async def _on_context_compacted(self, params: dict[str, Any], request: AgentRequest) -> None:+ await self._agent.controller.emit_agent_message(+ request.context,+ "notify",+ "🗜️ Codex context was compacted to free up token space.",+ )++ # ------------------------------------------------------------------+ # Cleanup+ # ------------------------------------------------------------------++ def clear_pending(self, turn_id: str) -> None:+ """Discard buffered text for a turn (e.g. on interruption)."""+ self._pending_assistant.pop(turn_id, None)++ # ------------------------------------------------------------------+ # Dispatch table+ # ------------------------------------------------------------------++ _DISPATCH: dict[str, Any] = {+ "thread/started": _on_thread_started,+ "turn/started": _on_turn_started,+ "turn/completed": _on_turn_completed,+ "item/completed": _on_item_completed,+ "error": _on_error,+ "item/agentMessage/delta": _on_agent_message_delta,+ "item/commandExecution/outputDelta": _on_command_output_delta,+ "item/reasoning/summaryTextDelta": _on_reasoning_delta,+ "thread/compacted": _on_context_compacted,+ }diff --git a/modules/agents/codex/session.py b/modules/agents/codex/session.pynew file mode 100644index 000000000..e71ed47e2--- /dev/null+++ b/modules/agents/codex/session.py@@ -0,0 +1,65 @@+"""Maps vibe-remote session keys to Codex thread/turn state."""++from __future__ import annotations++import logging+from typing import Optional++logger = logging.getLogger(__name__)+++class CodexSessionManager:+ """Track Codex thread and turn IDs per vibe-remote base session.++ A *base_session_id* corresponds to a Slack thread (channel + thread_ts).+ Each base session maps to exactly one Codex ``threadId``. At most one+ ``turnId`` may be active per base session at a time.+ """++ def __init__(self) -> None:+ # base_session_id → Codex threadId+ self._threads: dict[str, str] = {}+ # base_session_id → currently active Codex turnId+ self._active_turns: dict[str, str] = {}++ # -- Thread mapping ---------------------------------------------------++ def get_thread_id(self, base_session_id: str) -> Optional[str]:+ return self._threads.get(base_session_id)++ def set_thread_id(self, base_session_id: str, thread_id: str) -> None:+ self._threads[base_session_id] = thread_id+ logger.info("Session %s → Codex thread %s", base_session_id, thread_id)++ # -- Turn tracking ----------------------------------------------------++ def get_active_turn(self, base_session_id: str) -> Optional[str]:+ return self._active_turns.get(base_session_id)++ def set_active_turn(self, base_session_id: str, turn_id: str) -> None:+ self._active_turns[base_session_id] = turn_id++ def clear_active_turn(self, base_session_id: str) -> None:+ self._active_turns.pop(base_session_id, None)++ # -- Cleanup ----------------------------------------------------------++ def clear(self, base_session_id: str) -> None:+ """Remove all state for a session."""+ self._threads.pop(base_session_id, None)+ self._active_turns.pop(base_session_id, None)++ def clear_all(self) -> int:+ """Remove all tracked sessions. Returns count cleared."""+ count = len(self._threads)+ self._threads.clear()+ self._active_turns.clear()+ return count++ def all_thread_ids(self) -> list[str]:+ """Return all known Codex thread IDs (for archiving on shutdown)."""+ return list(self._threads.values())++ def all_base_sessions(self) -> list[str]:+ """Return all base session IDs being tracked."""+ return list(self._threads.keys())diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.pynew file mode 100644index 000000000..c89e79f59--- /dev/null+++ b/modules/agents/codex/transport.py@@ -0,0 +1,297 @@+"""JSON-RPC 2.0 transport over a persistent codex app-server subprocess."""++from __future__ import annotations++import asyncio+import json+import logging+import os+import signal+from asyncio.subprocess import Process+from typing import Any, Awaitable, Callable, Optional++logger = logging.getLogger(__name__)++STREAM_BUFFER_LIMIT = 8 * 1024 * 1024 # 8 MB+++class CodexTransport:+ """Manages a persistent ``codex app-server`` subprocess.++ Communication uses JSON-RPC 2.0 over stdin (requests/notifications from+ client) and stdout (responses, notifications, and requests from server).+ """++ def __init__(+ self,+ binary: str,+ cwd: str,+ extra_args: list[str] | None = None,+ ) -> None:+ self._binary = binary+ self._cwd = cwd+ self._extra_args = extra_args or []+ self._process: Optional[Process] = None+ self._request_id: int = 0+ self._pending: dict[int | str, asyncio.Future[dict[str, Any]]] = {}+ self._write_lock = asyncio.Lock()+ self._initialized = False+ self._reader_task: Optional[asyncio.Task[None]] = None+ self._stderr_task: Optional[asyncio.Task[None]] = None++ # Callbacks+ self._notification_cb: Optional[Callable[[str, dict[str, Any]], Awaitable[None]]] = None+ self._server_request_cb: Optional[Callable[[int | str, str, dict[str, Any]], Awaitable[dict[str, Any]]]] = None++ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------++ async def start(self) -> None:+ """Launch the app-server and perform the ``initialize`` handshake."""+ if self._process and self._process.returncode is None:+ logger.warning("CodexTransport.start() called but process is already running")+ return++ cmd = [self._binary, "app-server"] + self._extra_args+ logger.info("Launching Codex app-server: %s (cwd=%s)", " ".join(cmd), self._cwd)++ if not os.path.exists(self._cwd):+ os.makedirs(self._cwd, exist_ok=True)++ self._process = await asyncio.create_subprocess_exec(+ *cmd,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ cwd=self._cwd,+ limit=STREAM_BUFFER_LIMIT,+ **({"preexec_fn": os.setsid} if hasattr(os, "setsid") else {}),+ )+ logger.info("Codex app-server started (pid=%s)", self._process.pid)++ # Start background readers+ self._reader_task = asyncio.create_task(self._reader_loop())+ self._stderr_task = asyncio.create_task(self._stderr_reader())++ # Perform initialize handshake+ resp = await self.send_request(+ "initialize",+ {+ "clientInfo": {+ "name": "vibe-remote",+ "version": "1.0.0",+ },+ },+ )+ logger.info("Codex app-server initialized: %s", resp)+ await self.send_notification("initialized")+ self._initialized = True++ async def stop(self) -> None:+ """Gracefully shut down the app-server process."""+ self._initialized = False+ proc = self._process+ if not proc or proc.returncode is not None:+ self._cleanup_tasks()+ return++ # Close stdin to signal EOF+ if proc.stdin and not proc.stdin.is_closing():+ proc.stdin.close()++ # Wait briefly for graceful exit+ try:+ await asyncio.wait_for(proc.wait(), timeout=5.0)+ except asyncio.TimeoutError:+ logger.warning("Codex app-server did not exit gracefully, sending SIGTERM")+ try:+ if hasattr(os, "getpgid"):+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)+ else:+ proc.terminate()+ await asyncio.wait_for(proc.wait(), timeout=3.0)+ except (asyncio.TimeoutError, ProcessLookupError):+ logger.warning("Codex app-server did not respond to SIGTERM, sending SIGKILL")+ try:+ if hasattr(os, "getpgid"):+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)+ else:+ proc.kill()+ await proc.wait()+ except ProcessLookupError:+ pass++ self._cleanup_tasks()+ # Fail all pending futures+ for fut in self._pending.values():+ if not fut.done():+ fut.set_exception(ConnectionError("Transport stopped"))+ self._pending.clear()+ logger.info("Codex app-server stopped")++ def _cleanup_tasks(self) -> None:+ for task in (self._reader_task, self._stderr_task):+ if task and not task.done():+ task.cancel()+ self._reader_task = None+ self._stderr_task = None++ @property+ def is_alive(self) -> bool:+ return self._process is not None and self._process.returncode is None++ @property+ def is_initialized(self) -> bool:+ return self._initialized and self.is_alive++ # ------------------------------------------------------------------+ # Callbacks+ # ------------------------------------------------------------------++ def on_notification(+ self,+ callback: Callable[[str, dict[str, Any]], Awaitable[None]],+ ) -> None:+ self._notification_cb = callback++ def on_server_request(+ self,+ callback: Callable[[int | str, str, dict[str, Any]], Awaitable[dict[str, Any]]],+ ) -> None:+ self._server_request_cb = callback++ # ------------------------------------------------------------------+ # Sending+ # ------------------------------------------------------------------++ async def send_request(self, method: str, params: dict[str, Any]) -> dict[str, Any]:+ """Send a JSON-RPC request and return the result (blocking)."""+ self._request_id += 1+ req_id = self._request_id+ msg = {"jsonrpc": "2.0", "id": req_id, "method": method, "params": params}++ fut: asyncio.Future[dict[str, Any]] = asyncio.get_event_loop().create_future()+ self._pending[req_id] = fut++ await self._write_message(msg)+ try:+ return await asyncio.wait_for(fut, timeout=120.0)+ except asyncio.TimeoutError:+ self._pending.pop(req_id, None)+ raise TimeoutError(f"Codex RPC {method} (id={req_id}) timed out after 120s")++ async def send_notification(self, method: str, params: dict[str, Any] | None = None) -> None:+ """Send a JSON-RPC notification (fire-and-forget)."""+ msg: dict[str, Any] = {"jsonrpc": "2.0", "method": method}+ if params is not None:+ msg["params"] = params+ await self._write_message(msg)++ async def _write_message(self, msg: dict[str, Any]) -> None:+ proc = self._process+ if not proc or not proc.stdin or proc.stdin.is_closing():+ raise ConnectionError("Codex app-server stdin is not available")+ line = json.dumps(msg, separators=(",", ":")) + "\n"+ async with self._write_lock:+ proc.stdin.write(line.encode())+ await proc.stdin.drain()++ # ------------------------------------------------------------------+ # Reading+ # ------------------------------------------------------------------++ async def _reader_loop(self) -> None:+ """Read stdout line-by-line and dispatch JSON-RPC messages."""+ assert self._process and self._process.stdout+ try:+ while True:+ try:+ raw = await self._process.stdout.readline()+ except (asyncio.LimitOverrunError, ValueError) as err:+ logger.error("Codex stdout buffer error: %s", err)+ break+ if not raw:+ break # EOF+ line = raw.decode(errors="replace").strip()+ if not line:+ continue+ try:+ msg = json.loads(line)+ except json.JSONDecodeError:+ logger.debug("Non-JSON from Codex stdout: %s", line[:200])+ continue+ await self._dispatch(msg)+ except asyncio.CancelledError:+ return+ except Exception:+ logger.exception("Codex reader loop crashed")+ finally:+ # Process ended — fail pending futures+ for fut in self._pending.values():+ if not fut.done():+ fut.set_exception(ConnectionError("Codex app-server stdout closed"))+ self._pending.clear()++ async def _dispatch(self, msg: dict[str, Any]) -> None:+ """Route a parsed JSON-RPC message to the right handler."""+ # Response to our request+ if "id" in msg and ("result" in msg or "error" in msg):+ req_id = msg["id"]+ fut = self._pending.pop(req_id, None)+ if fut and not fut.done():+ if "error" in msg:+ fut.set_exception(RuntimeError(f"Codex RPC error: {msg['error']}"))+ else:+ fut.set_result(msg.get("result", {}))+ return++ method = msg.get("method")+ params = msg.get("params", {})++ # Server request (has id + method, expects a response)+ if "id" in msg and method:+ req_id = msg["id"]+ if self._server_request_cb:+ try:+ result = await self._server_request_cb(req_id, method, params)+ await self._send_response(req_id, result)+ except Exception as err:+ logger.error("Error handling server request %s: %s", method, err)+ await self._send_error(req_id, str(err))+ else:+ logger.warning("No handler for server request: %s", method)+ await self._send_error(req_id, "No handler registered")+ return++ # Notification (no id, has method)+ if method:+ if self._notification_cb:+ try:+ await self._notification_cb(method, params)+ except Exception:+ logger.exception("Error in notification handler for %s", method)+ return++ logger.debug("Unrecognized Codex message: %s", str(msg)[:200])++ async def _send_response(self, req_id: int | str, result: dict[str, Any]) -> None:+ await self._write_message({"jsonrpc": "2.0", "id": req_id, "result": result})++ async def _send_error(self, req_id: int | str, message: str) -> None:+ await self._write_message({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32000, "message": message}})++ async def _stderr_reader(self) -> None:+ """Drain stderr and log it."""+ assert self._process and self._process.stderr+ try:+ while True:+ line = await self._process.stderr.readline()+ if not line:+ break+ decoded = line.decode(errors="ignore").rstrip()+ logger.debug("Codex stderr: %s", decoded)+ except asyncio.CancelledError:+ return+ except Exception:+ logger.exception("Codex stderr reader crashed")diff --git a/modules/agents/codex_agent.py b/modules/agents/codex_agent.pydeleted file mode 100644index d1f07fc3d..000000000--- a/modules/agents/codex_agent.py+++ /dev/null@@ -1,366 +0,0 @@-import asyncio-import json-import logging-import os-import signal-from asyncio.subprocess import Process-from typing import Dict, Optional, Tuple--from markdown_to_mrkdwn import SlackMarkdownConverter--from modules.agents.base import AgentRequest, BaseAgent--logger = logging.getLogger(__name__)--STREAM_BUFFER_LIMIT = 8 * 1024 * 1024 # 8MB cap for Codex stdout/stderr streams---class CodexAgent(BaseAgent):- """Codex CLI integration via codex exec JSON streaming mode."""-- name = "codex"-- def __init__(self, controller, codex_config):- super().__init__(controller)- self.codex_config = codex_config- self.active_processes: Dict[str, Tuple[Process, str]] = {}- self.base_process_index: Dict[str, str] = {}- self.composite_to_base: Dict[str, str] = {}- self._initialized_sessions: set[str] = set()- self._pending_assistant_messages: Dict[str, Tuple[str, Optional[str]]] = {}- self._slack_markdown_converter = (- SlackMarkdownConverter() if getattr(self.controller.config, "platform", None) == "slack" else None- )-- async def handle_message(self, request: AgentRequest) -> None:- existing = self.base_process_index.get(request.base_session_id)- if existing and existing in self.active_processes:- await self.controller.emit_agent_message(- request.context,- "notify",- "⚠️ Codex is already processing a task in this thread. Cancelling the previous run...",- )- await self._terminate_process(existing)- await self.controller.emit_agent_message(- request.context,- "notify",- "⏹ Previous Codex task cancelled. Starting the new request...",- )- resume_id = self.settings_manager.get_agent_session_id(- request.settings_key,- request.base_session_id,- agent_name=self.name,- )-- if not os.path.exists(request.working_path):- os.makedirs(request.working_path, exist_ok=True)-- # Read channel-level configuration overrides- channel_settings = self.settings_manager.get_channel_settings(request.context.channel_id)- routing = channel_settings.routing if channel_settings else None-- # Priority: channel config > global default- effective_model = (routing.codex_model if routing else None) or self.codex_config.default_model- effective_reasoning_effort = routing.codex_reasoning_effort if routing else None-- cmd = self._build_command(request, resume_id, effective_model, effective_reasoning_effort)- try:- process = await asyncio.create_subprocess_exec(- *cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- cwd=request.working_path,- limit=STREAM_BUFFER_LIMIT,- **({"preexec_fn": os.setsid} if hasattr(os, "setsid") else {}),- )- except FileNotFoundError:- await self.controller.emit_agent_message(- request.context,- "notify",- "❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",- )- await self._remove_ack_reaction(request)- return- except Exception as e:- logger.error(f"Failed to launch Codex CLI: {e}", exc_info=True)- await self.controller.emit_agent_message(request.context, "notify", f"❌ Failed to start Codex CLI: {e}")- await self._remove_ack_reaction(request)- return-- await self._delete_ack(request)-- self.active_processes[request.composite_session_id] = (- process,- request.settings_key,- )- self.base_process_index[request.base_session_id] = request.composite_session_id- self.composite_to_base[request.composite_session_id] = request.base_session_id- logger.info(f"Codex session {request.composite_session_id} started (pid={process.pid})")-- stdout_task = asyncio.create_task(self._consume_stdout(process, request))- stderr_task = asyncio.create_task(self._consume_stderr(process, request))-- try:- await process.wait()- await asyncio.gather(stdout_task, stderr_task)- finally:- self._unregister_process(request.composite_session_id)- # Clean up reaction as fallback if turn.completed was never received- await self._remove_ack_reaction(request)-- if process.returncode != 0:- await self.controller.emit_agent_message(- request.context,- "notify",- "⚠️ Codex exited with a non-zero status. Review stderr for details.",- )-- async def clear_sessions(self, settings_key: str) -> int:- self.settings_manager.clear_agent_sessions(settings_key, self.name)- # Terminate any active processes scoped to this settings key- terminated = 0- for key, (_, stored_key) in list(self.active_processes.items()):- if stored_key == settings_key:- await self._terminate_process(key)- terminated += 1- return terminated-- async def handle_stop(self, request: AgentRequest) -> bool:- key = request.composite_session_id- if not await self._terminate_process(key):- key = self.base_process_index.get(request.base_session_id)- if not key or not await self._terminate_process(key):- return False- await self.controller.emit_agent_message(request.context, "notify", "🛑 Terminated Codex execution.")- logger.info(f"Codex session {key} terminated via /stop")- return True-- def _unregister_process(self, composite_key: str):- self.active_processes.pop(composite_key, None)- self._pending_assistant_messages.pop(composite_key, None)- base_id = self.composite_to_base.pop(composite_key, None)- if base_id and self.base_process_index.get(base_id) == composite_key:- self.base_process_index.pop(base_id, None)-- async def _terminate_process(self, composite_key: str) -> bool:- entry = self.active_processes.get(composite_key)- if not entry:- return False-- proc, _ = entry- try:- if hasattr(os, "getpgid"):- try:- os.killpg(os.getpgid(proc.pid), signal.SIGKILL)- except ProcessLookupError:- pass- else:- proc.kill()- await proc.wait()- except ProcessLookupError:- pass-- self._unregister_process(composite_key)- return True-- def _build_command(- self,- request: AgentRequest,- resume_id: Optional[str],- model: Optional[str] = None,- reasoning_effort: Optional[str] = None,- ) -> list:- cmd = [self.codex_config.binary, "exec", "--json"]- cmd += ["--dangerously-bypass-approvals-and-sandbox"]- cmd += ["--skip-git-repo-check"]-- # Model selection (priority: param > config default)- effective_model = model or self.codex_config.default_model- if effective_model:- cmd += ["--model", effective_model]-- # Reasoning effort (via -c config override)- if reasoning_effort:- cmd += ["-c", f"model_reasoning_effort={reasoning_effort}"]-- cmd += ["--cd", request.working_path]- cmd += self.codex_config.extra_args-- if resume_id:- cmd += ["resume", resume_id]-- cmd.append(request.message)-- logger.info(f"Executing Codex command: {' '.join(cmd[:-1])} <prompt>")- return cmd-- async def _consume_stdout(self, process: Process, request: AgentRequest):- assert process.stdout is not None- try:- while True:- try:- line = await process.stdout.readline()- except (asyncio.LimitOverrunError, ValueError) as err:- await self._notify_stream_error(request, f"Codex output too long; stream decode failed: {err}")- logger.exception("Codex stdout exceeded buffer limit")- break- if not line:- break- line = line.decode().strip()- if not line:- continue- try:- event = json.loads(line)- except json.JSONDecodeError:- logger.debug(f"Codex emitted non-JSON line: {line}")- continue- await self._handle_event(event, request)- except Exception as err:- await self._notify_stream_error(request, f"Codex stdout 读取异常:{err}")- logger.exception("Unexpected Codex stdout error")-- async def _consume_stderr(self, process: Process, request: AgentRequest):- assert process.stderr is not None- buffer = []- while True:- line = await process.stderr.readline()- if not line:- break- decoded = line.decode(errors="ignore").rstrip()- buffer.append(decoded)- logger.debug(f"Codex stderr: {decoded}")-- if buffer:- joined = "\n".join(buffer[-10:])- await self.controller.emit_agent_message(- request.context,- "notify",- f"❗️ Codex stderr:\n```stderr\n{joined}\n```",- parse_mode="markdown",- )-- async def _handle_event(self, event: Dict, request: AgentRequest):- event_type = event.get("type")-- if event_type == "thread.started":- thread_id = event.get("thread_id")- if thread_id:- self.settings_manager.set_agent_session_mapping(- request.settings_key,- self.name,- request.base_session_id,- thread_id,- )- session_key = request.composite_session_id- if session_key not in self._initialized_sessions:- self._initialized_sessions.add(session_key)- system_text = self.im_client.formatter.format_system_message(request.working_path, "init", thread_id)- await self.controller.emit_agent_message(- request.context,- "system",- system_text,- parse_mode="markdown",- )- return-- if event_type == "item.completed":- details = event.get("item", {})- item_type = details.get("type")-- if item_type == "agent_message":- text = details.get("text", "")- if text:- session_key = request.composite_session_id- pending = self._pending_assistant_messages.get(session_key)- if pending:- pending_text, pending_parse_mode = pending- await self.controller.emit_agent_message(- request.context,- "assistant",- pending_text,- parse_mode=pending_parse_mode or "markdown",- )-- self._pending_assistant_messages[session_key] = self._prepare_last_message_payload(text)- elif item_type == "command_execution":- command = details.get("command")- status = details.get("status")- if command:- toolcall = self.im_client.formatter.format_toolcall(- "bash",- {"command": command, "status": status},- )- await self.controller.emit_agent_message(- request.context,- "toolcall",- toolcall,- parse_mode="markdown",- )- elif item_type == "reasoning":- text = details.get("text", "")- if text:- await self.controller.emit_agent_message(- request.context,- "assistant",- f"_🧠 {text}_",- parse_mode="markdown",- )- return-- if event_type == "error":- message = event.get("message", "Unknown error")- await self.controller.emit_agent_message(request.context, "notify", f"❌ Codex error: {message}")- return-- if event_type == "turn.failed":- error = event.get("error", {}).get("message", "Turn failed.")- await self.controller.emit_agent_message(request.context, "notify", f"⚠️ Codex turn failed: {error}")- self._pending_assistant_messages.pop(request.composite_session_id, None)- return-- if event_type == "turn.completed":- pending = self._pending_assistant_messages.pop(request.composite_session_id, None)- if pending:- pending_text, pending_parse_mode = pending- await self.emit_result_message(- request.context,- pending_text,- subtype="success",- started_at=request.started_at,- parse_mode=pending_parse_mode or "markdown",- request=request,- )- else:- await self.emit_result_message(- request.context,- None,- subtype="success",- started_at=request.started_at,- parse_mode="markdown",- request=request,- )- return-- async def _delete_ack(self, request: AgentRequest):- ack_id = request.ack_message_id- if ack_id and hasattr(self.im_client, "delete_message"):- try:- await self.im_client.delete_message(request.context.channel_id, ack_id)- except Exception as err:- logger.debug(f"Could not delete ack message: {err}")- finally:- request.ack_message_id = None-- # _remove_ack_reaction is inherited from BaseAgent-- def _prepare_last_message_payload(self, text: str) -> Tuple[str, Optional[str]]:- """Prepare cached assistant text for reuse in result messages."""- return text, "markdown"-- async def _notify_stream_error(self, request: AgentRequest, message: str) -> None:- """Emit a notify message when Codex stdout handling fails."""- await self.controller.emit_agent_message(- request.context,- "notify",- f"⚠️ {message}\n请查看 `~/.vibe_remote/logs/vibe_remote.log` 获取更多细节。",- )