Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(auth): add remote setup flows and command docs
cyhd37932ca6724
diff --git a/README.md b/README.mdindex d88b1d19b..01c8c4ba7 100644--- a/README.md+++ b/README.md@@ -197,6 +197,11 @@ Ask your agent to schedule work for later, repeat a prompt on a cron, or queue a**Pro tip:** Each thread = isolated session. Start multiple threads for parallel tasks.+Detailed references:++- [Full Command Reference](docs/COMMANDS.md)+- [CLI Reference](docs/CLI.md)+---## Instant Agent Switching@@ -236,6 +241,11 @@ vibe task # Create and manage scheduled tasksvibe hook # Queue one-shot async sends```+Detailed references:++- [Full Command Reference](docs/COMMANDS.md)+- [CLI Reference](docs/CLI.md)+---## Prerequisitesdiff --git a/README_ZH.md b/README_ZH.mdindex 065e15251..e5278d386 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -197,6 +197,11 @@ Agent 需要输入时 — 文件选择、确认、选项 — 聊天 App 弹出**技巧:** 每个线程 = 独立会话。开多个线程可以并行任务。+详细参考:++- [完整命令参考](docs/COMMANDS_ZH.md)+- [CLI 参考手册](docs/CLI_ZH.md)+---## 即时切换 Agent@@ -236,6 +241,11 @@ vibe task # 创建和管理定时任务vibe hook # 队列化一次性异步发送```+详细参考:++- [完整命令参考](docs/COMMANDS_ZH.md)+- [CLI 参考手册](docs/CLI_ZH.md)+---## 前置条件diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pynew file mode 100644index 000000000..7e7edfd80--- /dev/null+++ b/core/agent_auth_service.py@@ -0,0 +1,638 @@+"""Agent OAuth setup orchestration for remote IM-driven login recovery."""++from __future__ import annotations++import asyncio+import json+import logging+import os+import re+import uuid+from dataclasses import dataclass+from typing import Optional++from modules.im import InlineButton, InlineKeyboard, MessageContext+from vibe.i18n import t as i18n_t++logger = logging.getLogger(__name__)++ANSI_ESCAPE_RE = re.compile(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\))")+CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")+CODEX_URL_RE = re.compile(r"https://auth\.openai\.com/codex/device")+URL_RE = re.compile(r"https?://\S+")+CODEX_DEVICE_CODE_RE = re.compile(r"\b[A-Z0-9]{4}(?:-[A-Z0-9]{4,})+\b")+CLAUDE_CODE_PROMPT_RE = re.compile(r"paste code here|if prompted", re.IGNORECASE)+OPENCODE_API_KEY_PROMPT_RE = re.compile(r"enteryourapikey", re.IGNORECASE)+++def classify_auth_error(backend: str, error_text: str) -> bool:+ """Return True when the error likely requires an OAuth reset."""+ text = (error_text or "").strip().lower()+ if not text:+ return False++ if backend == "codex":+ needles = (+ "401",+ "unauthorized",+ "not logged in",+ "login required",+ "authentication",+ "oauth",+ )+ return any(needle in text for needle in needles)++ if backend == "claude":+ needles = (+ "401",+ "unauthorized",+ "oauth",+ "re-auth",+ "re-authenticate",+ "auth login",+ "login",+ "logged out",+ )+ return any(needle in text for needle in needles)++ if backend == "opencode":+ needles = (+ "401",+ "unauthorized",+ "authentication",+ "credential",+ "api key",+ "provider",+ "failed to send message: 401",+ "failed to start async prompt: 401",+ )+ return any(needle in text for needle in needles)++ return False+++def sanitize_process_output(text: str) -> str:+ """Strip ANSI/control sequences so parsing works across TTY and non-TTY flows."""+ cleaned = ANSI_ESCAPE_RE.sub("", text)+ cleaned = CONTROL_CHAR_RE.sub("", cleaned)+ return cleaned.strip()+++@dataclass+class AgentAuthFlow:+ flow_id: str+ backend: str+ settings_key: str+ initiator_user_id: str+ context: MessageContext+ process: asyncio.subprocess.Process+ reader_task: asyncio.Task[None]+ waiter_task: asyncio.Task[None]+ pty_master_fd: int | None = None+ awaiting_code: bool = False+ login_prompt_sent: bool = False+ code_prompt_sent: bool = False+ url: str | None = None+ device_code: str | None = None+ provider: str | None = None+ last_status_text: str | None = None++ @property+ def flow_key(self) -> str:+ return f"{self.settings_key}:{self.backend}"+++class AgentAuthService:+ """Manage backend-specific login flows triggered through IM."""++ def __init__(self, controller):+ self.controller = controller+ self._flows: dict[str, AgentAuthFlow] = {}+ self._flows_by_id: dict[str, AgentAuthFlow] = {}+ self._flow_lock = asyncio.Lock()++ def _t(self, key: str, **kwargs) -> str:+ lang = getattr(self.controller, "_get_lang", lambda: getattr(self.controller.config, "language", "en"))()+ return i18n_t(key, lang, **kwargs)++ def _get_im_client(self, context: MessageContext):+ getter = getattr(self.controller, "get_im_client_for_context", None)+ if callable(getter):+ return getter(context)+ return self.controller.im_client++ def _get_settings_key(self, context: MessageContext) -> str:+ return self.controller._get_settings_key(context)++ def _make_flow_key(self, context: MessageContext, backend: str) -> str:+ return f"{self._get_settings_key(context)}:{backend}"++ def _get_cli_binary(self, backend: str) -> str:+ agents_cfg = getattr(getattr(self.controller, "config", None), "agents", None)+ backend_cfg = getattr(agents_cfg, backend, None) if agents_cfg is not None else None+ cli_path = getattr(backend_cfg, "cli_path", None)+ return cli_path or backend++ async def _resolve_opencode_provider(self, context: MessageContext) -> str:+ override_agent = None+ override_model = None+ get_overrides = getattr(self.controller, "get_opencode_overrides", None)+ if callable(get_overrides):+ override_agent, override_model, _ = get_overrides(context)++ if isinstance(override_model, str) and "/" in override_model:+ return override_model.split("/", 1)[0]++ agent_service = getattr(self.controller, "agent_service", None)+ opencode_agent = getattr(agent_service, "agents", {}).get("opencode") if agent_service else None+ if opencode_agent and hasattr(opencode_agent, "_get_server"):+ try:+ server = await opencode_agent._get_server()+ agent_to_use = override_agent or server.get_default_agent_from_config()+ model_str = server.get_agent_model_from_config(agent_to_use)+ if isinstance(model_str, str) and "/" in model_str:+ return model_str.split("/", 1)[0]+ except Exception as err: # noqa: BLE001+ logger.info("Falling back to default OpenCode provider after lookup failure: %s", err)++ return "opencode"++ def _get_opencode_login_method(self, provider: str) -> str | None:+ if provider == "openai":+ return "ChatGPT Pro/Plus (headless)"+ return None++ async def handle_setup_command(self, context: MessageContext, args: str = "") -> None:+ """Process `/setup`, `/setup <backend>`, or `/setup code <value>`."""+ parts = (args or "").strip().split(maxsplit=2)+ if parts and parts[0].lower() == "code":+ if len(parts) < 2 or not parts[1].strip():+ await self._send_message(context, f"❌ {self._t('command.setup.codeUsage')}")+ return+ if len(parts) == 2:+ await self.submit_code(context, parts[1].strip())+ return+ await self.submit_code(context, parts[2].strip(), backend_hint=parts[1].strip().lower())+ return++ backend_hint = parts[0].strip().lower() if parts else None+ if backend_hint in {"cc", "claude-code"}:+ backend_hint = "claude"+ elif backend_hint == "cx":+ backend_hint = "codex"++ if backend_hint in {"oc", "open-code"}:+ backend_hint = "opencode"++ if backend_hint and backend_hint not in {"claude", "codex", "opencode"}:+ await self._send_message(context, f"❌ {self._t('command.setup.unsupportedBackend', backend=backend_hint)}")+ return++ await self.start_setup(context, backend=backend_hint or None, force_reset=True)++ async def handle_setup_callback(self, context: MessageContext, callback_data: str) -> None:+ """Handle `auth_setup:*` callback buttons."""+ _, _, backend_hint = callback_data.partition(":")+ backend = backend_hint.strip().lower() or None+ if backend == "auto":+ backend = None+ await self.start_setup(context, backend=backend, force_reset=True)++ async def start_setup(self, context: MessageContext, backend: str | None = None, force_reset: bool = True) -> None:+ """Start an auth flow for the resolved backend."""+ resolved_backend = backend or self.controller.resolve_agent_for_context(context)+ if resolved_backend not in {"claude", "codex", "opencode"}:+ await self._send_message(+ context,+ f"❌ {self._t('command.setup.unsupportedBackend', backend=resolved_backend)}",+ )+ return++ async with self._flow_lock:+ flow_key = self._make_flow_key(context, resolved_backend)+ existing = self._flows.get(flow_key)+ if existing:+ await self._terminate_flow(existing)++ await self._send_message(+ context,+ f"⏳ {self._t('command.setup.starting', backend=resolved_backend)}",+ )++ if resolved_backend == "codex":+ process = await self._start_codex_process(force_reset=force_reset)+ flow = AgentAuthFlow(+ flow_id=uuid.uuid4().hex[:12],+ backend=resolved_backend,+ settings_key=self._get_settings_key(context),+ initiator_user_id=context.user_id,+ context=context,+ process=process,+ reader_task=asyncio.create_task(asyncio.sleep(0)),+ waiter_task=asyncio.create_task(asyncio.sleep(0)),+ )+ elif resolved_backend == "claude":+ process, master_fd = await self._start_claude_process(force_reset=force_reset)+ flow = AgentAuthFlow(+ flow_id=uuid.uuid4().hex[:12],+ backend=resolved_backend,+ settings_key=self._get_settings_key(context),+ initiator_user_id=context.user_id,+ context=context,+ process=process,+ reader_task=asyncio.create_task(asyncio.sleep(0)),+ waiter_task=asyncio.create_task(asyncio.sleep(0)),+ pty_master_fd=master_fd,+ )+ else:+ process, master_fd, provider = await self._start_opencode_process(context, force_reset=force_reset)+ flow = AgentAuthFlow(+ flow_id=uuid.uuid4().hex[:12],+ backend=resolved_backend,+ settings_key=self._get_settings_key(context),+ initiator_user_id=context.user_id,+ context=context,+ process=process,+ reader_task=asyncio.create_task(asyncio.sleep(0)),+ waiter_task=asyncio.create_task(asyncio.sleep(0)),+ pty_master_fd=master_fd,+ provider=provider,+ )++ self._flows[flow_key] = flow+ self._flows_by_id[flow.flow_id] = flow+ if resolved_backend == "codex":+ flow.reader_task = asyncio.create_task(self._read_codex_output(process, context, resolved_backend))+ else:+ assert flow.pty_master_fd is not None+ flow.reader_task = asyncio.create_task(+ self._read_pty_output(process, flow.pty_master_fd, context, resolved_backend)+ )+ flow.waiter_task = asyncio.create_task(self._wait_for_completion(flow))++ async def submit_code(self, context: MessageContext, code: str, backend_hint: str | None = None) -> None:+ """Submit follow-up code to an active auth flow."""+ flow = self._find_flow_for_submission(context, backend_hint)+ if flow is None:+ await self._send_message(context, f"❌ {self._t('command.setup.noActiveFlow')}")+ return+ if flow.initiator_user_id != context.user_id:+ await self._send_message(context, f"❌ {self._t('command.setup.notFlowOwner')}")+ return+ if flow.backend not in {"claude", "opencode"} or flow.pty_master_fd is None:+ await self._send_message(context, f"❌ {self._t('command.setup.codeNotSupported')}")+ return+ if not flow.awaiting_code:+ await self._send_message(context, f"❌ {self._t('command.setup.notAwaitingCode')}")+ return++ await asyncio.to_thread(os.write, flow.pty_master_fd, f"{code.strip()}\n".encode("utf-8"))+ flow.awaiting_code = False+ await self._send_message(context, f"✅ {self._t('command.setup.codeSubmitted', backend=flow.backend)}")++ async def maybe_emit_auth_recovery_message(self, context: MessageContext, backend: str, error_text: str) -> bool:+ """Emit a reset-oauth button when the backend error is auth-related."""+ if not classify_auth_error(backend, error_text):+ return False++ await self._send_message_with_button(+ context,+ f"{error_text}\n\n{self._t('command.setup.resetPrompt', backend=backend)}",+ button_text=self._t("button.resetOAuth"),+ callback_data=f"auth_setup:{backend}",+ )+ return True++ async def _send_message(self, context: MessageContext, text: str) -> Optional[str]:+ return await self._get_im_client(context).send_message(context, text)++ async def _send_message_with_button(+ self,+ context: MessageContext,+ text: str,+ *,+ button_text: str,+ callback_data: str,+ ) -> Optional[str]:+ im_client = self._get_im_client(context)+ if hasattr(im_client, "send_message_with_buttons"):+ keyboard = InlineKeyboard(buttons=[[InlineButton(text=button_text, callback_data=callback_data)]])+ return await im_client.send_message_with_buttons(context, text, keyboard)+ fallback = f"{text}\n\n{self._t('command.setup.manualFallback', backend=callback_data.split(':', 1)[1])}"+ return await im_client.send_message(context, fallback)++ async def _start_codex_process(self, *, force_reset: bool) -> asyncio.subprocess.Process:+ binary = self._get_cli_binary("codex")+ if force_reset:+ await self._run_utility_command(binary, "logout")+ return await asyncio.create_subprocess_exec(+ binary,+ "login",+ "--device-auth",+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ )++ async def _start_claude_process(self, *, force_reset: bool) -> tuple[asyncio.subprocess.Process, int]:+ binary = self._get_cli_binary("claude")+ if force_reset:+ await self._run_utility_command(binary, "auth", "logout")++ master_fd, slave_fd = os.openpty()+ try:+ process = await asyncio.create_subprocess_exec(+ binary,+ "auth",+ "login",+ "--claudeai",+ stdin=slave_fd,+ stdout=slave_fd,+ stderr=slave_fd,+ )+ finally:+ os.close(slave_fd)+ return process, master_fd++ async def _start_opencode_process(+ self,+ context: MessageContext,+ *,+ force_reset: bool,+ ) -> tuple[asyncio.subprocess.Process, int, str]:+ binary = self._get_cli_binary("opencode")+ provider = await self._resolve_opencode_provider(context)+ method = self._get_opencode_login_method(provider)+ # OpenCode auth is provider-scoped and may keep multiple credentials.+ # `opencode auth logout` can become interactive, so refresh by re-running+ # login for the target provider instead of forcing a global logout.+ master_fd, slave_fd = os.openpty()+ try:+ cmd = [+ binary,+ "auth",+ "login",+ "-p",+ provider,+ ]+ if method:+ cmd.extend(["-m", method])+ process = await asyncio.create_subprocess_exec(+ *cmd,+ stdin=slave_fd,+ stdout=slave_fd,+ stderr=slave_fd,+ )+ finally:+ os.close(slave_fd)+ return process, master_fd, provider++ async def _run_utility_command(self, *cmd: str) -> None:+ try:+ process = await asyncio.create_subprocess_exec(+ *cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ )+ await asyncio.wait_for(process.communicate(), timeout=20)+ except Exception as err: # noqa: BLE001+ logger.info("Ignoring setup preflight command failure for %s: %s", " ".join(cmd), err)++ async def _read_codex_output(+ self,+ process: asyncio.subprocess.Process,+ context: MessageContext,+ backend: str,+ ) -> None:+ assert process.stdout is not None+ while True:+ line = await process.stdout.readline()+ if not line:+ break+ await self._handle_process_text(context, backend, line.decode("utf-8", errors="replace"))++ async def _read_pty_output(+ self,+ process: asyncio.subprocess.Process,+ master_fd: int,+ context: MessageContext,+ backend: str,+ ) -> None:+ try:+ while process.returncode is None:+ chunk = await asyncio.to_thread(os.read, master_fd, 4096)+ if not chunk:+ break+ await self._handle_process_text(context, backend, chunk.decode("utf-8", errors="replace"))+ finally:+ try:+ os.close(master_fd)+ except OSError:+ pass++ async def _handle_process_text(self, context: MessageContext, backend: str, text: str) -> None:+ flow = self._flows.get(self._make_flow_key(context, backend))+ if flow is None:+ return++ clean = sanitize_process_output(text)+ if not clean:+ return++ flow.last_status_text = clean++ if backend == "codex":+ maybe_url = CODEX_URL_RE.search(clean)+ maybe_code = CODEX_DEVICE_CODE_RE.search(clean)+ if maybe_url:+ flow.url = maybe_url.group(0)+ if maybe_code:+ flow.device_code = maybe_code.group(0)+ if flow.url and flow.device_code and not flow.login_prompt_sent:+ flow.login_prompt_sent = True+ await self._send_message(+ flow.context,+ self._t(+ "command.setup.codexInstructions",+ url=flow.url,+ code=flow.device_code,+ ),+ )+ return++ maybe_url = URL_RE.search(clean)+ compact = re.sub(r"\s+", "", clean).lower()++ if backend == "claude":+ if maybe_url and "claude.ai/oauth/authorize" in maybe_url.group(0):+ flow.url = maybe_url.group(0)+ if flow.url and not flow.login_prompt_sent:+ flow.login_prompt_sent = True+ await self._send_message(+ flow.context,+ self._t("command.setup.claudeInstructions", url=flow.url),+ )++ if CLAUDE_CODE_PROMPT_RE.search(clean) and not flow.code_prompt_sent:+ flow.awaiting_code = True+ flow.code_prompt_sent = True+ await self._send_message(+ flow.context,+ self._t("command.setup.claudeCodePrompt"),+ )+ return++ maybe_code = CODEX_DEVICE_CODE_RE.search(clean)+ if maybe_url:+ flow.url = maybe_url.group(0)+ if maybe_code:+ flow.device_code = maybe_code.group(0)+ if flow.provider == "openai" and flow.url and flow.device_code and not flow.login_prompt_sent:+ flow.login_prompt_sent = True+ await self._send_message(+ flow.context,+ self._t(+ "command.setup.opencodeDeviceInstructions",+ url=flow.url,+ code=flow.device_code,+ ),+ )+ return++ if flow.url and not flow.login_prompt_sent and flow.provider != "openai":+ flow.login_prompt_sent = True+ await self._send_message(+ flow.context,+ self._t(+ "command.setup.opencodeInstructions",+ provider=flow.provider or "opencode",+ url=flow.url,+ ),+ )++ if OPENCODE_API_KEY_PROMPT_RE.search(compact) and not flow.code_prompt_sent:+ flow.awaiting_code = True+ flow.code_prompt_sent = True+ await self._send_message(+ flow.context,+ self._t(+ "command.setup.opencodeCodePrompt",+ provider=flow.provider or "opencode",+ ),+ )++ async def _wait_for_completion(self, flow: AgentAuthFlow) -> None:+ try:+ await flow.process.wait()+ await flow.reader_task+ ok, detail = await self._verify_login(flow.backend)+ if ok:+ if flow.backend == "opencode":+ await self._refresh_opencode_server()+ await self._send_message(+ flow.context,+ f"✅ {self._t('command.setup.success', backend=flow.backend)}",+ )+ else:+ detail_text = detail or self._t("command.setup.unknownFailure")+ await self._send_message_with_button(+ flow.context,+ f"❌ {self._t('command.setup.failed', backend=flow.backend, detail=detail_text)}",+ button_text=self._t("button.resetOAuth"),+ callback_data=f"auth_setup:{flow.backend}",+ )+ except asyncio.CancelledError:+ raise+ except Exception as err: # noqa: BLE001+ logger.error("Agent auth flow failed for %s: %s", flow.backend, err, exc_info=True)+ await self._send_message_with_button(+ flow.context,+ f"❌ {self._t('command.setup.failed', backend=flow.backend, detail=str(err))}",+ button_text=self._t("button.resetOAuth"),+ callback_data=f"auth_setup:{flow.backend}",+ )+ finally:+ self._drop_flow(flow)++ async def _verify_login(self, backend: str) -> tuple[bool, str]:+ if backend == "codex":+ binary = self._get_cli_binary("codex")+ process = await asyncio.create_subprocess_exec(+ binary,+ "login",+ "status",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ )+ stdout, _ = await process.communicate()+ text = stdout.decode("utf-8", errors="replace").strip()+ return ("not logged in" not in text.lower(), text)++ if backend == "opencode":+ binary = self._get_cli_binary("opencode")+ process = await asyncio.create_subprocess_exec(+ binary,+ "auth",+ "list",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ )+ stdout, _ = await process.communicate()+ text = stdout.decode("utf-8", errors="replace").strip()+ normalized = text.lower()+ return ("credentials" in normalized and "0 credentials" not in normalized, text)++ binary = self._get_cli_binary("claude")+ process = await asyncio.create_subprocess_exec(+ binary,+ "auth",+ "status",+ "--json",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ )+ stdout, _ = await process.communicate()+ text = stdout.decode("utf-8", errors="replace").strip()+ try:+ payload = json.loads(text)+ except json.JSONDecodeError:+ return False, text+ return (bool(payload.get("loggedIn")), text)++ async def _refresh_opencode_server(self) -> None:+ agent_service = getattr(self.controller, "agent_service", None)+ opencode_agent = getattr(agent_service, "agents", {}).get("opencode") if agent_service else None+ if not opencode_agent or not hasattr(opencode_agent, "_get_server"):+ return+ server = await opencode_agent._get_server()+ if hasattr(server, "restart_for_auth_refresh"):+ await server.restart_for_auth_refresh()++ def _find_flow_for_submission(self, context: MessageContext, backend_hint: str | None) -> AgentAuthFlow | None:+ settings_key = self._get_settings_key(context)+ if backend_hint:+ return self._flows.get(f"{settings_key}:{backend_hint}")++ for backend in ("claude", "codex", "opencode"):+ flow = self._flows.get(f"{settings_key}:{backend}")+ if flow is not None:+ return flow+ return None++ async def _terminate_flow(self, flow: AgentAuthFlow) -> None:+ if flow.waiter_task and not flow.waiter_task.done():+ flow.waiter_task.cancel()+ if flow.reader_task and not flow.reader_task.done():+ flow.reader_task.cancel()+ if flow.process.returncode is None:+ flow.process.terminate()+ try:+ await asyncio.wait_for(flow.process.wait(), timeout=5)+ except asyncio.TimeoutError:+ flow.process.kill()+ await flow.process.wait()+ self._drop_flow(flow)++ def _drop_flow(self, flow: AgentAuthFlow) -> None:+ self._flows.pop(flow.flow_key, None)+ self._flows_by_id.pop(flow.flow_id, None)diff --git a/core/auth.py b/core/auth.pyindex 2f117b2f1..b8a55de6a 100644--- a/core/auth.py+++ b/core/auth.py@@ -19,6 +19,7 @@ ADMIN_PROTECTED_ACTIONS: frozenset = frozenset("cmd_settings","cmd_routing","cmd_change_cwd",+ "auth_setup","vibe_update_now",# Feishu form submit button names"cwd_submit",@@ -26,6 +27,7 @@ ADMIN_PROTECTED_ACTIONS: frozenset = frozenset("routing_backend_select","routing_submit",# Text commands (used with _admin_guard)+ "setup","set_cwd","settings",}@@ -45,6 +47,8 @@ def _is_admin_protected(action: str) -> bool:# Prefix match for actions with dynamic suffixesif action.startswith("vibe_update_now"):return True+ if action.startswith("auth_setup"):+ return Truereturn Falsediff --git a/core/controller.py b/core/controller.pyindex 6c353dc73..c8c472698 100644--- a/core/controller.py+++ b/core/controller.py@@ -21,6 +21,7 @@ from core.handlers import (SettingsHandler,MessageHandler,)+from core.agent_auth_service import AgentAuthServicefrom core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.scheduled_tasks import ScheduledTaskServicefrom core.update_checker import UpdateChecker@@ -55,6 +56,7 @@ class Controller:# Initialize agents (depends on handlers/session handler)self._init_agents()+ self.agent_auth_service = AgentAuthService(self)# Validate default_backend against registered agentsself._validate_default_backend()@@ -309,6 +311,7 @@ class Controller:"cwd": self._dispatch_to_controller_loop(self.command_handler.handle_cwd),"set_cwd": self._dispatch_to_controller_loop(self.command_handler.handle_set_cwd),"resume": self._dispatch_to_controller_loop(self.command_handler.handle_resume),+ "setup": self._dispatch_to_controller_loop(self.command_handler.handle_setup),"settings": self._dispatch_to_controller_loop(self.settings_handler.handle_settings),"stop": self._dispatch_to_controller_loop(self.command_handler.handle_stop),"bind": self._dispatch_to_controller_loop(self.command_handler.handle_bind),diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 62d789ee6..28c62c84f 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -67,6 +67,7 @@ class CommandHandlers(BaseHandler):self._t("command.start.commandCwd"),self._t("command.start.commandSetCwd"),self._t("command.start.commandResume"),+ self._t("command.start.commandSetup"),self._t("command.start.commandStop", agent=agent_display_name),]if not supports_threads:@@ -763,6 +764,10 @@ class CommandHandlers(BaseHandler):channel_context = self._get_channel_context(context)await im_client.send_message(channel_context, f"❌ {self._t('error.resumeFailed')}")+ async def handle_setup(self, context: MessageContext, args: str = ""):+ """Start or continue backend OAuth setup via IM."""+ await self.controller.agent_auth_service.handle_setup_command(context, args)+async def handle_bind(self, context: MessageContext, args: str = ""):"""Handle bind command - bind a user to this Vibe Remote instance via bind code.diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 11486d9da..37bbba2c3 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -436,6 +436,9 @@ class MessageHandler(BaseHandler):elif callback_data == "cmd_resume":await command_handlers.handle_resume(context)+ elif callback_data.startswith("auth_setup:"):+ await self.controller.agent_auth_service.handle_setup_callback(context, callback_data)+elif callback_data == "cmd_settings":await settings_handler.handle_settings(context)diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdnew file mode 100644index 000000000..4c69ceeaf--- /dev/null+++ b/docs/COMMANDS.md@@ -0,0 +1,740 @@+# Vibe Remote Command Reference++This document is the exhaustive command reference for Vibe Remote.++It covers:++- in-chat commands users send to the bot from Slack, Discord, WeChat, and Lark+- command aliases and parser normalization rules+- platform differences+- permission requirements+- host-side CLI commands exposed by the `vibe` executable++For installation, setup, and operations background, also see:++- [CLI Reference](./CLI.md)+- [Slack Setup Guide](./SLACK_SETUP.md)++## 1. Command Surface Overview++Vibe Remote exposes two command families:++1. In-chat commands+ - Sent from an IM platform to the bot.+ - Examples: `/start`, `/resume`, `/setcwd ~/repo`, `/setup`.+2. Host CLI commands+ - Run on the machine where Vibe Remote is installed.+ - Examples: `vibe`, `vibe status`, `vibe task add ...`.++The two families solve different problems:++- in-chat commands control conversations, working directories, session resume, DM binding, and backend auth repair+- host CLI commands control the local service process, diagnostics, upgrades, scheduled tasks, and async hooks++## 2. In-Chat Commands++### 2.1 Supported in-chat commands++These commands are registered by the controller today:++| Command | Purpose |+| --- | --- |+| `/start` | Show the welcome panel / control entry |+| `/new` | Start a fresh session |+| `/clear` | Alias of `/new` |+| `/cwd` | Show current working directory |+| `/setcwd <path>` | Set working directory |+| `/set_cwd <path>` | Internal-style alias that also works |+| `/resume` | Resume a recent session |+| `/setup` | Repair backend login/auth |+| `/settings` | Open settings UI |+| `/stop` | Interrupt the active backend execution |+| `/bind <code>` | Bind a DM user to this Vibe Remote instance |+| `bind <code>` | Plain-text DM alias for unbound users only |++### 2.2 Permission model++Authorization is centralized in `core/auth.py`.++#### Available to any authorized channel user++- `/start`+- `/new`+- `/clear`+- `/cwd`+- `/resume`+- `/stop`++#### Admin-only commands++- `/setcwd <path>`+- `/set_cwd <path>`+- `/settings`+- `/setup`++Notes:++- `/setup` button callbacks such as `Reset OAuth` are also admin-protected.+- If a workspace has at least one admin configured, non-admins cannot run admin-only commands.++#### DM binding exception++- `/bind <code>` is allowed for unbound DM users.+- Plain `bind <code>` is also allowed for unbound DM users on platforms where plain-text bind is enabled as a workaround.++### 2.3 Platform behavior++#### Slack++- Native Slack slash commands are currently exposed only for `/start` and `/stop`.+- Other commands are typically sent as normal bot-directed messages, for example:+ - `@Vibe Remote /resume`+ - `@Vibe Remote /setcwd ~/work/repo`+- In DM, plain `bind <code>` is accepted for unbound users.++#### Discord++- Commands are parsed from normal messages that start with `/`.+- `/resume` opens a Discord-native resume picker flow when the platform interaction context is available.++#### Lark / Feishu++- Commands are parsed from normal messages that start with `/`.+- `/resume` and `/settings` prefer native cards/modals when available.+++- Commands are parsed from normal text messages that start with `/`.+- `/resume` uses a text-first flow instead of modals.+- `/resume 1`, `/resume more`, `/resume latest ...`, and manual resume syntax are especially relevant on WeChat.++### 2.4 Parser normalization and aliases++The shared parser in `modules/im/base.py` applies these rules:++- `/setcwd /tmp/work` is normalized to internal action `set_cwd`+- `/set_cwd /tmp/work` also works because `set_cwd` is a registered command name+- `bind abc123` is accepted only when plain bind is allowed for that DM user++Backend aliases used by `/resume` and `/setup`:++| Alias | Backend |+| --- | --- |+| `oc` | `opencode` |+| `open-code` | `opencode` |+| `cc` | `claude` |+| `claude-code` | `claude` |+| `cx` | `codex` |++## 3. In-Chat Command Reference++### `/start`++Show the welcome message and the main control entry for the current channel or DM scope.++#### Syntax++```text+/start+```++#### What it does++- shows the current platform+- shows the currently resolved backend for the scope+- shows the current channel when relevant+- lists the main text commands+- opens an interactive menu on platforms that support buttons++#### Typical usage++```text+@Vibe Remote /start+```++#### Notes++- This is the safest discovery command when a user is unsure what is currently configured.+- On some platforms the response appears in-channel rather than inside the thread.++### `/new`++Reset the current session state so the next user message starts a fresh conversation.++#### Syntax++```text+/new+```++#### What it does++- clears active session state for the current scope+- does not delete your repository+- does not change routing or working directory++#### Typical usage++```text+/new+```++### `/clear`++Alias of `/new`.++#### Syntax++```text+/clear+```++#### What it does++- dispatches to the same handler as `/new`++#### Recommendation++- Prefer `/new` in user-facing docs and examples.+- Keep `/clear` in mind for compatibility or old habits.++### `/cwd`++Show the working directory currently associated with the channel or DM scope.++#### Syntax++```text+/cwd+```++#### What it does++- prints the absolute working directory+- reports whether the directory exists+- reminds the user that this is where the backend executes commands++#### Typical usage++```text+/cwd+```++#### Example scenario++- Before asking the agent to edit code, confirm that the current scope points at the correct repository.++### `/setcwd <path>`++Set the working directory for the current channel or DM scope.++#### Syntax++```text+/setcwd <path>+```++Also accepted:++```text+/set_cwd <path>+```++#### What it does++- expands `~`+- converts the path to an absolute path+- creates the directory if it does not exist yet+- saves the custom working directory to the current settings scope++#### Examples++```text+/setcwd ~/projects/myapp+/setcwd /srv/repos/api+/set_cwd ../another-repo+```++#### Permission++- admin-only++#### Notes++- The scope is the current channel for channel chats.+- The scope is the current user for DMs.++### `/resume`++Resume a recent native agent session from the current working directory.++#### Core syntax++```text+/resume+```++#### Text-mode subcommands++```text+/resume 1+/resume more+/resume latest+/resume latest oc+/resume latest cc+/resume latest cx+/resume <backend> <session_id>+```++#### Backend names accepted in text-mode resume++- `oc`+- `opencode`+- `open-code`+- `cc`+- `claude`+- `claude-code`+- `cx`+- `codex`++#### What it does by platform++##### Slack++- `/resume` opens the resume picker when invoked from an interaction-capable context.+- If no modal trigger is available, the bot sends guidance telling the user to open the picker from the menu.++##### Discord++- `/resume` opens a native resume picker flow when the interaction context exists.++##### Lark++- `/resume` prefers a native card/modal flow.+++- `/resume` is text-driven.+- `/resume 1` restores item 1 from the current shown list.+- `/resume more` paginates.+- `/resume latest [backend]` restores the newest session.+- `/resume <backend> <session_id>` restores a session manually.++#### Typical usage++```text+/resume+```++Then, on WeChat text flow:++```text+/resume 1+/resume latest cc+/resume codex 123e4567-thread-id+```++#### Notes++- Resume only looks at sessions under the current working directory.+- If the working directory changed since the last list snapshot, selection-by-number expires.++### `/setup`++Repair backend login or provider auth through the IM flow.++#### Syntax++```text+/setup+/setup claude+/setup codex+/setup opencode+/setup cc+/setup cx+/setup oc+/setup code <value>+/setup code <backend> <value>+```++#### What it does++- resolves the backend for the current scope, unless an explicit backend is given+- starts a backend-specific auth recovery flow+- sends browser links, device codes, or follow-up prompts into chat+- waits for completion and verifies login status++#### Backend-specific behavior++##### Claude++- starts the Claude login flow+- sends the browser authorization URL into chat+- if Claude later asks for a pasted code, the user submits:++```text+/setup code <value>+```++##### Codex++- starts device auth+- sends a browser URL plus one-time code into chat+- the bot waits for completion and verifies `codex login status`++##### OpenCode++- infers the provider from current OpenCode routing/model when possible+- `openai` uses headless device-style auth+- other common providers such as `opencode` or `anthropic` use key-entry flows+- when OpenCode asks for a key, the user submits:++```text+/setup code <value>+```++#### Permission++- admin-only++#### Notes++- `/setup code <backend> <value>` is useful when multiple setup flows are open and the backend must be explicit.+- Only the user who started the setup flow can submit its follow-up code or key.++### `/settings`++Open the settings UI for the current scope.++#### Syntax++```text+/settings+```++#### What it does++- opens or routes to the settings menu for the current platform+- allows changing settings such as routing and other scope-level controls through UI flows++#### Permission++- admin-only++#### Notes++- This command is registered even though the exact UI differs by platform.+- Prefer it when users want a guided configuration flow instead of raw commands.++### `/stop`++Interrupt the active backend execution for the current scope.++#### Syntax++```text+/stop+```++#### What it does++- builds a stop request for the currently resolved backend+- asks the backend adapter to interrupt the active task+- if there is no active session, returns an informational response++#### Typical usage++```text+/stop+```++#### Notes++- In threaded platforms, a plain `stop` or `/stop` in-thread may also be recognized by the message path.+- This command does not change routing or clear historical state by itself.++### `/bind <code>`++Bind a DM user to this Vibe Remote instance using a bind code generated from the UI or admin workflow.++#### Syntax++```text+/bind <code>+bind <code>+```++#### What it does++- validates the bind code+- records the DM user as bound+- stores the DM chat ID+- may grant admin on the initial bootstrap bind, depending on the bind-code workflow++#### Permission and context++- DM-only+- allowed even before the user is bound++#### Examples++```text+/bind vr-a3x9k2+bind vr-a3x9k2+```++#### Notes++- Plain `bind <code>` is the compatibility path for platforms or contexts where leading `/` is awkward.+- If the user is already bound, the command returns an already-bound response instead of rebinding.++## 4. What Is Not a Command++These are important user-facing controls, but they are not text commands:++- `AgentName: your message`+ - Example: `Plan: Design a new caching layer`+ - This is the subagent prefix flow, not a command.+- `/start` menu buttons+ - Examples: `Settings`, `Resume Session`, `Change Work Dir`+ - These are button callbacks or modal flows, not slash commands.++## 5. Host CLI Commands++The `vibe` executable controls the local service and async automation features.++## 5.1 Top-level CLI commands++| Command | Purpose |+| --- | --- |+| `vibe` | Start or restart the service and Web UI |+| `vibe stop` | Stop the service and UI; also terminates OpenCode server |+| `vibe restart` | Stop then start again |+| `vibe status` | Print runtime status JSON |+| `vibe doctor` | Run diagnostics |+| `vibe version` | Show installed version |+| `vibe check-update` | Check for new version |+| `vibe upgrade` | Upgrade to latest version |+| `vibe task ...` | Manage scheduled tasks |+| `vibe hook send ...` | Queue one async hook without persisting a task |++### `vibe`++```bash+vibe+```++- starts or restarts the main service+- opens the Web UI+- preserves the running OpenCode server when possible++### `vibe stop`++```bash+vibe stop+```++- stops the main service+- stops the UI server+- terminates the OpenCode server too++### `vibe restart`++```bash+vibe restart+```++- equivalent lifecycle intent: stop, wait briefly, start again++### `vibe status`++```bash+vibe status+```++- prints runtime status JSON++### `vibe doctor`++```bash+vibe doctor+```++- validates config+- checks platform credentials+- checks backend CLI availability+- checks runtime environment++### `vibe version`++```bash+vibe version+```++- prints the installed package version++### `vibe check-update`++```bash+vibe check-update+```++- checks PyPI for a newer version++### `vibe upgrade`++```bash+vibe upgrade+```++- upgrades Vibe Remote using the selected upgrade plan+- recommends `vibe stop && vibe` after success++## 5.2 `vibe task`++`vibe task` manages persisted scheduled tasks.++### Supported subcommands++| Subcommand | Purpose |+| --- | --- |+| `vibe task add` | Create a task |+| `vibe task update` | Update a task |+| `vibe task list` | List tasks |+| `vibe task ls` | Hidden alias of `list` |+| `vibe task show <task_id>` | Show one task |+| `vibe task pause <task_id>` | Pause a task |+| `vibe task resume <task_id>` | Resume a task |+| `vibe task run <task_id>` | Run immediately |+| `vibe task remove <task_id>` | Delete a task |+| `vibe task rm <task_id>` | Hidden alias of `remove` |++### `vibe task add`++```bash+vibe task add --session-key <key> (--cron <expr> | --at <timestamp>) (--prompt <text> | --prompt-file <file>) [options]+```++Important options:++- `--name`+- `--session-key` required+- `--post-to {thread,channel}`+- `--deliver-key`+- `--cron`+- `--at`+- `--prompt`+- `--prompt-file`+- `--timezone`++### `vibe task update`++```bash+vibe task update <task_id> [options]+```++Important options:++- `--name`+- `--clear-name`+- `--session-key`+- `--post-to {thread,channel}`+- `--deliver-key`+- `--reset-delivery`+- `--cron`+- `--at`+- `--prompt`+- `--prompt-file`+- `--timezone`++### `vibe task list`++```bash+vibe task list [--all] [--brief]+```++### `vibe task show`++```bash+vibe task show <task_id>+```++### `vibe task pause`++```bash+vibe task pause <task_id>+```++### `vibe task resume`++```bash+vibe task resume <task_id>+```++### `vibe task run`++```bash+vibe task run <task_id>+```++### `vibe task remove`++```bash+vibe task remove <task_id>+```++## 5.3 `vibe hook send`++Queue one asynchronous turn without creating a stored task definition.++### Syntax++```bash+vibe hook send --session-key <key> (--prompt <text> | --prompt-file <file>) [options]+```++Important options:++- `--session-key` required+- `--post-to {thread,channel}`+- `--deliver-key`+- `--prompt`+- `--prompt-file`++## 6. Recommended Mental Model++Use the right command family for the job:++- Want to control a conversation from chat:+ - use `/start`, `/resume`, `/setcwd`, `/setup`, `/stop`+- Want to bootstrap or recover DM access:+ - use `/bind <code>` in DM+- Want to control the local daemon or troubleshoot installation:+ - use `vibe`, `vibe status`, `vibe doctor`, `vibe upgrade`+- Want asynchronous automation:+ - use `vibe task ...` or `vibe hook send ...`++## 7. Quick Examples++### In chat++```text+@Vibe Remote /start+@Vibe Remote /cwd+@Vibe Remote /setcwd ~/projects/backend+@Vibe Remote /setup+@Vibe Remote /setup codex+@Vibe Remote /setup code 123456+@Vibe Remote /stop+```++### On the host machine++```bash+vibe+vibe status+vibe doctor+vibe task list --brief+vibe hook send --session-key 'slack::channel::C123' --prompt 'Share the latest build summary.'+```+diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdnew file mode 100644index 000000000..c91ae6061--- /dev/null+++ b/docs/COMMANDS_ZH.md@@ -0,0 +1,719 @@+# Vibe Remote 命令参考手册++这是一份尽量完整的 Vibe Remote 命令参考文档。++它覆盖两大类命令:++- 在 Slack、Discord、微信、飞书里直接发给机器人的聊天命令+- 在安装了 Vibe Remote 的宿主机上执行的 `vibe` CLI 命令++相关文档:++- [CLI 参考手册](./CLI_ZH.md)+- [Slack 配置指南](./SLACK_SETUP_ZH.md)++## 1. 命令总览++Vibe Remote 当前有两套命令面:++1. 聊天命令+ - 从 IM 里发给 bot+ - 例如:`/start`、`/resume`、`/setcwd ~/repo`、`/setup`+2. 宿主机 CLI 命令+ - 在运行 Vibe Remote 的那台机器上执行+ - 例如:`vibe`、`vibe status`、`vibe task add ...`++这两类命令解决的问题不同:++- 聊天命令负责会话控制、工作目录切换、恢复历史会话、DM 绑定、后端认证修复+- CLI 命令负责本地服务进程、诊断、升级、定时任务和异步 hook++## 2. 聊天命令++### 2.1 当前支持的聊天命令++控制器当前注册了这些命令:++| 命令 | 作用 |+| --- | --- |+| `/start` | 显示欢迎面板 / 控制入口 |+| `/new` | 开启一个全新会话 |+| `/clear` | `/new` 的别名 |+| `/cwd` | 查看当前工作目录 |+| `/setcwd <路径>` | 设置工作目录 |+| `/set_cwd <路径>` | 内部风格别名,也能用 |+| `/resume` | 恢复最近会话 |+| `/setup` | 修复后端登录 / 认证 |+| `/settings` | 打开设置 UI |+| `/stop` | 中断当前后端执行 |+| `/bind <绑定码>` | 在 DM 里绑定当前用户 |+| `bind <绑定码>` | 仅限未绑定 DM 用户的纯文本别名 |++### 2.2 权限模型++权限由 `core/auth.py` 统一处理。++#### 已授权频道里的普通用户可用++- `/start`+- `/new`+- `/clear`+- `/cwd`+- `/resume`+- `/stop`++#### 仅管理员可用++- `/setcwd <路径>`+- `/set_cwd <路径>`+- `/settings`+- `/setup`++补充说明:++- `/setup` 相关按钮回调,例如 `Reset OAuth`,也属于管理员操作。+- 如果当前平台已经存在管理员,非管理员不能执行这些管理员命令。++#### DM 绑定例外++- `/bind <绑定码>` 允许未绑定的 DM 用户执行。+- `bind <绑定码>` 也允许未绑定的 DM 用户执行,用来兼容某些平台对 `/` 开头消息的不便场景。++### 2.3 平台差异++#### Slack++- 目前原生 Slack slash command 只公开了 `/start` 和 `/stop`。+- 其它命令通常以“普通消息 + bot 定向”的方式触发,例如:+ - `@Vibe Remote /resume`+ - `@Vibe Remote /setcwd ~/work/repo`+- 在 DM 中,未绑定用户可以直接发送 `bind <code>`。++#### Discord++- 命令通过普通消息解析,要求消息以 `/` 开头。+- `/resume` 在有 interaction 上下文时会优先打开 Discord 原生恢复选择器。++#### 飞书 / Lark++- 命令通过普通消息解析,要求消息以 `/` 开头。+- `/resume`、`/settings` 等会优先走卡片 / modal 交互。++#### 微信++- 命令通过普通文本解析,要求消息以 `/` 开头。+- `/resume` 是纯文本交互,不走 modal。+- `/resume 1`、`/resume more`、`/resume latest ...`、手动 session_id 恢复,主要是为微信文本流设计的。++### 2.4 解析规则与别名++共享解析器 `modules/im/base.py` 当前有这些归一化规则:++- `/setcwd /tmp/work` 会被归一化为内部动作 `set_cwd`+- `/set_cwd /tmp/work` 也能正常工作,因为 `set_cwd` 本身已经注册为命令+- `bind abc123` 只有在允许 plain bind 的 DM 场景下才会被识别++`/resume` 和 `/setup` 使用的 backend 别名:++| 别名 | 对应后端 |+| --- | --- |+| `oc` | `opencode` |+| `open-code` | `opencode` |+| `cc` | `claude` |+| `claude-code` | `claude` |+| `cx` | `codex` |++## 3. 聊天命令详细说明++### `/start`++显示欢迎消息,以及当前频道或 DM 作用域下的控制入口。++#### 语法++```text+/start+```++#### 作用++- 展示当前平台+- 展示当前作用域解析出来的 backend+- 在适用场景下展示当前频道名+- 列出主要文本命令+- 在支持按钮的平台上展示交互式菜单++#### 常见用法++```text+@Vibe Remote /start+```++#### 备注++- 如果用户不确定当前配置,先执行 `/start` 最稳妥。+- 某些平台会把命令回复发回频道,而不是发在线程里。++### `/new`++重置当前会话状态,让下一条消息从一个全新的对话开始。++#### 语法++```text+/new+```++#### 作用++- 清除当前作用域的活动会话状态+- 不会删除仓库+- 不会修改路由和工作目录++### `/clear`++`/new` 的别名。++#### 语法++```text+/clear+```++#### 作用++- 实际上会直接走 `/new` 的处理逻辑++#### 建议++- 面向用户的文档建议优先写 `/new`+- `/clear` 保留为兼容和习惯用法++### `/cwd`++查看当前频道或 DM 作用域绑定的工作目录。++#### 语法++```text+/cwd+```++#### 作用++- 输出当前绝对路径+- 提示该目录是否存在+- 提醒用户这里就是 Agent 执行命令的位置++#### 典型场景++- 在让 Agent 改代码之前,先确认当前 scope 指向的是正确仓库。++### `/setcwd <路径>`++为当前频道或 DM 作用域设置工作目录。++#### 语法++```text+/setcwd <路径>+```++也支持:++```text+/set_cwd <路径>+```++#### 作用++- 自动展开 `~`+- 自动转成绝对路径+- 如果目录不存在,会尝试创建+- 把这个路径保存到当前 settings scope++#### 示例++```text+/setcwd ~/projects/myapp+/setcwd /srv/repos/api+/set_cwd ../another-repo+```++#### 权限++- 仅管理员++#### 备注++- 在频道里,作用域是当前频道。+- 在 DM 里,作用域是当前用户。++### `/resume`++从当前工作目录里恢复最近的原生 Agent 会话。++#### 基础语法++```text+/resume+```++#### 文本模式子命令++```text+/resume 1+/resume more+/resume latest+/resume latest oc+/resume latest cc+/resume latest cx+/resume <backend> <session_id>+```++#### 支持的 backend 写法++- `oc`+- `opencode`+- `open-code`+- `cc`+- `claude`+- `claude-code`+- `cx`+- `codex`++#### 各平台行为++##### Slack++- `/resume` 在有交互上下文时会直接打开恢复选择器。+- 如果当前消息没有 modal trigger,bot 会提示用户回到菜单里点 `Resume Session`。++##### Discord++- `/resume` 在有 interaction 上下文时会打开原生恢复选择流程。++##### 飞书++- `/resume` 优先走卡片 / modal 流程。++##### 微信++- `/resume` 走纯文本交互。+- `/resume 1` 恢复当前列表中的第 1 项。+- `/resume more` 用于翻页。+- `/resume latest [backend]` 恢复最近会话。+- `/resume <backend> <session_id>` 用于手动恢复指定会话。++#### 典型用法++```text+/resume+```++然后在微信文本流里继续:++```text+/resume 1+/resume latest cc+/resume codex 123e4567-thread-id+```++#### 备注++- 恢复范围只看当前工作目录下的会话。+- 如果工作目录已经变了,之前展示出来的编号列表会过期。++### `/setup`++通过 IM 完成后端登录或 provider auth 修复。++#### 语法++```text+/setup+/setup claude+/setup codex+/setup opencode+/setup cc+/setup cx+/setup oc+/setup code <value>+/setup code <backend> <value>+```++#### 作用++- 如果没有显式 backend,就使用当前作用域绑定的 backend+- 启动对应后端的认证修复流程+- 把浏览器链接、device code、后续输入提示发回聊天+- 等待流程完成后做状态校验++#### 分 backend 行为++##### Claude++- 启动 Claude 登录流程+- 把浏览器授权 URL 发回聊天+- 如果 Claude 后续要求输入粘贴 code,用户在聊天里继续发:++```text+/setup code <value>+```++##### Codex++- 启动 device auth+- 把浏览器 URL 和一次性 code 发回聊天+- bot 会等待完成并用 `codex login status` 做校验++##### OpenCode++- 优先根据当前 OpenCode 路由模型推断 provider+- `openai` 走 headless device 风格认证+- 常见 provider,如 `opencode`、`anthropic`,走 key 输入流+- 当 OpenCode 提示要输入 key 时,用户在聊天里发:++```text+/setup code <value>+```++#### 权限++- 仅管理员++#### 备注++- `/setup code <backend> <value>` 适合多个 setup flow 并行时显式指定 backend。+- 只有发起该 setup flow 的用户才能提交后续验证码或 key。++### `/settings`++打开当前作用域的设置 UI。++#### 语法++```text+/settings+```++#### 作用++- 打开或路由到当前平台对应的设置面板+- 通过 UI 流程修改 routing 等作用域配置++#### 权限++- 仅管理员++#### 备注++- 这个命令已经注册,但不同平台的具体 UI 形态不完全一样。+- 如果用户希望走引导式配置,而不是记命令,优先让他用这个。++### `/stop`++中断当前作用域下正在执行的 backend 任务。++#### 语法++```text+/stop+```++#### 作用++- 根据当前作用域解析 backend+- 生成 stop 请求并交给 backend adapter 执行+- 如果当前没有活动会话,会返回提示消息++#### 备注++- 在支持线程的平台里,线程内直接发 `stop` 或 `/stop` 也可能被消息流识别。+- 这个命令不会顺手改路由,也不会删除历史状态。++### `/bind <绑定码>`++用绑定码把当前 DM 用户绑定到这个 Vibe Remote 实例。++#### 语法++```text+/bind <绑定码>+bind <绑定码>+```++#### 作用++- 校验绑定码+- 把当前 DM 用户记录为已绑定+- 保存 DM chat ID+- 在首个 bootstrap bind 等场景里,可能同时赋予管理员身份++#### 权限和上下文++- 只能在 DM 里使用+- 即使用户尚未绑定,也允许执行++#### 示例++```text+/bind vr-a3x9k2+bind vr-a3x9k2+```++#### 备注++- `bind <绑定码>` 是兼容路径,主要应对某些平台里 `/` 开头输入不方便的情况。+- 如果用户已经绑定,会返回 already bound,而不是重复绑定。++## 4. 哪些不是命令++这些是重要的用户入口,但它们不是文本命令:++- `AgentName: 你的消息`+ - 例如:`Plan: 设计一个新的缓存层`+ - 这是 subagent prefix,不是命令。+- `/start` 菜单按钮+ - 例如:`Settings`、`Resume Session`、`Change Work Dir`+ - 这些是按钮回调或 modal 流程,不是 slash command。++## 5. 宿主机 CLI 命令++`vibe` 可执行文件负责管理本地服务与异步自动化能力。++## 5.1 顶层 CLI 命令++| 命令 | 作用 |+| --- | --- |+| `vibe` | 启动或重启服务与 Web UI |+| `vibe stop` | 停止服务与 UI,同时终止 OpenCode server |+| `vibe restart` | 停止后重新启动 |+| `vibe status` | 输出运行状态 JSON |+| `vibe doctor` | 运行诊断 |+| `vibe version` | 查看当前版本 |+| `vibe check-update` | 检查是否有新版本 |+| `vibe upgrade` | 升级到最新版 |+| `vibe task ...` | 管理定时任务 |+| `vibe hook send ...` | 队列化一次异步 hook,不保存任务定义 |++### `vibe`++```bash+vibe+```++- 启动或重启主服务+- 打开 Web UI+- 尽量保留正在运行的 OpenCode server++### `vibe stop`++```bash+vibe stop+```++- 停止主服务+- 停止 UI 服务+- 同时终止 OpenCode server++### `vibe restart`++```bash+vibe restart+```++- 语义上等价于先停再启++### `vibe status`++```bash+vibe status+```++- 输出运行状态 JSON++### `vibe doctor`++```bash+vibe doctor+```++- 校验配置+- 检查平台凭据+- 检查 backend CLI 是否可用+- 检查运行环境++### `vibe version`++```bash+vibe version+```++- 输出当前安装版本++### `vibe check-update`++```bash+vibe check-update+```++- 检查 PyPI 是否有更高版本++### `vibe upgrade`++```bash+vibe upgrade+```++- 按升级计划升级 Vibe Remote+- 成功后通常建议再执行 `vibe stop && vibe`++## 5.2 `vibe task`++`vibe task` 用来管理持久化的定时任务。++### 支持的子命令++| 子命令 | 作用 |+| --- | --- |+| `vibe task add` | 创建任务 |+| `vibe task update` | 更新任务 |+| `vibe task list` | 列出任务 |+| `vibe task ls` | `list` 的隐藏别名 |+| `vibe task show <task_id>` | 查看单个任务 |+| `vibe task pause <task_id>` | 暂停任务 |+| `vibe task resume <task_id>` | 恢复任务 |+| `vibe task run <task_id>` | 立即运行一次 |+| `vibe task remove <task_id>` | 删除任务 |+| `vibe task rm <task_id>` | `remove` 的隐藏别名 |++### `vibe task add`++```bash+vibe task add --session-key <key> (--cron <表达式> | --at <时间戳>) (--prompt <文本> | --prompt-file <文件>) [options]+```++重要参数:++- `--name`+- `--session-key` 必填+- `--post-to {thread,channel}`+- `--deliver-key`+- `--cron`+- `--at`+- `--prompt`+- `--prompt-file`+- `--timezone`++### `vibe task update`++```bash+vibe task update <task_id> [options]+```++重要参数:++- `--name`+- `--clear-name`+- `--session-key`+- `--post-to {thread,channel}`+- `--deliver-key`+- `--reset-delivery`+- `--cron`+- `--at`+- `--prompt`+- `--prompt-file`+- `--timezone`++### `vibe task list`++```bash+vibe task list [--all] [--brief]+```++### `vibe task show`++```bash+vibe task show <task_id>+```++### `vibe task pause`++```bash+vibe task pause <task_id>+```++### `vibe task resume`++```bash+vibe task resume <task_id>+```++### `vibe task run`++```bash+vibe task run <task_id>+```++### `vibe task remove`++```bash+vibe task remove <task_id>+```++## 5.3 `vibe hook send`++队列化一次异步 turn,但不会创建持久化任务定义。++### 语法++```bash+vibe hook send --session-key <key> (--prompt <文本> | --prompt-file <文件>) [options]+```++重要参数:++- `--session-key` 必填+- `--post-to {thread,channel}`+- `--deliver-key`+- `--prompt`+- `--prompt-file`++## 6. 推荐心智模型++按用途选命令:++- 想在聊天里控制会话:+ - 用 `/start`、`/resume`、`/setcwd`、`/setup`、`/stop`+- 想开通或恢复 DM 使用权限:+ - 在 DM 里用 `/bind <code>`+- 想管理本地守护进程或排查安装问题:+ - 用 `vibe`、`vibe status`、`vibe doctor`、`vibe upgrade`+- 想做异步自动化:+ - 用 `vibe task ...` 或 `vibe hook send ...`++## 7. 快速示例++### 聊天里++```text+@Vibe Remote /start+@Vibe Remote /cwd+@Vibe Remote /setcwd ~/projects/backend+@Vibe Remote /setup+@Vibe Remote /setup codex+@Vibe Remote /setup code 123456+@Vibe Remote /stop+```++### 宿主机上++```bash+vibe+vibe status+vibe doctor+vibe task list --brief+vibe hook send --session-key 'slack::channel::C123' --prompt 'Share the latest build summary.'+```+diff --git a/docs/plans/agent-oauth-setup.md b/docs/plans/agent-oauth-setup.mdnew file mode 100644index 000000000..953a70367--- /dev/null+++ b/docs/plans/agent-oauth-setup.md@@ -0,0 +1,96 @@+# Agent OAuth Setup++## Background++Vibe Remote currently assumes Claude Code and Codex are already authenticated on the host machine. When the login state expires, recovery requires opening a shell on the machine and re-running the backend CLI login flow manually.++The requested product behavior is:++- `/setup` starts OAuth setup for the backend currently bound to the channel/user scope+- auth-related backend failures expose a `reset oauth` action button+- the browser link, device code, and any follow-up code submission happen through IM messages instead of SSHing into the machine++## Scope++First implementation focuses on:++- slash command entry: `/setup`, `/setup <backend>`, `/setup code <value>`+- callback entry: `reset oauth` button on recoverable Claude/Codex auth failures+- Codex setup via `codex login --device-auth`+- Claude setup via `claude auth login --claudeai`+- in-memory auth flow tracking for the running bot process++Out of scope for this pass:++- persistent auth flow resume after bot restart+- automatic DM handoff for secret-bearing setup messages+- OpenCode auth setup++## Design++Add a controller-owned `AgentAuthService` responsible for:++1. Resolving the effective backend for the current context+2. Starting a backend-specific auth subprocess+3. Parsing stdout/PTY output into user-facing IM prompts+4. Accepting follow-up code submission for active Claude flows+5. Verifying login status on completion+6. Sending success/failure notifications and cleanup++### Command semantics++- `/setup`+ - resolves the backend from current routing+ - force-resets existing cached OAuth session before starting a fresh flow+- `/setup claude|codex`+ - explicit backend override+- `/setup code <value>`+ - submits follow-up code into the currently active flow for this session/backend++### Error recovery button++Recoverable auth failures emit a button with callback data:++- `auth_setup:auto`+- `auth_setup:claude`+- `auth_setup:codex`++The callback re-runs the same setup flow as `/setup`.++### Backend behavior++#### Codex++- run `codex logout` best-effort+- run `codex login --device-auth`+- parse:+ - verification URL+ - one-time device code+- wait for process exit+- verify with `codex login status`++#### Claude++- run `claude auth logout` best-effort+- run `claude auth login --claudeai` inside a PTY+- parse:+ - OAuth URL+ - any prompt requesting a code paste+- when code is requested, prompt the user to send `/setup code <value>`+- wait for process exit+- verify with `claude auth status`++## Safety++- treat `/setup` and `auth_setup:*` as admin-protected actions+- never echo submitted codes back to chat+- never print credential file contents+- run auth flows in the same OS user context as the bot process++## Todo++- add `setup` command and callback routing+- implement `AgentAuthService`+- add auth error classification helpers for Claude/Codex+- emit recoverable auth errors with `reset oauth` buttons+- add focused tests for command parsing, callback routing, flow messaging, and auth error classificationdiff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 43817d3c0..241dd744e 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -96,7 +96,13 @@ class ClaudeAgent(BaseAgent):await self._remove_specific_pending_reaction(request.composite_session_id, context, request)self._remove_pending_request(request.composite_session_id, request)await self._remove_ack_reaction(request)- await self.session_handler.handle_session_error(request.composite_session_id, context, e)+ handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ context,+ "claude",+ f"❌ Claude error: {e}",+ )+ if not handled:+ await self.session_handler.handle_session_error(request.composite_session_id, context, e)finally:await self._delete_ack(context, request)diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 469046c88..0a11d62a0 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -141,11 +141,18 @@ class CodexAgent(BaseAgent):self._turn_registry.clear_pending_turn_start(request.base_session_id, request)logger.error("Error in Codex handle_message: %s", e, exc_info=True)- await self.controller.emit_agent_message(+ error_text = f"❌ Codex error: {e}"+ handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(request.context,- "notify",- f"❌ Codex error: {e}",+ "codex",+ error_text,)+ if not handled:+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ error_text,+ )await self._remove_ack_reaction(request)async def handle_stop(self, request: AgentRequest) -> bool:diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex 685abb362..74f7099ee 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -104,11 +104,18 @@ class CodexEventHandler:error_msg = self._extract_error_message(error_obj)if should_emit_terminal_error and not already_notified:- await self._agent.controller.emit_agent_message(+ message = f"❌ Codex turn failed: {error_msg}"+ handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(tracked_request.context,- "notify",- f"❌ Codex turn failed: {error_msg}",+ "codex",+ message,)+ if not handled:+ await self._agent.controller.emit_agent_message(+ tracked_request.context,+ "notify",+ message,+ )else:logger.info("Suppressing inactive Codex turn failure for %s: %s", turn_id, error_msg)@@ -255,21 +262,35 @@ class CodexEventHandler:self._agent._turn_registry.should_emit_terminal_error(turn_id)and not turn_state.terminal_error_notified):- await self._agent.controller.emit_agent_message(+ text = f"❌ Codex turn failed: {message}"+ handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(request.context,- "notify",- f"❌ Codex turn failed: {message}",+ "codex",+ text,)+ if not handled:+ await self._agent.controller.emit_agent_message(+ request.context,+ "notify",+ text,+ )turn_state.terminal_error_notified = Trueelse:logger.info("Logging inactive Codex turn error for %s: %s", turn_id, message)return- await self._agent.controller.emit_agent_message(+ text = f"❌ Codex error: {message}"+ handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(request.context,- "notify",- f"❌ Codex error: {message}",+ "codex",+ text,)+ if not handled:+ await self._agent.controller.emit_agent_message(+ request.context,+ "notify",+ text,+ )def _extract_error_message(self, error: Any) -> str:if isinstance(error, dict):diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex ef76f5cfc..19bfc4aed 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -348,11 +348,18 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):if session_id:self.sessions.remove_active_poll(session_id)- await self.controller.emit_agent_message(+ message = f"OpenCode request failed: {error_text}"+ handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(request.context,- "notify",- f"OpenCode request failed: {error_text}",+ "opencode",+ message,)+ if not handled:+ await self.controller.emit_agent_message(+ request.context,+ "notify",+ message,+ )async def handle_stop(self, request: AgentRequest) -> bool:task = self._active_requests.get(request.base_session_id)diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex f82e0ddec..3322c1a04 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -261,11 +261,18 @@ class OpenCodePollLoop:retry_err,)- await self._agent.controller.emit_agent_message(+ message = f"OpenCode error: {error_name} - {error_msg[:500]}"+ handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(request.context,- "notify",- f"OpenCode error: {error_name} - {error_msg[:500]}",+ "opencode",+ message,)+ if not handled:+ await self._agent.controller.emit_agent_message(+ request.context,+ "notify",+ message,+ )final_text = Nonebreak@@ -487,11 +494,18 @@ class OpenCodePollLoop:last_error_message_id = last_info.get("id")error_retry_count += 1if error_retry_count > error_retry_limit:- await self._agent.controller.emit_agent_message(+ message = f"OpenCode error: {error_text}"+ handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(context,- "notify",- f"OpenCode error: {error_text}",+ "opencode",+ message,)+ if not handled:+ await self._agent.controller.emit_agent_message(+ context,+ "notify",+ message,+ )self._agent.sessions.remove_active_poll(session_id)await _remove_ack_reaction()return@@ -559,8 +573,15 @@ class OpenCodePollLoop:self._agent.sessions.remove_active_poll(session_id)await _remove_ack_reaction()- await self._agent.controller.emit_agent_message(+ message = f"Restored OpenCode session failed: {error_text}"+ handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(context,- "notify",- f"Restored OpenCode session failed: {error_text}",+ "opencode",+ message,)+ if not handled:+ await self._agent.controller.emit_agent_message(+ context,+ "notify",+ message,+ )diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 0723e9642..d275abc8d 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -400,6 +400,35 @@ class OpenCodeServerManager:# Don't clear _process reference - just let it be garbage collected.self._process = None+ async def restart_for_auth_refresh(self) -> None:+ """Terminate the shared server so the next request reloads refreshed auth."""+ async with self._get_lock():+ if self._http_session:+ await self._http_session.close()+ self._http_session = None+ self._http_session_loop = None++ targets: list[int] = []+ info = self._read_pid_file()+ pid = info.get("pid") if isinstance(info, dict) else None+ if isinstance(pid, int) and self._pid_exists(pid):+ cmd = self._get_pid_command(pid)+ if cmd and self._is_opencode_serve_cmd(cmd, self.port):+ targets.append(pid)++ if not targets:+ for candidate in self._find_opencode_serve_pids(self.port):+ cmd = self._get_pid_command(candidate)+ if cmd and self._is_opencode_serve_cmd(cmd, self.port):+ targets.append(candidate)++ for target_pid in dict.fromkeys(targets):+ await self._terminate_pid(target_pid, reason="auth refresh")++ self._clear_pid_file()+ self._process = None+ self._base_url = None+@classmethoddef stop_instance_sync(cls) -> None:if cls._instance:diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pynew file mode 100644index 000000000..438de3856--- /dev/null+++ b/tests/test_agent_auth_service.py@@ -0,0 +1,258 @@+import asyncio+import sys+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from core.agent_auth_service import AgentAuthFlow, AgentAuthService, classify_auth_error+from modules.im import MessageContext+++class _StubIMClient:+ def __init__(self):+ self.sent_messages = []+ self.sent_button_messages = []++ async def send_message(self, context, text, parse_mode=None):+ self.sent_messages.append((context.channel_id, text))+ return "msg-1"++ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):+ self.sent_button_messages.append((context.channel_id, text, keyboard))+ return "btn-1"+++class _StubController:+ def __init__(self):+ self.config = SimpleNamespace(+ platform="slack",+ language="en",+ agents=SimpleNamespace(+ codex=SimpleNamespace(cli_path="codex"),+ claude=SimpleNamespace(cli_path="claude"),+ opencode=SimpleNamespace(cli_path="opencode"),+ ),+ )+ self.im_client = _StubIMClient()+ self.agent_service = SimpleNamespace(agents={})+ self.resolve_agent_for_context = AsyncMock(return_value="codex")++ def get_im_client_for_context(self, context):+ return self.im_client++ def _get_settings_key(self, context):+ return context.channel_id++ def _get_lang(self):+ return "en"++ def resolve_agent_for_context(self, context):+ return "codex"++ def get_opencode_overrides(self, context):+ return (None, None, None)+++class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):+ async def test_handle_setup_command_submits_code(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ service.submit_code = AsyncMock()+ context = MessageContext(user_id="U1", channel_id="C1")++ await service.handle_setup_command(context, "code 123456")++ service.submit_code.assert_awaited_once_with(context, "123456")++ async def test_handle_setup_command_starts_explicit_backend(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ service.start_setup = AsyncMock()+ context = MessageContext(user_id="U1", channel_id="C1")++ await service.handle_setup_command(context, "claude")++ service.start_setup.assert_awaited_once_with(context, backend="claude", force_reset=True)++ async def test_handle_setup_command_supports_opencode_alias(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ service.start_setup = AsyncMock()+ context = MessageContext(user_id="U1", channel_id="C1")++ await service.handle_setup_command(context, "oc")++ service.start_setup.assert_awaited_once_with(context, backend="opencode", force_reset=True)++ async def test_maybe_emit_auth_recovery_message_sends_reset_button(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")++ handled = await service.maybe_emit_auth_recovery_message(+ context,+ "codex",+ "❌ Codex error: 401 Unauthorized",+ )++ self.assertTrue(handled)+ self.assertEqual(len(controller.im_client.sent_button_messages), 1)+ _, text, keyboard = controller.im_client.sent_button_messages[0]+ self.assertIn("401 Unauthorized", text)+ self.assertEqual(keyboard.buttons[0][0].callback_data, "auth_setup:codex")++ async def test_handle_process_text_emits_codex_link_once_url_and_code_exist(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task+ flow = AgentAuthFlow(+ flow_id="flow-1",+ backend="codex",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=SimpleNamespace(returncode=None),+ reader_task=done_task,+ waiter_task=done_task,+ )+ service._flows[flow.flow_key] = flow++ await service._handle_process_text(context, "codex", "https://auth.openai.com/codex/device")+ await service._handle_process_text(context, "codex", "T74L-XU61D")++ self.assertEqual(len(controller.im_client.sent_messages), 1)+ _, text = controller.im_client.sent_messages[0]+ self.assertIn("T74L-XU61D", text)+ self.assertIn("https://auth.openai.com/codex/device", text)++ async def test_handle_process_text_marks_claude_flow_awaiting_code(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task+ flow = AgentAuthFlow(+ flow_id="flow-2",+ backend="claude",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=SimpleNamespace(returncode=None),+ reader_task=done_task,+ waiter_task=done_task,+ pty_master_fd=10,+ )+ service._flows[flow.flow_key] = flow++ await service._handle_process_text(+ context,+ "claude",+ "Paste code here if prompted >",+ )++ self.assertTrue(flow.awaiting_code)+ self.assertEqual(len(controller.im_client.sent_messages), 1)+ self.assertIn("/setup code <value>", controller.im_client.sent_messages[0][1])++ async def test_handle_process_text_marks_opencode_flow_awaiting_api_key(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task+ flow = AgentAuthFlow(+ flow_id="flow-3",+ backend="opencode",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=SimpleNamespace(returncode=None),+ reader_task=done_task,+ waiter_task=done_task,+ pty_master_fd=10,+ provider="opencode",+ )+ service._flows[flow.flow_key] = flow++ await service._handle_process_text(+ context,+ "opencode",+ "Create an api key at https://opencode.ai/auth",+ )+ await service._handle_process_text(+ context,+ "opencode",+ "E\nn\nt\ne\nr\ny\no\nu\nr\nA\nP\nI\nk\ne\ny",+ )++ self.assertTrue(flow.awaiting_code)+ self.assertEqual(len(controller.im_client.sent_messages), 2)+ self.assertIn("https://opencode.ai/auth", controller.im_client.sent_messages[0][1])+ self.assertIn("/setup code <value>", controller.im_client.sent_messages[1][1])++ async def test_resolve_opencode_provider_prefers_override_model(self):+ controller = _StubController()+ controller.get_opencode_overrides = lambda context: ("build", "openai/gpt-5.4", None)+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")++ provider = await service._resolve_opencode_provider(context)++ self.assertEqual(provider, "openai")++ async def test_handle_process_text_emits_opencode_device_flow_for_openai(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task+ flow = AgentAuthFlow(+ flow_id="flow-4",+ backend="opencode",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=SimpleNamespace(returncode=None),+ reader_task=done_task,+ waiter_task=done_task,+ pty_master_fd=10,+ provider="openai",+ )+ service._flows[flow.flow_key] = flow++ await service._handle_process_text(+ context,+ "opencode",+ "Go to: https://auth.openai.com/codex/device",+ )+ await service._handle_process_text(+ context,+ "opencode",+ "Enter code: TRVY-E7DCU",+ )++ self.assertEqual(len(controller.im_client.sent_messages), 1)+ message = controller.im_client.sent_messages[0][1]+ self.assertIn("https://auth.openai.com/codex/device", message)+ self.assertIn("TRVY-E7DCU", message)+++class ClassifyAuthErrorTests(unittest.TestCase):+ def test_codex_401_requires_reset(self):+ self.assertTrue(classify_auth_error("codex", "unexpected status 401 Unauthorized"))++ def test_non_auth_error_is_ignored(self):+ self.assertFalse(classify_auth_error("codex", "temporary network timeout"))++ def test_opencode_credential_error_requires_reset(self):+ self.assertTrue(classify_auth_error("opencode", "OpenCode error: missing provider credential"))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_auth_pipeline.py b/tests/test_auth_pipeline.pyindex 7bedb0e3c..ff338ff09 100644--- a/tests/test_auth_pipeline.py+++ b/tests/test_auth_pipeline.py@@ -1,4 +1,9 @@from types import SimpleNamespace+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))from core.auth import check_auth@@ -104,3 +109,21 @@ def test_admin_guard_denies_non_admin_for_protected_action():assert result.allowed is Falseassert result.denial == "not_admin"+++def test_admin_guard_denies_non_admin_for_auth_setup_callback():+ store = _Store()+ store.settings.channels["C1"] = SimpleNamespace(enabled=True)+ store._bound_users.add("U5")+ store._admins.add("U-admin")++ result = check_auth(+ user_id="U5",+ channel_id="C1",+ is_dm=False,+ action="auth_setup:codex",+ store=store,+ )++ assert result.allowed is False+ assert result.denial == "not_admin"diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.pyindex 2af893252..430a69e7f 100644--- a/tests/test_codex_event_handler.py+++ b/tests/test_codex_event_handler.py@@ -77,7 +77,10 @@ class _StubTurnRegistry:class _StubAgent:def __init__(self):self._turn_registry = _StubTurnRegistry()- self.controller = SimpleNamespace(emit_agent_message=AsyncMock())+ self.controller = SimpleNamespace(+ emit_agent_message=AsyncMock(),+ agent_auth_service=SimpleNamespace(maybe_emit_auth_recovery_message=AsyncMock(return_value=False)),+ )self.emit_result_message = AsyncMock()self._remove_ack_reaction = AsyncMock()@@ -115,6 +118,11 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):request,)+ agent.controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once_with(+ request.context,+ "codex",+ "❌ Codex turn failed: unexpected status 401 Unauthorized:",+ )agent.controller.emit_agent_message.assert_awaited_once_with(request.context,"notify",@@ -152,6 +160,11 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):request,)+ agent.controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once_with(+ request.context,+ "codex",+ "❌ Codex turn failed: fallback message",+ )agent.controller.emit_agent_message.assert_awaited_once_with(request.context,"notify",@@ -206,6 +219,24 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):agent.controller.emit_agent_message.assert_not_awaited()+ async def test_auth_recovery_message_suppresses_plain_notify(self):+ agent = _StubAgent()+ agent.controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)+ handler = CodexEventHandler(agent)+ request = SimpleNamespace(base_session_id="session-1", context=object(), started_at=0)+ agent._turn_registry.register_turn("turn-1", request)++ await handler._on_error(+ {+ "error": {"message": "unexpected status 401 Unauthorized:"},+ "willRetry": False,+ "turnId": "turn-1",+ },+ request,+ )++ agent.controller.emit_agent_message.assert_not_awaited()+async def test_inactive_turn_item_is_ignored(self):agent = _StubAgent()handler = CodexEventHandler(agent)diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.pyindex 648bb97ca..ddb349aa8 100644--- a/tests/test_command_handler_user_names.py+++ b/tests/test_command_handler_user_names.py@@ -144,6 +144,7 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):self.assertIn("/start - 显示欢迎消息", message)self.assertIn("/setcwd <路径> - 设置工作目录", message)self.assertIn("/resume - 恢复当前目录下最近的会话", message)+ self.assertIn("/setup [claude|codex|opencode] - 修复后端登录/认证", message)self.assertIn("/new - 开启一个全新的会话", message)self.assertNotIn("User ID", message)self.assertNotIn("How it works", message)diff --git a/tests/test_message_handler_auth_setup.py b/tests/test_message_handler_auth_setup.pynew file mode 100644index 000000000..551988703--- /dev/null+++ b/tests/test_message_handler_auth_setup.py@@ -0,0 +1,124 @@+import importlib.util+import sys+import types+import unittest+from pathlib import Path+from unittest.mock import AsyncMock++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from modules.im import MessageContext+++def _load_message_handler_class():+ agents_module = types.ModuleType("modules.agents")+ agents_module.__path__ = [str(ROOT / "modules" / "agents")]+ setattr(agents_module, "AgentRequest", type("AgentRequest", (), {}))+ sys.modules["modules.agents"] = agents_module+ agents_base_module = types.ModuleType("modules.agents.base")+ setattr(agents_base_module, "AgentRequest", type("AgentRequest", (), {}))+ sys.modules["modules.agents.base"] = agents_base_module++ core_pkg = types.ModuleType("core")+ core_pkg.__path__ = [str(ROOT / "core")]+ sys.modules["core"] = core_pkg++ handlers_pkg = types.ModuleType("core.handlers")+ handlers_pkg.__path__ = [str(ROOT / "core" / "handlers")]+ sys.modules["core.handlers"] = handlers_pkg++ for module_name, relative_path in (+ ("core.handlers.base", ROOT / "core" / "handlers" / "base.py"),+ ("core.handlers.message_handler", ROOT / "core" / "handlers" / "message_handler.py"),+ ):+ spec = importlib.util.spec_from_file_location(module_name, relative_path)+ assert spec is not None+ assert spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[module_name] = module+ spec.loader.exec_module(module)++ return sys.modules["core.handlers.message_handler"].MessageHandler+++MessageHandler = _load_message_handler_class()+++class _StubSessions:+ def is_message_already_processed(self, channel_id, thread_ts, message_ts):+ return False++ def record_processed_message(self, channel_id, thread_ts, message_ts):+ return None+++class _StubSettingsManager:+ def __init__(self):+ self.sessions = _StubSessions()++ def get_channel_routing(self, settings_key):+ return None++ def is_message_type_hidden(self, settings_key, canonical_type):+ return False+++class _StubIMClient:+ def __init__(self):+ self.sent_messages = []+ self.formatter = types.SimpleNamespace(format_error=lambda text: text, format_warning=lambda text: text)++ async def send_message(self, context, text, parse_mode=None, reply_to=None):+ self.sent_messages.append((context.channel_id, text))+ return "msg-1"+++class _StubController:+ def __init__(self):+ self.config = types.SimpleNamespace(platform="slack", ack_mode="reaction", include_user_info=False, language="en")+ self.im_client = _StubIMClient()+ self.settings_manager = _StubSettingsManager()+ self.session_manager = object()+ self.session_handler = None+ self.receiver_tasks = {}+ self.agent_service = types.SimpleNamespace(default_agent="codex")+ self.settings_handler = types.SimpleNamespace()+ self.command_handler = types.SimpleNamespace()+ self.agent_auth_service = types.SimpleNamespace(handle_setup_callback=AsyncMock())++ def get_im_client_for_context(self, context):+ return self.im_client++ def _get_settings_key(self, context):+ return context.channel_id++ def _get_session_key(self, context):+ return f"slack::{context.channel_id}"++ def _get_lang(self):+ return "en"+++class MessageHandlerAuthSetupTests(unittest.IsolatedAsyncioTestCase):+ async def test_auth_setup_callback_routes_to_agent_auth_service(self):+ controller = _StubController()+ controller.settings_handler.handle_info_message_types = AsyncMock()+ controller.settings_handler.handle_info_how_it_works = AsyncMock()+ controller.command_handler.handle_cwd = AsyncMock()+ controller.command_handler.handle_change_cwd_modal = AsyncMock()+ controller.command_handler.handle_new = AsyncMock()+ controller.command_handler.handle_resume = AsyncMock()+ controller.settings_handler.handle_settings = AsyncMock()+ controller.settings_handler.handle_routing = AsyncMock()++ handler = MessageHandler(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")++ await handler.handle_callback_query(context, "auth_setup:auto")++ controller.agent_auth_service.handle_setup_callback.assert_awaited_once_with(context, "auth_setup:auto")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex 1fb088e79..e59604890 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -52,11 +52,15 @@ class _FakeResponse:class _FakeSession:def __init__(self):self.posts = []+ self.closed = Falsedef post(self, url, json=None, headers=None):self.posts.append({"url": url, "json": json, "headers": headers})return _FakeResponse()+ async def close(self):+ self.closed = True+class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):async def test_prompt_async_includes_tools_when_provided(self):@@ -127,6 +131,32 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(pids, [1234])+ async def test_restart_for_auth_refresh_stops_known_server_and_clears_state(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ fake_session = _FakeSession()+ manager._http_session = fake_session+ manager._http_session_loop = object()+ manager._process = object()+ manager._base_url = "http://127.0.0.1:4096"+ manager._read_pid_file = lambda: {"pid": 321} # type: ignore[method-assign]+ manager._pid_exists = lambda pid: pid == 321 # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]+ terminated = []+ manager._terminate_pid = lambda pid, reason: terminated.append((pid, reason)) or _async_none() # type: ignore[method-assign]+ manager._clear_pid_file = lambda: terminated.append(("cleared", "")) # type: ignore[method-assign]++ await manager.restart_for_auth_refresh()++ self.assertTrue(fake_session.closed)+ self.assertIn((321, "auth refresh"), terminated)+ self.assertIn(("cleared", ""), terminated)+ self.assertIsNone(manager._process)+ self.assertIsNone(manager._base_url)+++async def _async_none():+ return None+if __name__ == "__main__":unittest.main()diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 6c2e45141..67acd531c 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -189,6 +189,7 @@"commandCwd": "/cwd - Show current working directory","commandSetCwd": "/setcwd <path> - Set working directory","commandResume": "/resume - Restore a recent session for this working directory",+ "commandSetup": "/setup [claude|codex|opencode] - Repair backend login/auth","commandStop": "/stop - Interrupt {agent} execution","commandNew": "/new - Start a fresh session","quickActions": "Quick Actions:",@@ -233,6 +234,27 @@"unknownCommand": "Unknown resume command.","noMorePages": "There are no more sessions to show."},+ "setup": {+ "starting": "Starting {backend} setup...",+ "unsupportedBackend": "Backend `{backend}` does not support setup yet.",+ "codeUsage": "Usage: `/setup code <value>` or `/setup code <backend> <value>`",+ "noActiveFlow": "There is no active setup flow for this channel.",+ "notFlowOwner": "Only the user who started this setup flow can submit the follow-up code.",+ "codeNotSupported": "This backend does not accept follow-up setup codes.",+ "notAwaitingCode": "This setup flow is not waiting for a code right now.",+ "codeSubmitted": "{backend} setup code submitted. Waiting for login confirmation...",+ "resetPrompt": "{backend} looks logged out. Use the button below to restart OAuth setup.",+ "manualFallback": "If inline buttons are unavailable, run `/setup {backend}`.",+ "codexInstructions": "Codex setup started.\n\n1. Open this URL in your browser:\n{url}\n\n2. Enter this one-time code:\n`{code}`\n\nThe bot will keep waiting here and confirm when login finishes.",+ "claudeInstructions": "Claude setup started.\n\nOpen this URL in your browser and finish the login flow:\n{url}\n\nIf Claude later asks for a pasted code, send `/setup code <value>` in this chat.",+ "claudeCodePrompt": "Claude is waiting for a follow-up code. Send `/setup code <value>` in this chat.",+ "opencodeDeviceInstructions": "OpenCode setup started.\n\n1. Open this URL in your browser:\n{url}\n\n2. Enter this one-time code:\n`{code}`\n\nThe bot will keep waiting here and confirm when authorization finishes.",+ "opencodeInstructions": "OpenCode setup started for `{provider}`.\n\nOpen this page to create or retrieve a credential:\n{url}\n\nWhen OpenCode asks for the key, send `/setup code <value>` in this chat.",+ "opencodeCodePrompt": "OpenCode is waiting for the `{provider}` API key. Send `/setup code <value>` in this chat.",+ "success": "{backend} login is active again.",+ "failed": "{backend} setup failed: {detail}",+ "unknownFailure": "Unknown login failure."+ },"stop": {"noActiveSession": "No active session to stop for this channel."}@@ -246,7 +268,8 @@"resumeSession": "Resume Session","agentSettings": "Agent Settings","howItWorks": "Features",- "aboutMessageTypes": "About Message Types"+ "aboutMessageTypes": "About Message Types",+ "resetOAuth": "Reset OAuth"},"messageType": {"system": "System",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 2e6a05a23..ac6a3c3bd 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -189,6 +189,7 @@"commandCwd": "/cwd - 显示当前工作目录","commandSetCwd": "/setcwd <路径> - 设置工作目录","commandResume": "/resume - 恢复当前目录下最近的会话",+ "commandSetup": "/setup [claude|codex|opencode] - 修复后端登录/认证","commandStop": "/stop - 中断 {agent} 当前执行","commandNew": "/new - 开启一个全新的会话","quickActions": "快捷操作:",@@ -233,6 +234,27 @@"unknownCommand": "未识别的恢复命令。","noMorePages": "已经没有更多会话了。"},+ "setup": {+ "starting": "正在启动 {backend} 的登录修复流程...",+ "unsupportedBackend": "后端 `{backend}` 暂不支持 setup。",+ "codeUsage": "用法:`/setup code <value>` 或 `/setup code <backend> <value>`",+ "noActiveFlow": "当前频道没有正在进行的 setup 流程。",+ "notFlowOwner": "只有发起这次 setup 的用户才能提交后续验证码。",+ "codeNotSupported": "这个后端不支持提交后续验证码。",+ "notAwaitingCode": "当前 setup 流程此时并不在等待验证码。",+ "codeSubmitted": "已提交 {backend} 的验证码,正在等待登录确认...",+ "resetPrompt": "{backend} 看起来已经掉线了。请点击下面的按钮重新发起 OAuth 登录。",+ "manualFallback": "如果当前平台不支持按钮,请执行 `/setup {backend}`。",+ "codexInstructions": "Codex 登录修复已开始。\n\n1. 在浏览器打开这个地址:\n{url}\n\n2. 输入这个一次性验证码:\n`{code}`\n\nBot 会继续等待,并在登录完成后回消息确认。",+ "claudeInstructions": "Claude 登录修复已开始。\n\n请在浏览器打开下面的地址并完成登录:\n{url}\n\n如果 Claude 后续要求粘贴验证码,请在当前聊天里发送 `/setup code <value>`。",+ "claudeCodePrompt": "Claude 正在等待后续验证码。请在当前聊天里发送 `/setup code <value>`。",+ "opencodeDeviceInstructions": "OpenCode 认证修复已开始。\n\n1. 请在浏览器打开这个地址:\n{url}\n\n2. 输入这个一次性验证码:\n`{code}`\n\nBot 会继续等待,并在授权完成后回消息确认。",+ "opencodeInstructions": "OpenCode 的 `{provider}` 认证修复已开始。\n\n请打开下面这个页面创建或获取凭据:\n{url}\n\n当 OpenCode 提示输入 key 时,请在当前聊天里发送 `/setup code <value>`。",+ "opencodeCodePrompt": "OpenCode 正在等待 `{provider}` 的 API key。请在当前聊天里发送 `/setup code <value>`。",+ "success": "{backend} 已重新登录,可继续使用。",+ "failed": "{backend} 登录修复失败:{detail}",+ "unknownFailure": "未知登录失败。"+ },"stop": {"noActiveSession": "此频道没有要停止的活动会话。"}@@ -246,7 +268,8 @@"resumeSession": "恢复会话","agentSettings": "Agent 设置","howItWorks": "特色功能",- "aboutMessageTypes": "关于消息类型"+ "aboutMessageTypes": "关于消息类型",+ "resetOAuth": "重置 OAuth"},"messageType": {"system": "系统",