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(routing): route prefix subagents with defaults
cyhhao47a5b6350973
diff --git a/AGENTS.md b/AGENTS.mdindex 5f09bded1..2cc3f00a1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -18,6 +18,9 @@ This file defines how coding agents should work in this repository.### Planning (When Work Is Non-trivial)- If the task is complex or ambiguous, propose a short plan and confirm it with the user before large changes.+- Before starting complex work, capture background, goal, solution, and todo items in a Markdown plan under `docs/plans/`.+- Implementations must follow the plan and its todo items; update the plan document when tasks or scope change.+- If requirements are unclear during planning, ask the user early and proceed only after confirmation.- If a plan-related subagent exists, prefer calling it to draft/refine the plan.### Code Review@@ -25,6 +28,10 @@ This file defines how coding agents should work in this repository.- If a review-related subagent exists, call it when the code is ready for review.- Address review findings as appropriate until no must-fix issues remain.+### Documentation Updates++- When adding user-visible features, update the user documentation with usage guidance alongside the code changes.+### Quality Bar- Prefer root-cause fixes over defensive patches.@@ -62,6 +69,7 @@ This file defines how coding agents should work in this repository.- Run:- `./start.sh` (preferred) or `python main.py`- `./status.sh` / `./stop.sh`+ - Restart: run `./start.sh` directly### Coding Conventionsdiff --git a/README.md b/README.mdindex f28b89974..b9ffc4a74 100644--- a/README.md+++ b/README.md@@ -188,6 +188,15 @@ telegram:- `/settings` configure message visibility- `/stop` force-stop the active agent session (Claude interrupt / Codex process kill)+### Subagent Prefix Routing++Use `SubagentName:` or `SubagentName:` at the start of a message (leading spaces/newlines allowed) to invoke a subagent for the channel’s current agent backend.++- Example: `Plan: outline the steps`+- Matching is case-insensitive; only the channel’s bound agent is searched.+- The subagent’s default model/reasoning are used automatically.+- The bot adds a 🤖 reaction to your message when a subagent is matched.+### Slack- In channels, run `/start` to open the interactive menu (Current Dir, Change Work Dir, Reset Session, Settings, How it Works)diff --git a/README_ZH.md b/README_ZH.mdindex 0d5ac0c7d..67a5caf33 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -188,6 +188,15 @@ telegram:- `/settings` 配置消息可见性- `/stop` 强制停止当前 Agent(Claude 发送 interrupt,Codex 直接终止进程)+### Subagent 前缀路由++消息开头使用 `SubagentName:` 或 `SubagentName:`(允许前置空格/换行),即可调用当前频道绑定 Agent 的 Subagent。++- 示例:`Plan: 先把实现步骤列出来`+- 匹配大小写不敏感,仅在当前绑定的 Agent 内查找+- 自动使用 Subagent 的默认 model / reasoning_effort+- 命中时机器人会在消息上加 🤖 reaction+### Slack- 在频道中运行 `/start` 打开交互菜单(Current Dir、Change Work Dir、Reset Session、Settings、How it Works)diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex fda53d45e..7d019d6b6 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -68,6 +68,9 @@ class MessageHandler:if await self._handle_inline_stop(context):return+ if not self.session_handler:+ raise RuntimeError("Session handler not initialized")+base_session_id, working_path, composite_key = (self.session_handler.get_session_info(context))@@ -75,6 +78,58 @@ class MessageHandler:agent_name = self.controller.resolve_agent_for_context(context)+ matched_prefix = None+ subagent_message = None+ subagent_name = None+ subagent_model = None+ subagent_reasoning_effort = None++ if agent_name in ["opencode", "claude"]:+ from modules.agents.subagent_router import (+ load_claude_subagent,+ normalize_subagent_name,+ parse_subagent_prefix,+ )++ parsed = parse_subagent_prefix(message)+ if parsed:+ normalized = normalize_subagent_name(parsed.name)+ if agent_name == "opencode":+ try:+ opencode_agent = self.controller.agent_service.agents.get("opencode")+ if opencode_agent and hasattr(opencode_agent, "_get_server"):+ server = await opencode_agent._get_server()+ await server.ensure_running()+ opencode_agents = await server.get_available_agents(+ self.controller.get_cwd(context)+ )+ name_map = {+ normalize_subagent_name(a.get("name", "")): a+ for a in opencode_agents+ if a.get("name")+ }+ match = name_map.get(normalized)+ if match:+ subagent_name = match.get("name")+ except Exception as err:+ logger.warning(f"Failed to resolve OpenCode subagent: {err}")+ else:+ try:+ subagent_def = load_claude_subagent(normalized)+ if subagent_def:+ subagent_name = subagent_def.name+ subagent_model = subagent_def.model+ subagent_reasoning_effort = subagent_def.reasoning_effort+ except Exception as err:+ logger.warning(f"Failed to resolve Claude subagent: {err}")++ if subagent_name:+ matched_prefix = parsed.name+ subagent_message = parsed.message++ if subagent_name and subagent_message:+ message = subagent_message+ack_message_id = Noneack_mode = getattr(self.config, "ack_mode", "reaction")ack_reaction_message_id = None@@ -107,6 +162,27 @@ class MessageHandler:except Exception as ack_err:logger.debug(f"Failed to add reaction ack: {ack_err}")+ if subagent_name and context.message_id:+ try:+ reaction = ":robot_face:" if self.config.platform == "slack" else "🤖"+ await self.im_client.add_reaction(+ context,+ context.message_id,+ reaction,+ )+ except Exception as err:+ logger.debug(f"Failed to add subagent reaction: {err}")+ if ack_reaction_message_id and ack_reaction_emoji:+ try:+ await self.im_client.remove_reaction(+ context, ack_reaction_message_id, ack_reaction_emoji+ )+ except Exception as err:+ logger.debug(+ f"Failed to remove reaction ack for subagent: {err}"+ )++request = AgentRequest(context=context,message=message,@@ -115,6 +191,10 @@ class MessageHandler:composite_session_id=composite_key,settings_key=settings_key,ack_message_id=ack_message_id,+ subagent_name=subagent_name,+ subagent_key=matched_prefix,+ subagent_model=subagent_model,+ subagent_reasoning_effort=subagent_reasoning_effort,)try:await self.controller.agent_service.handle_message(agent_name, request)@@ -124,12 +204,13 @@ class MessageHandler:if request.ack_message_id:await self._delete_ack(context.channel_id, request)elif ack_reaction_message_id and ack_reaction_emoji:- try:- await self.im_client.remove_reaction(- context, ack_reaction_message_id, ack_reaction_emoji- )- except Exception as err:- logger.debug(f"Failed to remove reaction ack: {err}")+ if not subagent_name:+ try:+ await self.im_client.remove_reaction(+ context, ack_reaction_message_id, ack_reaction_emoji+ )+ except Exception as err:+ logger.debug(f"Failed to remove reaction ack: {err}")except Exception as e:logger.error(f"Error processing user message: {e}", exc_info=True)await self.im_client.send_message(diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex e3200178d..4009bf8ad 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -52,21 +52,49 @@ class SessionHandler:composite_key = f"{base_session_id}:{working_path}"return base_session_id, working_path, composite_key- async def get_or_create_claude_session(self, context: MessageContext) -> ClaudeSDKClient:+ async def get_or_create_claude_session(+ self,+ context: MessageContext,+ subagent_name: Optional[str] = None,+ subagent_model: Optional[str] = None,+ subagent_reasoning_effort: Optional[str] = None,+ ) -> ClaudeSDKClient:"""Get existing Claude session or create a new one"""base_session_id, working_path, composite_key = self.get_session_info(context)-- if composite_key in self.claude_sessions:- logger.info(f"Using existing Claude SDK client for {base_session_id} at {working_path}")- return self.claude_sessions[composite_key]-- # Check if we have a stored session mapping- # Get correct settings key based on platform+settings_key = self._get_settings_key(context)stored_claude_session_id = self.settings_manager.get_claude_session_id(settings_key, base_session_id, working_path)-++ if composite_key in self.claude_sessions and not subagent_name:+ logger.info(f"Using existing Claude SDK client for {base_session_id} at {working_path}")+ return self.claude_sessions[composite_key]++ if subagent_name:+ cached_base = f"{base_session_id}:{subagent_name}"+ cached_key = f"{cached_base}:{working_path}"+ cached_session_id = self.settings_manager.get_agent_session_id(+ settings_key,+ cached_base,+ working_path,+ agent_name="claude",+ )+ if cached_key in self.claude_sessions:+ logger.info(+ "Using Claude subagent session for %s at %s", cached_base, working_path+ )+ return self.claude_sessions[cached_key]+ if cached_session_id:+ stored_claude_session_id = cached_session_id+ composite_key = cached_key+ base_session_id = cached_base+ if composite_key in self.claude_sessions:+ logger.info(+ "Using Claude subagent session for %s at %s", cached_base, working_path+ )+ return self.claude_sessions[composite_key]+# Ensure working directory existsif not os.path.exists(working_path):try:@@ -77,11 +105,20 @@ class SessionHandler:working_path = os.getcwd()# Create options for Claude client+ extra_args = {}+ if subagent_name:+ extra_args["agent"] = subagent_name+ if subagent_model:+ extra_args["model"] = subagent_model+ if subagent_reasoning_effort:+ extra_args["reasoning-effort"] = subagent_reasoning_effort+options = ClaudeCodeOptions(permission_mode=self.config.claude.permission_mode,cwd=working_path,system_prompt=self.config.claude.system_prompt,- resume=stored_claude_session_id if stored_claude_session_id else None+ resume=stored_claude_session_id if stored_claude_session_id else None,+ extra_args=extra_args,)# Log session creation details@@ -89,6 +126,8 @@ class SessionHandler:logger.info(f" Working directory: {working_path}")logger.info(f" Resume session ID: {stored_claude_session_id}")logger.info(f" Options.resume: {options.resume}")+ if subagent_name:+ logger.info(f" Subagent: {subagent_name}")# Log if we're resuming a sessionif stored_claude_session_id:@@ -98,18 +137,20 @@ class SessionHandler:# Create new Claude clientclient = ClaudeSDKClient(options=options)-+# Log the actual options being used- logger.info(f"ClaudeCodeOptions details:")+ logger.info("ClaudeCodeOptions details:")logger.info(f" - permission_mode: {options.permission_mode}")logger.info(f" - cwd: {options.cwd}")logger.info(f" - system_prompt: {options.system_prompt}")logger.info(f" - resume: {options.resume}")logger.info(f" - continue_conversation: {options.continue_conversation}")-+ if subagent_name:+ logger.info(f" - subagent: {subagent_name}")+# Connect the clientawait client.connect()-+self.claude_sessions[composite_key] = clientlogger.info(f"Created new Claude SDK client for {base_session_id} at {working_path}")diff --git a/docs/plans/subagent_prefix_routing.md b/docs/plans/subagent_prefix_routing.mdnew file mode 100644index 000000000..19950d9ca--- /dev/null+++ b/docs/plans/subagent_prefix_routing.md@@ -0,0 +1,37 @@+# SubAgent Prefix Routing++## Background++Users want to invoke OpenCode or ClaudeCode subagents by prefixing a message with `XXX:` (or `XXX:`). The system should detect the prefix, resolve it against the current channel's bound agent, and route the request to the matching subagent. When a subagent is used, its default `model` and `reasoning_effort` must take precedence over channel overrides.++## Goal++- Support prefix-triggered subagent routing with case-insensitive matching.+- Only search within the channel's bound agent (OpenCode or ClaudeCode).+- If the prefix matches a subagent name and the message body is non-empty:+ - Explicitly select that subagent.+ - Use the subagent's default `model` and `reasoning_effort`.+ - Add a `:robot_face:` reaction to the user's original message.+- If no match or empty body, fall back to existing channel logic.+- ClaudeCode subagent lookup reads installed agent definitions from the local Claude Code plugin directories.++## Proposed Solution++- Parse user messages by trimming leading whitespace, then match `^([^\s::]+)\s*[::]\s*(.*)$`.+- Normalize the prefix to lower-case for matching against subagent names.+- Resolve the current channel agent backend, then look up subagent names for that backend only.+- On match, pass the subagent identifier explicitly and override model/reasoning fields with subagent defaults.+- On match, add a `:robot_face:` reaction to the user's original message and remove the ack reaction when applicable.++## To-do++1. Add prefix parsing and match logic at the message entry point.+2. Implement subagent lookup for OpenCode and ClaudeCode backends, sourcing ClaudeCode agents from local agent definitions.+3. Apply subagent overrides (agent + default model/reasoning) when matched.+4. Add a `:robot_face:` reaction to the original user message on match.+5. Add tests covering:+ - Case-insensitive matching.+ - Chinese/English colon support.+ - Empty-body fallback behavior.+ - Non-match fallback behavior.+6. Update user documentation with usage instructions for the prefix routing feature.diff --git a/modules/agents/base.py b/modules/agents/base.pyindex b48462bed..c1614576b 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -21,6 +21,10 @@ class AgentRequest:composite_session_id: strsettings_key: strack_message_id: Optional[str] = None+ subagent_name: Optional[str] = None+ subagent_key: Optional[str] = None+ subagent_model: Optional[str] = None+ subagent_reasoning_effort: Optional[str] = Nonelast_agent_message: Optional[str] = Nonelast_agent_message_parse_mode: Optional[str] = Nonestarted_at: float = field(default_factory=time.monotonic)diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 19b41d14f..a7b78cc2a 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -30,7 +30,12 @@ class ClaudeAgent(BaseAgent):context = request.contexttry:- client = await self.session_handler.get_or_create_claude_session(context)+ client = await self.session_handler.get_or_create_claude_session(+ context,+ subagent_name=request.subagent_name,+ subagent_model=request.subagent_model,+ subagent_reasoning_effort=request.subagent_reasoning_effort,+ )await client.query(request.message, session_id=request.composite_session_iddiff --git a/modules/agents/opencode_agent.py b/modules/agents/opencode_agent.pyindex b708da61d..5e0c4d56d 100644--- a/modules/agents/opencode_agent.py+++ b/modules/agents/opencode_agent.py@@ -1323,14 +1323,26 @@ class OpenCodeAgent(BaseAgent):self.controller.get_opencode_overrides(request.context))+ override_agent = request.subagent_name or override_agent+ if request.subagent_name:+ override_model = request.subagent_model+ override_reasoning = request.subagent_reasoning_effort++ if request.subagent_name and not override_model:+ override_model = server.get_agent_model_from_config(request.subagent_name)+ if request.subagent_name and not override_reasoning:+ override_reasoning = server.get_agent_reasoning_effort_from_config(+ request.subagent_name+ )+# Determine agent to use- # Priority: 1) channel override, 2) opencode.json default, 3) None (let OpenCode decide)+ # Priority: 1) channel override or prefix subagent, 2) opencode.json default, 3) None (let OpenCode decide)agent_to_use = override_agentif not agent_to_use:agent_to_use = server.get_default_agent_from_config()# Determine model to use- # Priority: 1) channel override, 2) agent's config model, 3) global opencode.json model+ # Priority: 1) channel override or prefix subagent, 2) agent's config model, 3) global opencode.json modelmodel_dict = Nonemodel_str = override_modelif not model_str:@@ -1343,7 +1355,7 @@ class OpenCodeAgent(BaseAgent):model_dict = {"providerID": parts[0], "modelID": parts[1]}# Determine reasoningEffort to use- # Priority: 1) channel override, 2) agent's config, 3) global opencode.json config+ # Priority: 1) channel override or prefix subagent, 2) agent's config, 3) global opencode.json configreasoning_effort = override_reasoningif not reasoning_effort:reasoning_effort = server.get_agent_reasoning_effort_from_config(agent_to_use)diff --git a/modules/agents/subagent_router.py b/modules/agents/subagent_router.pynew file mode 100644index 000000000..2daa4be10--- /dev/null+++ b/modules/agents/subagent_router.py@@ -0,0 +1,136 @@+from __future__ import annotations++import os+import re+from dataclasses import dataclass+from pathlib import Path+from typing import Dict, Iterable, Optional++import yaml+++_PREFIX_PATTERN = re.compile(r"^([^\s::]+)\s*[::]\s*(.*)$", re.DOTALL)+++def _yaml_safe_load(text: str) -> dict:+ data = yaml.safe_load(text)+ return data if isinstance(data, dict) else {}+++@dataclass(frozen=True)+class SubagentDefinition:+ name: str+ model: Optional[str] = None+ reasoning_effort: Optional[str] = None+++@dataclass(frozen=True)+class PrefixMatch:+ name: str+ message: str+++def parse_subagent_prefix(message: str) -> Optional[PrefixMatch]:+ if not message:+ return None++ trimmed = message.lstrip()+ match = _PREFIX_PATTERN.match(trimmed)+ if not match:+ return None++ name = match.group(1).strip()+ body = match.group(2)+ if not name:+ return None++ if not body or not body.strip():+ return None++ return PrefixMatch(name=name, message=body.strip())+++def normalize_subagent_name(name: str) -> str:+ return (name or "").strip().lower()+++def list_claude_subagents(search_root: Optional[Path] = None) -> Dict[str, SubagentDefinition]:+ root = search_root or (Path.home() / ".claude")+ if not root.exists():+ return {}++ agent_files: list[Path] = []+ candidate_dirs = _find_claude_agent_dirs(root)+ for directory in candidate_dirs:+ agent_files.extend(directory.glob("*.md"))++ definitions: Dict[str, SubagentDefinition] = {}+ for agent_file in agent_files:+ definition = _parse_claude_agent_definition(agent_file)+ if not definition:+ continue+ key = normalize_subagent_name(definition.name)+ if key:+ definitions[key] = definition+ return definitions+++def load_claude_subagent(name: str, search_root: Optional[Path] = None) -> Optional[SubagentDefinition]:+ normalized = normalize_subagent_name(name)+ if not normalized:+ return None+ return list_claude_subagents(search_root).get(normalized)+++def _find_claude_agent_dirs(root: Path) -> Iterable[Path]:+ agent_dirs = []+ if (root / "agents").exists():+ agent_dirs.append(root / "agents")++ for path in root.rglob("agents"):+ if path.is_dir():+ agent_dirs.append(path)++ seen = set()+ unique = []+ for path in agent_dirs:+ resolved = os.path.normpath(str(path))+ if resolved in seen:+ continue+ seen.add(resolved)+ unique.append(path)+ return unique+++def _parse_claude_agent_definition(path: Path) -> Optional[SubagentDefinition]:+ try:+ text = path.read_text(encoding="utf-8")+ except Exception:+ return None++ if not text.startswith("---"):+ return None++ parts = text.split("---", 2)+ if len(parts) < 3:+ return None++ header = parts[1]+ try:+ data = _yaml_safe_load(header)+ except Exception:+ return None++ name = data.get("name")+ if not isinstance(name, str) or not name.strip():+ return None++ model = data.get("model")+ if not isinstance(model, str) or not model.strip():+ model = None++ reasoning_effort = data.get("reasoning_effort") or data.get("reasoningEffort")+ if not isinstance(reasoning_effort, str) or not reasoning_effort.strip():+ reasoning_effort = None++ return SubagentDefinition(name=name.strip(), model=model, reasoning_effort=reasoning_effort)diff --git a/tests/test_subagent_router.py b/tests/test_subagent_router.pynew file mode 100644index 000000000..9e50346d6--- /dev/null+++ b/tests/test_subagent_router.py@@ -0,0 +1,46 @@+from pathlib import Path++from modules.agents.subagent_router import (+ load_claude_subagent,+ normalize_subagent_name,+ parse_subagent_prefix,+)+++def test_parse_subagent_prefix_basic():+ match = parse_subagent_prefix("Plan: do something")+ assert match+ assert match.name == "Plan"+ assert match.message == "do something"+++def test_parse_subagent_prefix_chinese_colon_and_whitespace():+ match = parse_subagent_prefix(" \nPlan: test")+ assert match+ assert match.name == "Plan"+ assert match.message == "test"+++def test_parse_subagent_prefix_empty_body_returns_none():+ assert parse_subagent_prefix("Plan:") is None+ assert parse_subagent_prefix("Plan: ") is None+++def test_normalize_subagent_name():+ assert normalize_subagent_name(" Plan ") == "plan"+ assert normalize_subagent_name("PLAN") == "plan"+++def test_load_claude_subagent_from_agent_dir(tmp_path: Path):+ agent_dir = tmp_path / "agents"+ agent_dir.mkdir()+ agent_file = agent_dir / "code-reviewer.md"+ agent_file.write_text(+ "---\nname: code-reviewer\nmodel: sonnet\n---\n\nBody",+ encoding="utf-8",+ )++ definition = load_claude_subagent("CODE-REVIEWER", search_root=tmp_path)+ assert definition+ assert definition.name == "code-reviewer"+ assert definition.model == "sonnet"