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.

feat: add codex agent support

cyhhaof250f9c709f1
diff --git a/.env.example b/.env.example
index 3e97cac9e..995a7ea58 100644
--- a/.env.example
+++ b/.env.example
@@ -38,4 +38,18 @@ CLAUDE_DEFAULT_CWD=./_tmp
CLAUDE_SYSTEM_PROMPT=
# Application Configuration
-LOG_LEVEL=INFO
\ No newline at end of file
+LOG_LEVEL=INFO
+
+# Agent routing & Codex (optional)
+# Enable Codex CLI support (requires codex to be installed locally). Defaults to true.
+CODEX_ENABLED=true
+# Override Codex CLI binary (defaults to "codex")
+CODEX_CLI_PATH=codex
+# Allow Codex to run with --full-auto (write access)
+CODEX_ENABLE_FULL_AUTO=false
+# Extra CLI args appended to every codex exec invocation (use shell-style quoting)
+CODEX_EXTRA_ARGS=
+# Optionally force a specific Codex model
+CODEX_DEFAULT_MODEL=
+# Path to agent routing file (YAML/JSON). Defaults to config/agent_routes.yaml when present.
+AGENT_ROUTE_FILE=
diff --git a/.gitignore b/.gitignore
index 251dbbfbb..8471ffe46 100644
--- a/.gitignore
+++ b/.gitignore
@@ -150,6 +150,7 @@ _tmp/
logs/
.bot.pid
user_settings.json
+agent_routes.yaml
# Config files with secrets
config/secrets.py
@@ -163,4 +164,4 @@ sessions/
*.tmp
*.bak
*.swp
-*~
\ No newline at end of file
+*~
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 000000000..2ef10a202
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,29 @@
+# Repository Guidelines
+
+## Project Structure & Module Organization
+`main.py` is the entry point that wires `config.AppConfig` into the runtime `Controller`. Core orchestration和 handlers live under `core/` (e.g., `core/controller.py`, `core/handlers/*`). Agent integrations now live in `modules/agents/` (shared base, Claude/Codex backends, registry), while IM transports stay in `modules/im/`. Configuration defaults live in `config/` (`agent_routes.example.yaml` + gitignored `agent_routes.yaml` at repo root control per-channel routing), reference docs in `docs/`, static assets in `assets/`, and `_tmp/` is the default remote working directory for agent sessions. Keep runtime logs inside `logs/claude_proxy.log` and persist chat state in `user_settings.json`.
+
+## Build, Test, and Development Commands
+- `python -m venv .venv && source .venv/bin/activate` – create an isolated environment before installing dependencies.
+- `pip install -r requirements.txt` – install the Slack/Telegram/Claude clients plus Codex routing deps (`PyYAML` for route parsing).
+- `cp .env.example .env` – seed configuration; update IM platform tokens, `CLAUDE_DEFAULT_CWD`, and permission mode.
+- `./start.sh` (or `python main.py`) – run the bot locally; prefers Slack when both tokens exist.
+- `./status.sh` / `./stop.sh` – check or terminate the background process when using the helper scripts.
+
+## Coding Style & Naming Conventions
+Follow PEP 8 with four-space indentation, descriptive `snake_case` for functions, and `PascalCase` for classes/dataclasses (see `config/settings.py`). Type hints are expected for public functions, and inline logging should use the structured format in `main.py` for traceability. Keep modules small and cohesive; new handlers belong in `core/handlers/`, new IM transports under `modules/im/`. No repo-wide formatter is enforced—run your preferred tool (Black/Ruff) before opening a PR and document deviations.
+
+## Testing Guidelines
+There is no committed automated test suite yet; favor fast pytest-style modules named `test_<feature>.py` co-located with the code or under `tests/`. Exercise controller flows by faking IM payloads via lightweight fixtures and assert session state mutations. Run `pytest -q` (add it to your dev extras) before pushing; where live integrations are involved, stub Slack/Telegram clients and verify that outbound payloads match the documented schemas. Treat manual end-to-end checks (start bot, send `/start`) as mandatory until CI is in place.
+
+## Commit & Pull Request Guidelines
+Commits follow the `type(scope): summary` pattern visible in history (`fix(slack): …`, `feat(status): …`). Keep them small and focused on a single concern, referencing issues when relevant. Every PR must describe intent, list functional changes, attach logs or screenshots for UX-affecting updates, and call out config impacts (new env vars, migrations). Update README/docs whenever behavior or setup steps change, and ensure `pip install -r requirements.txt && ./start.sh` still works from a clean clone.
+
+## Security & Configuration Tips
+Never commit `.env`, tokens, or Slack/Telegram secrets; rely on `.env.example` plus local overrides. Validate IM scopes (`SLACK_REQUIRE_MENTION`, `TELEGRAM_TARGET_CHAT_ID`) through `config/settings.py` before shipping, and document any new flags. Keep `CLAUDE_DEFAULT_CWD` scoped to `_tmp/` or another sanitized path so that remote agents cannot escape the intended workspace. Logs may contain sensitive thread context—rotate `logs/claude_proxy.log` in production and scrub before sharing.
+
+## Agent Routing & Codex Notes
+- Enable Codex (on by default) via `CODEX_ENABLED=true` and ensure the CLI is reachable (`CODEX_CLI_PATH`); `CODEX_ENABLE_FULL_AUTO` propagates to `codex exec`.
+- Copy `agent_routes.example.yaml` → `agent_routes.yaml` to map Slack channel / Telegram chat IDs to agents; see `docs/CODEX_SETUP.md` for a full walkthrough.
+- Route Slack channel IDs or Telegram chat IDs in `AGENT_ROUTE_FILE` (`agent_routes.yaml` at repo root by default; copy from `agent_routes.example.yaml`). Keys map to agent names (`claude`, `codex`, future backends). Missing entries fall back to the platform default, then to the global default.
+- Session mappings inside `user_settings.json` are now namespaced per agent; avoid manual edits unless you know the nested structure `{agent -> base_session_id -> cwd -> session_id}`.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6b803a311..1d7ca0a6b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -14,6 +14,7 @@ Thanks for your interest in contributing!
- Run locally: `python main.py`
- Lint before PR (add your linter if used)
- Write clear commit messages
+- Codex-specific changes: install the Codex CLI, copy `agent_routes.example.yaml` → `agent_routes.yaml`, and route one Slack channel / Telegram chat to `codex` for manual testing (see `docs/CODEX_SETUP.md`).
## Pull Requests
diff --git a/README.md b/README.md
index b9429010b..90472b25b 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,7 @@ Vibe Remote lets you operate coding agents via IM. Type in Slack or Telegram to
- **Vibe coding, not micromanaging**: Let AI drive based on your intent and constraints; focus on outcomes.
- **Work from anywhere**: Control coding sessions over Slack/Telegram; no IDE tether.
- **Extensible by design**: Starts with Claude Code, built to support additional coding agents/CLIs.
+- **Multi-agent routing**: Route each Slack channel / Telegram chat to Claude Code or Codex by editing `agent_routes.yaml`.
- **Session persistence by thread + path**: Each Slack thread/Telegram chat maintains its own Claude session and working dir; auto‑resume via saved mappings.
- **Interactive Slack UX**: `/start` menu + Settings/CWD modals; buttons over commands for faster flow.
@@ -109,6 +110,35 @@ python main.py
- `CLAUDE_SYSTEM_PROMPT` optional
- `ANTHROPIC_API_KEY` if required by your SDK setup
+### Codex (optional agent)
+
+- Install the [Codex CLI](https://github.com/openai/codex) (e.g., `brew install codex`) and sign in (`codex --help`).
+- `CODEX_ENABLED=true` (default) enables the agent; set to false only if the Codex CLI is unavailable. `CODEX_CLI_PATH` overrides the binary path.
+- `CODEX_ENABLE_FULL_AUTO=true` maps to `codex exec --full-auto` for write access.
+- `CODEX_DEFAULT_MODEL` / `CODEX_EXTRA_ARGS` customize the underlying model or flags.
+
+### Agent routing
+
+- Copy `agent_routes.example.yaml` → `agent_routes.yaml` (repository root) to configure per-channel routing, or point `AGENT_ROUTE_FILE` to any YAML/JSON file.
+- File schema:
+
+```yaml
+default: claude
+slack:
+ default: claude
+ overrides:
+ C01EXAMPLE: codex
+telegram:
+ default: claude
+ overrides:
+ "123456789": codex
+```
+
+- Slack routes use channel IDs; Telegram routes use chat IDs. Unlisted channels fall back to the per-platform default (then to the global `default`). `agent_routes.yaml` is gitignored so each environment can customize it safely.
+
+- See [docs/CODEX_SETUP.md](docs/CODEX_SETUP.md) for a step‑by‑step guide to installing Codex CLI and configuring routing.
+- No file? Everything routes to Claude.
+
### App
- `LOG_LEVEL` default `INFO`
diff --git a/README_ZH.md b/README_ZH.md
index 823493617..b0bc7b667 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -25,7 +25,8 @@ Vibe Remote 把 AI 写代码搬到聊天软件。你在 Slack/Telegram 输入意
- **专注 vibe coding**:基于你的意图与约束让 AI 自主推进,你只把控方向与结果。
- **随时随地**:不被 IDE 束缚,直接在 Slack/Telegram 中远程操控编码会话。
-- **为扩展而生**:目前仅支持 Claude Code,后续可扩展到更多 coding agents/CLIs。
+- **为扩展而生**:目前已支持 Claude Code + Codex,并可扩展到更多 coding agents/CLIs。
+- **多 Agent 路由**:为不同 Slack Channel / Telegram Chat 指定 Agent,互不干扰。
- **按线程 + 路径持久化**:每个 Slack 线程/Telegram 对话都维持独立 Claude 会话与工作目录,并通过持久化映射自动恢复。
- **Slack 交互式体验**:`/start` 菜单 + Settings/CWD 模态,按钮优先于命令,更快上手。
@@ -109,6 +110,33 @@ python main.py
- `CLAUDE_SYSTEM_PROMPT` 可选
- `ANTHROPIC_API_KEY`(取决于你的 SDK 设置)
+### Codex(可选 Agent)
+
+- 安装并登录 [Codex CLI](https://github.com/openai/codex)(执行 `codex --help` 验证)。
+- `CODEX_ENABLED=true`(默认)启用 Codex;若环境没有 CLI 才需要设为 false。`CODEX_CLI_PATH` 可重定向可执行文件。
+- `CODEX_ENABLE_FULL_AUTO=true` 等同于 `codex exec --full-auto`,允许写操作。
+- `CODEX_DEFAULT_MODEL` / `CODEX_EXTRA_ARGS` 可强制模型或追加命令行参数。
+
+### Agent 路由
+
+- 复制 `agent_routes.example.yaml` 为仓库根目录的 `agent_routes.yaml`(或设置 `AGENT_ROUTE_FILE` 指向自定义 YAML/JSON)。
+- 示例:
+
+```yaml
+default: claude
+slack:
+ default: claude
+ overrides:
+ C01EXAMPLE: codex
+telegram:
+ default: claude
+ overrides:
+ "123456789": codex
+```
+
+- Slack 使用频道 ID,Telegram 使用聊天 ID。未命中的频道会落到平台默认值,然后回退到全局 `default`。`agent_routes.yaml` 已被 `.gitignore` 排除,可在不同环境独立配置。
+- 若未提供文件,则所有渠道继续使用 Claude。参见 [docs/CODEX_SETUP.md](docs/CODEX_SETUP.md) 获取更完整的 Codex 配置示例。
+
### 应用
- `LOG_LEVEL` 默认 `INFO`
diff --git a/agent_routes.example.yaml b/agent_routes.example.yaml
new file mode 100644
index 000000000..924be3b44
--- /dev/null
+++ b/agent_routes.example.yaml
@@ -0,0 +1,9 @@
+default: claude
+slack:
+ default: claude
+ overrides:
+ C01EXAMPLE: codex
+telegram:
+ default: claude
+ overrides:
+ "123456789": codex
diff --git a/config/settings.py b/config/settings.py
index b583fdf51..ba86e38e1 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -1,7 +1,9 @@
-import os
import logging
-from dataclasses import dataclass
-from typing import Optional, List, Union
+import os
+import shlex
+import shutil
+from dataclasses import dataclass, field
+from typing import List, Optional, Union
from modules.im.base import BaseIMConfig
logger = logging.getLogger(__name__)
@@ -84,6 +86,40 @@ class ClaudeConfig:
)
+@dataclass
+class CodexConfig:
+ binary: str = "codex"
+ enable_full_auto: bool = False
+ extra_args: List[str] = field(default_factory=list)
+ default_model: Optional[str] = None
+
+ @classmethod
+ def from_env(cls) -> "CodexConfig":
+ binary = os.getenv("CODEX_CLI_PATH", "codex")
+ if not shutil.which(binary):
+ raise ValueError(
+ f"Codex CLI binary '{binary}' not found in PATH. "
+ "Set CODEX_CLI_PATH or install Codex CLI."
+ )
+
+ extra_args_env = os.getenv("CODEX_EXTRA_ARGS", "").strip()
+ extra_args = shlex.split(extra_args_env) if extra_args_env else []
+ enable_full_auto = os.getenv("CODEX_ENABLE_FULL_AUTO", "false").lower() in [
+ "1",
+ "true",
+ "yes",
+ "on",
+ ]
+ default_model = os.getenv("CODEX_DEFAULT_MODEL")
+
+ return cls(
+ binary=binary,
+ enable_full_auto=enable_full_auto,
+ extra_args=extra_args,
+ default_model=default_model,
+ )
+
+
@dataclass
class SlackConfig(BaseIMConfig):
bot_token: str
@@ -150,8 +186,10 @@ class AppConfig:
telegram: Optional[TelegramConfig] = None
slack: Optional[SlackConfig] = None
claude: ClaudeConfig = None
+ codex: Optional[CodexConfig] = None
log_level: str = "INFO"
cleanup_enabled: bool = False
+ agent_route_file: Optional[str] = None
@classmethod
def from_env(cls) -> "AppConfig":
@@ -173,11 +211,34 @@ class AppConfig:
cleanup_enabled_env = os.getenv("CLEANUP_ENABLED", "false").lower()
cleanup_enabled = cleanup_enabled_env in ["1", "true", "yes", "on"]
+ agent_route_env = os.getenv("AGENT_ROUTE_FILE")
+ agent_route_file = agent_route_env
+ if not agent_route_file:
+ candidate = os.path.join(os.getcwd(), "agent_routes.yaml")
+ if os.path.exists(candidate):
+ agent_route_file = candidate
+
+ codex_config = None
+ codex_enabled = os.getenv("CODEX_ENABLED", "true").lower() in [
+ "1",
+ "true",
+ "yes",
+ "on",
+ ]
+ if codex_enabled:
+ try:
+ codex_config = CodexConfig.from_env()
+ except ValueError as exc:
+ logger.warning(f"Codex support disabled: {exc}")
+ codex_config = None
+
config = cls(
platform=platform,
claude=ClaudeConfig.from_env(),
log_level=log_level,
cleanup_enabled=cleanup_enabled,
+ codex=codex_config,
+ agent_route_file=agent_route_file,
)
# Load platform-specific config
diff --git a/core/controller.py b/core/controller.py
index e41d65350..b4c5aa5d2 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -7,6 +7,8 @@ from typing import Optional, Dict, Any
from config.settings import AppConfig
from modules.im import BaseIMClient, MessageContext, IMFactory
from modules.im.formatters import TelegramFormatter, SlackFormatter
+from modules.agent_router import AgentRouter
+from modules.agents import AgentService, ClaudeAgent, CodexAgent
from modules.claude_client import ClaudeClient
from modules.session_manager import SessionManager
from modules.settings_manager import SettingsManager
@@ -38,6 +40,9 @@ class Controller:
# Initialize handlers
self._init_handlers()
+ # Initialize agents (depends on handlers/session handler)
+ self._init_agents()
+
# Setup callbacks
self._setup_callbacks()
@@ -71,6 +76,11 @@ class Controller:
self.session_manager = SessionManager()
self.settings_manager = SettingsManager()
+ # Agent routing (service initialized later after handlers)
+ self.agent_router = AgentRouter.from_file(
+ self.config.agent_route_file, platform=self.config.platform
+ )
+
# Inject settings_manager into SlackBot if it's Slack platform
if self.config.platform == "slack":
# Import here to avoid circular dependency
@@ -90,6 +100,16 @@ class Controller:
# Set cross-references between handlers
self.message_handler.set_session_handler(self.session_handler)
+ def _init_agents(self):
+ """Initialize agent implementations (requires handlers ready)."""
+ self.agent_service = AgentService(self)
+ self.agent_service.register(ClaudeAgent(self))
+ if self.config.codex:
+ try:
+ self.agent_service.register(CodexAgent(self, self.config.codex))
+ except Exception as e:
+ logger.error(f"Failed to initialize Codex agent: {e}")
+
def _setup_callbacks(self):
"""Setup callback connections between modules"""
# Create command handlers dict
@@ -161,6 +181,27 @@ class Controller:
)
return context
+ async def emit_agent_message(
+ self,
+ context: MessageContext,
+ message_type: str,
+ text: str,
+ parse_mode: str = "markdown",
+ ):
+ """Centralized dispatch for agent messages with filtering."""
+ if not text or not text.strip():
+ return
+ settings_key = self._get_settings_key(context)
+ if self.settings_manager.is_message_type_hidden(settings_key, message_type):
+ logger.info(
+ f"Skipping {message_type} message for settings {settings_key} (hidden)"
+ )
+ return
+ target_context = self._get_target_context(context)
+ await self.im_client.send_message(
+ target_context, text, parse_mode=parse_mode
+ )
+
# Settings update handler (for Slack modal)
async def handle_settings_update(
self, user_id: str, hidden_message_types: list, channel_id: str = None
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 01e353b5e..19e310a26 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -3,6 +3,7 @@
import os
import logging
from typing import Optional
+from modules.agents import AgentRequest
from modules.im import MessageContext, InlineKeyboard, InlineButton
logger = logging.getLogger(__name__)
@@ -133,53 +134,19 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
# Get the correct settings key (channel_id for Slack, not user_id)
settings_key = self.controller._get_settings_key(context)
- # Get current session mappings before clearing them
- settings = self.settings_manager.get_user_settings(settings_key)
- session_bases_to_clear = set(settings.session_mappings.keys())
-
- # Clear ALL session mappings for this user/channel
- self.settings_manager.clear_all_session_mappings(settings_key)
-
- # Clear all Claude sessions from memory that belong to this channel/user
- sessions_to_clear = []
- for session_key in self.controller.claude_sessions.keys():
- # Session keys format: "base_session_id:working_path"
- base_part = (
- session_key.split(":")[0] if ":" in session_key else session_key
+ cleared = await self.controller.agent_service.clear_sessions(settings_key)
+ if not cleared:
+ full_response = (
+ "📋 No active sessions to clear.\n🔄 Session state has been reset."
)
-
- # Check if this session should be cleared
- if base_part in session_bases_to_clear:
- sessions_to_clear.append(session_key)
-
- # Clear identified sessions
- for session_key in sessions_to_clear:
- try:
- client = self.controller.claude_sessions[session_key]
- if hasattr(client, "close"):
- await client.close()
- del self.controller.claude_sessions[session_key]
- logger.info(f"Cleared Claude session: {session_key}")
- except Exception as e:
- logger.warning(f"Error clearing session {session_key}: {e}")
-
- # Clear session and disconnect clients (legacy)
- legacy_response = await self.session_manager.clear_session(settings_key)
- logger.info(
- f"User {context.user_id} cleared all sessions for {settings_key}"
- )
-
- # Build response message based on what was actually cleared
- if len(sessions_to_clear) > 0:
- full_response = f"✅ Cleared {len(sessions_to_clear)} active Claude session(s).\n🔄 All sessions have been reset."
- elif session_bases_to_clear:
- full_response = f"✅ Cleared {len(session_bases_to_clear)} stored session mapping(s).\n🔄 All sessions have been reset."
else:
+ details = "\n".join(
+ f"• {agent} → {count} session(s)" for agent, count in cleared.items()
+ )
full_response = (
- "📋 No active sessions to clear.\n🔄 Session state has been reset."
+ "✅ Cleared active sessions for:\n" f"{details}\n🔄 All sessions reset."
)
- # Send the complete response
channel_context = self._get_channel_context(context)
await self.im_client.send_message(channel_context, full_response)
logger.info(f"Sent clear response to user {context.user_id}")
@@ -330,68 +297,31 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
async def handle_stop(self, context: MessageContext, args: str = ""):
"""Handle /stop command - send interrupt message to Claude"""
try:
- # Get the session handler directly from controller
session_handler = self.controller.session_handler
- if not session_handler:
- channel_context = self._get_channel_context(context)
- await self.im_client.send_message(
- channel_context, "❌ Session handler not available"
- )
- return
-
- # Get session info for the current context
base_session_id, working_path, composite_key = (
session_handler.get_session_info(context)
)
-
- # Check if there's an active Claude session
- if composite_key not in self.controller.claude_sessions:
- channel_context = self._get_channel_context(context)
-
- # Provide helpful guidance based on platform
- if self.config.platform == "slack":
- formatter = self.im_client.formatter
- help_text = (
- f"ℹ️ {formatter.format_bold('No active Claude session to stop')}\n\n"
- f"The stop command interrupts Claude during execution.\n\n"
- f"{formatter.format_bold('How to use in Slack:')}\n"
- f"• In channel: `/stop`\n"
- f"• In thread: Type `stop` or `@bot /stop`\n"
- f" _(Slack doesn't support slash commands in threads)_\n\n"
- f"{formatter.format_bold('Steps:')}\n"
- f"1. Send a message to Claude in a thread\n"
- f"2. While Claude is processing, send `stop` in the thread\n"
- f"3. Claude will stop but keep the session active\n\n"
- f"💡 Tip: Start a conversation with Claude first, then use stop if needed."
- )
- else:
- help_text = (
- "ℹ️ **No active Claude session to stop**\n\n"
- "The `/stop` command interrupts Claude during execution.\n\n"
- "**How to use:**\n"
- "1. Send a message to Claude\n"
- "2. While Claude is processing, send `/stop`\n"
- "3. Claude will stop execution but keep the session active\n\n"
- "💡 Tip: Start a conversation with Claude first, then use `/stop` if needed."
- )
-
- await self.im_client.send_message(channel_context, help_text)
- return
-
- # Get the Claude client for this session
- client = self.controller.claude_sessions[composite_key]
-
- # Send acknowledgment - use original context to send to thread if applicable
- await self.im_client.send_message(
- context, # Use original context, not channel_context
- "🛑 Sending stop signal to Claude...",
+ settings_key = self.controller._get_settings_key(context)
+ agent_name = self.controller.agent_router.resolve(
+ self.config.platform, settings_key
+ )
+ request = AgentRequest(
+ context=context,
+ message="stop",
+ working_path=working_path,
+ base_session_id=base_session_id,
+ composite_session_id=composite_key,
+ settings_key=settings_key,
)
- # Send interrupt message to Claude through the same session
- stop_message = "Please stop the current execution immediately and wait for further instructions."
- await client.query(stop_message, session_id=composite_key)
-
- logger.info(f"Sent stop command to Claude session {composite_key}")
+ handled = await self.controller.agent_service.handle_stop(
+ agent_name, request
+ )
+ if not handled:
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(
+ channel_context, "ℹ️ No active session to stop for this channel."
+ )
except Exception as e:
logger.error(f"Error sending stop command: {e}", exc_info=True)
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index ee008ec05..ad0b62d05 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -1,9 +1,9 @@
-"""Message routing and Claude communication handlers"""
+"""Message routing and Agent communication handlers"""
-import asyncio
import logging
-import os
-from typing import Optional, Dict, Any, List
+from typing import Optional
+
+from modules.agents import AgentRequest
from modules.im import MessageContext
logger = logging.getLogger(__name__)
@@ -44,29 +44,8 @@ class MessageHandler:
)
return context
- def get_relative_path(self, abs_path: str, context: MessageContext = None) -> str:
- """Convert absolute path to relative path from working directory"""
- try:
- # Use unified method to get working path
- cwd = self.session_handler.get_working_path(context)
-
- # Convert input path to absolute
- abs_path = os.path.abspath(os.path.expanduser(abs_path))
-
- # Try to get relative path
- rel_path = os.path.relpath(abs_path, cwd)
-
- # If relative path goes up too many directories, use absolute
- if rel_path.startswith("../.."):
- return abs_path
-
- return rel_path
- except Exception:
- # If any error, return original path
- return abs_path
-
async def handle_user_message(self, context: MessageContext, message: str):
- """Process regular user messages and send to Claude"""
+ """Process regular user messages and route to configured agent"""
try:
# Safe cleanup: only remove completed receiver tasks when enabled
if getattr(self.config, "cleanup_enabled", False):
@@ -84,158 +63,50 @@ class MessageHandler:
except Exception as cleanup_err:
logger.debug(f"Safe cleanup skipped due to error: {cleanup_err}")
- # Check if message is a stop command in thread (for Slack)
- # This handles the case where slash commands don't work in threads
+ # Allow "stop" shortcut inside Slack threads
if context.thread_id and message.strip().lower() in ["stop", "/stop"]:
- logger.info(f"Detected stop command in thread: '{message}'")
- # Delegate to the stop command handler
- if hasattr(self.controller, "command_handler"):
- await self.controller.command_handler.handle_stop(context, "")
+ if await self._handle_inline_stop(context):
return
- # Get or create Claude session
base_session_id, working_path, composite_key = (
self.session_handler.get_session_info(context)
)
- client = await self.session_handler.get_or_create_claude_session(context)
+ settings_key = self._get_settings_key(context)
- # Send immediate acknowledgment for better UX
- ack_message = await self.im_client.send_message(
- context, "📨 Message received, processing..."
+ agent_name = self.controller.agent_router.resolve(
+ self.config.platform, settings_key
)
-
- # Send message to Claude
- await client.query(message, session_id=composite_key)
- logger.info(f"Sent message to Claude for session {composite_key}")
-
- # Delete acknowledgment message
- if ack_message and hasattr(self.im_client, "delete_message"):
- try:
- await self.im_client.delete_message(context.channel_id, ack_message)
- except Exception as e:
- logger.debug(f"Could not delete ack message: {e}")
-
- # Start receiver if not already running
- if (
- composite_key not in self.receiver_tasks
- or self.receiver_tasks[composite_key].done()
- ):
- logger.info(f"Starting message receiver for session {composite_key}")
- self.receiver_tasks[composite_key] = asyncio.create_task(
- self._receive_messages(
- client, base_session_id, working_path, context
- )
+ ack_context = self._get_target_context(context)
+ ack_text = self._get_ack_text(agent_name)
+ ack_message_id = None
+ try:
+ ack_message_id = await self.im_client.send_message(
+ ack_context, ack_text
)
-
+ except Exception as ack_err:
+ logger.debug(f"Failed to send ack message: {ack_err}")
+
+ request = AgentRequest(
+ context=context,
+ message=message,
+ working_path=working_path,
+ base_session_id=base_session_id,
+ composite_session_id=composite_key,
+ settings_key=settings_key,
+ ack_message_id=ack_message_id,
+ )
+ try:
+ await self.controller.agent_service.handle_message(agent_name, request)
+ except KeyError:
+ await self._handle_missing_agent(context, agent_name)
+ finally:
+ if request.ack_message_id:
+ await self._delete_ack(context.channel_id, request)
except Exception as e:
logger.error(f"Error processing user message: {e}", exc_info=True)
- _, _, composite_key = self.session_handler.get_session_info(context)
- await self.session_handler.handle_session_error(composite_key, context, e)
-
- async def _receive_messages(
- self, client, base_session_id: str, working_path: str, context: MessageContext
- ):
- """Receive messages from Claude SDK client"""
- try:
- settings_key = self._get_settings_key(context)
- settings = self.settings_manager.get_user_settings(settings_key)
- target_context = self._get_target_context(context)
-
- async for message in client.receive_messages():
- try:
- # Check for SystemMessage init to capture session_id
- if (
- hasattr(message, "__class__")
- and message.__class__.__name__ == "SystemMessage"
- ):
- if hasattr(message, "subtype") and message.subtype == "init":
- if (
- hasattr(message, "data")
- and "session_id" in message.data
- ):
- claude_session_id = message.data["session_id"]
- # Get correct settings key based on platform
- settings_key = self._get_settings_key(context)
- self.session_handler.capture_session_id(
- base_session_id,
- working_path,
- claude_session_id,
- settings_key,
- )
-
- # Skip certain messages
- if hasattr(
- self.controller, "claude_client"
- ) and self.controller.claude_client._is_skip_message(message):
- continue
-
- # Determine message type by class name
- message_type = None
- if hasattr(message, "__class__"):
- class_name = message.__class__.__name__
- if class_name == "SystemMessage":
- message_type = "system"
- elif class_name == "UserMessage":
- message_type = "user"
- elif class_name == "AssistantMessage":
- message_type = "assistant"
- elif class_name == "ResultMessage":
- message_type = "result"
-
- # Check if this message type should be hidden
- if message_type and self.settings_manager.is_message_type_hidden(
- settings_key, message_type
- ):
- logger.info(
- f"Skipping {message_type} message for settings key {settings_key} (hidden in settings)"
- )
- continue
-
- # Format and send message using claude_client
- if hasattr(self.controller, "claude_client"):
- # Provide a per-session relative path resolver to ensure correct cwd
- def _rel(path: str) -> str:
- return self.get_relative_path(path, context)
- formatted_message = (
- self.controller.claude_client.format_message(
- message, get_relative_path=_rel
- )
- )
- if formatted_message and formatted_message.strip():
- # Add separator line for Slack to improve message separation
- if self.config.platform == "slack":
- formatted_message = formatted_message + "\n---"
-
- await self.im_client.send_message(
- target_context, formatted_message, parse_mode="markdown"
- )
-
- # Check if this was a ResultMessage (query complete)
- if message_type == "result":
- # Mark session as not active
- session = (
- await self.controller.session_manager.get_or_create_session(
- context.user_id, context.channel_id
- )
- )
- if session:
- composite_key = f"{base_session_id}:{working_path}"
- session.session_active[composite_key] = False
-
- except Exception as e:
- logger.error(
- f"Error processing message from Claude: {e}", exc_info=True
- )
- # Continue processing other messages
- continue
-
- except Exception as e:
- composite_key = f"{base_session_id}:{working_path}"
- logger.error(
- f"Error in message receiver for session {composite_key}: {e}",
- exc_info=True,
+ await self.im_client.send_message(
+ context, self.formatter.format_error(f"Error: {str(e)}")
)
- await self.session_handler.handle_session_error(composite_key, context, e)
async def handle_callback_query(self, context: MessageContext, callback_data: str):
"""Route callback queries to appropriate handlers"""
@@ -308,3 +179,62 @@ class MessageHandler:
context,
self.formatter.format_error(f"Error processing action: {str(e)}"),
)
+
+ async def _handle_inline_stop(self, context: MessageContext) -> bool:
+ """Route inline 'stop' messages to the active agent."""
+ try:
+ base_session_id, working_path, composite_key = (
+ self.session_handler.get_session_info(context)
+ )
+ settings_key = self._get_settings_key(context)
+ agent_name = self.controller.agent_router.resolve(
+ self.config.platform, settings_key
+ )
+ request = AgentRequest(
+ context=context,
+ message="stop",
+ working_path=working_path,
+ base_session_id=base_session_id,
+ composite_session_id=composite_key,
+ settings_key=settings_key,
+ )
+ try:
+ handled = await self.controller.agent_service.handle_stop(
+ agent_name, request
+ )
+ except KeyError:
+ await self._handle_missing_agent(context, agent_name)
+ return False
+ if not handled:
+ await self.im_client.send_message(
+ context, "ℹ️ No active session to stop."
+ )
+ return handled
+ except Exception as e:
+ logger.error(f"Error handling inline stop: {e}", exc_info=True)
+ return False
+
+ async def _handle_missing_agent(self, context: MessageContext, agent_name: str):
+ """Notify user when a requested agent backend is unavailable."""
+ target = agent_name or self.controller.agent_service.default_agent
+ msg = (
+ f"❌ Agent `{target}` is not configured. "
+ "Make sure the Codex CLI is installed and environment variables are set "
+ "if this channel is routed to Codex."
+ )
+ await self.im_client.send_message(context, msg)
+
+ async def _delete_ack(self, channel_id: str, request: AgentRequest):
+ """Delete acknowledgement message if it still exists."""
+ if request.ack_message_id and hasattr(self.im_client, "delete_message"):
+ try:
+ await self.im_client.delete_message(channel_id, request.ack_message_id)
+ except Exception as err:
+ logger.debug(f"Failed to delete ack message: {err}")
+ finally:
+ request.ack_message_id = None
+
+ def _get_ack_text(self, agent_name: str) -> str:
+ """Unified acknowledgement text before agent processing."""
+ label = agent_name or self.controller.agent_service.default_agent
+ return f"📨 {label.capitalize()} received, processing..."
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 4a4eb31cf..e3200178d 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -190,13 +190,21 @@ class SessionHandler:
restored_count = 0
for user_id, user_settings in all_settings.items():
- if hasattr(user_settings, 'session_mappings') and user_settings.session_mappings:
- # Only handle new nested structure: {base_session_id: {path: claude_session_id}}
- for base_session_id, path_mappings in user_settings.session_mappings.items():
+ if (
+ hasattr(user_settings, "session_mappings")
+ and user_settings.session_mappings
+ and "claude" in user_settings.session_mappings
+ ):
+ claude_map = user_settings.session_mappings["claude"]
+ for base_session_id, path_mappings in claude_map.items():
if isinstance(path_mappings, dict):
- logger.info(f"Found {len(path_mappings)} path mappings for {base_session_id} (user {user_id})")
+ logger.info(
+ f"Found {len(path_mappings)} path mappings for {base_session_id} (user {user_id})"
+ )
for path, claude_session_id in path_mappings.items():
- logger.info(f" - {base_session_id}[{path}] -> {claude_session_id}")
+ logger.info(
+ f" - {base_session_id}[{path}] -> {claude_session_id}"
+ )
restored_count += 1
-
- logger.info(f"Session restoration complete. Restored {restored_count} session mappings.")
\ No newline at end of file
+
+ logger.info(f"Session restoration complete. Restored {restored_count} session mappings.")
diff --git a/docs/CODEX_SETUP.md b/docs/CODEX_SETUP.md
new file mode 100644
index 000000000..036a91f87
--- /dev/null
+++ b/docs/CODEX_SETUP.md
@@ -0,0 +1,68 @@
+# Codex Agent Setup
+
+Vibe Remote can route individual Slack channels / Telegram chats to Codex instead of Claude Code. This guide walks through enabling Codex end-to-end.
+
+## 1. Install and authenticate Codex CLI
+
+```bash
+brew install codex # or follow https://github.com/openai/codex
+codex --help # verify installation
+codex # sign in when prompted
+```
+
+Codex CLI must be available on the PATH of the host running Vibe Remote. The bot automatically runs Codex with `--json` and `--dangerously-bypass-approvals-and-sandbox`, so make sure you trust the workspace it operates in.
+
+## 2. Configure environment variables
+
+In `.env` (copied from `.env.example`):
+
+```
+CODEX_ENABLED=true # default; set false only if CLI is unavailable
+CODEX_CLI_PATH=codex # customise if the binary lives elsewhere
+CODEX_ENABLE_FULL_AUTO=true # optional, maps to --full-auto
+CODEX_DEFAULT_MODEL=gpt-5-codex # optional
+CODEX_EXTRA_ARGS=--ask-for-approval never # optional extra flags
+```
+
+No additional flag is required to bypass approvals—the bot always adds `--dangerously-bypass-approvals-and-sandbox`.
+
+## 3. Route channels to Codex
+
+Copy the example routing file and edit it:
+
+```bash
+cp agent_routes.example.yaml agent_routes.yaml
+```
+
+Example contents:
+
+```yaml
+default: claude
+slack:
+ default: claude
+ overrides:
+ C01ABCD2EFG: codex # Slack channel ID
+telegram:
+ default: claude
+ overrides:
+ "123456789": codex # Telegram chat ID
+```
+
+Each Slack channel ID (starts with `C`) or Telegram chat ID gets its own agent. Routes fall back to the platform default, then to the global `default`.
+
+`agent_routes.yaml` is gitignored so you can maintain different mappings per environment. Alternatively, point `AGENT_ROUTE_FILE` to a custom path.
+
+## 4. Restart the bot and test
+
+```bash
+source venv/bin/activate
+./start.sh
+```
+
+In a routed Slack channel run `@VibeRemote status` or any question—you should see an acknowledgement like `📨 Codex received, processing...` followed by Codex’s reply. If the CLI is missing, the bot will reply with “Agent `codex` is not configured”.
+
+## 5. Troubleshooting
+
+- **“Agent `codex` is not configured”**: ensure `codex` CLI is installed and on PATH; check `CODEX_ENABLED`.
+- **`codex exec` errors**: inspect the Slack/Telegram stderr snippet or tail the latest `logs/bot_*.log`.
+- **Routing not applied**: confirm the channel ID matches Slack’s `C...` value (copy from channel details) or Telegram’s numeric chat ID, and restart the bot after editing `agent_routes.yaml`.
diff --git a/modules/agent_router.py b/modules/agent_router.py
new file mode 100644
index 000000000..89c66f306
--- /dev/null
+++ b/modules/agent_router.py
@@ -0,0 +1,83 @@
+import json
+import logging
+import os
+from dataclasses import dataclass, field
+from typing import Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class PlatformRoute:
+ default: str = "claude"
+ overrides: Dict[str, str] = field(default_factory=dict)
+
+
+class AgentRouter:
+ """Resolve which agent should serve a given message context."""
+
+ def __init__(
+ self,
+ platform_routes: Dict[str, PlatformRoute],
+ global_default: str = "claude",
+ ):
+ self.platform_routes = platform_routes
+ self.global_default = global_default
+
+ @classmethod
+ def from_file(
+ cls, file_path: Optional[str], *, platform: str
+ ) -> "AgentRouter":
+ routes: Dict[str, PlatformRoute] = {}
+ global_default = "claude"
+
+ if file_path and os.path.exists(file_path):
+ try:
+ data = cls._load_file(file_path)
+ global_default = data.get("default", global_default)
+ for key, value in data.items():
+ if key == "default":
+ continue
+ if not isinstance(value, dict):
+ continue
+ routes[key] = PlatformRoute(
+ default=value.get("default", global_default),
+ overrides=value.get("overrides", {}) or {},
+ )
+ logger.info(
+ f"Loaded agent routing config from {file_path} "
+ f"(platforms: {list(routes.keys())})"
+ )
+ except Exception as e:
+ logger.error(f"Failed to parse agent route config {file_path}: {e}")
+ else:
+ if file_path:
+ logger.warning(
+ f"Agent route config file not found at {file_path}, using defaults"
+ )
+
+ # Ensure platform entry exists
+ routes.setdefault(platform, PlatformRoute(default=global_default))
+ return cls(routes, global_default=global_default)
+
+ @staticmethod
+ def _load_file(path: str) -> Dict:
+ _, ext = os.path.splitext(path)
+ if ext.lower() in {".yaml", ".yml"}:
+ try:
+ import yaml # type: ignore
+ except ImportError as exc:
+ raise RuntimeError(
+ "PyYAML is required to parse YAML agent route files. "
+ "Install with `pip install pyyaml` or use JSON."
+ ) from exc
+ with open(path, "r") as f:
+ return yaml.safe_load(f) or {}
+ with open(path, "r") as f:
+ return json.load(f)
+
+ def resolve(self, platform: str, channel_id: str) -> str:
+ platform_route = self.platform_routes.get(platform)
+ if not platform_route:
+ return self.global_default
+ return platform_route.overrides.get(channel_id, platform_route.default)
diff --git a/modules/agents/__init__.py b/modules/agents/__init__.py
new file mode 100644
index 000000000..f0bbe8c2a
--- /dev/null
+++ b/modules/agents/__init__.py
@@ -0,0 +1,13 @@
+from .base import BaseAgent, AgentRequest, AgentMessage
+from .claude_agent import ClaudeAgent
+from .codex_agent import CodexAgent
+from .service import AgentService
+
+__all__ = [
+ "AgentMessage",
+ "AgentRequest",
+ "BaseAgent",
+ "ClaudeAgent",
+ "CodexAgent",
+ "AgentService",
+]
diff --git a/modules/agents/base.py b/modules/agents/base.py
new file mode 100644
index 000000000..8d6ca8d1b
--- /dev/null
+++ b/modules/agents/base.py
@@ -0,0 +1,57 @@
+"""Abstract agent interfaces and shared dataclasses."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Any, Dict, Optional
+
+from modules.im import MessageContext
+
+
+@dataclass
+class AgentRequest:
+ """Normalized agent invocation request."""
+
+ context: MessageContext
+ message: str
+ working_path: str
+ base_session_id: str
+ composite_session_id: str
+ settings_key: str
+ ack_message_id: Optional[str] = None
+ last_agent_message: Optional[str] = None
+
+
+@dataclass
+class AgentMessage:
+ """Normalized message emitted by an agent implementation."""
+
+ text: str
+ message_type: str = "assistant"
+ parse_mode: str = "markdown"
+ metadata: Optional[Dict[str, Any]] = None
+
+
+class BaseAgent(ABC):
+ """Abstract base class for all agent implementations."""
+
+ name: str
+
+ def __init__(self, controller):
+ self.controller = controller
+ self.config = controller.config
+ self.im_client = controller.im_client
+ self.settings_manager = controller.settings_manager
+
+ @abstractmethod
+ async def handle_message(self, request: AgentRequest) -> None:
+ """Process a user message routed to this agent."""
+
+ async def clear_sessions(self, settings_key: str) -> int:
+ """Clear session state for a given settings key. Returns cleared count."""
+ return 0
+
+ async def handle_stop(self, request: AgentRequest) -> bool:
+ """Attempt to interrupt an in-flight task. Returns True if handled."""
+ return False
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
new file mode 100644
index 000000000..320cd0b0a
--- /dev/null
+++ b/modules/agents/claude_agent.py
@@ -0,0 +1,239 @@
+import asyncio
+import logging
+import os
+from typing import Callable, Optional
+
+from modules.agents.base import AgentRequest, BaseAgent
+from modules.im import MessageContext
+
+logger = logging.getLogger(__name__)
+
+
+class ClaudeAgent(BaseAgent):
+ """Existing Claude Code integration extracted into an agent backend."""
+
+ name = "claude"
+
+ def __init__(self, controller):
+ super().__init__(controller)
+ self.session_handler = controller.session_handler
+ self.session_manager = controller.session_manager
+ self.receiver_tasks = controller.receiver_tasks
+ self.claude_sessions = controller.claude_sessions
+ self.claude_client = controller.claude_client
+
+ async def handle_message(self, request: AgentRequest) -> None:
+ context = request.context
+
+ try:
+ client = await self.session_handler.get_or_create_claude_session(context)
+
+ await client.query(
+ request.message, session_id=request.composite_session_id
+ )
+ logger.info(
+ f"Sent message to Claude for session {request.composite_session_id}"
+ )
+
+ await self._delete_ack(context, request)
+
+ if (
+ request.composite_session_id not in self.receiver_tasks
+ or self.receiver_tasks[request.composite_session_id].done()
+ ):
+ self.receiver_tasks[request.composite_session_id] = asyncio.create_task(
+ self._receive_messages(
+ client, request.base_session_id, request.working_path, context
+ )
+ )
+ except Exception as e:
+ logger.error(f"Error processing Claude message: {e}", exc_info=True)
+ await self.session_handler.handle_session_error(
+ request.composite_session_id, context, e
+ )
+ finally:
+ await self._delete_ack(context, request)
+
+ async def clear_sessions(self, settings_key: str) -> int:
+ """Clear Claude sessions scoped to the provided settings key."""
+ settings = self.settings_manager.get_user_settings(settings_key)
+ claude_map = settings.session_mappings.get(self.name, {})
+ session_bases_to_clear = set(claude_map.keys())
+
+ self.settings_manager.clear_agent_sessions(settings_key, self.name)
+
+ sessions_to_clear = []
+ for session_key in list(self.claude_sessions.keys()):
+ base_part = session_key.split(":")[0] if ":" in session_key else session_key
+ if base_part in session_bases_to_clear:
+ sessions_to_clear.append(session_key)
+
+ for session_key in sessions_to_clear:
+ try:
+ client = self.claude_sessions[session_key]
+ if hasattr(client, "close"):
+ await client.close()
+ except Exception as e:
+ logger.warning(f"Error closing Claude session {session_key}: {e}")
+ finally:
+ self.claude_sessions.pop(session_key, None)
+
+ # Legacy session manager cleanup (best-effort)
+ await self.session_manager.clear_session(settings_key)
+
+ return len(sessions_to_clear) or len(session_bases_to_clear)
+
+ async def handle_stop(self, request: AgentRequest) -> bool:
+ composite_key = request.composite_session_id
+ if composite_key not in self.claude_sessions:
+ return False
+
+ client = self.claude_sessions[composite_key]
+ await self.controller.emit_agent_message(
+ request.context, "system", "🛑 Sending stop signal to Claude..."
+ )
+ stop_message = (
+ "Please stop the current execution immediately and wait for further instructions."
+ )
+ await client.query(stop_message, session_id=composite_key)
+ return True
+
+ async def _receive_messages(
+ self,
+ client,
+ base_session_id: str,
+ working_path: str,
+ context: MessageContext,
+ ):
+ """Receive messages from Claude SDK client."""
+ try:
+ settings_key = self.controller._get_settings_key(context)
+ async for message in client.receive_messages():
+ try:
+ claude_session_id = self._maybe_capture_session_id(
+ message, base_session_id, working_path, settings_key
+ )
+ if claude_session_id:
+ logger.info(
+ f"Captured Claude session id {claude_session_id} for {base_session_id}"
+ )
+
+ if self.claude_client._is_skip_message(message):
+ continue
+
+ message_type = self._detect_message_type(message)
+ if message_type and self.settings_manager.is_message_type_hidden(
+ settings_key, message_type
+ ):
+ continue
+
+ formatted_message = self.claude_client.format_message(
+ message,
+ get_relative_path=lambda path: self.get_relative_path(
+ path, context
+ ),
+ )
+ if not formatted_message or not formatted_message.strip():
+ continue
+
+ if self.config.platform == "slack":
+ formatted_message = formatted_message + "\n---"
+
+ await self.controller.emit_agent_message(
+ context,
+ message_type or "assistant",
+ formatted_message,
+ parse_mode="markdown",
+ )
+
+ if message_type == "result":
+ session = await self.session_manager.get_or_create_session(
+ context.user_id, context.channel_id
+ )
+ if session:
+ session.session_active[
+ f"{base_session_id}:{working_path}"
+ ] = False
+ except Exception as e:
+ logger.error(
+ f"Error processing message from Claude: {e}", exc_info=True
+ )
+ continue
+ except Exception as e:
+ composite_key = f"{base_session_id}:{working_path}"
+ logger.error(
+ f"Error in Claude receiver for session {composite_key}: {e}",
+ exc_info=True,
+ )
+ await self.session_handler.handle_session_error(composite_key, context, e)
+
+ async def _delete_ack(self, context: MessageContext, 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(context.channel_id, ack_id)
+ except Exception as err:
+ logger.debug(f"Could not delete ack message: {err}")
+ finally:
+ request.ack_message_id = None
+
+ def get_relative_path(
+ self, abs_path: str, context: Optional[MessageContext] = None
+ ) -> str:
+ """Convert absolute path to relative path from working directory."""
+ try:
+ cwd = self.session_handler.get_working_path(context)
+ abs_path = os.path.abspath(os.path.expanduser(abs_path))
+ rel_path = os.path.relpath(abs_path, cwd)
+ if rel_path.startswith("../.."):
+ return abs_path
+ return rel_path
+ except Exception:
+ return abs_path
+
+ def _get_target_context(self, context: MessageContext) -> MessageContext:
+ """Return context for sending messages (respect Slack thread replies)."""
+ if self.im_client.should_use_thread_for_reply() and context.thread_id:
+ return MessageContext(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ thread_id=context.thread_id,
+ message_id=context.message_id,
+ platform_specific=context.platform_specific,
+ )
+ return context
+
+ def _maybe_capture_session_id(
+ self,
+ message,
+ base_session_id: str,
+ working_path: str,
+ settings_key: str,
+ ) -> Optional[str]:
+ """Capture session id from system init messages."""
+ if (
+ hasattr(message, "__class__")
+ and message.__class__.__name__ == "SystemMessage"
+ and getattr(message, "subtype", None) == "init"
+ and getattr(message, "data", None)
+ ):
+ session_id = message.data.get("session_id")
+ if session_id:
+ self.session_handler.capture_session_id(
+ base_session_id, working_path, session_id, settings_key
+ )
+ return session_id
+ return None
+
+ def _detect_message_type(self, message) -> Optional[str]:
+ """Infer message type name from Claude SDK class."""
+ if not hasattr(message, "__class__"):
+ return None
+ class_name = message.__class__.__name__
+ mapping = {
+ "SystemMessage": "system",
+ "UserMessage": "user",
+ "AssistantMessage": "assistant",
+ "ResultMessage": "result",
+ }
+ return mapping.get(class_name)
diff --git a/modules/agents/codex_agent.py b/modules/agents/codex_agent.py
new file mode 100644
index 000000000..eeb9e88ee
--- /dev/null
+++ b/modules/agents/codex_agent.py
@@ -0,0 +1,263 @@
+import asyncio
+import json
+import logging
+import os
+from asyncio.subprocess import Process
+from typing import Dict, Optional, Tuple
+
+from modules.agents.base import AgentRequest, BaseAgent
+
+logger = logging.getLogger(__name__)
+
+
+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._initialized_sessions: set[str] = set()
+
+ async def handle_message(self, request: AgentRequest) -> None:
+ resume_id = self.settings_manager.get_agent_session_id(
+ request.settings_key,
+ request.base_session_id,
+ request.working_path,
+ agent_name=self.name,
+ )
+
+ if not os.path.exists(request.working_path):
+ os.makedirs(request.working_path, exist_ok=True)
+
+ cmd = self._build_command(request, resume_id)
+ try:
+ process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ cwd=request.working_path,
+ )
+ except FileNotFoundError:
+ await self.controller.emit_agent_message(
+ request.context,
+ "system",
+ "❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",
+ )
+ 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, "system", f"❌ Failed to start Codex CLI: {e}"
+ )
+ return
+
+ await self._delete_ack(request)
+
+ self.active_processes[request.composite_session_id] = (
+ process,
+ request.settings_key,
+ )
+
+ 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.active_processes.pop(request.composite_session_id, None)
+
+ if process.returncode != 0:
+ await self.controller.emit_agent_message(
+ request.context,
+ "system",
+ "⚠️ 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, (proc, stored_key) in list(self.active_processes.items()):
+ if stored_key == settings_key:
+ proc.kill()
+ terminated += 1
+ self.active_processes.pop(key, None)
+ return terminated
+
+ async def handle_stop(self, request: AgentRequest) -> bool:
+ entry = self.active_processes.get(request.composite_session_id)
+ if not entry:
+ return False
+ proc, _ = entry
+ proc.kill()
+ await self.controller.emit_agent_message(
+ request.context, "system", "🛑 Terminated Codex execution."
+ )
+ return True
+
+ def _build_command(self, request: AgentRequest, resume_id: Optional[str]) -> list:
+ cmd = [self.codex_config.binary, "exec", "--json"]
+ cmd += ["--dangerously-bypass-approvals-and-sandbox"]
+
+ if self.codex_config.enable_full_auto:
+ cmd += ["--full-auto"]
+
+ if self.codex_config.default_model:
+ cmd += ["--model", self.codex_config.default_model]
+
+ 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
+ while True:
+ line = await process.stdout.readline()
+ 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)
+
+ 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,
+ "system",
+ f"```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,
+ request.working_path,
+ thread_id,
+ )
+ session_key = request.composite_session_id
+ if session_key not in self._initialized_sessions:
+ self._initialized_sessions.add(session_key)
+ system_text = (
+ ":wrench: System init\n"
+ f":file_folder: Working directory: {request.working_path}\n"
+ f":link: Session ID: {thread_id}\n"
+ ":sparkles: Ready to work!\n---"
+ )
+ 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:
+ await self.controller.emit_agent_message(
+ request.context, "assistant", text, parse_mode="markdown"
+ )
+ request.last_agent_message = text
+ elif item_type == "command_execution":
+ command = details.get("command")
+ output = details.get("aggregated_output", "")
+ status = details.get("status")
+ message_parts = [f"🛠️ `{command}` → {status}"]
+ if output:
+ snippet = output[-2000:]
+ message_parts.append(f"```shell\n{snippet}\n```")
+ await self.controller.emit_agent_message(
+ request.context,
+ "assistant",
+ "\n".join(message_parts),
+ parse_mode="markdown",
+ )
+ elif item_type == "reasoning":
+ text = details.get("text", "")
+ if text:
+ await self.controller.emit_agent_message(
+ request.context,
+ "response",
+ f"_🧠 {text}_",
+ parse_mode="markdown",
+ )
+ return
+
+ if event_type == "error":
+ message = event.get("message", "Unknown error")
+ await self.controller.emit_agent_message(
+ request.context, "system", 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, "system", f"⚠️ Codex turn failed: {error}"
+ )
+ request.last_agent_message = None
+ return
+
+ if event_type == "turn.completed":
+ if request.last_agent_message:
+ await self.controller.emit_agent_message(
+ request.context,
+ "result",
+ request.last_agent_message,
+ parse_mode="markdown",
+ )
+ request.last_agent_message = None
+ 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
diff --git a/modules/agents/service.py b/modules/agents/service.py
new file mode 100644
index 000000000..d37b6925e
--- /dev/null
+++ b/modules/agents/service.py
@@ -0,0 +1,41 @@
+import logging
+from typing import Dict, Optional
+
+from .base import AgentRequest, BaseAgent
+
+logger = logging.getLogger(__name__)
+
+
+class AgentService:
+ """Registry and dispatcher for agent implementations."""
+
+ def __init__(self, controller):
+ self.controller = controller
+ self.agents: Dict[str, BaseAgent] = {}
+ self.default_agent = "claude"
+
+ def register(self, agent: BaseAgent):
+ self.agents[agent.name] = agent
+ logger.info(f"Registered agent backend: {agent.name}")
+
+ def get(self, agent_name: Optional[str]) -> BaseAgent:
+ target = agent_name or self.default_agent
+ if target in self.agents:
+ return self.agents[target]
+ raise KeyError(target)
+
+ async def handle_message(self, agent_name: str, request: AgentRequest):
+ agent = self.get(agent_name)
+ await agent.handle_message(request)
+
+ async def clear_sessions(self, settings_key: str) -> Dict[str, int]:
+ cleared: Dict[str, int] = {}
+ for name, agent in self.agents.items():
+ count = await agent.clear_sessions(settings_key)
+ if count:
+ cleared[name] = count
+ return cleared
+
+ async def handle_stop(self, agent_name: str, request: AgentRequest) -> bool:
+ agent = self.get(agent_name)
+ return await agent.handle_stop(request)
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 888b44ebe..214a24286 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1,5 +1,6 @@
import asyncio
import logging
+import time
from typing import Dict, Any, Optional, Callable
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.socket_mode.aiohttp import SocketModeClient
@@ -41,11 +42,27 @@ class SlackBot(BaseIMClient):
# Settings manager for thread tracking (will be injected later)
self.settings_manager = None
+ self._recent_event_ids: Dict[str, float] = {}
def set_settings_manager(self, settings_manager):
"""Set the settings manager for thread tracking"""
self.settings_manager = settings_manager
+ def _is_duplicate_event(self, event_id: Optional[str]) -> bool:
+ """Deduplicate Slack events using event_id with a short TTL."""
+ if not event_id:
+ return False
+ now = time.time()
+ expiry = now - 30 # retain for 30s
+ for key in list(self._recent_event_ids.keys()):
+ if self._recent_event_ids[key] < expiry:
+ del self._recent_event_ids[key]
+ if event_id in self._recent_event_ids:
+ logger.debug(f"Ignoring duplicate Slack event_id {event_id}")
+ return True
+ self._recent_event_ids[event_id] = now
+ return False
+
def get_default_parse_mode(self) -> str:
"""Get the default parse mode for Slack"""
return "markdown"
@@ -316,6 +333,9 @@ class SlackBot(BaseIMClient):
"""Handle Events API events"""
event = payload.get("event", {})
event_type = event.get("type")
+ event_id = payload.get("event_id")
+ if self._is_duplicate_event(event_id):
+ return
if event_type == "message":
# Ignore bot messages
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index a2ca45200..c7855501f 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -3,7 +3,7 @@ import logging
import os
import time
from dataclasses import dataclass, asdict, field
-from typing import Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional, Union
from pathlib import Path
@@ -18,8 +18,10 @@ class UserSettings:
default_factory=list
) # Message types to hide
custom_cwd: Optional[str] = None # Custom working directory
- # Nested map: {base_session_id: {working_path: claude_session_id}}
- session_mappings: Dict[str, Dict[str, str]] = field(default_factory=dict)
+ # Nested map: {agent_name: {base_session_id: {working_path: session_id}}}
+ session_mappings: Dict[str, Dict[str, Dict[str, str]]] = field(
+ default_factory=dict
+ )
# Slack active threads: {channel_id: {thread_ts: last_active_timestamp}}
active_slack_threads: Dict[str, Dict[str, float]] = field(default_factory=dict)
@@ -59,14 +61,13 @@ class SettingsManager:
with open(self.settings_file, "r") as f:
data = json.load(f)
for user_id_str, user_data in data.items():
- # Clean up old format session mappings, only keep nested dict format
+ # Normalize session mappings to agent-aware structure
if "session_mappings" in user_data:
- cleaned_mappings = {}
- for key, value in user_data["session_mappings"].items():
- # Only keep nested dictionary format
- if isinstance(value, dict):
- cleaned_mappings[key] = value
- user_data["session_mappings"] = cleaned_mappings
+ user_data["session_mappings"] = (
+ self._normalize_session_mappings(
+ user_data["session_mappings"]
+ )
+ )
# Ensure active_slack_threads exists and is properly formatted
if "active_slack_threads" not in user_data:
@@ -82,6 +83,39 @@ class SettingsManager:
logger.error(f"Error loading settings: {e}")
self.settings = {}
+ def _normalize_session_mappings(
+ self, mappings: Dict[str, Any]
+ ) -> Dict[str, Dict[str, Dict[str, str]]]:
+ """Normalize legacy session mapping schema into agent-aware structure."""
+ normalized: Dict[str, Dict[str, Dict[str, str]]] = {}
+
+ if not isinstance(mappings, dict):
+ return normalized
+
+ def is_path_map(value) -> bool:
+ return isinstance(value, dict) and all(
+ isinstance(v, str) for v in value.values()
+ )
+
+ # Detect new-format structure: {agent: {base_session_id: {path: session_id}}}
+ is_new_format = all(
+ isinstance(agent_map, dict) and all(is_path_map(path_map) for path_map in agent_map.values())
+ for agent_map in mappings.values()
+ )
+ if is_new_format:
+ return mappings
+
+ # Legacy structure: {base_session_id: {path: session_id}}
+ legacy_entries = {}
+ for base_session_id, path_map in mappings.items():
+ if is_path_map(path_map):
+ legacy_entries[base_session_id] = path_map
+
+ if legacy_entries:
+ normalized["claude"] = legacy_entries
+
+ return normalized
+
def _save_settings(self):
"""Save settings to JSON file"""
try:
@@ -163,65 +197,131 @@ class SettingsManager:
"result": "Result",
}
- def set_session_mapping(
+ def _ensure_agent_namespace(
+ self, settings: UserSettings, agent_name: str
+ ) -> Dict[str, Dict[str, str]]:
+ """Ensure nested dict for an agent exists."""
+ if agent_name not in settings.session_mappings:
+ settings.session_mappings[agent_name] = {}
+ return settings.session_mappings[agent_name]
+
+ def set_agent_session_mapping(
self,
user_id: Union[int, str],
+ agent_name: str,
base_session_id: str,
working_path: str,
- claude_session_id: str,
+ session_id: str,
):
- """Store mapping between base session ID, working path, and Claude session ID"""
+ """Store mapping between base session ID, working path, and agent session ID"""
settings = self.get_user_settings(user_id)
- if base_session_id not in settings.session_mappings:
- settings.session_mappings[base_session_id] = {}
- settings.session_mappings[base_session_id][working_path] = claude_session_id
+ agent_map = self._ensure_agent_namespace(settings, agent_name)
+ if base_session_id not in agent_map:
+ agent_map[base_session_id] = {}
+ agent_map[base_session_id][working_path] = session_id
self.update_user_settings(user_id, settings)
logger.info(
- f"Stored session mapping for user {user_id}: {base_session_id}[{working_path}] -> {claude_session_id}"
+ f"Stored {agent_name} session mapping for user {user_id}: "
+ f"{base_session_id}[{working_path}] -> {session_id}"
)
- def get_claude_session_id(
- self, user_id: Union[int, str], base_session_id: str, working_path: str
+ def get_agent_session_id(
+ self,
+ user_id: Union[int, str],
+ base_session_id: str,
+ working_path: str,
+ agent_name: str,
) -> Optional[str]:
- """Get Claude session ID for given base session ID and working path"""
+ """Get agent session ID for given base session ID and working path"""
settings = self.get_user_settings(user_id)
- if base_session_id in settings.session_mappings:
- return settings.session_mappings[base_session_id].get(working_path)
+ agent_map = settings.session_mappings.get(agent_name, {})
+ if base_session_id in agent_map:
+ return agent_map[base_session_id].get(working_path)
return None
- def clear_session_mapping(
+ def clear_agent_session_mapping(
self,
user_id: Union[int, str],
+ agent_name: str,
base_session_id: str,
working_path: Optional[str] = None,
):
"""Clear session mapping for given base session ID and optionally working path"""
settings = self.get_user_settings(user_id)
- if base_session_id in settings.session_mappings:
+ agent_map = settings.session_mappings.get(agent_name, {})
+ if base_session_id in agent_map:
if working_path:
- # Clear specific path mapping
- if working_path in settings.session_mappings[base_session_id]:
- del settings.session_mappings[base_session_id][working_path]
+ if working_path in agent_map[base_session_id]:
+ del agent_map[base_session_id][working_path]
logger.info(
- f"Cleared session mapping for user {user_id}: {base_session_id}[{working_path}]"
+ f"Cleared {agent_name} session mapping for user {user_id}: "
+ f"{base_session_id}[{working_path}]"
)
else:
- # Clear all mappings for this base session
- del settings.session_mappings[base_session_id]
+ del agent_map[base_session_id]
logger.info(
- f"Cleared all session mappings for user {user_id}: {base_session_id}"
+ f"Cleared all {agent_name} session mappings for user {user_id}: {base_session_id}"
)
self.update_user_settings(user_id, settings)
+ def clear_agent_sessions(self, user_id: Union[int, str], agent_name: str):
+ """Clear every session mapping for the specified agent."""
+ settings = self.get_user_settings(user_id)
+ if agent_name in settings.session_mappings:
+ del settings.session_mappings[agent_name]
+ logger.info(
+ f"Cleared all {agent_name} session namespaces for user {user_id}"
+ )
+ self.update_user_settings(user_id, settings)
+
def clear_all_session_mappings(self, user_id: Union[int, str]):
- """Clear all session mappings for a user"""
+ """Clear all session mappings for a user across agents"""
settings = self.get_user_settings(user_id)
if settings.session_mappings:
- count = len(settings.session_mappings)
+ count = sum(len(agent_map) for agent_map in settings.session_mappings.values())
settings.session_mappings.clear()
- logger.info(f"Cleared all {count} session mappings for user {user_id}")
+ logger.info(
+ f"Cleared all session mappings ({count} bases) for user {user_id}"
+ )
self.update_user_settings(user_id, settings)
+ def list_agent_session_bases(
+ self, user_id: Union[int, str], agent_name: str
+ ) -> Dict[str, Dict[str, str]]:
+ """Get copy of session mappings for an agent."""
+ settings = self.get_user_settings(user_id)
+ agent_map = settings.session_mappings.get(agent_name, {})
+ return {base: paths.copy() for base, paths in agent_map.items()}
+
+ # Backwards-compatible helpers for Claude-specific call sites
+ def set_session_mapping(
+ self,
+ user_id: Union[int, str],
+ base_session_id: str,
+ working_path: str,
+ claude_session_id: str,
+ ):
+ self.set_agent_session_mapping(
+ user_id, "claude", base_session_id, working_path, claude_session_id
+ )
+
+ def get_claude_session_id(
+ self, user_id: Union[int, str], base_session_id: str, working_path: str
+ ) -> Optional[str]:
+ return self.get_agent_session_id(
+ user_id, base_session_id, working_path, agent_name="claude"
+ )
+
+ def clear_session_mapping(
+ self,
+ user_id: Union[int, str],
+ base_session_id: str,
+ working_path: Optional[str] = None,
+ ):
+ self.clear_agent_session_mapping(
+ user_id, "claude", base_session_id, working_path
+ )
+
# ---------------------------------------------
# Slack thread management
# ---------------------------------------------
diff --git a/requirements.txt b/requirements.txt
index 49ec16de7..21902e639 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -6,4 +6,6 @@ slack-sdk>=3.26.0
aiohttp>=3.8.0
telegramify-markdown>=0.5.0
markdown_to_mrkdwn>=0.2.0
-typing_extensions>=4.12.2
\ No newline at end of file
+typing_extensions>=4.12.2
+PyYAML>=6.0
+dotenv==0.9.9
\ No newline at end of file