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
refactor(v2): move config to home dir and drop telegram
cyhhao0c3d0c1af7bb
diff --git a/AGENTS.md b/AGENTS.mdindex 8f2952d49..7a6fc6a46 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -48,28 +48,27 @@ This file defines how coding agents should work in this repository.### Structure-- Entry point: `main.py` wires `config.AppConfig` into `core/controller.py`.+- Entry point: `main.py` wires `config.V2Config` into `core/controller.py`.- Core orchestration and handlers: `core/` (notably `core/handlers/`).- Agent backends: `modules/agents/` (shared base, OpenCode/Claude/Codex backends, registry).-- IM transports: `modules/im/` (Slack/Telegram).+- IM transports: `modules/im/` (Slack-first; platform abstraction retained).- Config:- - Defaults and validation: `config/` (see `config/settings.py`).+ - Defaults and validation: `config/` (see `config/v2_config.py`).- Agent routing: optional local `agent_routes.yaml` (gitignored).- Runtime data:- - Logs: `logs/vibe_remote.log`.- - Persisted state: `user_settings.json`.- - Default remote working dir: `_tmp/`.+- Logs: `~/.vibe_remote/logs/vibe_remote.log`.+- Persisted state: `~/.vibe_remote/state/`.+- Default remote working dir: `_tmp/`.+### Common Commands- Setup:- - `python -m venv .venv && source .venv/bin/activate`- - `pip install -r requirements.txt`- - `cp .env.example .env`+ - `uv tool install vibe`- Run:- - `./start.sh` (preferred) or `python main.py`- - `./status.sh` / `./stop.sh`- - Restart: run `./start.sh` directly+ - `vibe`+ - `vibe status` / `vibe stop`+ - Restart: run `vibe`### Release Notes@@ -87,7 +86,7 @@ This file defines how coding agents should work in this repository.- No committed automated suite yet.- Prefer fast `pytest`-style tests (`test_<feature>.py`) colocated or under `tests/`.-- For IM integrations, stub Slack/Telegram clients and validate outbound payload schemas.+- For IM integrations, stub Slack clients and validate outbound payload schemas.- Do a manual E2E sanity check (start bot, send `/start`) until CI exists.### Agent Routing@@ -97,7 +96,7 @@ This file defines how coding agents should work in this repository.- Routing file:- Create `agent_routes.yaml` (local) only if you prefer file-based routing (legacy).- Controlled by `AGENT_ROUTE_FILE` (defaults to repo-root `agent_routes.yaml`).- - Keys are Slack channel IDs / Telegram chat IDs; values are agent names (e.g., `opencode`, `claude`, `codex`).+ - Keys are Slack channel IDs; values are agent names (e.g., `opencode`, `claude`, `codex`).- Missing entries fall back to platform default, then to global default.### Safety Notesdiff --git a/CLAUDE.md b/CLAUDE.mdindex 5f09bded1..b2528f00c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -41,27 +41,26 @@ This file defines how coding agents should work in this repository.### Structure-- Entry point: `main.py` wires `config.AppConfig` into `core/controller.py`.+- Entry point: `main.py` wires `config.V2Config` into `core/controller.py`.- Core orchestration and handlers: `core/` (notably `core/handlers/`).- Agent backends: `modules/agents/` (shared base, OpenCode/Claude/Codex backends, registry).-- IM transports: `modules/im/` (Slack/Telegram).+- IM transports: `modules/im/` (Slack-first; platform abstraction retained).- Config:- - Defaults and validation: `config/` (see `config/settings.py`).+ - Defaults and validation: `config/` (see `config/v2_config.py`).- Agent routing: optional local `agent_routes.yaml` (gitignored).- Runtime data:- - Logs: `logs/vibe_remote.log`.- - Persisted state: `user_settings.json`.- - Default remote working dir: `_tmp/`.+- Logs: `~/.vibe_remote/logs/vibe_remote.log`.+- Persisted state: `~/.vibe_remote/state/`.+- Default remote working dir: `_tmp/`.+### Common Commands- Setup:- - `python -m venv .venv && source .venv/bin/activate`- - `pip install -r requirements.txt`- - `cp .env.example .env`+ - `uv tool install vibe`- Run:- - `./start.sh` (preferred) or `python main.py`- - `./status.sh` / `./stop.sh`+ - `vibe`+ - `vibe status` / `vibe stop`### Coding Conventions@@ -75,7 +74,7 @@ This file defines how coding agents should work in this repository.- No committed automated suite yet.- Prefer fast `pytest`-style tests (`test_<feature>.py`) colocated or under `tests/`.-- For IM integrations, stub Slack/Telegram clients and validate outbound payload schemas.+- For IM integrations, stub Slack clients and validate outbound payload schemas.- Do a manual E2E sanity check (start bot, send `/start`) until CI exists.### Agent Routing@@ -85,7 +84,7 @@ This file defines how coding agents should work in this repository.- Routing file:- Create `agent_routes.yaml` (local) only if you prefer file-based routing (legacy).- Controlled by `AGENT_ROUTE_FILE` (defaults to repo-root `agent_routes.yaml`).- - Keys are Slack channel IDs / Telegram chat IDs; values are agent names (e.g., `opencode`, `claude`, `codex`).+ - Keys are Slack channel IDs; values are agent names (e.g., `opencode`, `claude`, `codex`).- Missing entries fall back to platform default, then to global default.### Safety Notesdiff --git a/README.md b/README.mdindex b9ffc4a74..2032f97ca 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@[Quick Start](#quick-start) · [Configuration](#configuration) · [Usage](#usage) · [Setup Guides](#setup-guides) · [Roadmap](#roadmap)[](https://www.python.org/)-[](#setup-guides)+[](#setup-guides)[](LICENSE)[](CONTRIBUTING.md)@@ -17,24 +17,24 @@</div>-_Remote vibe coding over chat — control AI coding agents (OpenCode, Claude Code, Codex, Cursor, etc.) from Slack/Telegram._+_Remote vibe coding over chat — control AI coding agents (OpenCode, Claude Code, Codex, Cursor, etc.) from Slack._-Vibe Remote lets you operate coding agents via IM. Type in Slack or Telegram to start and steer agents; describe intent and constraints, receive streaming results, and ship without being tied to a local IDE.+Vibe Remote lets you operate coding agents via Slack. Type in Slack to start and steer agents; describe intent and constraints, receive streaming results, and ship without being tied to a local IDE.## Why Vibe Remote- **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.+- **Work from anywhere**: Control coding sessions over Slack; no IDE tether.- **Extensible by design**: OpenCode-first, and also supports Claude Code + Codex; built to support additional coding agents/CLIs.-- **Multi-agent routing**: Route each Slack channel / Telegram chat to OpenCode, Claude Code, or Codex via `agent_routes.yaml` (and Slack UI when enabled).-- **Session persistence by thread + path**: Each Slack thread/Telegram chat maintains its own agent session and working dir; auto‑resume via saved mappings.+- **Multi-agent routing**: Route each Slack channel to OpenCode, Claude Code, or Codex via `agent_routes.yaml` (and Slack UI when enabled).+- **Session persistence by thread + path**: Each Slack thread maintains its own agent session and working dir; auto‑resume via saved mappings.- **Interactive Slack UX**: `/start` menu + Settings/CWD modals; buttons over commands for faster flow.> Recommendation: Prefer Slack as the primary platform. Threaded conversations enable parallel subtasks and keep channel history tidy — each subtask stays in its own thread.## Core Features-- **Multi‑platform**: First‑class Slack & Telegram support+- **Platform-first**: Slack-first today; platform abstraction retained for future Vibe app- **Hands‑free flow**: Minimal review; messages stream back in real time- **Persistent sessions**: Per chat/thread sessions, easy resume- **Threaded Slack UX**: Clean, per‑conversation threads@@ -43,8 +43,8 @@ Vibe Remote lets you operate coding agents via IM. Type in Slack or Telegram to## Architecture (Brief)-- `BaseIMClient` + platform implementations (`slack.py`, `telegram.py`)-- `IMFactory` to construct clients by `IM_PLATFORM`+- `BaseIMClient` + platform implementations (`slack.py`)+- `IMFactory` to construct clients by platform config- `Controller` orchestrates sessions, formatting, and command routing## Prerequisites@@ -92,43 +92,25 @@ claude --help## Quick Start-1. Install dependencies+1. Install```bash-pip install -r requirements.txt+curl -fsSL https://vibe.remote/install.sh | bash```-2. Create and edit `.env`+2. Run```bash-cp .env.example .env-# Set IM_PLATFORM and tokens-```--3. Run--```bash-./start.sh-# or-python main.py+vibe```## Configuration-### Platform selection--- `IM_PLATFORM=slack` or `IM_PLATFORM=telegram`-### Slack- `SLACK_BOT_TOKEN` (xoxb-...)- `SLACK_APP_TOKEN` (xapp-..., Socket Mode)-- `SLACK_TARGET_CHANNEL` optional whitelist of allowed channel IDs (channels only, start with `C`). Leave empty or omit to accept all channels. DMs are not supported currently.--### Telegram--- `TELEGRAM_BOT_TOKEN` from @BotFather-- `TELEGRAM_TARGET_CHAT_ID` optional whitelist: `[123,...]` | `[]` only DMs | `null` all+- `SLACK_TARGET_CHANNELS` optional whitelist of allowed channel IDs (channels only, start with `C`). Leave empty or omit to accept all channels. DMs are not supported currently.### Claude Code@@ -148,7 +130,7 @@ python main.py- OpenCode is enabled by `OPENCODE_ENABLED=true` (default: false). Ensure `opencode` is installed.- OpenCode runs as a local HTTP server started by Vibe Remote (`opencode serve --hostname=127.0.0.1 --port=4096`).-- Default agent/model settings are read from `~/.config/opencode/opencode.json`, and can be overridden per Slack channel via the Agent Settings dialog (if you use Slack).+- Default agent/model settings are read from `~/.config/opencode/opencode.json`, and can be overridden per Slack channel via the Agent Settings dialog.### Agent routing@@ -163,13 +145,9 @@ slack:default: opencodeoverrides:C01EXAMPLE: codex-telegram:- default: opencode- overrides:- "123456789": codex```-- Slack routes use channel IDs; Telegram routes use chat IDs.+- Slack routes use channel IDs.- See [docs/CODEX_SETUP.md](docs/CODEX_SETUP.md) for Codex install and routing notes.- No routing file? If OpenCode is enabled, the bot defaults to OpenCode; otherwise it falls back to Claude.@@ -179,7 +157,7 @@ telegram:## Usage-### Commands (all platforms)+### Commands- `/start` open menu / welcome- `/clear` reset conversation/session@@ -204,15 +182,9 @@ Use `SubagentName:` or `SubagentName:` at the start of a message (leading spac- Slack DMs are not supported currently- Slash commands are limited in threads; to stop in a thread, type `stop` directly-### Telegram--- DM or group; run `/start` then type naturally-- Real‑time streaming; long outputs are split and code blocks are formatted-## Setup Guides- Slack: [English](docs/SLACK_SETUP.md) | [中文](docs/SLACK_SETUP_ZH.md)-- Telegram: [English](docs/TELEGRAM_SETUP.md) | [中文](docs/TELEGRAM_SETUP_ZH.md)## Releases@@ -235,8 +207,8 @@ MIT. See `LICENSE`.## Security & Ops-- **Secrets**: Never commit tokens. Use `.env`. Rotate regularly.-- **Whitelists**: Restrict access via `SLACK_TARGET_CHANNEL` (channels only, `C…`) or `TELEGRAM_TARGET_CHAT_ID`. `null` accepts all; empty list limits to DMs/groups accordingly (Slack DMs currently unsupported).-- **Logs**: Runtime logs at `logs/vibe_remote.log`.-- **Session persistence**: `user_settings.json` stores per‑thread/chat session mappings and preferences; persist this file in production.+- **Secrets**: Never commit tokens. Store in `~/.vibe_remote/config/config.json` or your secret manager.+- **Whitelists**: Restrict access via `SLACK_TARGET_CHANNELS` (channels only, `C…`). Leave empty to accept all channels (Slack DMs currently unsupported).+- **Logs**: Runtime logs at `~/.vibe_remote/logs/vibe_remote.log`.+- **Session persistence**: `~/.vibe_remote/state/sessions.json` stores per‑thread session mappings; persist this file in production.- **Cleanup**: Set `CLEANUP_ENABLED=true` to safely prune completed receiver tasks during message handling for long‑running processes.diff --git a/README_ZH.md b/README_ZH.mdindex 67a5caf33..c6d1be648 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -7,7 +7,7 @@[快速开始](#快速开始) · [配置](#配置) · [使用方式](#使用方式) · [安装指南](#setup-guides) · [Roadmap](#roadmap)[](https://www.python.org/)-[](#setup-guides)+[](#setup-guides)[](LICENSE)[](CONTRIBUTING.md)@@ -17,24 +17,24 @@</div>-_在 Slack/Telegram 里通过聊天远程操控 AI 代理(如 OpenCode、Claude Code、Codex、Cursor),进行 Vibe Coding。_+_在 Slack 里通过聊天远程操控 AI 代理(如 OpenCode、Claude Code、Codex、Cursor),进行 Vibe Coding。_-Vibe Remote 把 AI 写代码搬到聊天软件。你在 Slack/Telegram 输入意图与约束,它会驱动相应的 AI agent 执行并反馈;结果实时流式返回,无需本地 IDE,随时随地推进任务。+Vibe Remote 把 AI 写代码搬到聊天软件。你在 Slack 输入意图与约束,它会驱动相应的 AI agent 执行并反馈;结果实时流式返回,无需本地 IDE,随时随地推进任务。## 为什么选择 Vibe Remote- **专注 vibe coding**:基于你的意图与约束让 AI 自主推进,你只把控方向与结果。-- **随时随地**:不被 IDE 束缚,直接在 Slack/Telegram 中远程操控编码会话。+- **随时随地**:不被 IDE 束缚,直接在 Slack 中远程操控编码会话。- **为扩展而生**:OpenCode 优先,同时支持 Claude Code + Codex;并可扩展到更多 coding agents/CLIs。-- **多 Agent 路由**:为不同 Slack Channel / Telegram Chat 指定 OpenCode / Claude Code / Codex,互不干扰。-- **按线程 + 路径持久化**:每个 Slack 线程/Telegram 对话都维持独立 Agent 会话与工作目录,并通过持久化映射自动恢复。+- **多 Agent 路由**:为不同 Slack Channel 指定 OpenCode / Claude Code / Codex,互不干扰。+- **按线程 + 路径持久化**:每个 Slack 线程维持独立 Agent 会话与工作目录,并通过持久化映射自动恢复。- **Slack 交互式体验**:`/start` 菜单 + Settings/CWD 模态,按钮优先于命令,更快上手。> 推荐:优先使用 Slack 作为主要平台。其线程模型更适合并行子任务,也能保持频道历史整洁(每个子任务都在各自的线程里)。## 核心特性-- **多平台**:原生支持 Slack 与 Telegram+- **平台优先**:V2 先聚焦 Slack;平台抽象保留以支持未来 Vibe App- **免干预工作流**:最小 review,实时流式回传消息- **持久会话**:按聊天/线程维度持久化,可随时恢复- **Slack 线程化 UX**:每个会话独立线程,保持频道整洁@@ -43,8 +43,8 @@ Vibe Remote 把 AI 写代码搬到聊天软件。你在 Slack/Telegram 输入意## 架构(简述)-- `BaseIMClient` + 平台实现(`modules/im/slack.py`、`modules/im/telegram.py`)-- `IMFactory` 通过 `IM_PLATFORM` 动态创建客户端+- `BaseIMClient` + 平台实现(`modules/im/slack.py`)+- `IMFactory` 通过配置创建客户端- `Controller` 统一编排会话、格式化与命令路由## 先决条件@@ -92,43 +92,25 @@ claude --help## 快速开始-1. 安装依赖+1. 安装```bash-pip install -r requirements.txt+curl -fsSL https://vibe.remote/install.sh | bash```-2. 创建并编辑 `.env`+2. 运行```bash-cp .env.example .env-# 设置 IM_PLATFORM 与各自的 Token-```--3. 运行--```bash-./start.sh-# 或-python main.py+vibe```## 配置-### 平台选择--- `IM_PLATFORM=slack` 或 `IM_PLATFORM=telegram`-### Slack- `SLACK_BOT_TOKEN`(xoxb-...)- `SLACK_APP_TOKEN`(xapp-...,用于 Socket Mode)-- `SLACK_TARGET_CHANNEL` 可选的频道 ID 白名单(仅频道,形如 `C...`)。留空或省略为接受所有频道。当前不支持 Slack DM。--### Telegram--- `TELEGRAM_BOT_TOKEN` 来自 @BotFather-- `TELEGRAM_TARGET_CHAT_ID` 可选的聊天白名单:`[123,...]` | `[]` 仅私聊 | `null` 允许全部+- `SLACK_TARGET_CHANNELS` 可选的频道 ID 白名单(仅频道,形如 `C...`)。留空或省略为接受所有频道。当前不支持 Slack DM。### Claude Code@@ -163,13 +145,9 @@ slack:default: opencodeoverrides:C01EXAMPLE: codex-telegram:- default: opencode- overrides:- "123456789": codex```-- Slack 使用频道 ID,Telegram 使用聊天 ID。+- Slack 使用频道 ID。- 参见 [docs/CODEX_SETUP.md](docs/CODEX_SETUP.md) 获取 Codex 安装与路由说明。- 未提供路由文件时:如果启用了 OpenCode,则默认使用 OpenCode;否则回退到 Claude。@@ -179,7 +157,7 @@ telegram:## 使用方式-### Commands(全平台)+### Commands- `/start` 打开菜单/欢迎信息- `/clear` 重置对话/会话@@ -204,15 +182,9 @@ telegram:- 当前不支持 Slack DM- Slash 命令在线程中受限;要在线程内停止,请直接输入 `stop`-### Telegram--- 支持私聊/群组;先运行 `/start` 然后直接对话-- 支持实时流式输出;长消息自动分割;代码块自动格式化-## Setup Guides- Slack: [English](docs/SLACK_SETUP.md) | [中文](docs/SLACK_SETUP_ZH.md)-- Telegram: [English](docs/TELEGRAM_SETUP.md) | [中文](docs/TELEGRAM_SETUP_ZH.md)## Releases@@ -235,8 +207,8 @@ MIT,详见 `LICENSE`。## Security & Ops-- **Secrets**:不要提交 Token;使用 `.env`,并定期轮换。-- **Whitelists**:通过 `SLACK_TARGET_CHANNEL`(仅频道,`C…`)或 `TELEGRAM_TARGET_CHAT_ID` 限制访问。`null` 允许全部;空列表则只在相应上下文生效(Slack DM 当前不支持)。-- **Logs**:运行日志位于 `logs/vibe_remote.log`。-- **会话持久化**:`user_settings.json` 存储每个线程/聊天的会话映射与偏好;生产环境请持久化此文件。+- **Secrets**:不要提交 Token;存储在 `~/.vibe_remote/config/config.json` 或你的密钥管理系统。+- **Whitelists**:通过 `SLACK_TARGET_CHANNELS`(仅频道,`C…`)限制访问。留空允许全部频道(Slack DM 当前不支持)。+- **Logs**:运行日志位于 `~/.vibe_remote/logs/vibe_remote.log`。+- **会话持久化**:`~/.vibe_remote/state/sessions.json` 存储每个线程的会话映射;生产环境请持久化此文件。- **清理**:设置 `CLEANUP_ENABLED=true`,在消息处理入口安全清理已完成的接收任务,适合长时间运行。diff --git a/SECURITY.md b/SECURITY.mdindex 703c6d11a..3f19b608b 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -5,5 +5,5 @@- Do not disclose publicly until we confirm a fix or mitigation.## Secrets-- Never commit secrets. Use environment variables (`.env` is git-ignored).-- Tokens required: Telegram/Slack tokens, and the Claude/Anthropic credentials used by `claude-code-sdk` (e.g., `ANTHROPIC_API_KEY`).+- Never commit secrets. Store them in `~/.vibe_remote/config/config.json` or a secret manager.+- Tokens required: Slack tokens, and the Claude/Anthropic credentials used by `claude-code-sdk` (e.g., `ANTHROPIC_API_KEY`).diff --git a/config/__init__.py b/config/__init__.pyindex f714213a5..cfa8a32c1 100644--- a/config/__init__.py+++ b/config/__init__.py@@ -1,3 +1,29 @@-from .settings import AppConfig, TelegramConfig, ClaudeConfig+from .paths import (+ get_vibe_remote_dir,+ get_config_dir,+ get_state_dir,+ get_logs_dir,+ get_runtime_dir,+ get_config_path,+ get_settings_path,+ get_sessions_path,+ ensure_data_dirs,+)+from .v2_config import V2Config+from .v2_settings import SettingsStore+from .v2_sessions import SessionsStore-__all__ = ['AppConfig', 'TelegramConfig', 'ClaudeConfig']\ No newline at end of file+__all__ = [+ "V2Config",+ "SettingsStore",+ "SessionsStore",+ "get_vibe_remote_dir",+ "get_config_dir",+ "get_state_dir",+ "get_logs_dir",+ "get_runtime_dir",+ "get_config_path",+ "get_settings_path",+ "get_sessions_path",+ "ensure_data_dirs",+]diff --git a/config/paths.py b/config/paths.pynew file mode 100644index 000000000..fbfc18a0a--- /dev/null+++ b/config/paths.py@@ -0,0 +1,40 @@+from pathlib import Path+++def get_vibe_remote_dir() -> Path:+ return Path.home() / ".vibe_remote"+++def get_config_dir() -> Path:+ return get_vibe_remote_dir() / "config"+++def get_state_dir() -> Path:+ return get_vibe_remote_dir() / "state"+++def get_logs_dir() -> Path:+ return get_vibe_remote_dir() / "logs"+++def get_runtime_dir() -> Path:+ return get_vibe_remote_dir() / "runtime"+++def get_config_path() -> Path:+ return get_config_dir() / "config.json"+++def get_settings_path() -> Path:+ return get_state_dir() / "settings.json"+++def get_sessions_path() -> Path:+ return get_state_dir() / "sessions.json"+++def ensure_data_dirs() -> None:+ get_config_dir().mkdir(parents=True, exist_ok=True)+ get_state_dir().mkdir(parents=True, exist_ok=True)+ get_logs_dir().mkdir(parents=True, exist_ok=True)+ get_runtime_dir().mkdir(parents=True, exist_ok=True)diff --git a/config/settings.py b/config/settings.pydeleted file mode 100644index 5eedcd601..000000000--- a/config/settings.py+++ /dev/null@@ -1,304 +0,0 @@-import logging-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__)---@dataclass-class TelegramConfig(BaseIMConfig):- bot_token: str- target_chat_id: Optional[Union[List[int], str]] = (- None # Whitelist of chat IDs. Empty list = DM only, null/None = accept all- )-- @classmethod- def from_env(cls) -> "TelegramConfig":- bot_token = os.getenv("TELEGRAM_BOT_TOKEN")- if not bot_token:- raise ValueError("TELEGRAM_BOT_TOKEN environment variable is required")-- target_chat_id = None- target_chat_id_str = os.getenv("TELEGRAM_TARGET_CHAT_ID")- if target_chat_id_str:- # Handle null string- if target_chat_id_str.lower() in ["null", "none"]:- target_chat_id = None- # Handle empty list- elif target_chat_id_str.strip() in ["[]", ""]:- target_chat_id = []- # Handle comma-separated list- else:- try:- # Remove brackets if present and split by comma- ids_str = target_chat_id_str.strip("[]")- if ids_str:- target_chat_id = [int(id.strip()) for id in ids_str.split(",")]- else:- target_chat_id = []- except ValueError:- raise ValueError(- f"Invalid TELEGRAM_TARGET_CHAT_ID format: {target_chat_id_str}"- )-- return cls(bot_token=bot_token, target_chat_id=target_chat_id)-- def validate(self) -> bool:- """Validate Telegram configuration"""- if not self.bot_token:- raise ValueError("TELEGRAM_BOT_TOKEN is required")- # Telegram bot token format is typically "<digits>:<token>"- if ":" not in self.bot_token:- logger.warning("Telegram bot token format might be invalid: missing colon")- else:- prefix = self.bot_token.split(":", 1)[0]- if not prefix.isdigit():- logger.warning(- "Telegram bot token format might be invalid: non-numeric prefix"- )- return True---@dataclass-class ClaudeConfig:- permission_mode: str- cwd: str- system_prompt: Optional[str] = None-- @classmethod- def from_env(cls) -> "ClaudeConfig":- permission_mode = os.getenv("CLAUDE_PERMISSION_MODE")- if not permission_mode:- raise ValueError("CLAUDE_PERMISSION_MODE environment variable is required")-- cwd = os.getenv("AGENT_DEFAULT_CWD") or os.getenv("CLAUDE_DEFAULT_CWD")- if not cwd:- raise ValueError(- "AGENT_DEFAULT_CWD (or legacy CLAUDE_DEFAULT_CWD) environment variable is required"- )-- return cls(- permission_mode=permission_mode,- cwd=cwd,- system_prompt=os.getenv("CLAUDE_SYSTEM_PROMPT"),- )---@dataclass-class CodexConfig:- binary: str = "codex"- 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 []- default_model = os.getenv("CODEX_DEFAULT_MODEL")-- return cls(- binary=binary,- extra_args=extra_args,- default_model=default_model,- )---@dataclass-class OpenCodeConfig:- binary: str = "opencode"- port: int = 4096- request_timeout_seconds: int = 60-- @classmethod- def from_env(cls) -> "OpenCodeConfig":- binary = os.getenv("OPENCODE_CLI_PATH", "opencode")- if not shutil.which(binary):- raise ValueError(- f"OpenCode CLI binary '{binary}' not found in PATH. "- "Install OpenCode or set OPENCODE_CLI_PATH."- )-- port_str = os.getenv("OPENCODE_PORT", "4096")- try:- port = int(port_str)- except ValueError:- logger.warning(- f"Invalid OPENCODE_PORT '{port_str}', falling back to 4096"- )- port = 4096-- return cls(- binary=binary,- port=port,- )---@dataclass-class SlackConfig(BaseIMConfig):- bot_token: str- app_token: Optional[str] = None # For Socket Mode- signing_secret: Optional[str] = None # For webhook mode- target_channel: Optional[Union[List[str], str]] = (- None # Whitelist of channel IDs. Empty list = DM only, null/None = accept all- )- require_mention: bool = False # Require @mention in channels (ignored in DMs)-- @classmethod- def from_env(cls) -> "SlackConfig":- bot_token = os.getenv("SLACK_BOT_TOKEN")- if not bot_token:- raise ValueError("SLACK_BOT_TOKEN environment variable is required")-- return cls(- bot_token=bot_token,- app_token=os.getenv("SLACK_APP_TOKEN"),- signing_secret=os.getenv("SLACK_SIGNING_SECRET"),- target_channel=cls._parse_channel_list(os.getenv("SLACK_TARGET_CHANNEL")),- require_mention=os.getenv("SLACK_REQUIRE_MENTION", "false").lower()- == "true",- )-- def validate(self) -> bool:- """Validate Slack configuration"""- if not self.bot_token:- raise ValueError("SLACK_BOT_TOKEN is required")- if not self.bot_token.startswith("xoxb-"):- raise ValueError("Invalid Slack bot token format (should start with xoxb-)")- if self.app_token and not self.app_token.startswith("xapp-"):- raise ValueError("Invalid Slack app token format (should start with xapp-)")- return True-- @classmethod- def _parse_channel_list(- cls, value: Optional[str]- ) -> Optional[Union[List[str], str]]:- """Parse channel list from environment variable"""- if not value:- return None-- # Handle null string- if value.lower() in ["null", "none"]:- return None-- # Handle empty list- if value.strip() in ["[]", ""]:- return []-- # Handle comma-separated list- # Remove brackets if present and split by comma- ids_str = value.strip("[]")- if ids_str:- return [id.strip() for id in ids_str.split(",")]- else:- return []---@dataclass-class AppConfig:- platform: str- claude: ClaudeConfig- telegram: Optional[TelegramConfig] = None- slack: Optional[SlackConfig] = None- codex: Optional[CodexConfig] = None- opencode: Optional[OpenCodeConfig] = None- log_level: str = "INFO"- cleanup_enabled: bool = False- ack_mode: str = "reaction" # "reaction" (default) | "message"- agent_route_file: Optional[str] = None-- @classmethod- def from_env(cls) -> "AppConfig":- platform = os.getenv("IM_PLATFORM")- if not platform:- raise ValueError("IM_PLATFORM environment variable is required")-- platform = platform.lower()- if platform not in ["telegram", "slack"]:- raise ValueError(- f"Invalid IM_PLATFORM: {platform}. Must be 'telegram' or 'slack'"- )-- log_level = os.getenv(- "LOG_LEVEL", "INFO"- ) # Keep default for log level as it's optional-- # Cleanup toggle (safe cleanup of completed tasks only)- cleanup_enabled_env = os.getenv("CLEANUP_ENABLED", "false").lower()- cleanup_enabled = cleanup_enabled_env in ["1", "true", "yes", "on"]-- # Acknowledgement behavior before agent processing- # - reaction: add 👀/:eyes: to the user's message (default)- # - message: send "📨 <agent> received, processing..." as a bot message- ack_mode = os.getenv("ACK_MODE", "reaction").strip().lower() or "reaction"- if ack_mode not in ["reaction", "message"]:- logger.warning(- f"Invalid ACK_MODE '{ack_mode}', falling back to 'reaction'"- )- ack_mode = "reaction"-- 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-- opencode_config = None- opencode_enabled = os.getenv("OPENCODE_ENABLED", "false").lower() in [- "1",- "true",- "yes",- "on",- ]- if opencode_enabled:- try:- opencode_config = OpenCodeConfig.from_env()- except ValueError as exc:- logger.warning(f"OpenCode support disabled: {exc}")- opencode_config = None-- config = cls(- platform=platform,- claude=ClaudeConfig.from_env(),- log_level=log_level,- cleanup_enabled=cleanup_enabled,- ack_mode=ack_mode,- codex=codex_config,- opencode=opencode_config,- agent_route_file=agent_route_file,- )-- # Load platform-specific config- if platform == "telegram":- config.telegram = TelegramConfig.from_env()- config.telegram.validate()- elif platform == "slack":- config.slack = SlackConfig.from_env()- config.slack.validate()-- return configdiff --git a/config/v2_compat.py b/config/v2_compat.pynew file mode 100644index 000000000..bd8c58e54--- /dev/null+++ b/config/v2_compat.py@@ -0,0 +1,75 @@+from dataclasses import dataclass+from typing import Optional++from config.v2_config import V2Config, SlackConfig+++@dataclass+class ClaudeCompatConfig:+ permission_mode: str+ cwd: str+ system_prompt: Optional[str] = None++ def __post_init__(self) -> None:+ self.permission_mode = str(self.permission_mode)+ self.cwd = str(self.cwd)+++@dataclass+class CodexCompatConfig:+ binary: str+ extra_args: list[str]+ default_model: Optional[str] = None+++@dataclass+class OpenCodeCompatConfig:+ binary: str+ port: int+ request_timeout_seconds: int+++@dataclass+class AppCompatConfig:+ platform: str+ slack: SlackConfig+ claude: ClaudeCompatConfig+ codex: Optional[CodexCompatConfig]+ opencode: Optional[OpenCodeCompatConfig]+ log_level: str+ cleanup_enabled: bool+ ack_mode: str+ agent_route_file: Optional[str]+++def to_app_config(v2: V2Config) -> AppCompatConfig:+ claude = ClaudeCompatConfig(+ permission_mode="default",+ cwd=v2.runtime.default_cwd,+ system_prompt=None,+ )+ codex = None+ if v2.agents.codex.enabled:+ codex = CodexCompatConfig(+ binary=v2.agents.codex.cli_path,+ extra_args=[],+ default_model=v2.agents.codex.default_model,+ )+ opencode = None+ if v2.agents.opencode.enabled:+ opencode = OpenCodeCompatConfig(+ binary=v2.agents.opencode.cli_path,+ port=4096,+ request_timeout_seconds=60,+ )+ return AppCompatConfig(+ platform="slack",+ slack=v2.slack,+ claude=claude,+ codex=codex,+ opencode=opencode,+ log_level=v2.runtime.log_level,+ cleanup_enabled=v2.cleanup_enabled,+ ack_mode=v2.ack_mode,+ agent_route_file=v2.agent_route_file,+ )diff --git a/config/v2_config.py b/config/v2_config.pynew file mode 100644index 000000000..a0337f6b7--- /dev/null+++ b/config/v2_config.py@@ -0,0 +1,164 @@+import json+import logging+from dataclasses import dataclass, field+from pathlib import Path+from typing import List, Optional++from config import paths+from modules.im.base import BaseIMConfig++logger = logging.getLogger(__name__)+++@dataclass+class SlackConfig(BaseIMConfig):+ bot_token: str+ app_token: Optional[str] = None+ signing_secret: Optional[str] = None+ team_id: Optional[str] = None+ team_name: Optional[str] = None+ app_id: Optional[str] = None+ require_mention: bool = False+ target_channels: Optional[List[str]] = None++ def validate(self) -> None:+ if not self.bot_token or not self.bot_token.startswith("xoxb-"):+ raise ValueError("Invalid Slack bot token format (should start with xoxb-)")+ if self.app_token and not self.app_token.startswith("xapp-"):+ raise ValueError("Invalid Slack app token format (should start with xapp-)")+++@dataclass+class GatewayConfig:+ relay_url: Optional[str] = None+ workspace_token: Optional[str] = None+ client_id: Optional[str] = None+ client_secret: Optional[str] = None+ last_connected_at: Optional[str] = None+++@dataclass+class RuntimeConfig:+ default_cwd: str+ log_level: str = "INFO"+ require_mention: bool = False+ target_channels: Optional[List[str]] = None+++@dataclass+class OpenCodeConfig:+ enabled: bool = True+ cli_path: str = "opencode"+ default_agent: Optional[str] = None+ default_model: Optional[str] = None+ default_reasoning_effort: Optional[str] = None+++@dataclass+class ClaudeConfig:+ enabled: bool = True+ cli_path: str = "claude"+ default_model: Optional[str] = None+++@dataclass+class CodexConfig:+ enabled: bool = True+ cli_path: str = "codex"+ default_model: Optional[str] = None+++@dataclass+class AgentsConfig:+ default_backend: str = "opencode"+ opencode: OpenCodeConfig = field(default_factory=OpenCodeConfig)+ claude: ClaudeConfig = field(default_factory=ClaudeConfig)+ codex: CodexConfig = field(default_factory=CodexConfig)+++@dataclass+class UiConfig:+ setup_port: int = 5123+ open_browser: bool = True+++@dataclass+class V2Config:+ mode: str+ version: str+ slack: SlackConfig+ runtime: RuntimeConfig+ agents: AgentsConfig+ gateway: Optional[GatewayConfig] = None+ ui: UiConfig = field(default_factory=UiConfig)+ ack_mode: str = "reaction"+ cleanup_enabled: bool = False+ agent_route_file: Optional[str] = None++ @classmethod+ def load(cls, config_path: Optional[Path] = None) -> "V2Config":+ paths.ensure_data_dirs()+ path = config_path or paths.get_config_path()+ if not path.exists():+ raise FileNotFoundError(f"Config not found: {path}")+ payload = json.loads(path.read_text(encoding="utf-8"))+ return cls.from_payload(payload)++ @classmethod+ def from_payload(cls, payload: dict) -> "V2Config":+ slack_payload = payload.get("slack") or {}+ slack = SlackConfig(**slack_payload)+ gateway_payload = payload.get("gateway")+ gateway = GatewayConfig(**gateway_payload) if gateway_payload else None+ runtime_payload = payload.get("runtime") or {}+ runtime = RuntimeConfig(**runtime_payload)+ agents_payload = payload.get("agents") or {}+ opencode = OpenCodeConfig(**(agents_payload.get("opencode") or {}))+ claude = ClaudeConfig(**(agents_payload.get("claude") or {}))+ codex = CodexConfig(**(agents_payload.get("codex") or {}))+ agents = AgentsConfig(+ default_backend=agents_payload.get("default_backend", "opencode"),+ opencode=opencode,+ claude=claude,+ codex=codex,+ )+ ui = UiConfig(**(payload.get("ui") or {}))+ return cls(+ mode=payload.get("mode", "self_host"),+ version=payload.get("version", "v2"),+ slack=slack,+ runtime=runtime,+ agents=agents,+ gateway=gateway,+ ui=ui,+ ack_mode=payload.get("ack_mode", "reaction"),+ cleanup_enabled=payload.get("cleanup_enabled", False),+ agent_route_file=payload.get("agent_route_file"),+ )++ def save(self, config_path: Optional[Path] = None) -> None:+ paths.ensure_data_dirs()+ path = config_path or paths.get_config_path()+ payload = {+ "mode": self.mode,+ "version": self.version,+ "slack": self.slack.__dict__,+ "runtime": {+ "default_cwd": self.runtime.default_cwd,+ "log_level": self.runtime.log_level,+ "require_mention": self.runtime.require_mention,+ "target_channels": self.runtime.target_channels,+ },+ "agents": {+ "default_backend": self.agents.default_backend,+ "opencode": self.agents.opencode.__dict__,+ "claude": self.agents.claude.__dict__,+ "codex": self.agents.codex.__dict__,+ },+ "gateway": self.gateway.__dict__ if self.gateway else None,+ "ui": self.ui.__dict__,+ "ack_mode": self.ack_mode,+ "cleanup_enabled": self.cleanup_enabled,+ "agent_route_file": self.agent_route_file,+ }+ path.write_text(json.dumps(payload, indent=2), encoding="utf-8")diff --git a/config/v2_sessions.py b/config/v2_sessions.pynew file mode 100644index 000000000..08b042625--- /dev/null+++ b/config/v2_sessions.py@@ -0,0 +1,71 @@+import json+import logging+from dataclasses import dataclass, field+from pathlib import Path+from typing import Dict, Optional++from config import paths++logger = logging.getLogger(__name__)+++@dataclass+class SessionState:+ session_mappings: Dict[str, Dict[str, Dict[str, Dict[str, str]]]] = field(+ default_factory=dict+ )+ active_slack_threads: Dict[str, Dict[str, Dict[str, float]]] = field(+ default_factory=dict+ )+ last_activity: Optional[str] = None+++@dataclass+class SessionsStore:+ sessions_path: Path = field(default_factory=paths.get_sessions_path)+ state: SessionState = field(default_factory=SessionState)++ def load(self) -> None:+ if not self.sessions_path.exists():+ return+ try:+ payload = json.loads(self.sessions_path.read_text(encoding="utf-8"))+ except Exception as exc:+ logger.error("Failed to load sessions: %s", exc)+ return+ self.state = SessionState(+ session_mappings=payload.get("session_mappings", {}),+ active_slack_threads=payload.get("active_slack_threads", {}),+ last_activity=payload.get("last_activity"),+ )++ def _ensure_user_namespace(self, user_id: str) -> None:+ if user_id not in self.state.session_mappings:+ self.state.session_mappings[user_id] = {}+ if user_id not in self.state.active_slack_threads:+ self.state.active_slack_threads[user_id] = {}++ def get_agent_map(self, user_id: str, agent_name: str) -> Dict[str, Dict[str, str]]:+ self._ensure_user_namespace(user_id)+ agent_map = self.state.session_mappings[user_id].get(agent_name)+ if agent_map is None:+ agent_map = {}+ self.state.session_mappings[user_id][agent_name] = agent_map+ return agent_map++ def get_thread_map(self, user_id: str, channel_id: str) -> Dict[str, float]:+ self._ensure_user_namespace(user_id)+ channel_map = self.state.active_slack_threads[user_id].get(channel_id)+ if channel_map is None:+ channel_map = {}+ self.state.active_slack_threads[user_id][channel_id] = channel_map+ return channel_map++ def save(self) -> None:+ paths.ensure_data_dirs()+ payload = {+ "session_mappings": self.state.session_mappings,+ "active_slack_threads": self.state.active_slack_threads,+ "last_activity": self.state.last_activity,+ }+ self.sessions_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")diff --git a/config/v2_settings.py b/config/v2_settings.pynew file mode 100644index 000000000..ea1d319ca--- /dev/null+++ b/config/v2_settings.py@@ -0,0 +1,92 @@+import json+import logging+from dataclasses import dataclass, field+from pathlib import Path+from typing import Dict, List, Optional++from config import paths++logger = logging.getLogger(__name__)+++@dataclass+class RoutingSettings:+ agent_backend: Optional[str] = None+ opencode_agent: Optional[str] = None+ opencode_model: Optional[str] = None+ opencode_reasoning_effort: Optional[str] = None+++@dataclass+class ChannelSettings:+ enabled: bool = True+ hidden_message_types: List[str] = field(+ default_factory=lambda: ["system", "assistant", "toolcall"]+ )+ custom_cwd: Optional[str] = None+ routing: RoutingSettings = field(default_factory=RoutingSettings)+++@dataclass+class SettingsState:+ channels: Dict[str, ChannelSettings] = field(default_factory=dict)+++class SettingsStore:+ def __init__(self, settings_path: Optional[Path] = None):+ self.settings_path = settings_path or paths.get_settings_path()+ self.settings: SettingsState = SettingsState()+ self._load()++ def _load(self) -> None:+ if not self.settings_path.exists():+ return+ try:+ payload = json.loads(self.settings_path.read_text(encoding="utf-8"))+ except Exception as exc:+ logger.error("Failed to load settings: %s", exc)+ return+ channels = {}+ for channel_id, channel_payload in (payload.get("channels") or {}).items():+ routing_payload = channel_payload.get("routing") or {}+ routing = RoutingSettings(+ agent_backend=routing_payload.get("agent_backend"),+ opencode_agent=routing_payload.get("opencode_agent"),+ opencode_model=routing_payload.get("opencode_model"),+ opencode_reasoning_effort=routing_payload.get("opencode_reasoning_effort"),+ )+ channels[channel_id] = ChannelSettings(+ enabled=channel_payload.get("enabled", True),+ hidden_message_types=channel_payload.get(+ "hidden_message_types", ["system", "assistant", "toolcall"]+ ),+ custom_cwd=channel_payload.get("custom_cwd"),+ routing=routing,+ )+ self.settings = SettingsState(channels=channels)++ def save(self) -> None:+ paths.ensure_data_dirs()+ payload = {"channels": {}}+ for channel_id, settings in self.settings.channels.items():+ payload["channels"][channel_id] = {+ "enabled": settings.enabled,+ "hidden_message_types": settings.hidden_message_types,+ "custom_cwd": settings.custom_cwd,+ "routing": {+ "agent_backend": settings.routing.agent_backend,+ "opencode_agent": settings.routing.opencode_agent,+ "opencode_model": settings.routing.opencode_model,+ "opencode_reasoning_effort": settings.routing.opencode_reasoning_effort,+ },+ }+ self.settings_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")++ def get_channel(self, channel_id: str) -> ChannelSettings:+ if channel_id not in self.settings.channels:+ self.settings.channels[channel_id] = ChannelSettings()+ return self.settings.channels[channel_id]++ def update_channel(self, channel_id: str, settings: ChannelSettings) -> None:+ self.settings.channels[channel_id] = settings+ self.save()diff --git a/core/controller.py b/core/controller.pyindex 9a1c35442..9b7b08d85 100644--- a/core/controller.py+++ b/core/controller.py@@ -4,9 +4,8 @@ import asyncioimport osimport loggingfrom typing import Optional, Dict, Any-from config.settings import AppConfigfrom modules.im import BaseIMClient, MessageContext, IMFactory-from modules.im.formatters import TelegramFormatter, SlackFormatter+from modules.im.formatters import SlackFormatterfrom modules.agent_router import AgentRouterfrom modules.agents import AgentService, ClaudeAgent, CodexAgent, OpenCodeAgentfrom modules.claude_client import ClaudeClient@@ -25,7 +24,7 @@ logger = logging.getLogger(__name__)class Controller:"""Main controller that coordinates all bot operations"""- def __init__(self, config: AppConfig):+ def __init__(self, config):"""Initialize controller with configuration"""self.config = config@@ -63,15 +62,7 @@ class Controller:self.im_client: BaseIMClient = IMFactory.create_client(self.config)# Create platform-specific formatter- if self.config.platform == "telegram":- formatter = TelegramFormatter()- elif self.config.platform == "slack":- formatter = SlackFormatter()- else:- logger.warning(- f"Unknown platform: {self.config.platform}, using Telegram formatter"- )- formatter = TelegramFormatter()+ formatter = SlackFormatter()# Inject formatter into clientsself.im_client.formatter = formatter@@ -169,7 +160,7 @@ class Controller:elif custom_cwd:logger.warning(f"Custom CWD does not exist: {custom_cwd}, using default")- # Fall back to default from .env+ # Fall back to default from config.jsondefault_cwd = self.config.claude.cwdif default_cwd:return os.path.abspath(os.path.expanduser(default_cwd))@@ -179,15 +170,8 @@ class Controller:def _get_settings_key(self, context: MessageContext) -> str:"""Get settings key based on context"""- if self.config.platform == "slack":- # For Slack, always use channel_id as the key- return context.channel_id- elif self.config.platform == "telegram":- # For Telegram groups, use channel_id; for DMs use user_id- if context.channel_id != context.user_id:- return context.channel_id- return context.user_id- return context.user_id+ # Slack only in V2+ return context.channel_iddef _get_target_context(self, context: MessageContext) -> MessageContext:"""Get target context for sending messages"""@@ -213,19 +197,10 @@ class Controller:def _get_consolidated_max_chars(self) -> int:# Slack max message length is ~40k characters.- if self.config.platform == "slack":- return 35000- # Telegram hard limit is 4096; MarkdownV2 escaping expands.- if self.config.platform == "telegram":- return 3200- return 8000+ return 35000def _get_result_max_chars(self) -> int:- if self.config.platform == "slack":- return 30000- if self.config.platform == "telegram":- return 3200- return 8000+ return 30000def _build_result_summary(self, text: str, max_chars: int) -> str:if len(text) <= max_chars:@@ -400,7 +375,7 @@ class Controller:# Settings update handler (for Slack modal)async def handle_settings_update(- self, user_id: str, hidden_message_types: list, channel_id: str = None+ self, user_id: str, hidden_message_types: list, channel_id: Optional[str] = None):"""Handle settings update (typically from Slack modal)"""try:@@ -449,7 +424,7 @@ class Controller:# Working directory change handler (for Slack modal)async def handle_change_cwd_submission(- self, user_id: str, new_cwd: str, channel_id: str = None+ self, user_id: str, new_cwd: str, channel_id: Optional[str] = None):"""Handle working directory change submission (from Slack modal) - reuse command handler logic"""try:@@ -563,7 +538,7 @@ class Controller:try:opencode_agent = self.agent_service.agents.get("opencode")if opencode_agent and hasattr(opencode_agent, "_get_server"):- server = await opencode_agent._get_server()+ server = await opencode_agent._get_server() # type: ignore[attr-defined]await server.ensure_running()cwd = self.get_cwd(context)opencode_agents = await server.get_available_agents(cwd)@@ -573,7 +548,7 @@ class Controller:logger.warning(f"Failed to fetch OpenCode data: {e}")if hasattr(self.im_client, "update_routing_modal"):- await self.im_client.update_routing_modal(+ await self.im_client.update_routing_modal( # type: ignore[attr-defined]view_id=view_id,view_hash=view_hash,channel_id=resolved_channel_id,diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex bc637dfe7..71bcaf774 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -152,9 +152,7 @@ class MessageHandler:try:if context.message_id:ack_reaction_message_id = context.message_id- ack_reaction_emoji = (- ":eyes:" if self.config.platform == "slack" else "👀"- )+ ack_reaction_emoji = ":eyes:"ok = await self.im_client.add_reaction(context, ack_reaction_message_id, ack_reaction_emoji)@@ -167,7 +165,7 @@ class MessageHandler:if subagent_name and context.message_id:try:- reaction = ":robot_face:" if self.config.platform == "slack" else "🤖"+ reaction = ":robot_face:"await self.im_client.add_reaction(context,context.message_id,diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 4009bf8ad..42c21b7fa 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -30,15 +30,8 @@ class SessionHandler:def get_base_session_id(self, context: MessageContext) -> str:"""Get base session ID based on platform and context (without path)"""- if self.config.platform == "telegram":- # For Telegram, use channel/chat ID- return f"telegram_{context.channel_id}"- elif self.config.platform == "slack":- # For Slack, always use thread ID (now always available)- return f"slack_{context.thread_id}"- else:- # Default to user ID- return f"{self.config.platform}_{context.user_id}"+ # Slack only in V2; always use thread ID+ return f"slack_{context.thread_id}"def get_working_path(self, context: MessageContext) -> str:"""Get working directory - delegate to controller's get_cwd"""@@ -217,7 +210,7 @@ class SessionHandler:def capture_session_id(self, base_session_id: str, working_path: str, claude_session_id: str, settings_key: str):"""Capture and store Claude session ID mapping"""- # Persist to settings with nested structure (settings_key is channel_id for Slack, user/channel_id for Telegram)+ # Persist to settings with nested structure (settings_key is channel_id for Slack)self.settings_manager.set_session_mapping(settings_key, base_session_id, working_path, claude_session_id)logger.info(f"Captured Claude session_id: {claude_session_id} for {base_session_id} at {working_path}")@@ -226,26 +219,20 @@ class SessionHandler:"""Restore session mappings from settings on startup"""logger.info("Initializing session mappings from saved settings...")- # Get all user settings- all_settings = self.settings_manager.settings-+ session_state = self.settings_manager.sessions_store.state.session_mappings+restored_count = 0- for user_id, user_settings in all_settings.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):+ for user_id, agent_map in session_state.items():+ claude_map = agent_map.get("claude", {}) if isinstance(agent_map, dict) else {}+ 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})"+ )+ for path, claude_session_id in path_mappings.items():logger.info(- f"Found {len(path_mappings)} path mappings for {base_session_id} (user {user_id})"+ f" - {base_session_id}[{path}] -> {claude_session_id}")- for path, claude_session_id in path_mappings.items():- logger.info(- f" - {base_session_id}[{path}] -> {claude_session_id}"- )- restored_count += 1+ restored_count += 1logger.info(f"Session restoration complete. Restored {restored_count} session mappings.")diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex b4deba431..bccc61a1a 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -45,7 +45,7 @@ class SettingsHandler:)async def _handle_settings_traditional(self, context: MessageContext):- """Handle settings for non-Slack platforms (Telegram, etc)"""+ """Handle settings for non-Slack platforms"""# Get current settingssettings_key = self._get_settings_key(context)user_settings = self.settings_manager.get_user_settings(settings_key)@@ -184,15 +184,9 @@ class SettingsHandler:action = "hidden" if is_hidden else "shown"# Platform-specific callback answering- if self.config.platform == "telegram":- # For Telegram, we need the actual callback query object- # This is handled in the telegram bot handler- pass- elif self.config.platform == "slack":- # For Slack, we might send an ephemeral message- await self.im_client.send_message(- context, f"{display_name} messages are now {action}"- )+ await self.im_client.send_message(+ context, f"{display_name} messages are now {action}"+ )except Exception as e:logger.error(f"Error toggling message type {msg_type}: {e}")diff --git a/docs/CODEX_SETUP.md b/docs/CODEX_SETUP.mdindex 4beca713e..8cb7e419d 100644--- a/docs/CODEX_SETUP.md+++ b/docs/CODEX_SETUP.md@@ -1,6 +1,6 @@# Codex Agent Setup-Vibe Remote can route individual Slack channels / Telegram chats to Codex instead of Claude Code. (OpenCode is also supported and recommended; see README for quick enablement.) This guide walks through enabling Codex end-to-end.+Vibe Remote can route individual Slack channels to Codex instead of Claude Code. (OpenCode is also supported and recommended; see README for quick enablement.) This guide walks through enabling Codex end-to-end.## 1. Install and authenticate Codex CLI@@ -41,13 +41,9 @@ slack:default: claudeoverrides: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`.+Each Slack channel ID (starts with `C`) 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.@@ -63,5 +59,5 @@ In a routed Slack channel run `@VibeRemote status` or any question—you should## 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`.+- **`codex exec` errors**: inspect the Slack stderr snippet or tail the latest `~/.vibe_remote/logs/vibe_remote.log`.+- **Routing not applied**: confirm the channel ID matches Slack’s `C...` value (copy from channel details), and restart the bot after editing `agent_routes.yaml`.diff --git a/docs/DYNAMIC_ROUTING_DESIGN.md b/docs/DYNAMIC_ROUTING_DESIGN.mdindex bc35ba81a..627c39150 100644--- a/docs/DYNAMIC_ROUTING_DESIGN.md+++ b/docs/DYNAMIC_ROUTING_DESIGN.md@@ -2,7 +2,7 @@## Overview-Replace static `agent_routes.yaml` with dynamic per-channel routing configuration that users can change via Slack/Telegram menus.+Replace static `agent_routes.yaml` with dynamic per-channel routing configuration that users can change via Slack menus.## Requirements@@ -11,14 +11,13 @@ Replace static `agent_routes.yaml` with dynamic per-channel routing configuratio- Agent selection (build, plan, etc.) - from `/agent` API- Model selection - from `/config/providers` API3. **Claude/Codex**: No model selection (use their defaults)-4. **Fallback**: `agent_routes.yaml` remains as default; UI overrides are persisted in `user_settings.json`-5. **Entry points**:+4. **Fallback**: `agent_routes.yaml` remains as default; UI overrides are persisted in `~/.vibe_remote/state/settings.json`+5. **Entry points**:- Slack: `/start` button "Switch Agent" + `/settings` modal- - Telegram: inline keyboard in settings (backend only for now)## Data Structure-### UserSettings (in `user_settings.json`)+### UserSettings (in `~/.vibe_remote/state/settings.json`)```python@dataclass@@ -31,10 +30,8 @@ class ChannelRouting:class UserSettings:hidden_message_types: List[str] = ...custom_cwd: Optional[str] = None- session_mappings: Dict[...] = ...- active_slack_threads: Dict[...] = ...- # NEW- channel_routing: Optional[ChannelRouting] = None+ channel_routing: Optional[ChannelRouting] = None+```### JSON Representation@@ -44,7 +41,6 @@ class UserSettings:"C0A6U2GH6P5": {"hidden_message_types": ["system", "assistant", "user"],"custom_cwd": "/path/to/project",- "session_mappings": {...},"channel_routing": {"agent_backend": "opencode","opencode_agent": "build",@@ -272,9 +268,9 @@ view = {12. [ ] Handle `routing_modal` submission in `_handle_view_submission()`13. [ ] Add `cmd_routing` callback handler-### Phase 4: Telegram UI (Optional)-14. [ ] Add backend switching to Telegram inline keyboard-15. [ ] (Future) Add OpenCode agent/model selection for Telegram+### Phase 4: Future App UI (Optional)+14. [ ] Add backend switching to the Vibe app UI+15. [ ] (Future) Add OpenCode agent/model selection to the Vibe app UI## File Changes Summarydiff --git a/docs/TELEGRAM_SETUP.md b/docs/TELEGRAM_SETUP.mddeleted file mode 100644index 35d67702d..000000000--- a/docs/TELEGRAM_SETUP.md+++ /dev/null@@ -1,288 +0,0 @@-# Telegram Bot Setup Guide--This guide will walk you through setting up a Telegram bot for Vibe Remote.--## Prerequisites--- Telegram account-- Python 3.6 or higher installed-- Vibe Remote cloned and dependencies installed--## Step 1: Create a Telegram Bot--1. Open Telegram and search for **@BotFather**-2. Start a conversation with BotFather-3. Send the command `/newbot`-4. Follow the prompts:- - Choose a name for your bot (e.g., "Vibe Remote")- - Choose a username for your bot (must end in `bot`, e.g., `claude_code_bot`)-5. BotFather will provide you with a **bot token** that looks like:- ```- 1234567890:ABCdefGHIjklMNOpqrsTUVwxyz1234567890- ```-6. **Save this token** - you'll need it for configuration--## Step 2: Configure Bot Settings (Optional)--While still chatting with BotFather, you can configure additional settings:--### Set Bot Description--```-/setdescription-```--Then select your bot and provide a description like:-"Vibe Remote - trigger AI coding from Telegram"--### Set About Text--```-/setabouttext-```--Select your bot and add:-"Vibe Remote - AI-powered remote coding assistant"--### Set Bot Commands--```-/setcommands-```--Select your bot and paste these commands:--```-start - Show welcome message and available commands-clear - Reset conversation and start fresh-cwd - Show current working directory-set_cwd - Change working directory-settings - Open personalization settings-```--### Enable Inline Mode (Optional)--```-/setinline-```--This allows the bot to be used inline in other chats.--## Step 3: Configure Your Environment--Update your `.env` file with the following:--```env-# Set platform to telegram-IM_PLATFORM=telegram--# Telegram configuration-TELEGRAM_BOT_TOKEN=your-bot-token-here--# Optional: Whitelist specific chat IDs (null = all chats allowed)-TELEGRAM_TARGET_CHAT_ID=[-1001234567890,987654321]--# Default working directory for the coding agent-AGENT_DEFAULT_CWD=/path/to/your/project-# Legacy alias (still supported):-# CLAUDE_DEFAULT_CWD=/path/to/your/project-```--### Finding Chat IDs--To find a chat ID:--#### For Personal Chats--1. Send any message to your bot-2. Check the bot logs - the chat ID will be displayed-3. Personal chat IDs are positive numbers--#### For Groups--1. Add the bot to the group-2. Send a message in the group-3. Check the bot logs for the chat ID-4. Group chat IDs are negative numbers starting with `-100`--#### Using IDBot (Alternative)--1. Add **@username_to_id_bot** to your group-2. It will automatically display the chat ID-3. Remove the bot after getting the ID--## Step 4: Bot Permissions for Groups--If you want to use the bot in groups:--1. Talk to **@BotFather**-2. Send `/mybots`-3. Select your bot-4. Click **Bot Settings**-5. Click **Group Privacy**-6. **Disable** privacy mode--This allows the bot to see all messages in groups, not just commands.--## Step 5: Start the Bot--```bash-python main.py-```--The bot should now be running and ready to accept commands.--## Usage--### Commands--- `/start` - Display welcome message and available commands-- `/clear` - Reset the conversation context-- `/cwd` - Show current working directory-- `/set_cwd <path>` - Change working directory-- `/settings` - Configure message visibility and preferences--### Sending Messages to Your Agent--After starting the bot, simply send any message and it will be forwarded to your configured agent. The bot will:--1. Send your message to the configured agent-2. Stream the response back in real-time-3. Maintain conversation context for follow-ups--### In Groups--When using the bot in groups:--- Messages must start with `/` to be processed as commands-- Regular messages are processed as agent queries-- The bot maintains separate sessions for each chat--## Features--### Message Formatting--The bot supports Telegram's MarkdownV2 format:--- **Bold text** with `**text**`-- _Italic text_ with `*text*`-- `Code` with backticks-- `Code blocks` with triple backticks--### Inline Keyboards--The settings command provides inline keyboard buttons for:--- Show/hide raw agent output-- Show/hide thinking process-- Reset session-- Return to main menu--### Real-time Streaming--Messages from your agent are streamed in real-time:--- Long messages are automatically split-- Code blocks are properly formatted-- Progress is shown during processing--## Troubleshooting--### Bot not responding--1. Check the bot token is correct in `.env`-2. Ensure the bot is running (check logs)-3. Verify your chat ID is whitelisted (if using whitelist)--### "Unauthorized" errors--1. Double-check the bot token-2. Make sure you're using the token from BotFather-3. Regenerate the token if necessary:- - Talk to @BotFather- - Send `/revoke`- - Select your bot- - Get the new token--### Bot not seeing messages in groups--1. Ensure privacy mode is disabled (Step 4)-2. Check that the bot is an admin in the group (optional but recommended)-3. Verify the group chat ID is whitelisted if using `TELEGRAM_TARGET_CHAT_ID`--### Message formatting issues--1. The bot uses MarkdownV2 which requires escaping special characters-2. If messages appear broken, check logs for parsing errors-3. Special characters like `_`, `*`, `[`, `]`, `(`, `)`, `~`, `` ` ``, `>`, `#`, `+`, `-`, `=`, `|`, `{`, `}`, `.`, `!` need escaping--### Rate limiting--Telegram has rate limits:--- 30 messages per second to different users-- 20 messages per minute to the same group-- 1 message per second to the same user--If you hit rate limits, the bot will automatically retry with delays.--## Security Considerations--### Token Security--- Never commit the bot token to version control-- Keep the token private - anyone with it can control your bot-- Regenerate the token if it's ever exposed--### Chat Whitelisting--- Use `TELEGRAM_TARGET_CHAT_ID` to restrict bot access to specific chats-- This prevents unauthorized users from using your bot-- Leave it as `null` only for development/testing--### Group Security--- Consider making the bot admin with restricted permissions-- Monitor bot usage in groups-- Use chat whitelisting for production deployments--## Advanced Configuration--### Webhook Mode (Optional)--For production deployments, you can use webhooks instead of polling:--1. Set up an HTTPS endpoint-2. Configure the webhook URL with Telegram API-3. Update your bot code to handle webhook requests--### Custom Keyboards--You can implement custom keyboard layouts for frequently used commands:--- Reply keyboards for quick command access-- Inline keyboards for interactive menus-- Remove keyboards when not needed--### Persistent Settings--User settings are stored in `user_settings.json`:--- Per-user preferences-- Session management-- Message visibility options--## Additional Resources--- [Telegram Bot API Documentation](https://core.telegram.org/bots/api)-- [Python Telegram Bot Library](https://python-telegram-bot.org/)-- [BotFather Commands](https://core.telegram.org/bots#botfather)-- [Telegram Bot Best Practices](https://core.telegram.org/bots/faq)--## Tips--1. **Testing**: Create a test bot first to experiment with settings-2. **Logging**: Enable debug logging to troubleshoot issues-3. **Updates**: Keep the python-telegram-bot library updated-4. **Monitoring**: Use bot analytics to track usage-5. **Backups**: Regularly backup your `user_settings.json` filediff --git a/docs/TELEGRAM_SETUP_ZH.md b/docs/TELEGRAM_SETUP_ZH.mddeleted file mode 100644index e46f58b1c..000000000--- a/docs/TELEGRAM_SETUP_ZH.md+++ /dev/null@@ -1,288 +0,0 @@-# Telegram 机器人设置指南--本指南将指导你为 Vibe Remote 设置 Telegram 机器人。--## 前置条件--- Telegram 账户-- 已安装 Python 3.6 或更高版本-- 已克隆 Vibe Remote 并安装依赖--## 步骤 1:创建 Telegram 机器人--1. 打开 Telegram 并搜索 **@BotFather**-2. 与 BotFather 开始对话-3. 发送命令 `/newbot`-4. 按照提示操作:- - 为你的机器人选择一个名称(例如 "Vibe Remote")- - 为你的机器人选择用户名(必须以 `bot` 结尾,例如 `claude_code_bot`)-5. BotFather 会提供一个**机器人令牌**,格式如下:- ```- 1234567890:ABCdefGHIjklMNOpqrsTUVwxyz1234567890- ```-6. **保存此令牌** - 配置时需要使用--## 步骤 2:配置机器人设置(可选)--继续与 BotFather 对话,你可以配置其他设置:--### 设置机器人描述--```-/setdescription-```--然后选择你的机器人并提供描述,例如:-"Vibe Remote - 远程编码助手"--### 设置关于文本--```-/setabouttext-```--选择你的机器人并添加:-"Vibe Remote - AI 驱动的远程编码助手"--### 设置机器人命令--```-/setcommands-```--选择你的机器人并粘贴这些命令:--```-start - 显示欢迎消息和可用命令-clear - 重置对话并重新开始-cwd - 显示当前工作目录-set_cwd - 更改工作目录-settings - 打开个性化设置-```--### 启用内联模式(可选)--```-/setinline-```--这允许机器人在其他聊天中以内联方式使用。--## 步骤 3:配置你的环境--使用以下内容更新你的 `.env` 文件:--```env-# 设置平台为 telegram-IM_PLATFORM=telegram--# Telegram 配置-TELEGRAM_BOT_TOKEN=your-bot-token-here--# 可选:白名单特定聊天 ID(null = 允许所有聊天)-TELEGRAM_TARGET_CHAT_ID=[-1001234567890,987654321]--# 编码 Agent 的默认工作目录-AGENT_DEFAULT_CWD=/path/to/your/project-# 兼容别名(仍支持):-# CLAUDE_DEFAULT_CWD=/path/to/your/project-```--### 查找聊天 ID--查找聊天 ID 的方法:--#### 个人聊天--1. 向你的机器人发送任何消息-2. 检查机器人日志 - 将显示聊天 ID-3. 个人聊天 ID 是正数--#### 群组--1. 将机器人添加到群组-2. 在群组中发送消息-3. 检查机器人日志中的聊天 ID-4. 群组聊天 ID 是以 `-100` 开头的负数--#### 使用 IDBot(替代方法)--1. 将 **@username_to_id_bot** 添加到你的群组-2. 它会自动显示聊天 ID-3. 获取 ID 后移除该机器人--## 步骤 4:群组的机器人权限--如果你想在群组中使用机器人:--1. 与 **@BotFather** 对话-2. 发送 `/mybots`-3. 选择你的机器人-4. 点击 **Bot Settings**-5. 点击 **Group Privacy**-6. **禁用**隐私模式--这允许机器人查看群组中的所有消息,而不仅仅是命令。--## 步骤 5:启动机器人--```bash-python main.py-```--机器人现在应该正在运行并准备接受命令。--## 使用方法--### 命令--- `/start` - 显示欢迎消息和可用命令-- `/clear` - 重置对话上下文-- `/cwd` - 显示当前工作目录-- `/set_cwd <路径>` - 更改工作目录-- `/settings` - 配置消息可见性和偏好设置--### 向 Agent 发送消息--启动机器人后,只需发送任何消息,它就会被转发到已配置的 Agent。机器人将:--1. 将你的消息发送到已配置的 Agent-2. 实时流式传输响应-3. 为后续消息维护对话上下文--### 在群组中使用--在群组中使用机器人时:--- 消息必须以 `/` 开头才能作为命令处理-- 常规消息作为 Agent 查询处理-- 机器人为每个聊天维护独立的会话--## 功能特性--### 消息格式化--机器人支持 Telegram 的 MarkdownV2 格式:--- **粗体文本** 使用 `**文本**`-- _斜体文本_ 使用 `*文本*`-- `代码` 使用反引号-- `代码块` 使用三个反引号--### 内联键盘--设置命令提供内联键盘按钮:--- 显示/隐藏原始 Agent 输出-- 显示/隐藏思考过程-- 重置会话-- 返回主菜单--### 实时流式传输--来自 Agent 的消息实时流式传输:--- 长消息自动分割-- 代码块正确格式化-- 处理期间显示进度--## 故障排除--### 机器人无响应--1. 检查 `.env` 中的机器人令牌是否正确-2. 确保机器人正在运行(检查日志)-3. 验证你的聊天 ID 是否在白名单中(如果使用白名单)--### "未授权"错误--1. 仔细检查机器人令牌-2. 确保你使用的是来自 BotFather 的令牌-3. 如有必要,重新生成令牌:- - 与 @BotFather 对话- - 发送 `/revoke`- - 选择你的机器人- - 获取新令牌--### 机器人在群组中看不到消息--1. 确保隐私模式已禁用(步骤 4)-2. 检查机器人是否是群组管理员(可选但推荐)-3. 如果使用 `TELEGRAM_TARGET_CHAT_ID`,验证群组聊天 ID 是否在白名单中--### 消息格式问题--1. 机器人使用 MarkdownV2,需要转义特殊字符-2. 如果消息显示异常,检查日志中的解析错误-3. 特殊字符如 `_`、`*`、`[`、`]`、`(`、`)`、`~`、`` ` ``、`>`、`#`、`+`、`-`、`=`、`|`、`{`、`}`、`.`、`!` 需要转义--### 速率限制--Telegram 有速率限制:--- 每秒向不同用户发送 30 条消息-- 每分钟向同一群组发送 20 条消息-- 每秒向同一用户发送 1 条消息--如果达到速率限制,机器人将自动延迟重试。--## 安全注意事项--### 令牌安全--- 永远不要将机器人令牌提交到版本控制-- 保持令牌私密 - 任何拥有它的人都可以控制你的机器人-- 如果令牌曾经暴露,请重新生成--### 聊天白名单--- 使用 `TELEGRAM_TARGET_CHAT_ID` 限制机器人访问特定聊天-- 这可以防止未授权用户使用你的机器人-- 仅在开发/测试时将其设置为 `null`--### 群组安全--- 考虑将机器人设为具有受限权限的管理员-- 监控群组中的机器人使用情况-- 在生产部署中使用聊天白名单--## 高级配置--### Webhook 模式(可选)--对于生产部署,你可以使用 webhook 而不是轮询:--1. 设置 HTTPS 端点-2. 使用 Telegram API 配置 webhook URL-3. 更新机器人代码以处理 webhook 请求--### 自定义键盘--你可以为常用命令实现自定义键盘布局:--- 用于快速命令访问的回复键盘-- 用于交互式菜单的内联键盘-- 不需要时移除键盘--### 持久化设置--用户设置存储在 `user_settings.json` 中:--- 每用户偏好设置-- 会话管理-- 消息可见性选项--## 其他资源--- [Telegram Bot API 文档](https://core.telegram.org/bots/api)-- [Python Telegram Bot 库](https://python-telegram-bot.org/)-- [BotFather 命令](https://core.telegram.org/bots#botfather)-- [Telegram Bot 最佳实践](https://core.telegram.org/bots/faq)--## 提示--1. **测试**:先创建一个测试机器人来试验设置-2. **日志**:启用调试日志以排除问题-3. **更新**:保持 python-telegram-bot 库更新-4. **监控**:使用机器人分析跟踪使用情况-5. **备份**:定期备份你的 `user_settings.json` 文件diff --git a/docs/plans/message_consolidation_and_toolcall.md b/docs/plans/message_consolidation_and_toolcall.mdindex ce27b16b2..259f7561a 100644--- a/docs/plans/message_consolidation_and_toolcall.md+++ b/docs/plans/message_consolidation_and_toolcall.md@@ -12,7 +12,7 @@本改动的目标是:-- **System / Assistant / Toolcall**:在同一个 Slack thread / Telegram chat 内,只维护并更新 **一条可编辑消息**(append-only 视角)。+- **System / Assistant / Toolcall**:在同一个 Slack thread 内,只维护并更新 **一条可编辑消息**(append-only 视角)。- **Result**:单独发送一条消息,并且 **永远发送**(不可隐藏)。- **Notify**:保持现状(warning/error 及时通知,逐条发送)。@@ -32,11 +32,10 @@## Consolidated Message 行为-- Key:按会话上下文聚合(Slack 用 thread_id;Telegram 用 chat_id)。+- Key:按会话上下文聚合(Slack 用 thread_id)。- 追加规则:每条新内容在末尾追加,并以 `---` 分隔。- 截断规则:超长时丢弃最早内容,并在开头加 `…(truncated)…`。- Slack:默认保留最后 35000 字符- - Telegram:默认保留最后 3200 字符(预留 MarkdownV2 转义膨胀空间)- Visibility:当 `system/assistant/toolcall` 全部被 hide 时,不发送/不更新 consolidated。## Toolcall 定义diff --git a/docs/plans/v2/00_background_and_vision.md b/docs/plans/v2/00_background_and_vision.mdnew file mode 100644index 000000000..50cf2a2a8--- /dev/null+++ b/docs/plans/v2/00_background_and_vision.md@@ -0,0 +1,15 @@+# Background and Vision++## Background++Vibe Remote is evolving from a Slack-first chat bot into a broader agent platform. Today the system primarily routes messages to OpenCode/Claude/Codex backends and responds in chat. This creates adoption friction for new users (Slack app setup, tokens, and event delivery) and limits the product surface to a chat-only experience.++We want to commercialize Vibe Remote while keeping a strong open-source core. The OSS path must remain fully usable for self-hosting and privacy-minded users. The commercial SaaS path must provide a true "one-click" experience, stability, and a higher-level agent platform that individuals are willing to pay for.++## Vision++Build a developer-first agent platform where:+- The default path is frictionless (official Slack app + OAuth + one-step local gateway pairing).+- Privacy-first users can self-host with full functionality.+- Vibe's own agent becomes the primary orchestrator, with OpenCode/ClaudeCode as sub-agents for coding execution.+- Over time, a Vibe-native app becomes the primary user interface, with Slack as a trigger and notification channel.diff --git a/docs/plans/v2/01_goals.md b/docs/plans/v2/01_goals.mdnew file mode 100644index 000000000..3ddb3102f--- /dev/null+++ b/docs/plans/v2/01_goals.md@@ -0,0 +1,30 @@+# Goals (Long-term and Mid-term)++## Long-term Goals++1. Vibe Agent as Primary Orchestrator+ - Vibe's agent handles intent, planning, routing, tool selection, and final response.+ - OpenCode/ClaudeCode/Codex are specialized sub-agents for coding and execution.++2. Vibe-Owned App+ - A Vibe-native app becomes the main UI for complex interactions.+ - Slack remains a trigger/notification surface, not the primary interface.++3. Sustainable Commercial Model+ - SaaS delivers measurable value (ease, stability, observability, premium agent capabilities).+ - Open-source remains fully functional for private/self-host use.++## Mid-term Goals++1. "One-click" SaaS Onboarding+ - Official Slack app + OAuth install.+ - Automatic workspace binding.+ - Local gateway pairing with a single command.++2. Gateway-First Architecture+ - All code execution stays local in the user's environment.+ - Cloud is responsible for ingress, routing, and reliability (no content persistence).++3. Unified Agent Runtime Model+ - Standardized envelope for requests/responses/traces across transports.+ - Consistent routing and control paths for SaaS and self-host.diff --git a/docs/plans/v2/02_implementation_plan.md b/docs/plans/v2/02_implementation_plan.mdnew file mode 100644index 000000000..e4a258a22--- /dev/null+++ b/docs/plans/v2/02_implementation_plan.md@@ -0,0 +1,27 @@+# Implementation Plan++## Phase 0: Foundation Alignment++- Define the transport abstraction for inbound events (Slack Socket Mode vs Cloud Relay).+- Define a unified agent run model (request, response, trace, metadata).+- Make sure the self-host path remains fully functional with Socket Mode.++## Phase 1: SaaS MVP (No Data Persistence)++- Official Slack app with OAuth install.+- Cloud ingress for Slack Events API.+- Relay service that forwards events to local gateways over WebSocket/gRPC.+- Local gateway that connects out to the relay and forwards events to the existing agent runtime.+- Minimal control plane: workspace status, gateway online/offline, basic error logs.++## Phase 2: Commercial Value Expansion++- Observability: structured run logs, performance metrics, error diagnostics.+- Higher-level Vibe agent orchestration (task planning + sub-agent execution).+- Tiered limits and billing (per user or per workspace).++## Phase 3: Vibe App++- Web console evolves into a real UI for tasks, runs, and approvals.+- Slack becomes a trigger/notification channel.+- Integrations extend beyond Slack (GitHub/CI, issue trackers).diff --git a/docs/plans/v2/03_architecture_and_design.md b/docs/plans/v2/03_architecture_and_design.mdnew file mode 100644index 000000000..166941ca2--- /dev/null+++ b/docs/plans/v2/03_architecture_and_design.md@@ -0,0 +1,45 @@+# Architecture and Design++## Deployment Modes++### SaaS (Commercial)++Slack Events API -> Cloud Ingress -> Relay -> Local Gateway -> Agent Runtime -> Sub-Agents++- Cloud does not persist message content.+- Gateway performs all local execution and tool access.+- Cloud maintains workspace bindings and connection routing.++### Self-host (Open Source)++Slack Socket Mode -> Local Gateway -> Agent Runtime -> Sub-Agents++- No cloud dependency.+- User provides Slack app tokens and runs the gateway locally.++## Core Components++1. Ingress Adapter+ - Slack Events API (SaaS)+ - Slack Socket Mode (Self-host)++2. Relay Transport+ - Outbound WebSocket or gRPC from gateway to cloud+ - Authentication via workspace-scoped token+ - Heartbeats + retry++3. Agent Runtime+ - Unified request/response envelope+ - Routing to Vibe Agent or sub-agents+ - Tool execution is local++4. Control Plane (SaaS)+ - Workspace management+ - Gateway status+ - Minimal observability++## Key Design Decisions++- Gateway-first execution for privacy and local tooling.+- Cloud as ingress and reliability layer, not a data store.+- Open-source core under Apache license; cloud features deliver commercial value.diff --git a/docs/plans/v2/04_v2_milestones.md b/docs/plans/v2/04_v2_milestones.mdnew file mode 100644index 000000000..14fa7d793--- /dev/null+++ b/docs/plans/v2/04_v2_milestones.md@@ -0,0 +1,57 @@+# V2 Milestones and Decisions++## Confirmed Decisions++- Implementation language: Python (no TypeScript rewrite for V2).+- Install flow: single Bash command, prefer `uv` tooling, CLI-first.+- Configuration UI: local web server launched from CLI.+- Data model: JSON files only.+- Storage location: `~/.vibe_remote/`.+- Modes: Slack-only for V2 (platform abstraction remains for future Vibe app).+- Migration: no V1 migration; V2 starts clean.++## V2 Milestones++### M1: Local Data Directory + Config Model++- Establish `~/.vibe_remote/` as the single home for config/state/logs.+- Split settings and sessions into separate JSON files.+- Remove `.env` and legacy config paths from the V2 flow.++Proposed structure:++- `~/.vibe_remote/config/config.json`+- `~/.vibe_remote/state/settings.json`+- `~/.vibe_remote/state/sessions.json`+- `~/.vibe_remote/logs/vibe_remote.log`++### M2: CLI Install + Command Surface++- One-line install (Bash + `uv` tooling).+- CLI commands:+ - `vibe-remote setup` (launch local config UI)+ - `vibe-remote start` (run service)+ - `vibe-remote status` (runtime status)+ - `vibe-remote stop` (stop runtime)+ - `vibe-remote doctor` (self-check)++### M3: Local Web UI (Setup Wizard)++- UI starts from CLI and opens a browser.+- Two setup paths:+ - SaaS: OAuth flow, workspace binding, local gateway pairing.+ - Self-host: Slack app manifest guidance + token validation.++### M4: SaaS MVP (No Data Persistence)++- Official Slack App + OAuth install.+- Events API ingress.+- Relay to local gateway (WebSocket/gRPC).+- Cloud stores only workspace binding and connection status.++## Non-Goals (V2)++- Telegram support in V2 (explicitly out of scope).+- V1 migration or `.env` compatibility.+- Cloud-hosted execution/workspaces.+- TypeScript rewrite or Bun-based binaries.diff --git a/docs/plans/v2/05_config_model.md b/docs/plans/v2/05_config_model.mdnew file mode 100644index 000000000..0797ef6d7--- /dev/null+++ b/docs/plans/v2/05_config_model.md@@ -0,0 +1,92 @@+# Configuration Model (V2)++V2 stores all user data under `~/.vibe_remote/` as JSON files. The model preserves current functionality while separating user settings from session state.++## File Layout++- `~/.vibe_remote/config/config.json`+- `~/.vibe_remote/state/settings.json`+- `~/.vibe_remote/state/sessions.json`+- `~/.vibe_remote/logs/vibe_remote.log`++## config.json (Global Configuration)++### Top-level++- `mode`: `"saas"` | `"self_host"`+- `version`: config schema version (string)++### slack++- `bot_token`: Slack bot token (`xoxb-...`)+- `app_token`: Slack app token (`xapp-...`) (self-host only)+- `team_id`: Slack workspace ID (SaaS OAuth)+- `team_name`: Slack workspace name (SaaS OAuth)+- `app_id`: Slack app ID (optional, for diagnostics)+- `signing_secret`: optional for SaaS relay validation++### gateway++- `relay_url`: cloud relay endpoint (SaaS only)+- `workspace_token`: workspace binding token for relay auth+- `client_id`: local gateway identifier+- `client_secret`: local gateway secret or pairing token+- `last_connected_at`: last successful relay connect (ISO 8601)++### runtime++- `default_cwd`: default working directory+- `log_level`: `"DEBUG" | "INFO" | "WARNING" | "ERROR"`+- `require_mention`: bool (channel messages require @mention)+- `target_channels`: list of channel IDs or `"*"` for all++### agents++- `default_backend`: `"opencode" | "claude" | "codex"`+- `opencode`:+ - `enabled`: bool+ - `cli_path`: absolute path to OpenCode CLI+ - `default_agent`: optional default OpenCode agent+ - `default_model`: optional default model+ - `default_reasoning_effort`: `"low" | "medium" | "high" | "xhigh"`+- `claude`:+ - `enabled`: bool+ - `cli_path`: absolute path to ClaudeCode CLI+ - `default_model`: optional model override+- `codex`:+ - `enabled`: bool+ - `cli_path`: absolute path to Codex CLI+ - `default_model`: optional model override++### ui++- `setup_port`: port for local setup UI+- `open_browser`: bool++## settings.json (User/Channel Settings)++Settings are stored per channel and preserve existing functionality.++- `channels`: map keyed by `channel_id`+ - `hidden_message_types`: list (default: `system`, `assistant`, `toolcall`)+ - `custom_cwd`: optional cwd override+ - `routing`:+ - `agent_backend`: `"opencode" | "claude" | "codex" | null`+ - `opencode_agent`: optional OpenCode agent+ - `opencode_model`: optional OpenCode model+ - `opencode_reasoning_effort`: optional OpenCode reasoning effort++## sessions.json (Session State)++Session tracking is separated from settings and aligned with current behavior.++- `channels`: map keyed by `channel_id`+ - `session_mappings`: map of base session to path -> session_id (agent-aware)+ - `active_threads`: Slack thread tracking+ - `last_activity`: ISO 8601 timestamp++## Notes++- V2 does not read `.env` or legacy settings files.+- All keys are optional unless required by the selected mode.+- Default values should be applied by the loader if fields are missing.diff --git a/docs/plans/v2/06_gateway_protocol.md b/docs/plans/v2/06_gateway_protocol.mdnew file mode 100644index 000000000..83face6e2--- /dev/null+++ b/docs/plans/v2/06_gateway_protocol.md@@ -0,0 +1,155 @@+# Gateway Protocol (V2)++This document defines the minimal relay protocol between the local gateway and the cloud (SaaS mode). The protocol must support low-latency delivery, reconnect safety, and workspace isolation.++## Transport++- Preferred: WebSocket (gateway initiates outbound connection).+- Alternative: gRPC streaming (compatible envelope below).+- All messages are JSON objects.++## Authentication++Gateway connects with workspace-scoped credentials.++- `workspace_token`: issued after OAuth install.+- `client_id`: locally generated unique id.++Handshake payload:++```+{+ "type": "hello",+ "workspace_token": "...",+ "client_id": "...",+ "client_version": "v2",+ "capabilities": ["events", "commands", "files"]+}+```++Server responds:++```+{+ "type": "hello_ack",+ "status": "ok",+ "server_time": "2026-01-18T12:00:00Z",+ "heartbeat_interval": 25+}+```++## Message Envelope++All payloads use a shared envelope to enable retry, tracing, and ordering.++Common fields:++- `id`: unique message id (uuid)+- `type`: `event` | `command` | `response` | `error` | `ack` | `heartbeat`+- `workspace_id`: Slack team id+- `channel_id`: Slack channel id+- `thread_id`: Slack thread id (optional)+- `user_id`: Slack user id+- `timestamp`: ISO 8601+- `payload`: event-specific body+- `trace_id`: optional run trace id++Example inbound event:++```+{+ "id": "...",+ "type": "event",+ "workspace_id": "T123",+ "channel_id": "C456",+ "thread_id": "123.456",+ "user_id": "U789",+ "timestamp": "2026-01-18T12:00:01Z",+ "payload": {+ "event_type": "message",+ "text": "hello",+ "message_id": "1700000000.0001"+ }+}+```++## ACK + Retry++- The gateway must ACK every `event` with `ack` containing the same `id`.+- Server retries if no ACK within `ack_timeout` (default 5s).+- `retry_count` is included in retried messages.++ACK example:++```+{+ "type": "ack",+ "id": "...",+ "timestamp": "2026-01-18T12:00:02Z"+}+```++## Responses (Gateway -> Cloud)++Gateway responses return execution output to cloud for Slack posting.++```+{+ "id": "...",+ "type": "response",+ "workspace_id": "T123",+ "channel_id": "C456",+ "thread_id": "123.456",+ "user_id": "U789",+ "timestamp": "2026-01-18T12:00:05Z",+ "payload": {+ "text": "...",+ "blocks": [],+ "attachments": [],+ "status": "ok"+ },+ "trace_id": "run-..."+}+```++## Heartbeats++- Gateway sends `heartbeat` every `heartbeat_interval` seconds.+- Server responds with `heartbeat_ack`.++```+{"type": "heartbeat", "timestamp": "..."}+```++## Error Handling++```+{+ "type": "error",+ "id": "...",+ "timestamp": "...",+ "payload": {+ "code": "invalid_auth",+ "message": "..."+ }+}+```++## Reconnect Behavior++- Gateway reconnects with exponential backoff.+- After reconnect, gateway may send `resume` with last seen message id.+- Server can re-deliver missed events by id.++```+{+ "type": "resume",+ "last_event_id": "..."+}+```++## Security Notes++- Only workspace-scoped tokens are used.+- No Slack app-level tokens are exposed to the gateway.+- Cloud stores minimal metadata (workspace binding + connection status).diff --git a/docs/plans/v2/07_repo_and_split.md b/docs/plans/v2/07_repo_and_split.mdnew file mode 100644index 000000000..29ca824a7--- /dev/null+++ b/docs/plans/v2/07_repo_and_split.md@@ -0,0 +1,78 @@+# Client/Server Split and Repo Layout++This document clarifies what lives in the local gateway (client) vs cloud SaaS (server), and proposes a short-term repo layout.++## Boundary Summary++- Client (local gateway): anything that needs local resources or local execution.+- Server (cloud): Slack OAuth, Events API ingress, tenant routing, and relay.++## Client (Local Gateway) Scope++Keep in client:+- `core/` (controller, handlers, routing)+- `modules/agents/` (OpenCode, ClaudeCode, Codex)+- `modules/session_manager.py`+- `modules/settings_manager.py`+- `modules/im/formatters/`+- `modules/im/base.py` (interface)+- `modules/im/slack.py` (Socket Mode only, self-host path)+- `config/` (client runtime config loader)+- `main.py` (client entrypoint, CLI hooks)++Client responsibilities:+- Connect to relay (SaaS mode) or Slack Socket Mode (self-host mode).+- Execute agent logic locally and return results.+- Maintain local session/settings state under `~/.vibe_remote/`.++## Server (Cloud SaaS) Scope++Move to server:+- OAuth install flow+- Slack Events API receiver+- Workspace binding and connection state+- Relay routing (WebSocket/gRPC)+- Slack Web API for message responses++Server responsibilities:+- No local execution, no filesystem access.+- No message persistence (V2 requirement).++## Minimal File Migration (Conceptual)++From current code, split logically as follows:++- Extract Slack Events API handler from `modules/im/slack.py` into `cloud/ingress/slack_events.py`.+- Create `cloud/relay/` service to manage gateway connections and routing.+- Create `cloud/api/oauth.py` for Slack OAuth callbacks and workspace token issuance.+- Keep Socket Mode handling inside client `modules/im/slack.py` for self-host mode only.++## Repo Layout (Short-term)++Keep one repo for fast iteration. Add a `cloud/` module:++```+/ (repo root)+ core/+ modules/+ config/+ cloud/+ ingress/+ relay/+ api/+ storage/+ scripts/+ docs/+```++## Repo Layout (Long-term)++Split into two repos after V2 stabilizes:++- `vibe-remote-gateway` (client)+- `vibe-remote-cloud` (server)++## Notes++- The client remains the open-source Apache component.+- The server (cloud) can be proprietary or open-core as needed.diff --git a/docs/plans/v2/08_web_ui_flow.md b/docs/plans/v2/08_web_ui_flow.mdnew file mode 100644index 000000000..80acf2210--- /dev/null+++ b/docs/plans/v2/08_web_ui_flow.md@@ -0,0 +1,65 @@+# Web UI Setup Flow (V2)++This document defines the local setup UI flow, covering SaaS and self-host modes.++## Entry++- CLI command: `vibe-remote setup`+- Starts a local web server and opens the browser.++## Page Outline++1. Welcome+2. Mode selection (SaaS / Self-host)+3. Local agent executors (OpenCode / ClaudeCode / Codex)+4. Slack configuration (mode-specific)+5. Channel-level settings+6. Validation + finish+7. Start service++## SaaS Mode++### OAuth callback++- Slack OAuth requires HTTPS and a public domain.+- Default flow: OAuth redirects to cloud, then the local UI polls cloud for status.+- Optional: if Slack supports localhost redirect for the installed app, the UI can handle direct callback.++### Workspace binding++- Show team name/id, bot user id, and connection status.+- Display the relay binding token and gateway status.++### Channel list++- Fetch the list of channels where the bot is present.+- For each channel, allow per-channel configuration:+ - Enable/disable bot responses.+ - Assign local work path.+ - Select agent backend (OpenCode / ClaudeCode / Codex).+ - Configure backend-specific options (model, reasoning effort, agent).++## Self-host Mode (Socket Mode)++- Provide an auto-generated Slack App Manifest (copy button).+- Guide the user to create the app and install it.+- Ask for `xoxb-` and `xapp-` tokens.+- Signing secret is optional (Socket Mode does not require it).+- Validate with `auth.test` and a Socket Mode connection check.++## Local Executors++- Detect CLI paths automatically with a "Detect" button.+- Allow manual override.+- OpenCode is the recommended default backend.++## Validation++- Slack token validation (`auth.test`).+- Optional test message to a selected channel.+- Report missing scopes or misconfigurations.++## Single Workspace Constraint++- V2 supports only one workspace binding.+- The UI should block additional workspace installs until reset.diff --git a/docs/plans/v2/09_cli_and_install.md b/docs/plans/v2/09_cli_and_install.mdnew file mode 100644index 000000000..b00f73e78--- /dev/null+++ b/docs/plans/v2/09_cli_and_install.md@@ -0,0 +1,56 @@+# CLI and Install Flow (V2)++This document defines the install script, CLI command surface, and runtime behavior.++## Install Script++Entry point:++```+curl -fsSL https://vibe.remote/install.sh | bash+```++Behavior:++- Auto-install `uv` without user confirmation.+- Version check:+ - If `uv` exists and meets minimum version, keep it.+ - If `uv` exists but is outdated, upgrade automatically.+ - If `uv` is missing, install automatically.+- Install CLI via `uv tool install vibe`.++## CLI Command Surface++### `vibe`++Single smart entrypoint.++- If config directory or files do not exist, initialize and launch the setup UI.+- If config exists, start the service.+- Always starts the service in the background.+- Automatically opens the Web UI, then exits the CLI.++### `vibe stop`++- Stop the background service by PID.+- Clears runtime state.++### `vibe status`++- Show service state (running/stopped), mode, workspace, and relay status.++### `vibe doctor`++- Full diagnostics with detailed output:+ - Config validation+ - Slack token checks (`auth.test`)+ - CLI executables detection+ - Relay connectivity (SaaS)+- The same diagnostic results are visible in the Web UI.++## Runtime Behavior++- Service runs in the background by default.+- Web UI is opened automatically on start.+- Web UI provides start/stop/restart controls.+- Runtime data stored under `~/.vibe_remote/runtime/` (pid, ports, status).diff --git a/docs/plans/v2/10_slack_permissions.md b/docs/plans/v2/10_slack_permissions.mdnew file mode 100644index 000000000..a6d52e8f3--- /dev/null+++ b/docs/plans/v2/10_slack_permissions.md@@ -0,0 +1,64 @@+# Slack Permissions and Event Template (V2)++This template consolidates the recommended Slack scopes and event subscriptions based on `docs/SLACK_SETUP.md`.++## OAuth Scopes (Bot Token)++### Essential (Required)++- `channels:history` (public channel message history)+- `channels:read` (public channel metadata)+- `chat:write` (send messages)+- `app_mentions:read` (mentions)+- `users:read` (basic user info)+- `commands` (slash commands)++### Private Channel Support++- `groups:read` (private channel metadata)+- `groups:history` (private channel message history)+- `groups:write` (send messages to private channels)++### Enhanced Features++- `chat:write.public` (send without joining)+- `chat:write.customize` (custom username/avatar)+- `files:read` (read shared files)+- `files:write` (upload files)+- `reactions:read` (read reactions)+- `reactions:write` (add/remove reactions)+- `users:read.email` (read user emails)+- `team:read` (workspace metadata)++## Socket Mode (Self-host Only)++- App-level token scope: `connections:write`++## Event Subscriptions++### Required Bot Events++- `message.channels`+- `message.groups`+- `app_mention`++### Optional/Recommended Bot Events++- `member_joined_channel`+- `member_left_channel`+- `channel_created`+- `channel_renamed`+- `team_join`++## Slash Commands (Self-host Socket Mode)++Create the following commands with empty Request URL:++- `/start` (Open main menu)+- `/stop` (Stop current session)++## Notes++- Add all scopes up front to avoid reinstall loops.+- Socket Mode is used for self-host; SaaS uses Events API.+- Slash command creation is manual in Slack UI.diff --git a/docs/plans/v2/README.md b/docs/plans/v2/README.mdnew file mode 100644index 000000000..27a6fb232--- /dev/null+++ b/docs/plans/v2/README.md@@ -0,0 +1,15 @@+# V2 Plan Overview++This folder contains the V2 plan for Vibe Remote, including background/vision, goals, implementation plan, and architecture/design.++- 00_background_and_vision.md+- 01_goals.md+- 02_implementation_plan.md+- 03_architecture_and_design.md+- 04_v2_milestones.md+- 05_config_model.md+- 06_gateway_protocol.md+- 07_repo_and_split.md+- 08_web_ui_flow.md+- 09_cli_and_install.md+- 10_slack_permissions.mddiff --git a/main.py b/main.pyindex dec0ddad2..321d858b3 100644--- a/main.py+++ b/main.py@@ -4,13 +4,10 @@ import signalimport sysimport loggingimport asyncio-from dotenv import load_dotenv-from config.settings import AppConfig+from config.paths import ensure_data_dirs, get_logs_dir+from config.v2_config import V2Configfrom core.controller import Controller-# Load environment variables from .env file-load_dotenv()-def setup_logging(level: str = "INFO"):"""Setup logging configuration with file location and line numbers"""@@ -20,13 +17,8 @@ def setup_logging(level: str = "INFO"):# For development, you can use this more detailed format:# log_format = '%(asctime)s - %(name)s - %(levelname)s - [%(pathname)s:%(lineno)d] - %(funcName)s() - %(message)s'- # Ensure logs directory exists- logs_dir = 'logs'- try:- os.makedirs(logs_dir, exist_ok=True)- except Exception:- # Fallback to current directory if logs dir cannot be created- logs_dir = '.'+ ensure_data_dirs()+ logs_dir = str(get_logs_dir())logging.basicConfig(level=getattr(logging, level.upper()),@@ -62,19 +54,21 @@ def main():"""Main entry point"""try:# Load configuration- config = AppConfig.from_env()-+ config = V2Config.load()+# Setup logging- setup_logging(config.log_level)+ setup_logging(config.runtime.log_level)logger = logging.getLogger(__name__)apply_claude_sdk_patches()logger.info("Starting vibe-remote service...")- logger.info(f"Working directory: {config.claude.cwd}")+ logger.info(f"Working directory: {config.runtime.default_cwd}")# Create and run controller- controller = Controller(config)+ from config.v2_compat import to_app_config++ controller = Controller(to_app_config(config))shutdown_initiated = Falsediff --git a/modules/agents/codex_agent.py b/modules/agents/codex_agent.pyindex 57000227a..d9dcc3457 100644--- a/modules/agents/codex_agent.py+++ b/modules/agents/codex_agent.py@@ -366,5 +366,5 @@ class CodexAgent(BaseAgent):await self.controller.emit_agent_message(request.context,"notify",- f"⚠️ {message}\n请查看 `logs/vibe_remote.log` 获取更多细节。",+ f"⚠️ {message}\n请查看 `~/.vibe_remote/logs/vibe_remote.log` 获取更多细节。",)diff --git a/modules/claude_client.py b/modules/claude_client.pyindex d66a7d531..fd074ba5f 100644--- a/modules/claude_client.py+++ b/modules/claude_client.py@@ -11,8 +11,8 @@ from claude_code_sdk import (ToolUseBlock,ToolResultBlock,)-from config import ClaudeConfig-from modules.im.formatters import BaseMarkdownFormatter, TelegramFormatter+from config.v2_compat import ClaudeCompatConfig+from modules.im.formatters import BaseMarkdownFormatter, SlackFormatterlogger = logging.getLogger(__name__)@@ -20,17 +20,15 @@ logger = logging.getLogger(__name__)class ClaudeClient:def __init__(- self, config: ClaudeConfig, formatter: Optional[BaseMarkdownFormatter] = None+ self, config: ClaudeCompatConfig, formatter: Optional[BaseMarkdownFormatter] = None):self.config = config- self.formatter = (- formatter or TelegramFormatter()- ) # Default to Telegram for backward compatibility+ self.formatter = formatter or SlackFormatter()self.options = ClaudeCodeOptions(- permission_mode=config.permission_mode,+ permission_mode=config.permission_mode, # type: ignore[arg-type]cwd=config.cwd,system_prompt=config.system_prompt,- )+ ) # type: ignore[arg-type]def format_message(self, message, get_relative_path: Optional[Callable[[str], str]] = None@@ -111,7 +109,9 @@ class ClaudeClient:def _format_tool_result_block(self, block: ToolResultBlock) -> str:"""Format ToolResultBlock using formatter"""- return self.formatter.format_tool_result(block.is_error, block.content)+ is_error = bool(block.is_error) if block.is_error is not None else False+ content = block.content if isinstance(block.content, str) else None+ return self.formatter.format_tool_result(is_error, content)def _format_system_message(self, message: SystemMessage) -> str:"""Format SystemMessage using formatter"""diff --git a/modules/im/__init__.py b/modules/im/__init__.pyindex 53879f334..6fdce8ff1 100644--- a/modules/im/__init__.py+++ b/modules/im/__init__.py@@ -27,23 +27,15 @@ from .factory import IMFactory# Platform implementations are available but not imported by default# to avoid circular import issues. Import them explicitly if needed:-# from .telegram import TelegramBot# from .slack import SlackBot-# Package metadata-__version__ = "1.0.0"__all__ = [- # Core abstractions"BaseIMClient",- "BaseIMConfig",+ "BaseIMConfig","MessageContext","InlineButton","InlineKeyboard",- # Factory"IMFactory",- # Implementations available via dynamic import- # "TelegramBot",- # "SlackBot",]# Convenience function for quick client creationdiff --git a/modules/im/base.py b/modules/im/base.pyindex 7876664fc..9259b61ef 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -37,23 +37,15 @@ class InlineKeyboard:class BaseIMConfig(ABC):"""Abstract base class for IM platform configurations"""- @classmethod@abstractmethod- def from_env(cls) -> 'BaseIMConfig':- """Create configuration from environment variables"""- pass-- @abstractmethod- def validate(self) -> bool:+ def validate(self) -> None:"""Validate the configuration-- Returns:- True if configuration is valid-+Raises:ValueError: If configuration is invalid"""pass+def validate_required_string(self, value: Optional[str], field_name: str) -> None:"""Helper method to validate required string fields@@ -81,9 +73,9 @@ class BaseIMConfig(ABC):Raises:ValueError: If value is not a valid integer"""- if not value:+ if value is None or value == "":return None-+try:return int(value)except ValueError:@@ -101,7 +93,7 @@ class BaseIMClient(ABC):self.on_command_callbacks: Dict[str, Callable] = {}self.on_callback_query_callback: Optional[Callable] = None# Platform-specific formatter will be set by subclasses- self.formatter = None+ self.formatter: Optional[Any] = Nonedef get_default_parse_mode(self) -> Optional[str]:"""Get the default parse mode for this platformdiff --git a/modules/im/factory.py b/modules/im/factory.pyindex 629ab4cd2..5c4faa3f6 100644--- a/modules/im/factory.py+++ b/modules/im/factory.py@@ -7,7 +7,7 @@ from .base import BaseIMClient# Use delayed imports to avoid circular import issuesif TYPE_CHECKING:- from config.settings import AppConfig, TelegramConfig, SlackConfig+ from config.v2_config import V2Configlogger = logging.getLogger(__name__)@@ -29,34 +29,21 @@ class IMFactory:ValueError: If platform is not supported"""# Dynamic imports to avoid circular dependency- from .telegram import TelegramBotfrom .slack import SlackBot-- platform = config.platform.lower()-- if platform == "telegram":- if not config.telegram:- raise ValueError("Telegram configuration not found")- logger.info("Creating Telegram client")- return TelegramBot(config.telegram)-- elif platform == "slack":- if not config.slack:- raise ValueError("Slack configuration not found")- logger.info("Creating Slack client")- return SlackBot(config.slack)-- else:- raise ValueError(f"Unsupported IM platform: {platform}")++ if not config.slack:+ raise ValueError("Slack configuration not found")+ logger.info("Creating Slack client")+ return SlackBot(config.slack)@staticmethoddef get_supported_platforms() -> list[str]:"""Get list of supported platforms-+Returns:List of supported platform names"""- return ["telegram", "slack"]+ return ["slack"]@staticmethoddef validate_platform_config(config) -> None:@@ -68,15 +55,6 @@ class IMFactory:Raises:ValueError: If configuration is invalid"""- platform = config.platform.lower()-- if platform not in IMFactory.get_supported_platforms():- raise ValueError(f"Unsupported platform: {platform}")-- # Validate platform-specific configuration- if platform == "telegram" and config.telegram:- config.telegram.validate()- elif platform == "slack" and config.slack:- config.slack.validate()- else:- raise ValueError(f"Missing configuration for platform: {platform}")\ No newline at end of file+ if config.slack is None:+ raise ValueError("Missing configuration for platform: slack")+ config.slack.validate()diff --git a/modules/im/formatters/__init__.py b/modules/im/formatters/__init__.pyindex 646df275c..da4bea291 100644--- a/modules/im/formatters/__init__.py+++ b/modules/im/formatters/__init__.py@@ -1,5 +1,4 @@from .base_formatter import BaseMarkdownFormatter-from .telegram_formatter import TelegramFormatterfrom .slack_formatter import SlackFormatter-__all__ = ['BaseMarkdownFormatter', 'TelegramFormatter', 'SlackFormatter']\ No newline at end of file+__all__ = ['BaseMarkdownFormatter', 'SlackFormatter']diff --git a/modules/im/formatters/telegram_formatter.py b/modules/im/formatters/telegram_formatter.pydeleted file mode 100644index 6fbf0e760..000000000--- a/modules/im/formatters/telegram_formatter.py+++ /dev/null@@ -1,53 +0,0 @@-from .base_formatter import BaseMarkdownFormatter---class TelegramFormatter(BaseMarkdownFormatter):- """Telegram formatter that outputs standard markdown-- This formatter outputs clean markdown that will be converted to HTML- before sending to Telegram, avoiding MarkdownV2 escaping issues entirely.- """-- # Tool output emoji prefixes that indicate pre-formatted content- TOOL_EMOJI_PREFIXES = ("🔧", "💻", "🔍", "📖", "✏️", "📝", "📄", "📓", "🌐", "✅", "❌", "🤖", "📂", "🔎", "🚪")-- # ============================================================================- # Core abstract method implementations - Standard Markdown- # ============================================================================-- def format_bold(self, text: str) -> str:- """Format bold text in standard markdown"""- return f"**{text}**"-- def format_italic(self, text: str) -> str:- """Format italic text in standard markdown"""- return f"*{text}*"-- def format_strikethrough(self, text: str) -> str:- """Format strikethrough text in standard markdown"""- return f"~~{text}~~"-- def format_link(self, text: str, url: str) -> str:- """Format hyperlink in standard markdown"""- return f"[{text}]({url})"-- def escape_special_chars(self, text: str) -> str:- """No escaping needed for HTML conversion - return text as-is"""- return text-- # ============================================================================- # Override message formatting methods to handle Claude content appropriately- # ============================================================================-- def format_assistant_message(self, content_parts: list[str]) -> str:- """Format assistant message with clean markdown"""- header = self.format_section_header("Assistant", "🤖")-- # For HTML conversion, we don't need to escape tool output differently- # Just join all parts cleanly- parts = [header] + content_parts- return "\n\n".join(parts)-- def _is_tool_output(self, text: str) -> bool:- """Check if text is already formatted tool output"""- return text.startswith(self.TOOL_EMOJI_PREFIXES)\ No newline at end of filediff --git a/modules/im/slack.py b/modules/im/slack.pyindex 527dfc766..55126b07c 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -11,7 +11,7 @@ from slack_sdk.errors import SlackApiErrorfrom markdown_to_mrkdwn import SlackMarkdownConverterfrom .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton-from config.settings import SlackConfig+from config.v2_config import SlackConfigfrom .formatters import SlackFormatterlogger = logging.getLogger(__name__)@@ -446,7 +446,7 @@ class SlackBot(BaseIMClient):self, callback_id: str, text: Optional[str] = None, show_alert: bool = False) -> bool:"""Answer a Slack interactive callback"""- # In Slack, we don't have a direct equivalent to Telegram's answer_callback_query+ # Slack does not have a direct equivalent to answer_callback_query# Instead, we typically update the message or send an ephemeral message# This will be handled in the event processingreturn True@@ -1847,7 +1847,7 @@ class SlackBot(BaseIMClient):async def _is_authorized_channel(self, channel_id: str) -> bool:"""Check if a channel is authorized based on whitelist configuration"""- target_channel = self.config.target_channel+ target_channel = self.config.target_channels# If None/null, accept all channelsif target_channel is None:diff --git a/modules/im/telegram.py b/modules/im/telegram.pydeleted file mode 100644index 5ba5dd670..000000000--- a/modules/im/telegram.py+++ /dev/null@@ -1,544 +0,0 @@-import asyncio-import logging-from typing import Callable, Optional, Dict, Any-from telegramify_markdown import markdownify-from telegram import (- Update,- Bot,- InlineKeyboardMarkup as TGInlineKeyboardMarkup,- InlineKeyboardButton as TGInlineKeyboardButton,-)-from telegram.ext import (- Application,- CommandHandler,- MessageHandler,- filters,- ContextTypes,- CallbackQueryHandler,-)-from telegram.error import TelegramError-from config.settings import TelegramConfig-from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton-from .formatters import TelegramFormatter---logger = logging.getLogger(__name__)---class TelegramBot(BaseIMClient):- def __init__(self, config: TelegramConfig):- super().__init__(config)- self.application = Application.builder().token(config.bot_token).build()-- # Initialize Telegram formatter- self.formatter = TelegramFormatter()-- # Store callback queries for answering- self._callback_queries: Dict[str, Any] = {}-- def _convert_to_markdownv2(self, text: str) -> str:- """Convert markdown text to Telegram MarkdownV2 format"""- try:- # Use telegramify_markdown to convert to MarkdownV2- return markdownify(text)- except Exception as e:- logger.warning(f"Error converting to MarkdownV2: {e}, sending as plain text")- # Fallback: escape basic special characters- import re- # Escape special characters for MarkdownV2- escape_chars = r'_*[]()~`>#+-=|{}.!'- for char in escape_chars:- text = text.replace(char, f'\\{char}')- return text--- def get_default_parse_mode(self) -> str:- """Get the default parse mode for Telegram - uses MarkdownV2"""- return "MarkdownV2"-- def should_use_thread_for_reply(self) -> bool:- """Telegram doesn't use threads for replies"""- return False-- async def handle_telegram_message(- self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE- ):- """Handle incoming text messages from Telegram"""- chat_id = update.effective_chat.id- chat_type = update.effective_chat.type-- # Check if message is authorized based on whitelist- if not self._is_authorized_chat(chat_id, chat_type):- logger.info(f"Unauthorized message from chat: {chat_id}")- await self._send_unauthorized_message(chat_id)- return-- # Create MessageContext- context = MessageContext(- user_id=str(update.effective_user.id),- channel_id=str(chat_id),- message_id=str(update.message.message_id),- platform_specific={"update": update, "tg_context": tg_context},- )-- message_text = update.message.text-- # Check if it's a command- if message_text.startswith("/"):- parts = message_text.split(maxsplit=1)- command = parts[0][1:] # Remove the /- args = parts[1] if len(parts) > 1 else ""-- if command in self.on_command_callbacks:- await self.on_command_callbacks[command](context, args)- elif self.on_message_callback:- await self.on_message_callback(context, message_text)-- async def handle_telegram_callback(- self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE- ):- """Handle callback queries from inline keyboards"""- query = update.callback_query- chat_id = query.message.chat_id- chat_type = query.message.chat.type-- logger.info(f"Telegram callback received: data='{query.data}', user={query.from_user.id}, chat={chat_id}")-- # Check if callback is authorized based on whitelist- if not self._is_authorized_chat(chat_id, chat_type):- logger.info(f"Unauthorized callback from chat: {chat_id}")- # For callback queries, we can answer with an alert- await query.answer(- "❌ This chat is not authorized to use bot commands.", show_alert=True- )- return-- # Store the query for later use in answer_callback- self._callback_queries[query.id] = query-- # Create MessageContext- context = MessageContext(- user_id=str(query.from_user.id),- channel_id=str(chat_id),- message_id=str(query.message.message_id),- platform_specific={- "query": query,- "update": update,- "tg_context": tg_context,- "callback_id": query.id,- },- )-- if self.on_callback_query_callback:- logger.info(f"Calling on_callback_query_callback with data: {query.data}")- await self.on_callback_query_callback(context, query.data)- logger.info(f"Finished on_callback_query_callback for data: {query.data}")- else:- logger.warning("No on_callback_query_callback registered!")-- # Always answer the callback to stop loading animation- try:- await query.answer()- except Exception as e:- logger.warning(f"Failed to answer callback query: {e}")-- async def _wrap_command(- self, command_name: str, update: Update, tg_context: ContextTypes.DEFAULT_TYPE- ):- """Wrap a command handler to convert Update to MessageContext"""- if command_name not in self.on_command_callbacks:- return-- chat_id = update.effective_chat.id- chat_type = update.effective_chat.type-- # Check if command is authorized based on whitelist- if not self._is_authorized_chat(chat_id, chat_type):- logger.info(f"Unauthorized command from chat: {chat_id}")- await self._send_unauthorized_message(chat_id)- return-- # Extract args- message_text = update.message.text- parts = message_text.split(maxsplit=1)- args = parts[1] if len(parts) > 1 else ""-- # Create MessageContext- context = MessageContext(- user_id=str(update.effective_user.id),- channel_id=str(update.effective_chat.id),- message_id=str(update.message.message_id),- platform_specific={"update": update, "tg_context": tg_context},- )-- await self.on_command_callbacks[command_name](context, args)-- def setup_handlers(self):- """Setup bot command and message handlers"""- # Register command handlers dynamically- for command in self.on_command_callbacks:- async def handler(update, context, cmd=command):- try:- await self._wrap_command(cmd, update, context)- except Exception as e:- logger.error(f"Error in command handler {cmd}: {e}", exc_info=True)- try:- await update.message.reply_text(f"❌ Error processing command: {str(e)}")- except Exception as reply_error:- logger.error(f"Failed to send error reply: {reply_error}")-- self.application.add_handler(CommandHandler(command, handler))-- # Register callback query handler- self.application.add_handler(- CallbackQueryHandler(self.handle_telegram_callback)- )-- # Register message handler- self.application.add_handler(- MessageHandler(- filters.TEXT & ~filters.COMMAND, self.handle_telegram_message- )- )-- async def send_settings_message(- self, chat_id: int, text: str, reply_markup: TGInlineKeyboardMarkup- ):- """Send message with inline keyboard"""- bot = self.application.bot- await bot.send_message(- chat_id=chat_id,- text=text,- parse_mode="MarkdownV2",- reply_markup=reply_markup,- )--- def run(self):- """Run the bot with infinite retry mechanism"""- import time-- self.setup_handlers()-- retry_delay = 5 # seconds- attempt = 1-- while True:- try:- logger.info(f"Starting Telegram bot (attempt {attempt})...")- self.application.run_polling()- break # If successful, break out of retry loop-- except KeyboardInterrupt:- logger.info("Received keyboard interrupt, shutting down...")- break-- except Exception as e:- logger.error(f"Telegram bot failed (attempt {attempt}): {e}")- logger.info(f"Retrying in {retry_delay} seconds...")-- try:- time.sleep(retry_delay)- except KeyboardInterrupt:- logger.info(- "Received keyboard interrupt during retry wait, shutting down..."- )- break-- retry_delay = min(retry_delay * 1.5, 60) # Exponential backoff, max 60s- attempt += 1-- # Implementation of BaseIMClient abstract methods-- async def send_message(- self,- context: MessageContext,- text: str,- parse_mode: Optional[str] = None, # Kept for interface compatibility, but ignored- reply_to: Optional[str] = None,- ) -> str:- """Send a text message - BaseIMClient implementation"""- bot = self.application.bot-- # Convert MessageContext to Telegram chat_id- chat_id = int(context.channel_id)-- # Convert markdown to MarkdownV2 for better compatibility- markdownv2_text = self._convert_to_markdownv2(text)- kwargs = {"chat_id": chat_id, "text": markdownv2_text}-- # Always use MarkdownV2 since we converted with markdownify- kwargs["parse_mode"] = "MarkdownV2"-- if reply_to or context.thread_id:- kwargs["reply_to_message_id"] = int(reply_to or context.thread_id)-- try:- message = await bot.send_message(**kwargs)- return str(message.message_id)- except TelegramError as e:- logger.error(f"Error sending message: {e}")- raise-- async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:- """Add a reaction emoji to a Telegram message."""- bot = self.application.bot-- reaction = (emoji or "").strip()- if reaction in [":eyes:", "eyes", "👀"]:- reaction = "👀"-- if not reaction:- return False-- try:- await bot.set_message_reaction(- chat_id=int(context.channel_id),- message_id=int(message_id),- reaction=reaction,- )- return True- except TelegramError as e:- logger.debug(f"Failed to add Telegram reaction: {e}")- return False- except Exception as e:- logger.debug(f"Failed to add Telegram reaction: {e}")- return False-- async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:- """Remove a reaction emoji from a Telegram message."""- bot = self.application.bot-- try:- await bot.set_message_reaction(- chat_id=int(context.channel_id),- message_id=int(message_id),- reaction=None,- )- return True- except TelegramError as e:- logger.debug(f"Failed to remove Telegram reaction: {e}")- return False- except Exception as e:- logger.debug(f"Failed to remove Telegram reaction: {e}")- return False-- async def send_message_with_buttons(- self,- context: MessageContext,- text: str,- keyboard: InlineKeyboard,- parse_mode: Optional[str] = None,- ) -> str:- """Send a message with inline buttons - BaseIMClient implementation"""- bot = self.application.bot-- # Convert markdown to MarkdownV2 for better compatibility- markdownv2_text = self._convert_to_markdownv2(text)-- # Convert our generic keyboard to Telegram keyboard- tg_keyboard = []- for row in keyboard.buttons:- tg_row = []- for button in row:- tg_button = TGInlineKeyboardButton(- text=button.text, callback_data=button.callback_data- )- tg_row.append(tg_button)- tg_keyboard.append(tg_row)-- reply_markup = TGInlineKeyboardMarkup(tg_keyboard)-- chat_id = int(context.channel_id)-- try:- message = await bot.send_message(- chat_id=chat_id,- text=markdownv2_text,- parse_mode="MarkdownV2",- reply_markup=reply_markup,- )- return str(message.message_id)- except TelegramError as e:- logger.error(f"Error sending message with buttons: {e}")- raise-- async def edit_message(- self,- context: MessageContext,- message_id: str,- text: Optional[str] = None,- keyboard: Optional[InlineKeyboard] = None,- parse_mode: Optional[str] = None,- ) -> bool:- """Edit an existing message - BaseIMClient implementation"""- bot = self.application.bot- chat_id = int(context.channel_id)-- markdownv2_text = None- if text is not None:- markdownv2_text = (- self._convert_to_markdownv2(text)- if parse_mode in (None, "markdown")- else text- )-- try:- if markdownv2_text is not None and keyboard:- # Convert keyboard- tg_keyboard = []- for row in keyboard.buttons:- tg_row = []- for button in row:- tg_button = TGInlineKeyboardButton(- text=button.text, callback_data=button.callback_data- )- tg_row.append(tg_button)- tg_keyboard.append(tg_row)-- reply_markup = TGInlineKeyboardMarkup(tg_keyboard)-- await bot.edit_message_text(- chat_id=chat_id,- message_id=int(message_id),- text=markdownv2_text,- parse_mode="MarkdownV2",- reply_markup=reply_markup,- )- elif markdownv2_text is not None:- await bot.edit_message_text(- chat_id=chat_id,- message_id=int(message_id),- text=markdownv2_text,- parse_mode="MarkdownV2",- )- elif keyboard:- # Convert keyboard- tg_keyboard = []- for row in keyboard.buttons:- tg_row = []- for button in row:- tg_button = TGInlineKeyboardButton(- text=button.text, callback_data=button.callback_data- )- tg_row.append(tg_button)- tg_keyboard.append(tg_row)-- reply_markup = TGInlineKeyboardMarkup(tg_keyboard)-- await bot.edit_message_reply_markup(- chat_id=chat_id,- message_id=int(message_id),- reply_markup=reply_markup,- )-- return True- except TelegramError as e:- logger.error(f"Error editing message: {e}")- return False-- async def remove_inline_keyboard(- self, context: MessageContext, message_id: str, parse_mode: Optional[str] = None- ) -> bool:- """Remove inline keyboard from a Telegram message."""- bot = self.application.bot- chat_id = int(context.channel_id)- try:- await bot.edit_message_reply_markup(- chat_id=chat_id,- message_id=int(message_id),- reply_markup=None,- )- return True- except TelegramError as e:- logger.error(f"Error removing message keyboard: {e}")- return False-- async def answer_callback(- self, callback_id: str, text: Optional[str] = None, show_alert: bool = False- ) -> bool:- """Answer a callback query - BaseIMClient implementation"""- # Get the stored callback query- if callback_id in self._callback_queries:- query = self._callback_queries[callback_id]- try:- await query.answer(text=text, show_alert=show_alert)- # Clean up- del self._callback_queries[callback_id]- return True- except TelegramError as e:- logger.error(f"Error answering callback: {e}")- return False- return False-- def register_handlers(self):- """Register platform-specific handlers - BaseIMClient implementation"""- # This is already implemented as setup_handlers()- self.setup_handlers()-- async def get_user_info(self, user_id: str) -> Dict[str, Any]:- """Get information about a user - BaseIMClient implementation"""- bot = self.application.bot-- try:- user = await bot.get_chat(int(user_id))- return {- "id": str(user.id),- "username": user.username,- "first_name": user.first_name,- "last_name": user.last_name,- "type": user.type,- }- except TelegramError as e:- logger.error(f"Error getting user info: {e}")- raise-- async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:- """Get information about a channel/chat - BaseIMClient implementation"""- bot = self.application.bot-- try:- chat = await bot.get_chat(int(channel_id))- return {- "id": str(chat.id),- "title": chat.title,- "type": chat.type,- "username": chat.username,- }- except TelegramError as e:- logger.error(f"Error getting channel info: {e}")- raise-- def format_markdown(self, text: str) -> str:- """Format markdown text for Telegram using telegramify_markdown-- Converts standard markdown to Telegram's MarkdownV2 format- """- return self._convert_to_markdownv2(text)-- def _is_authorized_chat(self, chat_id: int, chat_type: str) -> bool:- """Check if a chat is authorized based on whitelist configuration"""- target_chat_id = self.config.target_chat_id-- # If None/null, accept all chats- if target_chat_id is None:- return True-- # If list with IDs, check whitelist- if isinstance(target_chat_id, list):- return chat_id in target_chat_id-- # Should not reach here, but handle gracefully- logger.warning(f"Unexpected target_chat_id type: {type(target_chat_id)}")- return False-- async def _send_unauthorized_message(self, chat_id: int):- """Send unauthorized access message to chat"""- try:- bot = self.application.bot- await bot.send_message(- chat_id=chat_id,- text="❌ This chat is not authorized to use bot commands.",- )- except Exception as e:- logger.error(f"Failed to send unauthorized message to {chat_id}: {e}")diff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex 6cd44009a..98d0bb744 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -6,6 +6,9 @@ from dataclasses import dataclass, asdict, fieldfrom typing import Any, Dict, List, Optional, Unionfrom pathlib import Path+from config import paths+from config.v2_sessions import SessionsStore+logger = logging.getLogger(__name__)@@ -45,10 +48,6 @@ class UserSettings:default_factory=lambda: DEFAULT_HIDDEN_MESSAGE_TYPES.copy())custom_cwd: Optional[str] = None- session_mappings: Dict[str, Dict[str, Dict[str, str]]] = field(- default_factory=dict- )- active_slack_threads: Dict[str, Dict[str, float]] = field(default_factory=dict)channel_routing: Optional[ChannelRouting] = Nonedef to_dict(self) -> dict:@@ -82,9 +81,12 @@ class SettingsManager:"tool": "toolcall",}- def __init__(self, settings_file: str = "user_settings.json"):- self.settings_file = Path(settings_file)+ def __init__(self, settings_file: Optional[str] = None):+ paths.ensure_data_dirs()+ self.settings_file = Path(settings_file) if settings_file else paths.get_settings_path()self.settings: Dict[Union[int, str], UserSettings] = {}+ self.sessions_store = SessionsStore()+ self.sessions_store.load()self._load_settings()# ---------------------------------------------@@ -105,19 +107,6 @@ class SettingsManager:with open(self.settings_file, "r") as f:data = json.load(f)for user_id_str, user_data in data.items():- # Normalize session mappings to agent-aware structure- if "session_mappings" in user_data:- 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:- user_data["active_slack_threads"] = {}-- # Always keep user_id as string in memoryuser_id = user_id_strsettings = UserSettings.from_dict(user_data)settings.hidden_message_types = self._normalize_hidden_message_types(@@ -132,38 +121,6 @@ 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 normalizeddef _save_settings(self):"""Save settings to JSON file"""@@ -251,13 +208,9 @@ class SettingsManager:"toolcall": "Toolcall",}- 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 _ensure_agent_namespace(self, user_id: Union[int, str], agent_name: str) -> Dict[str, Dict[str, str]]:+ user_key = self._normalize_user_id(user_id)+ return self.sessions_store.get_agent_map(user_key, agent_name)def set_agent_session_mapping(self,@@ -268,12 +221,11 @@ class SettingsManager:session_id: str,):"""Store mapping between base session ID, working path, and agent session ID"""- settings = self.get_user_settings(user_id)- agent_map = self._ensure_agent_namespace(settings, agent_name)+ agent_map = self._ensure_agent_namespace(user_id, 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)+ self.sessions_store.save()logger.info(f"Stored {agent_name} session mapping for user {user_id}: "f"{base_session_id}[{working_path}] -> {session_id}"@@ -287,8 +239,8 @@ class SettingsManager:agent_name: str,) -> Optional[str]:"""Get agent session ID for given base session ID and working path"""- settings = self.get_user_settings(user_id)- agent_map = settings.session_mappings.get(agent_name, {})+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)if base_session_id in agent_map:return agent_map[base_session_id].get(working_path)return None@@ -322,8 +274,8 @@ class SettingsManager:working_path: Optional[str] = None,):"""Clear session mapping for given base session ID and optionally working path"""- settings = self.get_user_settings(user_id)- agent_map = settings.session_mappings.get(agent_name, {})+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)if base_session_id in agent_map:if working_path:if working_path in agent_map[base_session_id]:@@ -337,35 +289,37 @@ class SettingsManager:logger.info(f"Cleared all {agent_name} session mappings for user {user_id}: {base_session_id}")- self.update_user_settings(user_id, settings)+ self.sessions_store.save()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]+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)+ if agent_map:+ self.sessions_store.state.session_mappings[user_key][agent_name] = {}logger.info(f"Cleared all {agent_name} session namespaces for user {user_id}")- self.update_user_settings(user_id, settings)+ self.sessions_store.save()def clear_all_session_mappings(self, user_id: Union[int, str]):"""Clear all session mappings for a user across agents"""- settings = self.get_user_settings(user_id)- if settings.session_mappings:- count = sum(len(agent_map) for agent_map in settings.session_mappings.values())- settings.session_mappings.clear()+ user_key = self._normalize_user_id(user_id)+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})+ if agent_maps:+ count = sum(len(agent_map) for agent_map in agent_maps.values())+ self.sessions_store.state.session_mappings[user_key] = {}logger.info(f"Cleared all session mappings ({count} bases) for user {user_id}")- self.update_user_settings(user_id, settings)+ self.sessions_store.save()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, {})+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)return {base: paths.copy() for base, paths in agent_map.items()}# Backwards-compatible helpers for Claude-specific call sites@@ -404,13 +358,10 @@ class SettingsManager:self, user_id: Union[int, str], channel_id: str, thread_ts: str):"""Mark a Slack thread as active with current timestamp"""- settings = self.get_user_settings(user_id)-- if channel_id not in settings.active_slack_threads:- settings.active_slack_threads[channel_id] = {}-- settings.active_slack_threads[channel_id][thread_ts] = time.time()- self.update_user_settings(user_id, settings)+ user_key = self._normalize_user_id(user_id)+ channel_map = self.sessions_store.get_thread_map(user_key, channel_id)+ channel_map[thread_ts] = time.time()+ self.sessions_store.save()logger.info(f"Marked thread active for user {user_id}: channel={channel_id}, thread={thread_ts}")@@ -419,59 +370,54 @@ class SettingsManager:self, user_id: Union[int, str], channel_id: str, thread_ts: str) -> bool:"""Check if a Slack thread is active (within 24 hours)"""- settings = self.get_user_settings(user_id)+ user_key = self._normalize_user_id(user_id)# First cleanup expired threads for this channelself._cleanup_expired_threads_for_channel(user_id, channel_id)- # Then check if thread is active- if channel_id in settings.active_slack_threads:- if thread_ts in settings.active_slack_threads[channel_id]:- return True-- return False+ channel_map = self.sessions_store.get_thread_map(user_key, channel_id)+ return thread_ts in channel_mapdef _cleanup_expired_threads_for_channel(self, user_id: Union[int, str], channel_id: str):"""Remove threads older than 24 hours for a specific channel"""- settings = self.get_user_settings(user_id)+ user_key = self._normalize_user_id(user_id)+ channel_map = self.sessions_store.get_thread_map(user_key, channel_id)- if channel_id not in settings.active_slack_threads:+ if not channel_map:returncurrent_time = time.time()twenty_four_hours_ago = current_time - (24 * 60 * 60)- # Find expired threadsexpired_threads = [thread_ts- for thread_ts, last_active in settings.active_slack_threads[channel_id].items()+ for thread_ts, last_active in channel_map.items()if last_active < twenty_four_hours_ago]- # Remove expired threadsif expired_threads:for thread_ts in expired_threads:- del settings.active_slack_threads[channel_id][thread_ts]+ del channel_map[thread_ts]- # Clean up empty channel dict- if not settings.active_slack_threads[channel_id]:- del settings.active_slack_threads[channel_id]+ if not channel_map:+ self.sessions_store.state.active_slack_threads[user_key].pop(channel_id, None)- self.update_user_settings(user_id, settings)+ self.sessions_store.save()logger.info(f"Cleaned up {len(expired_threads)} expired threads for channel {channel_id}")def cleanup_all_expired_threads(self, user_id: Union[int, str]):"""Remove all threads older than 24 hours for all channels"""- settings = self.get_user_settings(user_id)+ user_key = self._normalize_user_id(user_id)+ channel_map = self.sessions_store.state.active_slack_threads.get(user_key, {})- if not settings.active_slack_threads:+ if not channel_map:return- channels_to_clean = list(settings.active_slack_threads.keys())+ channels_to_clean = list(channel_map.keys())for channel_id in channels_to_clean:self._cleanup_expired_threads_for_channel(user_id, channel_id)diff --git a/scripts/send_long_result_test.py b/scripts/send_long_result_test.pyindex 36026f225..b2e07ab09 100644--- a/scripts/send_long_result_test.py+++ b/scripts/send_long_result_test.py@@ -2,7 +2,8 @@ import asyncioimport osfrom dataclasses import dataclass-from config.settings import AppConfig+from config.v2_config import V2Config+from config.v2_compat import to_app_configfrom core.controller import Controllerfrom modules.im import MessageContext@@ -16,7 +17,7 @@ async def main() -> None:channel_id = os.getenv("TEST_SLACK_CHANNEL_ID") or "C0A6U2GH6P5"thread_id = os.getenv("TEST_SLACK_THREAD_TS")- config = AppConfig.from_env()+ config = to_app_config(V2Config.load())controller = Controller(config)context = MessageContext(diff --git a/tests/test_v2_paths.py b/tests/test_v2_paths.pynew file mode 100644index 000000000..50623d5be--- /dev/null+++ b/tests/test_v2_paths.py@@ -0,0 +1,18 @@+from config import paths+++def test_paths_are_under_home():+ root = paths.get_vibe_remote_dir()+ assert root.name == ".vibe_remote"+ assert paths.get_config_path().parent == paths.get_config_dir()+ assert paths.get_settings_path().parent == paths.get_state_dir()+ assert paths.get_sessions_path().parent == paths.get_state_dir()+++def test_ensure_data_dirs(tmp_path, monkeypatch):+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")+ paths.ensure_data_dirs()+ assert (tmp_path / ".vibe_remote" / "config").exists()+ assert (tmp_path / ".vibe_remote" / "state").exists()+ assert (tmp_path / ".vibe_remote" / "logs").exists()+ assert (tmp_path / ".vibe_remote" / "runtime").exists()diff --git a/tests/test_v2_sessions.py b/tests/test_v2_sessions.pynew file mode 100644index 000000000..3d36e8d93--- /dev/null+++ b/tests/test_v2_sessions.py@@ -0,0 +1,30 @@+from config import paths+from config.v2_sessions import SessionsStore+++def test_sessions_store_roundtrip(tmp_path, monkeypatch):+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")+ store = SessionsStore()+ store.state.session_mappings = {+ "U1": {"claude": {"base": {"/tmp": "session-1"}}}+ }+ store.state.active_slack_threads = {"U1": {"C1": {"123.456": 1.0}}}+ store.state.last_activity = "2026-01-18T12:00:00Z"+ store.save()++ reloaded = SessionsStore()+ reloaded.load()+ assert reloaded.state.session_mappings["U1"]["claude"]["base"]["/tmp"] == "session-1"+ assert reloaded.state.active_slack_threads["U1"]["C1"]["123.456"] == 1.0+ assert reloaded.state.last_activity == "2026-01-18T12:00:00Z"+++def test_sessions_store_namespaces(tmp_path, monkeypatch):+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")+ store = SessionsStore()+ agent_map = store.get_agent_map("U2", "opencode")+ thread_map = store.get_thread_map("U2", "C2")+ assert agent_map == {}+ assert thread_map == {}+ assert "U2" in store.state.session_mappings+ assert "U2" in store.state.active_slack_threads