Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(opencode): add reasoningEffort config and unify settings from opencode.json

cyhhao67df3d901dd1
diff --git a/.env.example b/.env.example
index 1dbd9cfb7..59b4b6dc7 100644
--- a/.env.example
+++ b/.env.example
@@ -57,10 +57,8 @@ OPENCODE_ENABLED=false
OPENCODE_CLI_PATH=opencode
# OpenCode server port (defaults to 4096)
OPENCODE_PORT=4096
-# Default agent to use (e.g., "plan" or "build")
-OPENCODE_DEFAULT_AGENT=
-# Default model in format "provider/model" (e.g., "anthropic/claude-sonnet-4-20250514")
-OPENCODE_DEFAULT_MODEL=
+# Note: OpenCode agent/model/reasoningEffort settings are read from ~/.config/opencode/opencode.json
+# and can be overridden per-channel via the Agent Settings dialog in Slack.
# Path to agent routing file (YAML/JSON). Defaults to config/agent_routes.yaml when present.
AGENT_ROUTE_FILE=
diff --git a/config/settings.py b/config/settings.py
index a721cf347..82f81b45a 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -116,8 +116,6 @@ class CodexConfig:
class OpenCodeConfig:
binary: str = "opencode"
port: int = 4096
- default_agent: Optional[str] = None
- default_model: Optional[str] = None
@classmethod
def from_env(cls) -> "OpenCodeConfig":
@@ -140,8 +138,6 @@ class OpenCodeConfig:
return cls(
binary=binary,
port=port,
- default_agent=os.getenv("OPENCODE_DEFAULT_AGENT"),
- default_model=os.getenv("OPENCODE_DEFAULT_MODEL"),
)
diff --git a/core/controller.py b/core/controller.py
index f41ba6e15..ba4dc27e4 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -133,6 +133,7 @@ class Controller:
on_callback_query=self.message_handler.handle_callback_query,
on_settings_update=self.handle_settings_update,
on_change_cwd=self.handle_change_cwd_submission,
+ on_routing_update=self.handle_routing_update,
)
# Utility methods used by handlers
@@ -185,6 +186,52 @@ class Controller:
)
return context
+ def resolve_agent_for_context(self, context: MessageContext) -> str:
+ """Unified agent resolution with dynamic override support.
+
+ Priority:
+ 1. channel_routing.agent_backend (from user_settings.json)
+ 2. agent_routes.yaml overrides[channel_id]
+ 3. agent_routes.yaml platform.default
+ 4. agent_routes.yaml global default
+ 5. AgentService.default_agent ("claude")
+ """
+ settings_key = self._get_settings_key(context)
+
+ # Check dynamic override first
+ routing = self.settings_manager.get_channel_routing(settings_key)
+ if routing and routing.agent_backend:
+ # Verify the agent is registered
+ if routing.agent_backend in self.agent_service.agents:
+ return routing.agent_backend
+ else:
+ logger.warning(
+ f"Channel routing specifies '{routing.agent_backend}' but agent is not registered, "
+ f"falling back to static routing"
+ )
+
+ # Fall back to static routing
+ return self.agent_router.resolve(self.config.platform, settings_key)
+
+ def get_opencode_overrides(
+ self, context: MessageContext
+ ) -> tuple[Optional[str], Optional[str], Optional[str]]:
+ """Get OpenCode agent, model, and reasoning effort overrides for this channel.
+
+ Returns:
+ Tuple of (opencode_agent, opencode_model, opencode_reasoning_effort)
+ or (None, None, None) if no overrides.
+ """
+ settings_key = self._get_settings_key(context)
+ routing = self.settings_manager.get_channel_routing(settings_key)
+ if routing:
+ return (
+ routing.opencode_agent,
+ routing.opencode_model,
+ routing.opencode_reasoning_effort,
+ )
+ return None, None, None
+
async def emit_agent_message(
self,
context: MessageContext,
@@ -290,6 +337,73 @@ class Controller:
context, f"❌ Failed to change working directory: {str(e)}"
)
+ # Routing update handler (for Slack modal)
+ async def handle_routing_update(
+ self,
+ user_id: str,
+ channel_id: str,
+ backend: str,
+ opencode_agent: Optional[str],
+ opencode_model: Optional[str],
+ opencode_reasoning_effort: Optional[str] = None,
+ ):
+ """Handle routing update submission (from Slack modal)"""
+ from modules.settings_manager import ChannelRouting
+
+ try:
+ # Create routing object
+ routing = ChannelRouting(
+ agent_backend=backend,
+ opencode_agent=opencode_agent,
+ opencode_model=opencode_model,
+ opencode_reasoning_effort=opencode_reasoning_effort,
+ )
+
+ # Get settings key
+ settings_key = channel_id if channel_id else user_id
+
+ # Save routing
+ self.settings_manager.set_channel_routing(settings_key, routing)
+
+ # Build confirmation message
+ parts = [f"Backend: **{backend}**"]
+ if backend == "opencode":
+ if opencode_agent:
+ parts.append(f"Agent: **{opencode_agent}**")
+ if opencode_model:
+ parts.append(f"Model: **{opencode_model}**")
+ if opencode_reasoning_effort:
+ parts.append(f"Reasoning Effort: **{opencode_reasoning_effort}**")
+
+ # Create context for confirmation message
+ context = MessageContext(
+ user_id=user_id,
+ channel_id=channel_id if channel_id else user_id,
+ platform_specific={},
+ )
+
+ await self.im_client.send_message(
+ context,
+ f"✅ Agent routing updated!\n" + "\n".join(parts),
+ parse_mode="markdown",
+ )
+
+ logger.info(
+ f"Routing updated for {settings_key}: backend={backend}, "
+ f"agent={opencode_agent}, model={opencode_model}"
+ )
+
+ except Exception as e:
+ logger.error(f"Error updating routing: {e}")
+ context = MessageContext(
+ user_id=user_id,
+ channel_id=channel_id if channel_id else user_id,
+ platform_specific={},
+ )
+ await self.im_client.send_message(
+ context, f"❌ Failed to update routing: {str(e)}"
+ )
+
# Main run method
def run(self):
"""Run the controller"""
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 0e72ad0c1..df5942d81 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -57,10 +57,7 @@ class CommandHandlers:
),
}
- settings_key = self.controller._get_settings_key(context)
- agent_name = self.controller.agent_router.resolve(
- self.config.platform, settings_key
- )
+ agent_name = self.controller.resolve_agent_for_context(context)
default_agent = getattr(self.controller.agent_service, "default_agent", None)
agent_display_name = get_agent_display_name(
agent_name, fallback=default_agent or "Unknown"
@@ -119,7 +116,9 @@ class CommandHandlers:
InlineButton(text="🔄 Clear All Session", callback_data="cmd_clear"),
InlineButton(text="⚙️ Settings", callback_data="cmd_settings"),
],
- # Row 3: Help
+ # Row 3: Agent/Model switching
+ [InlineButton(text="🤖 Agent Settings", callback_data="cmd_routing")],
+ # Row 4: Help
[InlineButton(text="ℹ️ How it Works", callback_data="info_how_it_works")],
]
@@ -315,9 +314,7 @@ Use the buttons below to manage your {agent_display_name} sessions, or simply ty
session_handler.get_session_info(context)
)
settings_key = self.controller._get_settings_key(context)
- agent_name = self.controller.agent_router.resolve(
- self.config.platform, settings_key
- )
+ agent_name = self.controller.resolve_agent_for_context(context)
request = AgentRequest(
context=context,
message="stop",
diff --git a/modules/agents/opencode_agent.py b/modules/agents/opencode_agent.py
index b2e650dd0..45140b6dc 100644
--- a/modules/agents/opencode_agent.py
+++ b/modules/agents/opencode_agent.py
@@ -5,7 +5,7 @@ import logging
import os
import time
from asyncio.subprocess import Process
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple
import aiohttp
@@ -174,6 +174,7 @@ class OpenCodeServerManager:
text: str,
agent: Optional[str] = None,
model: Optional[Dict[str, str]] = None,
+ reasoning_effort: Optional[str] = None,
) -> Dict[str, Any]:
session = await self._get_http_session()
@@ -184,6 +185,8 @@ class OpenCodeServerManager:
body["agent"] = agent
if model:
body["model"] = model
+ if reasoning_effort:
+ body["reasoningEffort"] = reasoning_effort
async with session.post(
f"{self.base_url}/session/{session_id}/message",
@@ -225,6 +228,182 @@ class OpenCodeServerManager:
logger.debug(f"Failed to get session {session_id}: {e}")
return None
+ async def get_available_agents(self, directory: str) -> List[Dict[str, Any]]:
+ """Fetch available agents from OpenCode server.
+
+ Returns:
+ List of agent dicts with 'name', 'mode', 'native', etc.
+ """
+ session = await self._get_http_session()
+ try:
+ async with session.get(
+ f"{self.base_url}/agent",
+ headers={"x-opencode-directory": directory},
+ ) as resp:
+ if resp.status == 200:
+ agents = await resp.json()
+ # Filter to primary agents (build, plan), exclude hidden/subagent
+ return [
+ a for a in agents
+ if a.get("mode") == "primary" and not a.get("hidden", False)
+ ]
+ return []
+ except Exception as e:
+ logger.warning(f"Failed to get available agents: {e}")
+ return []
+
+ async def get_available_models(self, directory: str) -> Dict[str, Any]:
+ """Fetch available models from OpenCode server.
+
+ Returns:
+ Dict with 'providers' list and 'default' dict mapping provider to default model.
+ """
+ session = await self._get_http_session()
+ try:
+ async with session.get(
+ f"{self.base_url}/config/providers",
+ headers={"x-opencode-directory": directory},
+ ) as resp:
+ if resp.status == 200:
+ return await resp.json()
+ return {"providers": [], "default": {}}
+ except Exception as e:
+ logger.warning(f"Failed to get available models: {e}")
+ return {"providers": [], "default": {}}
+
+ async def get_default_config(self, directory: str) -> Dict[str, Any]:
+ """Fetch current default config from OpenCode server.
+
+ Returns:
+ Config dict including 'model' (current default), 'agent' configs, etc.
+ """
+ session = await self._get_http_session()
+ try:
+ async with session.get(
+ f"{self.base_url}/config",
+ headers={"x-opencode-directory": directory},
+ ) as resp:
+ if resp.status == 200:
+ return await resp.json()
+ return {}
+ except Exception as e:
+ logger.warning(f"Failed to get default config: {e}")
+ return {}
+
+ def get_agent_model_from_config(self, agent_name: Optional[str]) -> Optional[str]:
+ """Read agent's default model from user's opencode.json config file.
+
+ This is a workaround for OpenCode server not using agent-specific models
+ when only the agent parameter is passed to the message API.
+
+ Args:
+ agent_name: Name of the agent (e.g., "build", "plan"), or None for global default
+
+ Returns:
+ Model string in "provider/model" format, or None if not configured.
+ """
+ import json
+ from pathlib import Path
+
+ config_path = Path.home() / ".config" / "opencode" / "opencode.json"
+ if not config_path.exists():
+ return None
+
+ try:
+ with open(config_path, "r") as f:
+ config = json.load(f)
+
+ # If agent_name is provided, try to get agent-specific model first
+ if agent_name:
+ agent_config = config.get("agent", {}).get(agent_name, {})
+ model = agent_config.get("model")
+ if model:
+ logger.debug(f"Found model '{model}' for agent '{agent_name}' in opencode.json")
+ return model
+
+ # Fall back to global default model
+ model = config.get("model")
+ if model:
+ logger.debug(f"Using global default model '{model}' from opencode.json")
+ return model
+ except Exception as e:
+ logger.warning(f"Failed to read model from opencode.json: {e}")
+ return None
+
+ def get_agent_reasoning_effort_from_config(
+ self, agent_name: Optional[str]
+ ) -> Optional[str]:
+ """Read agent's reasoningEffort from user's opencode.json config file.
+
+ Args:
+ agent_name: Name of the agent (e.g., "build", "plan"), or None for global default
+
+ Returns:
+ reasoningEffort string (e.g., "low", "medium", "high", "xhigh"), or None if not configured.
+ """
+ import json
+ from pathlib import Path
+
+ config_path = Path.home() / ".config" / "opencode" / "opencode.json"
+ if not config_path.exists():
+ return None
+
+ try:
+ with open(config_path, "r") as f:
+ config = json.load(f)
+
+ # If agent_name is provided, try to get agent-specific reasoningEffort first
+ if agent_name:
+ agent_config = config.get("agent", {}).get(agent_name, {})
+ reasoning_effort = agent_config.get("reasoningEffort")
+ if reasoning_effort:
+ logger.debug(
+ f"Found reasoningEffort '{reasoning_effort}' for agent '{agent_name}' in opencode.json"
+ )
+ return reasoning_effort
+
+ # Fall back to global default reasoningEffort
+ reasoning_effort = config.get("reasoningEffort")
+ if reasoning_effort:
+ logger.debug(
+ f"Using global default reasoningEffort '{reasoning_effort}' from opencode.json"
+ )
+ return reasoning_effort
+ except Exception as e:
+ logger.warning(f"Failed to read reasoningEffort from opencode.json: {e}")
+ return None
+
+ def get_default_agent_from_config(self) -> Optional[str]:
+ """Read the default agent from user's opencode.json config file.
+
+ OpenCode server doesn't automatically use its configured default agent
+ when called via API, so we need to read and pass it explicitly.
+
+ Returns:
+ Default agent name (e.g., "build", "plan"), or None if not configured.
+ """
+ import json
+ from pathlib import Path
+
+ config_path = Path.home() / ".config" / "opencode" / "opencode.json"
+ if not config_path.exists():
+ return None
+
+ try:
+ with open(config_path, "r") as f:
+ config = json.load(f)
+
+ # OpenCode uses "agent" key with a default agent, or we look for
+ # a commonly used pattern. The default agent is typically not
+ # explicitly marked, but we can check if there's a single agent
+ # or use "build" as the conventional default.
+ # For now, return None to let OpenCode decide.
+ # Users can override via channel settings or agent_routes.yaml.
+ return None
+ except Exception as e:
+ logger.warning(f"Failed to read default agent from opencode.json: {e}")
+ return None
+
class OpenCodeAgent(BaseAgent):
"""OpenCode Server API integration via HTTP."""
@@ -386,18 +565,44 @@ class OpenCodeAgent(BaseAgent):
)
try:
+ # Get per-channel overrides from user_settings.json
+ override_agent, override_model, override_reasoning = (
+ self.controller.get_opencode_overrides(request.context)
+ )
+
+ # Determine agent to use
+ # Priority: 1) channel override, 2) opencode.json default, 3) None (let OpenCode decide)
+ agent_to_use = override_agent
+ if not agent_to_use:
+ agent_to_use = server.get_default_agent_from_config()
+ # If still None, we don't pass agent parameter, letting OpenCode use its default
+
+ # Determine model to use
+ # Priority: 1) channel override, 2) agent's config model, 3) global opencode.json model
model_dict = None
- if self.opencode_config.default_model:
- parts = self.opencode_config.default_model.split("/", 1)
+ model_str = override_model
+ if not model_str:
+ # OpenCode server doesn't use agent's configured model when called via API,
+ # so we read it from opencode.json explicitly
+ model_str = server.get_agent_model_from_config(agent_to_use)
+ if model_str:
+ parts = model_str.split("/", 1)
if len(parts) == 2:
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
+ reasoning_effort = override_reasoning
+ if not reasoning_effort:
+ reasoning_effort = server.get_agent_reasoning_effort_from_config(agent_to_use)
+
response = await server.send_message(
session_id=session_id,
directory=request.working_path,
text=request.message,
- agent=self.opencode_config.default_agent,
+ agent=agent_to_use,
model=model_dict,
+ reasoning_effort=reasoning_effort,
)
result_text = self._extract_response_text(response)
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 23487396e..d73536aff 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -351,12 +351,6 @@ class SlackBot(BaseIMClient):
channel_id = event.get("channel")
- # Check if channel is authorized based on whitelist configuration
- if not await self._is_authorized_channel(channel_id):
- logger.info(f"Unauthorized message from channel: {channel_id}")
- await self._send_unauthorized_message(channel_id)
- return
-
# Check if this message contains a bot mention
# If it does, skip processing as it will be handled by app_mention event
text = (event.get("text") or "").strip()
@@ -375,20 +369,14 @@ class SlackBot(BaseIMClient):
logger.debug("Ignoring Slack message with empty text")
return
- # Check if channel is authorized based on whitelist
- if not await self._is_authorized_channel(channel_id):
- logger.info(f"Unauthorized message from channel: {channel_id}")
- await self._send_unauthorized_message(channel_id)
- return
-
# Check if we require mention in channels (not DMs)
# For threads: only respond if the bot is active in that thread
is_thread_reply = event.get("thread_ts") is not None
if self.config.require_mention and not channel_id.startswith("D"):
- # In channel main thread: require mention
+ # In channel main thread: require mention (silently ignore)
if not is_thread_reply:
- logger.info(f"Ignoring non-mention message in channel: '{text}'")
+ logger.debug(f"Ignoring non-mention message in channel: '{text}'")
return
# In thread: check if bot is active in this thread
@@ -397,13 +385,19 @@ class SlackBot(BaseIMClient):
# If we have settings_manager, check if thread is active
if self.settings_manager:
if not self.settings_manager.is_thread_active(user_id, channel_id, thread_ts):
- logger.info(f"Ignoring message in inactive thread {thread_ts}: '{text}'")
+ logger.debug(f"Ignoring message in inactive thread {thread_ts}: '{text}'")
return
else:
# Without settings_manager, fall back to ignoring non-mention in threads
- logger.info(f"No settings_manager, ignoring thread message: '{text}'")
+ logger.debug(f"No settings_manager, ignoring thread message: '{text}'")
return
+ # Only check channel authorization for messages we're actually going to process
+ if not await self._is_authorized_channel(channel_id):
+ logger.info(f"Unauthorized message from channel: {channel_id}")
+ await self._send_unauthorized_message(channel_id)
+ return
+
# Extract context
# For Slack: if no thread_ts, use the message's own ts as thread_id (start of thread)
thread_id = event.get("thread_ts") or event.get("ts")
@@ -647,6 +641,46 @@ class SlackBot(BaseIMClient):
# We need to find the right channel to send the message
# For now, we'll rely on the controller to handle this
+ elif callback_id == "routing_modal":
+ # Handle routing modal submission
+ user_id = payload.get("user", {}).get("id")
+ values = view.get("state", {}).get("values", {})
+ channel_id = view.get("private_metadata")
+
+ # Extract backend
+ backend_data = values.get("backend_block", {}).get("backend_select", {})
+ backend = backend_data.get("selected_option", {}).get("value")
+
+ # Extract OpenCode agent (optional)
+ oc_agent_data = values.get("opencode_agent_block", {}).get(
+ "opencode_agent_select", {}
+ )
+ oc_agent = oc_agent_data.get("selected_option", {}).get("value")
+ if oc_agent == "__default__":
+ oc_agent = None
+
+ # Extract OpenCode model (optional)
+ oc_model_data = values.get("opencode_model_block", {}).get(
+ "opencode_model_select", {}
+ )
+ oc_model = oc_model_data.get("selected_option", {}).get("value")
+ if oc_model == "__default__":
+ oc_model = None
+
+ # Extract OpenCode reasoning effort (optional)
+ oc_reasoning_data = values.get("opencode_reasoning_block", {}).get(
+ "opencode_reasoning_select", {}
+ )
+ oc_reasoning = oc_reasoning_data.get("selected_option", {}).get("value")
+ if oc_reasoning == "__default__":
+ oc_reasoning = None
+
+ # Update routing via callback
+ if hasattr(self, "_on_routing_update"):
+ await self._on_routing_update(
+ user_id, channel_id, backend, oc_agent, oc_model, oc_reasoning
+ )
+
def run(self):
"""Run the Slack bot"""
if self.config.app_token:
@@ -914,6 +948,314 @@ class SlackBot(BaseIMClient):
logger.error(f"Error opening change CWD modal: {e}")
raise
+ async def open_routing_modal(
+ self,
+ trigger_id: str,
+ channel_id: str,
+ registered_backends: list,
+ current_backend: str,
+ current_routing, # Optional[ChannelRouting]
+ opencode_agents: list,
+ opencode_models: dict,
+ opencode_default_config: dict,
+ ):
+ """Open a modal dialog for agent/model routing settings"""
+ self._ensure_clients()
+
+ # Build backend options
+ backend_display_names = {
+ "claude": "Claude Code",
+ "codex": "Codex",
+ "opencode": "OpenCode",
+ }
+ backend_options = []
+ for backend in registered_backends:
+ display_name = backend_display_names.get(backend, backend.capitalize())
+ backend_options.append({
+ "text": {"type": "plain_text", "text": display_name},
+ "value": backend,
+ })
+
+ # Find initial backend option
+ initial_backend = None
+ for opt in backend_options:
+ if opt["value"] == current_backend:
+ initial_backend = opt
+ break
+
+ # Backend select element
+ backend_select = {
+ "type": "static_select",
+ "action_id": "backend_select",
+ "placeholder": {"type": "plain_text", "text": "Select backend"},
+ "options": backend_options,
+ }
+ if initial_backend:
+ backend_select["initial_option"] = initial_backend
+
+ # Build blocks
+ blocks = [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"*Current Backend:* {backend_display_names.get(current_backend, current_backend)}",
+ },
+ },
+ {"type": "divider"},
+ {
+ "type": "input",
+ "block_id": "backend_block",
+ "element": backend_select,
+ "label": {"type": "plain_text", "text": "Backend"},
+ },
+ ]
+
+ # OpenCode-specific options (only if opencode is registered)
+ if "opencode" in registered_backends:
+ # Get current opencode settings
+ current_oc_agent = (
+ current_routing.opencode_agent if current_routing else None
+ )
+ current_oc_model = (
+ current_routing.opencode_model if current_routing else None
+ )
+ current_oc_reasoning = (
+ current_routing.opencode_reasoning_effort if current_routing else None
+ )
+
+ # Determine default agent/model from OpenCode config
+ default_model_str = opencode_default_config.get("model") # e.g., "anthropic/claude-opus-4-5"
+
+ # Build agent options
+ agent_options = [
+ {"text": {"type": "plain_text", "text": "(Default)"}, "value": "__default__"}
+ ]
+ for agent in opencode_agents:
+ agent_name = agent.get("name", "")
+ if agent_name:
+ agent_options.append({
+ "text": {"type": "plain_text", "text": agent_name},
+ "value": agent_name,
+ })
+
+ # Find initial agent
+ initial_agent = agent_options[0] # Default
+ if current_oc_agent:
+ for opt in agent_options:
+ if opt["value"] == current_oc_agent:
+ initial_agent = opt
+ break
+
+ agent_select = {
+ "type": "static_select",
+ "action_id": "opencode_agent_select",
+ "placeholder": {"type": "plain_text", "text": "Select OpenCode agent"},
+ "options": agent_options,
+ "initial_option": initial_agent,
+ }
+
+ # Build model options
+ model_options = [
+ {"text": {"type": "plain_text", "text": f"(Default){' - ' + default_model_str if default_model_str else ''}"}, "value": "__default__"}
+ ]
+
+ # Add models from providers
+ providers_data = opencode_models.get("providers", [])
+ defaults = opencode_models.get("default", {})
+
+ # Calculate max models per provider to fit within Slack's 100 option limit
+ # Reserve 1 for "(Default)" option
+ num_providers = len(providers_data)
+ max_per_provider = max(5, (99 // num_providers)) if num_providers > 0 else 99
+
+ for provider in providers_data:
+ provider_id = provider.get("id", "")
+ provider_name = provider.get("name", provider_id)
+ models = provider.get("models", {})
+
+ # Handle both dict and list formats for models
+ if isinstance(models, dict):
+ model_items = list(models.items())
+ elif isinstance(models, list):
+ model_items = [(m, m) if isinstance(m, str) else (m.get("id", ""), m) for m in models]
+ else:
+ model_items = []
+
+ # Limit models per provider
+ provider_model_count = 0
+ for model_id, model_info in model_items:
+ if provider_model_count >= max_per_provider:
+ break
+
+ # Get model name
+ if isinstance(model_info, dict):
+ model_name = model_info.get("name", model_id)
+ else:
+ model_name = model_id
+
+ if model_id:
+ full_model = f"{provider_id}/{model_id}"
+ # Mark if this is the provider's default
+ is_default = defaults.get(provider_id) == model_id
+ display = f"{provider_name}: {model_name}"
+ if is_default:
+ display += " (default)"
+
+ model_options.append({
+ "text": {"type": "plain_text", "text": display[:75]}, # Slack limit
+ "value": full_model,
+ })
+ provider_model_count += 1
+
+ # Final safety check for Slack's 100 option limit
+ if len(model_options) > 100:
+ model_options = model_options[:100]
+ logger.warning("Truncated model options to 100 for Slack modal")
+
+ # Find initial model
+ initial_model = model_options[0] # Default
+ if current_oc_model:
+ for opt in model_options:
+ if opt["value"] == current_oc_model:
+ initial_model = opt
+ break
+
+ model_select = {
+ "type": "static_select",
+ "action_id": "opencode_model_select",
+ "placeholder": {"type": "plain_text", "text": "Select model"},
+ "options": model_options,
+ "initial_option": initial_model,
+ }
+
+ # Build reasoning effort options dynamically based on model variants
+ # Determine target model for variants lookup
+ target_model = current_oc_model or default_model_str
+ model_variants = {}
+
+ if target_model:
+ # Parse provider/model format
+ parts = target_model.split("/", 1)
+ if len(parts) == 2:
+ target_provider, target_model_id = parts
+ # Search for this model in providers data
+ for provider in providers_data:
+ if provider.get("id") == target_provider:
+ models = provider.get("models", {})
+ if isinstance(models, dict):
+ model_info = models.get(target_model_id, {})
+ if isinstance(model_info, dict):
+ model_variants = model_info.get("variants", {})
+ break
+
+ # Build options from variants or use fallback
+ reasoning_effort_options = [
+ {"text": {"type": "plain_text", "text": "(Default)"}, "value": "__default__"}
+ ]
+
+ if model_variants:
+ # Use model-specific variants
+ variant_display_names = {
+ "none": "None",
+ "minimal": "Minimal",
+ "low": "Low",
+ "medium": "Medium",
+ "high": "High",
+ "xhigh": "Extra High",
+ "max": "Max",
+ }
+ for variant_key in model_variants.keys():
+ display_name = variant_display_names.get(variant_key, variant_key.capitalize())
+ reasoning_effort_options.append({
+ "text": {"type": "plain_text", "text": display_name},
+ "value": variant_key,
+ })
+ else:
+ # Fallback to common options
+ reasoning_effort_options.extend([
+ {"text": {"type": "plain_text", "text": "Low"}, "value": "low"},
+ {"text": {"type": "plain_text", "text": "Medium"}, "value": "medium"},
+ {"text": {"type": "plain_text", "text": "High"}, "value": "high"},
+ ])
+
+ # Find initial reasoning effort
+ initial_reasoning = reasoning_effort_options[0] # Default
+ if current_oc_reasoning:
+ for opt in reasoning_effort_options:
+ if opt["value"] == current_oc_reasoning:
+ initial_reasoning = opt
+ break
+
+ reasoning_select = {
+ "type": "static_select",
+ "action_id": "opencode_reasoning_select",
+ "placeholder": {"type": "plain_text", "text": "Select reasoning effort"},
+ "options": reasoning_effort_options,
+ "initial_option": initial_reasoning,
+ }
+
+ # Add OpenCode section
+ blocks.extend([
+ {"type": "divider"},
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": "*OpenCode Options* (only applies when backend is OpenCode)",
+ },
+ },
+ {
+ "type": "input",
+ "block_id": "opencode_agent_block",
+ "optional": True,
+ "element": agent_select,
+ "label": {"type": "plain_text", "text": "OpenCode Agent"},
+ },
+ {
+ "type": "input",
+ "block_id": "opencode_model_block",
+ "optional": True,
+ "element": model_select,
+ "label": {"type": "plain_text", "text": "Model"},
+ },
+ {
+ "type": "input",
+ "block_id": "opencode_reasoning_block",
+ "optional": True,
+ "element": reasoning_select,
+ "label": {"type": "plain_text", "text": "Reasoning Effort (Thinking Mode)"},
+ },
+ ])
+
+ # Add tip
+ blocks.append({
+ "type": "context",
+ "elements": [
+ {
+ "type": "mrkdwn",
+ "text": "_💡 Select (Default) to use OpenCode's configured defaults._",
+ }
+ ],
+ })
+
+ # Create modal view
+ view = {
+ "type": "modal",
+ "callback_id": "routing_modal",
+ "private_metadata": channel_id,
+ "title": {"type": "plain_text", "text": "Agent Settings"},
+ "submit": {"type": "plain_text", "text": "Save"},
+ "close": {"type": "plain_text", "text": "Cancel"},
+ "blocks": blocks,
+ }
+
+ try:
+ await self.web_client.views_open(trigger_id=trigger_id, view=view)
+ except SlackApiError as e:
+ logger.error(f"Error opening routing modal: {e}")
+ raise
+
def register_callbacks(
self,
on_message: Optional[Callable] = None,
@@ -942,6 +1284,10 @@ class SlackBot(BaseIMClient):
if "on_change_cwd" in kwargs:
self._on_change_cwd = kwargs["on_change_cwd"]
+ # Register routing update handler
+ if "on_routing_update" in kwargs:
+ self._on_routing_update = kwargs["on_routing_update"]
+
async def get_or_create_thread(
self, channel_id: str, user_id: str
) -> Optional[str]:
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index d83272d08..b35c5ea22 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -13,6 +13,32 @@ logger = logging.getLogger(__name__)
DEFAULT_HIDDEN_MESSAGE_TYPES = ["system", "assistant", "user"]
+@dataclass
+class ChannelRouting:
+ """Per-channel agent routing configuration."""
+
+ agent_backend: Optional[str] = None # "claude" | "codex" | "opencode" | None
+ opencode_agent: Optional[str] = None # "build" | "plan" | ... | None
+ opencode_model: Optional[str] = None # "provider/model" | None
+ opencode_reasoning_effort: Optional[str] = None # "low" | "medium" | "high" | "xhigh" | None
+
+ def to_dict(self) -> dict:
+ """Convert to dictionary for JSON serialization"""
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict) -> "ChannelRouting":
+ """Create from dictionary"""
+ if data is None:
+ return None
+ return cls(
+ agent_backend=data.get("agent_backend"),
+ opencode_agent=data.get("opencode_agent"),
+ opencode_model=data.get("opencode_model"),
+ opencode_reasoning_effort=data.get("opencode_reasoning_effort"),
+ )
+
+
@dataclass
class UserSettings:
hidden_message_types: List[str] = field(
@@ -23,15 +49,25 @@ class UserSettings:
default_factory=dict
)
active_slack_threads: Dict[str, Dict[str, float]] = field(default_factory=dict)
+ channel_routing: Optional[ChannelRouting] = None
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization"""
- return asdict(self)
+ result = asdict(self)
+ # Handle ChannelRouting serialization
+ if self.channel_routing is not None:
+ result["channel_routing"] = self.channel_routing.to_dict()
+ return result
@classmethod
def from_dict(cls, data: dict) -> "UserSettings":
"""Create from dictionary"""
- return cls(**data)
+ # Handle channel_routing deserialization
+ routing_data = data.pop("channel_routing", None)
+ settings = cls(**data)
+ if routing_data:
+ settings.channel_routing = ChannelRouting.from_dict(routing_data)
+ return settings
class SettingsManager:
@@ -408,3 +444,35 @@ class SettingsManager:
channels_to_clean = list(settings.active_slack_threads.keys())
for channel_id in channels_to_clean:
self._cleanup_expired_threads_for_channel(user_id, channel_id)
+
+ # ---------------------------------------------
+ # Channel routing management
+ # ---------------------------------------------
+ def get_channel_routing(
+ self, settings_key: Union[int, str]
+ ) -> Optional[ChannelRouting]:
+ """Get channel routing override for the given settings key."""
+ settings = self.get_user_settings(settings_key)
+ return settings.channel_routing
+
+ def set_channel_routing(
+ self, settings_key: Union[int, str], routing: ChannelRouting
+ ):
+ """Set channel routing override."""
+ settings = self.get_user_settings(settings_key)
+ settings.channel_routing = routing
+ self.update_user_settings(settings_key, settings)
+ logger.info(
+ f"Updated channel routing for {settings_key}: "
+ f"backend={routing.agent_backend}, "
+ f"opencode_agent={routing.opencode_agent}, "
+ f"opencode_model={routing.opencode_model}"
+ )
+
+ def clear_channel_routing(self, settings_key: Union[int, str]):
+ """Clear channel routing override (fall back to agent_routes.yaml)."""
+ settings = self.get_user_settings(settings_key)
+ if settings.channel_routing:
+ settings.channel_routing = None
+ self.update_user_settings(settings_key, settings)
+ logger.info(f"Cleared channel routing for {settings_key}")