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(im): route a channel to an Agent, as the Web picker does (#2949)

Call White3fc38dddf614
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index a632a3b93..38808a14c 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -18,6 +18,7 @@ from config.v2_settings import normalize_routing_settings
from core.modals import (
DEFAULT_OPTION_VALUE,
STORED_OPTION_VALUE,
+ AgentChoice,
BackendRouteMenu,
RouteOption,
RoutingModalData,
@@ -480,56 +481,67 @@ class SettingsHandler(BaseHandler):
async def _gather_routing_modal_data(
self,
context: MessageContext,
- selected_backend: Optional[str] = None,
+ selected_agent: Optional[str] = None,
include_all_backend_data: bool = False,
) -> RoutingModalData:
- """Collect each shown backend's route menu for the routing form renderers."""
+ """Collect the Agents a route can name and the menus of their backends for the routing form renderers."""
settings_key = self._get_settings_key(context)
current_routing = self._get_settings_manager(context).get_channel_routing(settings_key)
- all_backends = list(self.controller.agent_service.agents.keys())
- current_backend = self.controller.resolve_agent_for_context(context)
- enabled_backends = [backend for backend in all_backends if self._is_backend_enabled(backend)]
- if not enabled_backends and current_backend:
- enabled_backends = [current_backend]
- # Catalog order, the built-in backend first. As for the default Agent, the fallback
- # selection is the built-in backend only when no other backend is enabled.
+ # The Agents the Web route picker lists, on a backend this runtime can run.
+ runnable = {backend for backend in self.controller.agent_service.agents if self._is_backend_enabled(backend)}
+ store = self.controller.vibe_agent_store
+ listed = await asyncio.to_thread(store.list_agents, include_disabled=False)
catalog_order = {backend: index for index, backend in enumerate(AGENT_BACKENDS)}
- registered_backends = sorted(enabled_backends, key=lambda x: catalog_order.get(x, len(catalog_order)))
- active_backend = min(registered_backends, key=implicit_default_rank, default=current_backend)
- if current_backend in registered_backends:
- active_backend = current_backend
- if selected_backend in registered_backends:
- active_backend = selected_backend
- visible_current_backend = current_backend if current_backend in registered_backends else active_backend
- backends_to_load = registered_backends if include_all_backend_data else [active_backend]
-
+ agents = [
+ AgentChoice(agent.id, agent.name, agent.backend, agent.model, agent.reasoning_effort)
+ for agent in listed
+ if agent.backend in runnable
+ ]
+ current = self.controller.resolve_vibe_agent_for_context(context, required=False)
+ im_client = self._get_im_client(context)
data = RoutingModalData(
- registered_backends=registered_backends,
- current_backend=visible_current_backend,
+ agents=agents,
+ current_agent=current.id if current is not None else "",
current_routing=current_routing,
+ agent_option_limit=getattr(im_client, "route_option_limit", None),
)
- im_client = self._get_im_client(context)
- for backend in backends_to_load:
+ if data.agent(data.current_agent) is None and agents:
+ # The scope's Agent cannot run here. As for a default Agent, the built-in backend's is the
+ # replacement only when no other Agent is listed.
+ data.current_agent = min(agents, key=lambda agent: implicit_default_rank(agent.backend)).id
+ current_agent = data.agent(data.current_agent)
+ shown = data.agent(data.shown_agent(selected_agent))
+ # A form refreshed per change loads only the shown Agent's backend; the others load every listed one.
+ backends = {agent.backend for agent in agents} if include_all_backend_data else {shown.backend} if shown else set()
+ for backend in sorted(backends, key=lambda name: catalog_order.get(name, len(catalog_order))):
menu = BackendRouteMenu(
backend,
option_limit=getattr(im_client, "route_option_limit", None),
value_limit=getattr(im_client, "route_option_value_limit", None),
- stored=data.stored_draft(backend),
)
+ # The stored route's model leads the provider order of the backend it runs on.
+ stored_model = (
+ data.stored_draft(current_agent.id).model if current_agent and current_agent.backend == backend else None
+ )
+ # Efforts are built for every model a form on this backend can show or inherit, listed or not.
+ wanted = {model for model in (stored_model, *(a.model for a in agents if a.backend == backend)) if model}
loader = self._route_menu_loaders.get(backend)
if loader is not None:
try:
- await loader(self, context, menu, menu.stored.model)
+ await loader(self, context, menu, stored_model, wanted)
except Exception as e:
logger.warning("Failed to load %s routing options: %s", backend, e)
data.menus[backend] = menu
return data
# Where each backend's route lists come from: the only backend-specific part of the routing form. Each
- # loader fills ``menu`` in place; ``stored_model`` is the stored route's model when this is its backend.
+ # loader fills ``menu`` in place; ``stored_model`` is the stored route's model when this is its backend, and
+ # ``wanted`` every model a form on this backend can show or inherit, whose efforts it needs.
- async def _load_opencode_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:
+ async def _load_opencode_route_menu(
+ self, context, menu: BackendRouteMenu, stored_model: Optional[str], wanted: set[str]
+ ) -> None:
from modules.agents.opencode.utils import (
build_opencode_model_option_items,
build_reasoning_effort_options,
@@ -563,10 +575,12 @@ class SettingsHandler(BaseHandler):
keep=menu.fits,
)
menu.models = [RouteOption(str(entry["value"]), str(entry["label"])) for entry in entries if entry.get("value")]
- for model in {"", *(option.value for option in menu.models), stored_model or ""}:
+ for model in {"", *(option.value for option in menu.models), *wanted}:
menu.efforts[model] = _effort_options(build_reasoning_effort_options(models, model or None))
- async def _load_claude_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:
+ async def _load_claude_route_menu(
+ self, context, menu: BackendRouteMenu, stored_model: Optional[str], wanted: set[str]
+ ) -> None:
from modules.agents.opencode.utils import (
build_claude_reasoning_options,
format_claude_model_label,
@@ -588,12 +602,14 @@ class SettingsHandler(BaseHandler):
menu.models = [RouteOption(model, format_claude_model_label(model)) for model in ordered]
catalog = models_result.get("reasoning_options")
catalog = catalog if isinstance(catalog, dict) else None
- for model in {"", *ordered, stored_model or ""}:
+ for model in {"", *ordered, *wanted}:
menu.efforts[model] = _effort_options(
resolve_model_reasoning_options(catalog, model, build_claude_reasoning_options(model or None))
)
- async def _load_codex_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:
+ async def _load_codex_route_menu(
+ self, context, menu: BackendRouteMenu, stored_model: Optional[str], wanted: set[str]
+ ) -> None:
from modules.agents.opencode.utils import build_codex_reasoning_options, resolve_model_reasoning_options
from vibe.api import codex_agents as get_codex_agents, codex_models as get_codex_models
@@ -607,16 +623,17 @@ class SettingsHandler(BaseHandler):
menu.models = [RouteOption(model, model) for model in models]
catalog = models_result.get("reasoning_options")
catalog = catalog if isinstance(catalog, dict) else None
- for model in {"", *models, stored_model or ""}:
+ for model in {"", *models, *wanted}:
menu.efforts[model] = _effort_options(
resolve_model_reasoning_options(catalog, model, build_codex_reasoning_options())
)
- async def _load_vibey_route_menu(self, context, menu: BackendRouteMenu, stored_model: Optional[str]) -> None:
+ async def _load_vibey_route_menu(
+ self, context, menu: BackendRouteMenu, stored_model: Optional[str], wanted: set[str]
+ ) -> None:
"""Vibey's menu from Model Hub, as the Web route picker reads it.
- An effort Model Hub's ``effort_menu`` omits would only fail, so it is not offered. A route without its
- own model inherits the built-in Vibey Agent's, so ``""`` holds that model's efforts.
+ An effort Model Hub's ``effort_menu`` omits would only fail, so it is not offered.
"""
model_hub_service = getattr(self.controller, "model_hub_service", None)
if model_hub_service is None:
@@ -637,15 +654,6 @@ class SettingsHandler(BaseHandler):
if effort not in omitted
]
)
- store = getattr(self.controller, "vibe_agent_store", None)
- agent = (
- await asyncio.to_thread(store.get_builtin_default_agent_for_backend, "vibey", enabled_only=False)
- if store
- else None
- )
- inherited = menu.efforts.get(str(getattr(agent, "model", None) or "").strip())
- if inherited is not None:
- menu.efforts[""] = inherited
_route_menu_loaders = {
"opencode": _load_opencode_route_menu,
@@ -662,11 +670,6 @@ class SettingsHandler(BaseHandler):
return False
return bool(getattr(backend_config, "enabled", True))
- def _routing_agent_name(self, backend: str) -> str:
- """A backend choice routes to that backend's built-in Agent, under whatever name the row holds."""
- store = getattr(self.controller, "vibe_agent_store", None)
- return store.routing_name_for_backend(backend) if store is not None else backend
-
def _resolve_route_backend(self, agent_name: Optional[str]) -> Optional[str]:
if not agent_name:
return None
@@ -719,9 +722,13 @@ class SettingsHandler(BaseHandler):
return False
current_target = self._routing_target_from_row(row)
next_target = self._routing_target_from_settings(routing)
- current_backend = current_target[1]
- next_backend = next_target[1]
- return bool(current_backend and next_backend and current_backend != next_backend)
+ current_agent, current_backend = current_target[0], current_target[1]
+ next_agent, next_backend = next_target[0], next_target[1]
+ if current_backend and next_backend and current_backend != next_backend:
+ return True
+ # The scope's session keeps the Agent it started with, so another Agent, even on the same backend, takes
+ # a new session to run.
+ return bool(current_agent and next_agent and current_agent != next_agent)
async def handle_settings_update(
self,
@@ -825,14 +832,8 @@ class SettingsHandler(BaseHandler):
)
im_client = self._get_im_client(context)
- resolved_backend = self.controller.resolve_agent_for_context(context)
- selected_backend = selection.selected_backend or resolved_backend
- routing_data = await self._gather_routing_modal_data(context, selected_backend=selected_backend)
- visible_selected_backend = (
- selected_backend
- if selected_backend in routing_data.registered_backends
- else routing_data.current_backend
- )
+ routing_data = await self._gather_routing_modal_data(context, selected_agent=selection.selected_agent)
+ shown_agent = routing_data.shown_agent(selection.selected_agent)
if hasattr(im_client, "update_routing_modal"):
await im_client.update_routing_modal( # type: ignore[attr-defined]
@@ -840,9 +841,9 @@ class SettingsHandler(BaseHandler):
view_hash=view_hash,
channel_id=resolved_channel_id,
routing=routing_data,
- selected_backend=visible_selected_backend,
- # A backend switch shows a section the form had no controls for: the stored route, not blanks.
- draft=selection.draft if visible_selected_backend == selected_backend else None,
+ selected_agent=shown_agent,
+ # An Agent switch shows a section the form had no controls for: the stored route, not blanks.
+ draft=selection.draft if shown_agent == selection.selected_agent else None,
)
except Exception as e:
logger.error(f"Error updating routing modal: {e}", exc_info=True)
@@ -851,7 +852,7 @@ class SettingsHandler(BaseHandler):
self,
user_id: str,
channel_id: str,
- backend: str,
+ agent_id: str,
*,
variant: object = _UNSET,
model: Optional[str] = None,
@@ -861,10 +862,10 @@ class SettingsHandler(BaseHandler):
is_dm: bool = False,
platform: Optional[str] = None,
):
- """Save a routing form's choices for one backend.
+ """Save a routing form's choices: the Agent the scope runs, and its overrides.
- ``variant`` is the backend's native agent; omitted, the stored one stays. Other backends' native agents
- always stay, so switching back finds them.
+ ``variant`` is the Agent's backend's native agent; omitted, the stored one stays. Other backends' native
+ agents always stay, so switching back finds them.
"""
from config.v2_settings import RoutingSettings
from modules.agents.opencode.utils import normalize_claude_reasoning_effort
@@ -880,12 +881,14 @@ class SettingsHandler(BaseHandler):
settings_key = self._get_settings_key(context)
im_client = self._get_im_client(context)
settings_manager = self._get_settings_manager(context)
+ agent = self.controller.vibe_agent_store.require_reference_by_id(agent_id)
+ backend = agent.backend
existing_routing = settings_manager.get_channel_routing(settings_key)
# A platform shows a stored choice it cannot carry as its own option value through a stand-in option;
- # saving that option keeps the stored choice. It stands for this backend's route only: one changed to
- # another backend since the form rendered has no such choice, so the stand-in saves as Default.
+ # saving that option keeps the stored choice. It stands for this Agent's route only: one changed to
+ # another Agent since the form rendered has no such choice, so the stand-in saves as Default.
stored = normalize_routing_settings(existing_routing)
- if self._resolve_route_backend(stored.agent_name) != backend:
+ if stored.agent_name != agent.name:
stored = normalize_routing_settings(None)
if model == STORED_OPTION_VALUE:
model = stored.model
@@ -901,14 +904,15 @@ class SettingsHandler(BaseHandler):
variants[backend] = variant
if backend == "claude":
# Claude Code rejects an effort its model does not support.
+ effective_model = model or agent.model
reasoning_effort = normalize_claude_reasoning_effort(
- model,
+ effective_model,
reasoning_effort,
- backend_model_catalog.catalog_reasoning_efforts_for_model("claude", model),
+ backend_model_catalog.catalog_reasoning_efforts_for_model("claude", effective_model),
)
routing = RoutingSettings(
- agent_name=self._routing_agent_name(backend),
+ agent_name=agent.name,
model=model,
reasoning_effort=reasoning_effort,
**{f"{native}_agent": value for native, value in variants.items()},
@@ -917,16 +921,18 @@ class SettingsHandler(BaseHandler):
settings_manager.set_channel_routing(settings_key, routing)
needs_new_session_hint = self._routing_update_needs_new_session_hint(context, routing)
- parts = [f"{self._t('routing.label.backend')}: **{display_name_for_backend(backend)}**"]
- for label_key, value in (
- ("routing.label.agent", variants.get(backend)),
- ("routing.label.model", model),
- ("routing.label.reasoningEffort", reasoning_effort),
+ backend_name = display_name_for_backend(backend)
+ parts = []
+ for label, value in (
+ (self._t("routing.label.agent"), f"{agent.name} · {backend_name}"),
+ (self._t("modal.routing.backendAgent", backend=backend_name), variants.get(backend)),
+ (self._t("routing.label.model"), model),
+ (self._t("routing.label.reasoningEffort"), reasoning_effort),
):
if value:
# Route values are opaque and unbounded; a confirmation must fit any platform's message.
shown = value if len(value) <= 100 else f"{value[:99]}…"
- parts.append(f"{self._t(label_key)}: **{shown}**")
+ parts.append(f"{label}: **{shown}**")
if needs_new_session_hint:
parts.extend(["", self._t("success.routingUpdateNeedsNewSession")])
@@ -938,7 +944,7 @@ class SettingsHandler(BaseHandler):
)
logger.info(
- f"Routing updated for {settings_key}: backend={backend}, variant={variants.get(backend)}, "
+ f"Routing updated for {settings_key}: agent={agent.name}, variant={variants.get(backend)}, "
f"model={model}, reasoning_effort={reasoning_effort}"
)
diff --git a/core/modals.py b/core/modals.py
index 47530b3c7..2981d5735 100644
--- a/core/modals.py
+++ b/core/modals.py
@@ -1,10 +1,10 @@
"""Platform-neutral modal data models.
-A channel route is the same four choices for every backend: the backend, its native agent (``variant``; only
-native CLI backends have one), the model, and the reasoning effort. Backends differ only in where those lists
-come from, which the settings handler resolves into one :class:`BackendRouteMenu` per backend. Each IM platform
-then renders a single generic section from the menu and a :class:`RouteDraft`, so a new backend needs no
-platform code.
+A channel route names an Agent, as the Web route picker does, and may override its model and reasoning effort;
+on a native CLI backend it may also pick that backend's own agent (``variant``). Backends differ only in where
+the model and effort lists come from, which the settings handler resolves into one :class:`BackendRouteMenu`
+per backend. Each IM platform renders an Agent select and one generic section from the chosen Agent's menu and a
+:class:`RouteDraft`, so a new backend or Agent needs no platform code.
"""
from __future__ import annotations
@@ -13,7 +13,7 @@ from dataclasses import dataclass, field, replace
from typing import Callable, Optional
from config.v2_settings import normalize_routing_settings
-from modules.agents.catalog import NATIVE_CLI_BACKENDS
+from modules.agents.catalog import NATIVE_CLI_BACKENDS, display_name_for_backend
from modules.settings_manager import ChannelRouting
# The value of every select's Default option: no choice of its own, so the route inherits its Agent's.
@@ -29,9 +29,26 @@ class RouteOption:
label: str
+@dataclass(frozen=True)
+class AgentChoice:
+ """An Agent a channel route can name, as the routing form lists it."""
+
+ id: str
+ name: str
+ backend: str
+ model: Optional[str] = None
+ reasoning_effort: Optional[str] = None
+
+ @property
+ def label(self) -> str:
+ # Agent names have no length bound, and every platform caps the text it shows.
+ name = self.name if len(self.name) <= 80 else f"{self.name[:79]}…"
+ return f"{name} · {display_name_for_backend(self.backend)}"
+
+
@dataclass(frozen=True)
class RouteDraft:
- """What a routing form shows for one backend; ``None`` is the Default option."""
+ """What a routing form shows for one Agent; ``None`` is the Default option."""
variant: Optional[str] = None
model: Optional[str] = None
@@ -63,6 +80,8 @@ class BackendRouteMenu:
option_limit: Optional[int] = None
value_limit: Optional[int] = None
stored: RouteDraft = field(default_factory=RouteDraft)
+ # The Agent's own model and effort: what a Default option inherits.
+ inherited: RouteDraft = field(default_factory=RouteDraft)
def variant_options(self, current: Optional[str]) -> list[RouteOption]:
return self._bounded(self.variants, current, self.stored.variant)
@@ -72,11 +91,20 @@ class BackendRouteMenu:
def effort_options(self, model: Optional[str], current: Optional[str]) -> list[RouteOption]:
model = self.stored.model if model == STORED_OPTION_VALUE else model
- listed = self.efforts.get(model or "")
+ # A route without its own model runs the Agent's.
+ listed = self.efforts.get(model or self.inherited.model or "")
return self._bounded(
self.efforts.get("", []) if listed is None else listed, current, self.stored.reasoning_effort
)
+ def default_option(self, field: str) -> RouteOption:
+ """A select's Default option, named after what it inherits from the Agent where that is known."""
+ inherited = getattr(self.inherited, field, None) if field in ("model", "reasoning_effort") else None
+ if not inherited:
+ return RouteOption(DEFAULT_OPTION_VALUE, "")
+ label = next((option.label for option in self.models if option.value == inherited), inherited)
+ return RouteOption(DEFAULT_OPTION_VALUE, label if field == "model" else inherited)
+
def fits(self, value: object) -> bool:
"""Whether a select on this platform can carry ``value`` as an option of its own."""
return (
@@ -117,24 +145,61 @@ class BackendRouteMenu:
@dataclass
class RoutingModalData:
- """Shared routing modal payload consumed by platform renderers."""
+ """Shared routing modal payload consumed by platform renderers.
- registered_backends: list[str]
- current_backend: str
+ ``agents`` are the Agents a route can name, ``current_agent`` the id of the one the scope runs now, and
+ ``menus`` each listed backend's menu, sized for the platform. ``agent_option_limit`` caps the Agent select.
+ """
+
+ agents: list[AgentChoice]
+ current_agent: str
current_routing: ChannelRouting | None
menus: dict[str, BackendRouteMenu] = field(default_factory=dict)
+ agent_option_limit: Optional[int] = None
+
+ def agent(self, agent_id: Optional[str]) -> Optional[AgentChoice]:
+ return next((agent for agent in self.agents if agent.id == agent_id), None)
+
+ def shown_agent(self, agent_id: Optional[str]) -> Optional[str]:
+ """The Agent a form shows for ``agent_id``: that one if listed, else the scope's, else the first."""
+ for candidate in (agent_id, self.current_agent):
+ if self.agent(candidate) is not None:
+ return candidate
+ return self.agents[0].id if self.agents else None
+
+ def agent_options(self) -> list[AgentChoice]:
+ """The Agent select's options within its cap, keeping the scope's Agent shown."""
+ limit = self.agent_option_limit
+ if limit is None or len(self.agents) <= limit:
+ return list(self.agents)
+ kept = self.agents[:limit]
+ current = self.agent(self.current_agent)
+ if current is not None and current not in kept:
+ kept = [*self.agents[: limit - 1], current]
+ return kept
+
+ def menu(self, agent_id: str) -> BackendRouteMenu:
+ """The chosen Agent's menu: its backend's lists, its stored choices, and what Default inherits from it."""
+ agent = self.agent(agent_id)
+ backend = agent.backend if agent else ""
+ base = self.menus.get(backend) or BackendRouteMenu(backend)
+ return replace(
+ base,
+ stored=self.stored_draft(agent_id),
+ inherited=RouteDraft(model=agent.model, reasoning_effort=agent.reasoning_effort) if agent else RouteDraft(),
+ )
- def menu(self, backend: str) -> BackendRouteMenu:
- return self.menus.get(backend) or BackendRouteMenu(backend, stored=self.stored_draft(backend))
-
- def stored_draft(self, backend: str) -> RouteDraft:
- """The stored route as one backend's form shows it before any change.
+ def stored_draft(self, agent_id: str) -> RouteDraft:
+ """The stored route as one Agent's form shows it before any change.
- The stored model and effort belong to the stored backend's Agent only; another backend starts at Default.
+ The stored model and effort belong to the scope's Agent only; another Agent starts at Default, its own. A
+ backend's native agent is stored per backend, so every Agent on that backend shows it.
"""
routing = self.current_routing
+ agent = self.agent(agent_id)
+ backend = agent.backend if agent else ""
variant = getattr(routing, f"{backend}_agent", None) if routing and backend in NATIVE_CLI_BACKENDS else None
- if routing is None or backend != self.current_backend:
+ if routing is None or agent_id != self.current_agent:
return RouteDraft(variant=variant)
normalized = normalize_routing_settings(routing)
return RouteDraft(variant=variant, model=normalized.model, reasoning_effort=normalized.reasoning_effort)
@@ -144,21 +209,31 @@ class RoutingModalData:
class RoutingModalSelection:
"""A routing form's state as an update reports it.
- ``draft`` is the shown backend's choices; ``None`` when the form had no section for ``selected_backend`` (a
- backend switch), which then starts from the stored route instead of blanks that saving would persist.
+ ``draft`` is the shown Agent's choices; ``None`` when the form had no section for ``selected_agent`` (an Agent
+ switch), which then starts from the stored route instead of blanks that saving would persist.
"""
- selected_backend: str
+ selected_agent: str
draft: Optional[RouteDraft] = None
+def _effort_text(translate: Callable[[str], str], effort: str, fallback: str) -> str:
+ key = f"reasoning.{effort}"
+ translated = translate(key)
+ return translated if translated != key else fallback
+
+
def route_option_label(translate: Callable[[str], str], option: RouteOption, *, effort: bool = False) -> str:
- """An option's text: Default and effort tiers are translated, a model or agent keeps its catalog label."""
+ """An option's text: Default and effort tiers are translated, a model or agent keeps its catalog label.
+
+ A Default option that names what it inherits reads ``Default · <that>``.
+ """
if option.value == DEFAULT_OPTION_VALUE:
- return translate("common.default")
+ default = translate("common.default")
+ if not option.label:
+ return default
+ inherited = _effort_text(translate, option.label, option.label) if effort else option.label
+ return f"{default} · {inherited}"
if effort:
- key = f"reasoning.{option.value}"
- translated = translate(key)
- if translated != key:
- return translated
+ return _effort_text(translate, option.value, option.label)
return option.label
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 2f5ba6b57..4068e2ac3 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -29,7 +29,7 @@ from .download_target import open_download_target
from config.v2_config import DiscordConfig
from .formatters import DiscordFormatter
from vibe.i18n import get_supported_languages, t as i18n_t
-from core.modals import DEFAULT_OPTION_VALUE, RouteDraft, RouteOption, RoutingModalData, route_option_label
+from core.modals import DEFAULT_OPTION_VALUE, RouteDraft, RoutingModalData, route_option_label
from modules.agents.native_sessions.display import format_display_summary, format_display_time
from modules.agents.native_sessions.types import NativeResumeSession
@@ -1572,24 +1572,18 @@ class DiscordBot(BaseIMClient):
super().__init__(timeout=900)
self.outer = outer
self.owner_id = owner_id
- registered = routing.registered_backends
- self.selected_backend = (
- routing.current_backend
- if routing.current_backend in registered
- else (registered[0] if registered else routing.current_backend)
- )
- # Each backend keeps its own choices while the view is open; one not yet shown starts stored.
+ self.selected_agent = routing.shown_agent(routing.current_agent)
+ # Each Agent keeps its own choices while the view is open; one not yet shown starts stored.
self.drafts: dict[str, RouteDraft] = {}
self._render()
def _draft(self) -> RouteDraft:
- backend = self.selected_backend
- if backend not in self.drafts:
- self.drafts[backend] = routing.stored_draft(backend)
- return self.drafts[backend]
+ agent_id = self.selected_agent
+ if agent_id not in self.drafts:
+ self.drafts[agent_id] = routing.stored_draft(agent_id)
+ return self.drafts[agent_id]
- def _select(self, placeholder: str, prefix: str, options, shown: str, *, effort=False):
- default = RouteOption(DEFAULT_OPTION_VALUE, "")
+ def _select(self, placeholder: str, prefix: str, default, options, shown: str, *, effort=False):
return discord.ui.Select(
placeholder=placeholder,
options=[
@@ -1607,44 +1601,48 @@ class DiscordBot(BaseIMClient):
def _render(self):
self.clear_items()
t = self.outer._t
- backend_select = discord.ui.Select(
- placeholder=t("modal.routing.selectBackend"),
+ agent_select = discord.ui.Select(
+ placeholder=t("modal.routing.selectAgent"),
options=[
discord.SelectOption(
- label=_prefixed_label(t("discord.labels.backend"), display_name_for_backend(backend)),
- value=backend,
- default=backend == self.selected_backend,
+ label=_prefixed_label(t("discord.labels.agent"), agent.label),
+ value=agent.id,
+ default=agent.id == self.selected_agent,
)
- for backend in routing.registered_backends[:25]
+ for agent in routing.agent_options()
],
min_values=1,
max_values=1,
)
- async def backend_callback(select_interaction: discord.Interaction):
- if backend_select.values:
- self.selected_backend = backend_select.values[0]
+ async def agent_callback(select_interaction: discord.Interaction):
+ if agent_select.values:
+ self.selected_agent = agent_select.values[0]
await self._refresh(select_interaction)
- backend_select.callback = backend_callback
- self.add_item(backend_select)
+ agent_select.callback = agent_callback
+ self.add_item(agent_select)
- backend = self.selected_backend
- menu = routing.menu(backend)
+ agent = routing.agent(self.selected_agent)
+ if agent is None:
+ return
+ agent_id = agent.id
+ menu = routing.menu(agent_id)
draft = self._draft()
- backend_name = display_name_for_backend(backend)
+ backend_name = display_name_for_backend(agent.backend)
variants = menu.variant_options(draft.variant)
if variants:
variant_select = self._select(
t("modal.routing.selectBackendAgent", backend=backend_name),
t("discord.labels.backendAgent", backend=backend_name),
+ menu.default_option("variant"),
variants,
menu.shown_value(draft.variant),
)
async def variant_callback(select_interaction: discord.Interaction):
if variant_select.values:
- self.drafts[backend] = replace(
+ self.drafts[agent_id] = replace(
self._draft(), variant=menu.chosen("variant", _choice(variant_select.values[0]))
)
await select_interaction.response.defer()
@@ -1655,13 +1653,14 @@ class DiscordBot(BaseIMClient):
model_select = self._select(
t("modal.routing.selectModel"),
t("discord.labels.model"),
+ menu.default_option("model"),
menu.model_options(draft.model),
menu.shown_value(draft.model),
)
async def model_callback(select_interaction: discord.Interaction):
if model_select.values:
- self.drafts[backend] = self._draft().with_model(
+ self.drafts[agent_id] = self._draft().with_model(
menu.chosen("model", _choice(model_select.values[0]))
)
await self._refresh(select_interaction)
@@ -1672,6 +1671,7 @@ class DiscordBot(BaseIMClient):
effort_select = self._select(
t("modal.routing.selectReasoningEffort"),
t("discord.labels.reasoningEffort"),
+ menu.default_option("reasoning_effort"),
menu.effort_options(draft.model, draft.reasoning_effort),
menu.shown_value(draft.reasoning_effort),
effort=True,
@@ -1679,7 +1679,7 @@ class DiscordBot(BaseIMClient):
async def effort_callback(select_interaction: discord.Interaction):
if effort_select.values:
- self.drafts[backend] = replace(
+ self.drafts[agent_id] = replace(
self._draft(),
reasoning_effort=menu.chosen("reasoning_effort", _choice(effort_select.values[0])),
)
@@ -1726,7 +1726,7 @@ class DiscordBot(BaseIMClient):
await self.outer._on_routing_update(
user_id=str(interaction.user.id),
channel_id=channel_id,
- backend=self.selected_backend,
+ agent_id=self.selected_agent,
variant=draft.variant,
model=draft.model,
reasoning_effort=draft.reasoning_effort,
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index b74c7cbe5..b8de9e40b 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -32,7 +32,7 @@ from config.v2_config import LarkConfig
from core.citations import spell_destination
from core.reply_enhancer import inline_links
from vibe.i18n import get_supported_languages, t as i18n_t
-from core.modals import DEFAULT_OPTION_VALUE, RouteDraft, RouteOption, RoutingModalData, route_option_label
+from core.modals import DEFAULT_OPTION_VALUE, RouteDraft, RoutingModalData, route_option_label
from modules.agents.native_sessions.display import format_display_summary, format_display_time
from modules.agents.native_sessions.types import NativeResumeSession
@@ -2086,10 +2086,10 @@ class FeishuBot(BaseIMClient):
)
async def _handle_routing_backend_select(self, context: MessageContext, form_value: Dict[str, Any]):
- """Handle step 1 of routing: user selected a backend, now show backend-specific options."""
- selected_backend = form_value.get("backend", "")
- if not selected_backend:
- logger.warning("Routing backend select submitted with empty backend")
+ """Handle step 1 of routing: the user picked an Agent, now show its route fields."""
+ selected_agent = form_value.get("agent", "")
+ if not selected_agent:
+ logger.warning("Routing agent select submitted with empty agent")
return
cache_key = f"{context.channel_id}:{context.user_id}"
@@ -2097,7 +2097,7 @@ class FeishuBot(BaseIMClient):
logger.warning("No cached routing data for %s", cache_key)
return
- await self._send_routing_backend_options_card(context.channel_id, selected_backend, context.user_id)
+ await self._send_routing_backend_options_card(context.channel_id, selected_agent, context.user_id)
@staticmethod
def _normalize_routing_field_value(value: Any) -> Optional[str]:
@@ -2105,23 +2105,23 @@ class FeishuBot(BaseIMClient):
return None
return str(value)
- # A routing card's select names (``<prefix>:<backend>``) and the draft field each sets. The backend is in
- # every name, so a card acts on its own backend even after the step-1 card opened another one.
+ # A routing card's select names (``<prefix>:<agent id>``) and the draft field each sets. The Agent is in
+ # every name, so a card acts on its own Agent even after the step-1 card opened another one.
_ROUTE_FIELDS = {"route_variant": "variant", "route_model": "model", "route_effort": "reasoning_effort"}
@classmethod
def _route_field(cls, name: object) -> tuple[Optional[str], str]:
- """A routing control's draft field and backend, from its name."""
- prefix, _, backend = str(name or "").partition(":")
- return cls._ROUTE_FIELDS.get(prefix), backend
+ """A routing control's draft field and Agent id, from its name."""
+ prefix, _, agent_id = str(name or "").partition(":")
+ return cls._ROUTE_FIELDS.get(prefix), agent_id
@staticmethod
- def _routing_draft(cache: Dict[str, Any], backend: str) -> RouteDraft:
- """The backend's choices on this card; one not yet shown starts from the stored route."""
+ def _routing_draft(cache: Dict[str, Any], agent_id: str) -> RouteDraft:
+ """The Agent's choices on this card; one not yet shown starts from the stored route."""
drafts = cache.setdefault("drafts", {})
- if backend not in drafts:
- drafts[backend] = cache["routing"].stored_draft(backend)
- return drafts[backend]
+ if agent_id not in drafts:
+ drafts[agent_id] = cache["routing"].stored_draft(agent_id)
+ return drafts[agent_id]
@staticmethod
def _extract_select_action_value(action: Dict[str, Any]) -> Optional[str]:
@@ -2162,47 +2162,47 @@ class FeishuBot(BaseIMClient):
raise RuntimeError(f"Feishu patch card failed: {response.msg}")
async def _handle_routing_select_change(self, context: MessageContext, action: Dict[str, Any]) -> bool:
- draft_field, backend = self._route_field(action.get("name"))
+ draft_field, agent_id = self._route_field(action.get("name"))
if not draft_field:
return False
cache = self._routing_cache.get(f"{context.channel_id}:{context.user_id}")
- if not cache or not backend or "routing" not in cache:
+ if not cache or not agent_id or "routing" not in cache:
return False
- draft = self._routing_draft(cache, backend)
- value = cache["routing"].menu(backend).chosen(
+ draft = self._routing_draft(cache, agent_id)
+ value = cache["routing"].menu(agent_id).chosen(
draft_field, self._normalize_routing_field_value(self._extract_select_action_value(action))
)
if draft_field != "model":
- cache["drafts"][backend] = replace(draft, **{draft_field: value})
+ cache["drafts"][agent_id] = replace(draft, **{draft_field: value})
return True
# A model change offers that model's efforts afresh, so the card is rebuilt around it.
- cache["drafts"][backend] = draft.with_model(value)
- card = self._build_routing_backend_options_card(context.channel_id, backend, context.user_id)
+ cache["drafts"][agent_id] = draft.with_model(value)
+ card = self._build_routing_backend_options_card(context.channel_id, agent_id, context.user_id)
await self._patch_card_message(context.message_id, card)
return True
async def _handle_routing_form_submit(self, context: MessageContext, form_value: Dict[str, Any], button_name: str):
- """Handle step 2 routing form submission: the options card of the backend its button names."""
+ """Handle step 2 routing form submission: the options card of the Agent its button names."""
cached = self._routing_cache.get(f"{context.channel_id}:{context.user_id}", {})
- backend = button_name.partition(":")[2]
- if not backend or "routing" not in cached:
- logger.warning("Routing form submitted without a backend or cached routing, ignoring")
+ agent_id = button_name.partition(":")[2]
+ if not agent_id or "routing" not in cached:
+ logger.warning("Routing form submitted without an Agent or cached routing, ignoring")
return
# The form carries what its selects show; a field it omits keeps the card's draft.
- menu = cached["routing"].menu(backend)
+ menu = cached["routing"].menu(agent_id)
changes = {}
for name, value in form_value.items():
- draft_field, field_backend = self._route_field(name)
- if draft_field and field_backend == backend:
+ draft_field, field_agent = self._route_field(name)
+ if draft_field and field_agent == agent_id:
changes[draft_field] = menu.chosen(draft_field, self._normalize_routing_field_value(value))
- draft = replace(self._routing_draft(cached, backend), **changes)
+ draft = replace(self._routing_draft(cached, agent_id), **changes)
if self._on_routing_update:
await self._on_routing_update(
user_id=context.user_id,
channel_id=context.channel_id,
- backend=backend,
+ agent_id=agent_id,
variant=draft.variant,
model=draft.model,
reasoning_effort=draft.reasoning_effort,
@@ -2547,38 +2547,34 @@ class FeishuBot(BaseIMClient):
logger.error("Failed to send CWD card: %s", exc)
async def open_routing_modal(self, trigger_id: Any, channel_id: str = None, routing: RoutingModalData = None):
- """Step 1: send a card with only the backend selector.
+ """Step 1: send a card with only the Agent selector.
The route menus are cached so that step 2 (``_send_routing_backend_options_card``) renders the selected
- backend's options without re-fetching.
+ Agent's options without re-fetching.
"""
t = lambda key, **kw: self._t(key, channel_id, **kw)
- registered_backends = routing.registered_backends
# Cache per channel+user, so users opening routing in one channel concurrently do not cross.
cache_user_id = trigger_id.user_id if isinstance(trigger_id, MessageContext) else "unknown"
self._routing_cache[f"{channel_id or ''}:{cache_user_id}"] = {"routing": routing, "drafts": {}}
- backend_options = [
- {"text": {"tag": "plain_text", "content": display_name_for_backend(b)}, "value": b}
- for b in registered_backends
+ agent_options = [
+ {"text": {"tag": "plain_text", "content": agent.label[:60]}, "value": agent.id}
+ for agent in routing.agent_options()
]
- if not backend_options:
+ if not agent_options:
ctx = MessageContext(user_id="system", channel_id=channel_id or "")
- await self.send_message(ctx, "No agent backends available.")
+ await self.send_message(ctx, t("routing.noAgents"))
return
- backend_initial = (
- routing.current_backend if routing.current_backend in registered_backends else registered_backends[0]
- )
form_elements: list = [
- {"tag": "markdown", "content": f"**{t('modal.routing.backend')}**"},
+ {"tag": "markdown", "content": f"**{t('modal.routing.agent')}**"},
{
"tag": "select_static",
- "name": "backend",
- "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectBackend")},
- "options": backend_options,
- "initial_option": backend_initial,
+ "name": "agent",
+ "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectAgent")},
+ "options": agent_options,
+ "initial_option": routing.shown_agent(routing.current_agent),
},
{"tag": "markdown", "content": t("modal.routing.tip")},
{
@@ -2606,18 +2602,21 @@ class FeishuBot(BaseIMClient):
except Exception as exc:
logger.error("Failed to send routing backend card: %s", exc)
- def _build_routing_backend_options_card(self, channel_id: str, selected_backend: str, user_id: str) -> Dict[str, Any]:
- """Build the step-2 routing card: the selected backend's route fields."""
+ def _build_routing_backend_options_card(self, channel_id: str, agent_id: str, user_id: str) -> Dict[str, Any]:
+ """Build the step-2 routing card: the selected Agent's route fields."""
t = lambda key, **kw: self._t(key, channel_id, **kw)
cache = self._routing_cache.setdefault(f"{channel_id}:{user_id}", {})
- cache.setdefault("routing", RoutingModalData(registered_backends=[], current_backend="", current_routing=None))
- menu = cache["routing"].menu(selected_backend)
- draft = self._routing_draft(cache, selected_backend)
- backend_name = display_name_for_backend(selected_backend)
- default = RouteOption(DEFAULT_OPTION_VALUE, "")
- form_elements: list = [{"tag": "markdown", "content": f"**{t('modal.routing.backend')}**: {backend_name}"}]
-
- def _select(name: str, label: str, placeholder: str, options, current, *, effort: bool = False) -> None:
+ cache.setdefault("routing", RoutingModalData(agents=[], current_agent="", current_routing=None))
+ routing = cache["routing"]
+ agent = routing.agent(agent_id)
+ menu = routing.menu(agent_id)
+ draft = self._routing_draft(cache, agent_id)
+ backend_name = display_name_for_backend(agent.backend) if agent else ""
+ agent_label = agent.label if agent else agent_id
+ form_elements: list = [{"tag": "markdown", "content": f"**{t('modal.routing.agent')}**: {agent_label}"}]
+
+ def _select(field: str, name: str, label: str, placeholder: str, options, current) -> None:
+ effort = field == "reasoning_effort"
form_elements.append({"tag": "markdown", "content": label})
form_elements.append(
{
@@ -2629,7 +2628,7 @@ class FeishuBot(BaseIMClient):
"text": {"tag": "plain_text", "content": route_option_label(t, option, effort=effort)[:60]},
"value": option.value,
}
- for option in [default, *options]
+ for option in [menu.default_option(field), *options]
],
"initial_option": menu.shown_value(current),
}
@@ -2638,26 +2637,28 @@ class FeishuBot(BaseIMClient):
variants = menu.variant_options(draft.variant)
if variants:
_select(
- f"route_variant:{selected_backend}",
+ "variant",
+ f"route_variant:{agent_id}",
t("modal.routing.backendAgent", backend=backend_name),
t("modal.routing.selectBackendAgent", backend=backend_name),
variants,
draft.variant,
)
_select(
- f"route_model:{selected_backend}",
+ "model",
+ f"route_model:{agent_id}",
t("modal.routing.model"),
t("modal.routing.selectModel"),
menu.model_options(draft.model),
draft.model,
)
_select(
- f"route_effort:{selected_backend}",
+ "reasoning_effort",
+ f"route_effort:{agent_id}",
t("modal.routing.reasoningEffort"),
t("modal.routing.selectReasoningEffort"),
menu.effort_options(draft.model, draft.reasoning_effort),
draft.reasoning_effort,
- effort=True,
)
form_elements.append(
{
@@ -2665,13 +2666,13 @@ class FeishuBot(BaseIMClient):
"text": {"tag": "plain_text", "content": t("common.save")},
"type": "primary",
"action_type": "form_submit",
- "name": f"routing_submit:{selected_backend}",
+ "name": f"routing_submit:{agent_id}",
}
)
return {
"schema": "2.0",
"header": {
- "title": {"tag": "plain_text", "content": f"{t('modal.routing.title')} — {backend_name}"},
+ "title": {"tag": "plain_text", "content": f"{t('modal.routing.title')} — {agent_label}"},
"template": "blue",
},
"body": {
@@ -2680,9 +2681,9 @@ class FeishuBot(BaseIMClient):
},
}
- async def _send_routing_backend_options_card(self, channel_id: str, selected_backend: str, user_id: str):
- """Step 2: send a card with options specific to the selected backend."""
- card = self._build_routing_backend_options_card(channel_id, selected_backend, user_id)
+ async def _send_routing_backend_options_card(self, channel_id: str, agent_id: str, user_id: str):
+ """Step 2: send a card with the selected Agent's route fields."""
+ card = self._build_routing_backend_options_card(channel_id, agent_id, user_id)
ctx = MessageContext(user_id="system", channel_id=channel_id or "")
try:
await self._send_card_to_channel(ctx, card)
diff --git a/modules/im/slack.py b/modules/im/slack.py
index ecbc437a0..c243caea1 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -44,9 +44,9 @@ from vibe.i18n import get_supported_languages, t as i18n_t
from vibe.proxy import resolve_proxy
from core.modals import (
DEFAULT_OPTION_VALUE,
+ AgentChoice,
BackendRouteMenu,
RouteDraft,
- RouteOption,
RoutingModalData,
route_option_label,
)
@@ -2542,7 +2542,7 @@ class SlackBot(BaseIMClient):
# A routing form refreshes when the backend or the model changes: each decides what the
# fields below it offer.
should_update = view.get("callback_id") == "routing_modal" and (
- action.get("action_id") == "backend_select"
+ action.get("action_id") == "agent_select"
or str(action.get("block_id") or "").startswith("route_model:")
)
if should_update:
@@ -2754,7 +2754,7 @@ class SlackBot(BaseIMClient):
await self._on_routing_update(
user_id=user_id,
channel_id=channel_id,
- backend=selection.selected_backend,
+ agent_id=selection.selected_agent,
variant=draft.variant,
model=draft.model,
reasoning_effort=draft.reasoning_effort,
@@ -3444,55 +3444,53 @@ class SlackBot(BaseIMClient):
self,
channel_id: str,
routing: RoutingModalData,
- selected_backend: Optional[str] = None,
+ selected_agent: Optional[str] = None,
draft: Optional[RouteDraft] = None,
) -> dict:
- """Build the routing modal: the backend select, then the shown backend's route section.
+ """Build the routing modal: the Agent select, then the shown Agent's route section.
- ``draft`` is the shown backend's choices; without one the section shows the stored route.
+ ``draft`` is the shown Agent's choices; without one the section shows the stored route.
"""
- registered_backends = routing.registered_backends
- current_backend = routing.current_backend
- backend_options = [
- {"text": {"type": "plain_text", "text": display_name_for_backend(backend)}, "value": backend}
- for backend in registered_backends
+ shown_id = routing.shown_agent(selected_agent)
+ shown = routing.agent(shown_id)
+ current = routing.agent(routing.current_agent)
+ agent_options = [
+ {"text": {"type": "plain_text", "text": agent.label[:75]}, "value": agent.id}
+ for agent in routing.agent_options()
]
- shown_backend = selected_backend if selected_backend in registered_backends else current_backend
- if shown_backend not in registered_backends:
- shown_backend = registered_backends[0] if registered_backends else None
- backend_select = {
+ agent_select = {
"type": "static_select",
- "action_id": "backend_select",
- "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectBackend")},
- "options": backend_options,
+ "action_id": "agent_select",
+ "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectAgent")},
+ "options": agent_options,
}
- initial_backend = next((option for option in backend_options if option["value"] == shown_backend), None)
- if initial_backend is not None:
- backend_select["initial_option"] = initial_backend
+ initial_agent = next((option for option in agent_options if option["value"] == shown_id), None)
+ if initial_agent is not None:
+ agent_select["initial_option"] = initial_agent
blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
- "text": f"*{self._t('modal.routing.currentBackend')}* {display_name_for_backend(current_backend)}",
+ "text": f"*{self._t('modal.routing.currentAgent')}* {current.label if current else ''}",
},
},
{"type": "divider"},
{
"type": "input",
- "block_id": "backend_block",
+ "block_id": "agent_block",
"dispatch_action": True,
- "element": backend_select,
- "label": {"type": "plain_text", "text": self._t("modal.routing.backend")},
+ "element": agent_select,
+ "label": {"type": "plain_text", "text": self._t("modal.routing.agent")},
},
]
- if shown_backend:
+ if shown is not None:
blocks.extend(
self._route_section_blocks(
- shown_backend,
- routing.menu(shown_backend),
- draft if draft is not None else routing.stored_draft(shown_backend),
+ shown,
+ routing.menu(shown.id),
+ draft if draft is not None else routing.stored_draft(shown.id),
)
)
blocks.append(
@@ -3511,22 +3509,22 @@ class SlackBot(BaseIMClient):
"blocks": blocks,
}
- def _route_section_blocks(self, backend: str, menu: BackendRouteMenu, draft: RouteDraft) -> list[dict]:
- """One backend's route fields, keyed by backend so a backend switch never carries another's input.
+ def _route_section_blocks(self, agent: AgentChoice, menu: BackendRouteMenu, draft: RouteDraft) -> list[dict]:
+ """One Agent's route fields, keyed by Agent so an Agent switch never carries another's input.
Slack keeps an input's state across ``views.update`` while its block stays the same, so the effort block
is also keyed by model: a model change then offers that model's efforts afresh.
"""
- backend_name = display_name_for_backend(backend)
- default = RouteOption(DEFAULT_OPTION_VALUE, "")
+ backend_name = display_name_for_backend(agent.backend)
- def _select(block_id, label, placeholder, options, current, *, effort=False, dispatch=False) -> dict:
+ def _select(field, block_id, label, placeholder, options, current, *, dispatch=False) -> dict:
+ effort = field == "reasoning_effort"
slack_options = [
{
"text": {"type": "plain_text", "text": route_option_label(self._t, option, effort=effort)[:75]},
"value": option.value,
}
- for option in [default, *options]
+ for option in [menu.default_option(field), *options]
]
block = {
"type": "input",
@@ -3552,17 +3550,15 @@ class SlackBot(BaseIMClient):
{"type": "divider"},
{
"type": "section",
- "text": {
- "type": "mrkdwn",
- "text": f"*{self._t('modal.routing.backendSettings', backend=backend_name)}*",
- },
+ "text": {"type": "mrkdwn", "text": f"*{agent.label}*"},
},
]
variants = menu.variant_options(draft.variant)
if variants:
blocks.append(
_select(
- f"route_variant:{backend}",
+ "variant",
+ f"route_variant:{agent.id}",
self._t("modal.routing.backendAgent", backend=backend_name),
self._t("modal.routing.selectBackendAgent", backend=backend_name),
variants,
@@ -3571,7 +3567,8 @@ class SlackBot(BaseIMClient):
)
blocks.append(
_select(
- f"route_model:{backend}",
+ "model",
+ f"route_model:{agent.id}",
self._t("modal.routing.model"),
self._t("modal.routing.selectModel"),
menu.model_options(draft.model),
@@ -3582,12 +3579,12 @@ class SlackBot(BaseIMClient):
effort_key = hashlib.sha256((draft.model or DEFAULT_OPTION_VALUE).encode("utf-8")).hexdigest()
blocks.append(
_select(
- f"route_effort:{backend}:{effort_key}",
+ "reasoning_effort",
+ f"route_effort:{agent.id}:{effort_key}",
self._t("modal.routing.reasoningEffort"),
self._t("modal.routing.selectReasoningEffort"),
menu.effort_options(draft.model, draft.reasoning_effort),
draft.reasoning_effort,
- effort=True,
)
)
return blocks
@@ -3750,13 +3747,13 @@ class SlackBot(BaseIMClient):
view_hash: str,
channel_id: str,
routing: RoutingModalData,
- selected_backend: Optional[str] = None,
+ selected_agent: Optional[str] = None,
draft: Optional[RouteDraft] = None,
) -> None:
"""Update routing modal when selections change."""
self._ensure_clients()
view = self._build_routing_modal_view(
- channel_id=channel_id, routing=routing, selected_backend=selected_backend, draft=draft
+ channel_id=channel_id, routing=routing, selected_agent=selected_agent, draft=draft
)
try:
await self.web_client.views_update(view_id=view_id, hash=view_hash, view=view)
diff --git a/modules/im/slack_modal.py b/modules/im/slack_modal.py
index 7681c71a2..0ec9acb61 100644
--- a/modules/im/slack_modal.py
+++ b/modules/im/slack_modal.py
@@ -24,28 +24,28 @@ def _choice(value: Optional[str]) -> Optional[str]:
def parse_routing_modal_selection(*, view: dict, action: dict) -> RoutingModalSelection:
- """Parse the routing modal's state into the shown backend and its route choices.
+ """Parse the routing modal's state into the shown Agent and its route choices.
- Route blocks are ``route_<field>:<backend>[:...]`` (see ``SlackBot._route_section_blocks``). The draft is
- ``None`` when the section on screen is not the selected backend's, as right after a backend switch.
+ Route blocks are ``route_<field>:<agent id>[:<model digest>]`` (see ``SlackBot._route_section_blocks``). The
+ draft is ``None`` when the section on screen is not the selected Agent's, as right after an Agent switch.
"""
values = view.get("state", {}).get("values", {})
- selected_backend = _selected_value(values.get("backend_block")) or ""
+ selected_agent = _selected_value(values.get("agent_block")) or ""
fields: dict[str, Optional[str]] = {}
- section_backend = None
+ section_agent = None
for block_id, block in values.items():
if not isinstance(block_id, str) or not block_id.startswith("route_"):
continue
field, _, rest = block_id.partition(":")
- section_backend = rest.split(":", 1)[0]
+ section_agent = rest.split(":", 1)[0]
fields[field] = _choice(_selected_value(block))
block_id = str(action.get("block_id") or "")
value = (action.get("selected_option") or {}).get("value") if isinstance(action, dict) else None
- if action.get("action_id") == "backend_select" and isinstance(value, str):
- selected_backend = value
- if not selected_backend or section_backend != selected_backend:
- return RoutingModalSelection(selected_backend=selected_backend)
+ if action.get("action_id") == "agent_select" and isinstance(value, str):
+ selected_agent = value
+ if not selected_agent or section_agent != selected_agent:
+ return RoutingModalSelection(selected_agent=selected_agent)
draft = RouteDraft(
variant=fields.get("route_variant"),
@@ -64,4 +64,4 @@ def parse_routing_modal_selection(*, view: dict, action: dict) -> RoutingModalSe
None,
)
draft = replace(draft, model=_choice(shown)).with_model(_choice(value))
- return RoutingModalSelection(selected_backend=selected_backend, draft=draft)
+ return RoutingModalSelection(selected_agent=selected_agent, draft=draft)
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index c7d2a1d6d..5e5f8d038 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -71,20 +71,16 @@ class _TelegramRoutingState:
user_id: str
is_dm: bool
routing: RoutingModalData
- backend: str
- # Each backend keeps its own choices while the form is open; one not yet shown starts from the stored route.
+ agent: str
+ # Each Agent keeps its own choices while the form is open; one not yet shown starts from the stored route.
drafts: dict[str, RouteDraft] = field(default_factory=dict)
picker_field: Optional[str] = None
picker_page: int = 0
- @property
- def registered_backends(self) -> list[str]:
- return self.routing.registered_backends
-
def draft(self) -> RouteDraft:
- if self.backend not in self.drafts:
- self.drafts[self.backend] = self.routing.stored_draft(self.backend)
- return self.drafts[self.backend]
+ if self.agent not in self.drafts:
+ self.drafts[self.agent] = self.routing.stored_draft(self.agent)
+ return self.drafts[self.agent]
@dataclass
@@ -1713,7 +1709,6 @@ class TelegramBot(BaseIMClient):
context = trigger_id if isinstance(trigger_id, MessageContext) else None
if context is None:
raise ValueError("Telegram routing flow requires a message context")
- registered = routing.registered_backends
state = _TelegramRoutingState(
message_id="",
channel_id=channel_id,
@@ -1721,11 +1716,7 @@ class TelegramBot(BaseIMClient):
user_id=context.user_id,
is_dm=bool((context.platform_specific or {}).get("is_dm")),
routing=routing,
- backend=(
- routing.current_backend
- if routing.current_backend in registered
- else (registered[0] if registered else routing.current_backend)
- ),
+ agent=routing.shown_agent(routing.current_agent) or "",
)
text, keyboard = self._render_routing_state(state)
message_id = await self.send_message_with_buttons(context, text, keyboard)
@@ -1757,8 +1748,10 @@ class TelegramBot(BaseIMClient):
else:
state.message_id = await self.send_message_with_buttons(target_context, text, keyboard)
- def _get_backend_label(self, backend: str) -> str:
- return display_name_for_backend(backend)
+ @staticmethod
+ def _agent_label(state: _TelegramRoutingState, agent_id: str) -> str:
+ agent = state.routing.agent(agent_id)
+ return agent.label if agent else agent_id
def _question_definition(self, question: Any) -> tuple[str, str, list[tuple[str, str]], bool]:
if isinstance(question, dict):
@@ -1890,19 +1883,22 @@ class TelegramBot(BaseIMClient):
synthetic_payload = f"{state.callback_prefix}:modal:{json.dumps(answers_payload, ensure_ascii=True)}"
await self.on_callback_query_callback(context, synthetic_payload)
- def _routing_field_label(self, field: Optional[str]) -> str:
+ def _routing_field_label(self, state: _TelegramRoutingState, field: Optional[str]) -> str:
+ agent = state.routing.agent(state.agent)
mapping = {
- "backend": self._t("routing.label.backend"),
- "variant": self._t("routing.label.agent"),
+ "agent": self._t("routing.label.agent"),
+ "variant": self._t(
+ "modal.routing.backendAgent", backend=display_name_for_backend(agent.backend) if agent else ""
+ ),
"model": self._t("routing.label.model"),
"reasoning_effort": self._t("routing.label.reasoningEffort"),
}
return mapping.get(field or "", field or "")
def _routing_fields(self, state: _TelegramRoutingState) -> list[tuple[str, str]]:
- """The shown backend's fields as ``(field, current value's text)``; the agent only where it has one."""
+ """The shown Agent's fields as ``(field, current value's text)``; the native agent only where it has one."""
draft = state.draft()
- menu = state.routing.menu(state.backend)
+ menu = state.routing.menu(state.agent)
fields = [("model", draft.model), ("reasoning_effort", draft.reasoning_effort)]
if menu.variant_options(draft.variant):
fields.insert(0, ("variant", draft.variant))
@@ -1919,18 +1915,18 @@ class TelegramBot(BaseIMClient):
lines = [
f"🤖 {self._t('telegram.routingTitle')}",
"",
- f"{self._t('routing.label.backend')}: {self._get_backend_label(state.backend)}",
+ f"{self._t('routing.label.agent')}: {self._agent_label(state, state.agent)}",
]
- lines.extend(f"{self._routing_field_label(name)}: {text}" for name, text in self._routing_fields(state))
+ lines.extend(f"{self._routing_field_label(state, name)}: {text}" for name, text in self._routing_fields(state))
return lines
def _routing_picker_options(
self, state: _TelegramRoutingState, field_name: Optional[str] = None
) -> list[tuple[str, Optional[str]]]:
field_name = field_name or state.picker_field
- if field_name == "backend":
- return [(self._get_backend_label(backend), backend) for backend in state.registered_backends]
- menu = state.routing.menu(state.backend)
+ if field_name == "agent":
+ return [(agent.label, agent.id) for agent in state.routing.agent_options()]
+ menu = state.routing.menu(state.agent)
draft = state.draft()
if field_name == "variant":
options = menu.variant_options(draft.variant)
@@ -1941,20 +1937,21 @@ class TelegramBot(BaseIMClient):
else:
return []
effort = field_name == "reasoning_effort"
- return [(self._t("common.default"), None)] + [
+ default = route_option_label(self._t, menu.default_option(field_name), effort=effort)
+ return [(default, None)] + [
(route_option_label(self._t, option, effort=effort), option.value) for option in options
]
def _apply_routing_option(self, state: _TelegramRoutingState, value: Optional[str]) -> None:
draft = state.draft()
if state.picker_field in ("variant", "model", "reasoning_effort"):
- value = state.routing.menu(state.backend).chosen(state.picker_field, value)
+ value = state.routing.menu(state.agent).chosen(state.picker_field, value)
if state.picker_field == "model":
- state.drafts[state.backend] = draft.with_model(value)
+ state.drafts[state.agent] = draft.with_model(value)
elif state.picker_field == "variant":
- state.drafts[state.backend] = replace(draft, variant=value)
+ state.drafts[state.agent] = replace(draft, variant=value)
elif state.picker_field == "reasoning_effort":
- state.drafts[state.backend] = replace(draft, reasoning_effort=value)
+ state.drafts[state.agent] = replace(draft, reasoning_effort=value)
state.picker_field = None
state.picker_page = 0
@@ -1963,31 +1960,31 @@ class TelegramBot(BaseIMClient):
return self._render_routing_picker(state)
text = "\n".join(self._routing_summary_lines(state))
- backend_row = [
+ # Agent names are free text and Telegram callback data holds 64 bytes, so buttons carry list positions.
+ agents = state.routing.agent_options()
+ agent_row = [
InlineButton(
- text=(f"☑️ {self._get_backend_label(backend)}" if backend == state.backend else self._get_backend_label(backend))[
- :40
- ],
- callback_data=f"tg_route:backend:{backend}",
+ text=(f"☑️ {agent.name}" if agent.id == state.agent else agent.name)[:40],
+ callback_data=f"tg_route:agent:{index}",
)
- for backend in state.registered_backends[:3]
+ for index, agent in enumerate(agents[:3])
]
rows: list[list[InlineButton]] = []
- if backend_row:
- rows.append(backend_row)
- if len(state.registered_backends) > 3:
+ if agent_row:
+ rows.append(agent_row)
+ if len(agents) > 3:
rows.append(
[
InlineButton(
- text=f"… {self._t('routing.label.backend')}"[:40],
- callback_data="tg_route:field:backend",
+ text=f"… {self._t('routing.label.agent')}"[:40],
+ callback_data="tg_route:field:agent",
)
]
)
rows.extend(
[
InlineButton(
- text=f"{self._routing_field_label(name)}: {value_text}"[:40],
+ text=f"{self._routing_field_label(state, name)}: {value_text}"[:40],
callback_data=f"tg_route:field:{name}",
)
]
@@ -2013,7 +2010,7 @@ class TelegramBot(BaseIMClient):
lines.extend(
[
"",
- f"{self._t('telegram.routingChoosePrefix')} {self._routing_field_label(state.picker_field)}",
+ f"{self._t('telegram.routingChoosePrefix')} {self._routing_field_label(state, state.picker_field)}",
]
)
rows = [
@@ -2052,7 +2049,7 @@ class TelegramBot(BaseIMClient):
routing_update = {
"user_id": state.user_id,
"channel_id": state.channel_id,
- "backend": state.backend,
+ "agent_id": state.agent,
"variant": draft.variant,
"model": draft.model,
"reasoning_effort": draft.reasoning_effort,
@@ -2067,20 +2064,17 @@ class TelegramBot(BaseIMClient):
if action == "back":
state.picker_field = None
state.picker_page = 0
- elif action == "backend" and len(parts) > 2:
- backend = parts[2]
- if backend in state.registered_backends:
- state.backend = backend
+ elif action == "agent" and len(parts) > 2:
+ agents = state.routing.agent_options()
+ index = int(parts[2]) if parts[2].isdigit() else -1
+ if 0 <= index < len(agents):
+ state.agent = agents[index].id
state.picker_field = None
state.picker_page = 0
elif action == "page" and len(parts) > 2:
state.picker_page += -1 if parts[2] == "prev" else 1
elif action == "field" and len(parts) > 2:
- field = parts[2]
- if field == "backend":
- state.picker_field = "backend"
- else:
- state.picker_field = field
+ state.picker_field = parts[2]
state.picker_page = 0
elif action == "option" and len(parts) > 2:
try:
@@ -2090,8 +2084,8 @@ class TelegramBot(BaseIMClient):
options = self._routing_picker_options(state)
if 0 <= option_index < len(options):
_, value = options[option_index]
- if state.picker_field == "backend" and value:
- state.backend = value
+ if state.picker_field == "agent" and value:
+ state.agent = value
state.picker_field = None
state.picker_page = 0
else:
diff --git a/tests/test_feishu_routing_card.py b/tests/test_feishu_routing_card.py
index b42f73063..38a808f51 100644
--- a/tests/test_feishu_routing_card.py
+++ b/tests/test_feishu_routing_card.py
@@ -4,7 +4,7 @@ from unittest.mock import AsyncMock
from config.v2_config import LarkConfig
from config.v2_settings import RoutingSettings
-from core.modals import BackendRouteMenu, RouteOption, RoutingModalData
+from core.modals import AgentChoice, BackendRouteMenu, RouteOption, RoutingModalData
from core.auth import AuthResult
from modules.im.base import MessageContext
from modules.im.feishu import FeishuBot
@@ -26,8 +26,8 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
def _claude_routing() -> RoutingModalData:
efforts = [RouteOption("high", "High"), RouteOption("max", "Max")]
return RoutingModalData(
- registered_backends=["claude", "codex"],
- current_backend="claude",
+ agents=[AgentChoice("id-claude", "claude", "claude"), AgentChoice("id-codex", "codex", "codex")],
+ current_agent="id-claude",
current_routing=RoutingSettings(agent_name="claude", model="claude-sonnet-4-5", claude_agent="helper"),
menus={
"claude": BackendRouteMenu(
@@ -49,17 +49,17 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
return {
"operator": {"open_id": "user"},
"context": {"open_message_id": "om_123", "open_chat_id": "chat"},
- "action": {"tag": "select_static", "name": "route_model:claude", "option": {"value": model}},
+ "action": {"tag": "select_static", "name": "route_model:id-claude", "option": {"value": model}},
}
await bot._async_handle_card_action(_event("claude-sonnet-4-6"))
await bot._async_handle_card_action(_event("claude-opus-4-6"))
self.assertEqual(bot._patch_card_message.await_count, 2)
- self.assertEqual(bot._routing_cache["chat:user"]["drafts"]["claude"].model, "claude-opus-4-6")
+ self.assertEqual(bot._routing_cache["chat:user"]["drafts"]["id-claude"].model, "claude-opus-4-6")
_, latest_card = bot._patch_card_message.await_args.args
reasoning_values = [
- option["value"] for option in self._find_select(latest_card, "route_effort:claude")["options"]
+ option["value"] for option in self._find_select(latest_card, "route_effort:id-claude")["options"]
]
self.assertIn("max", reasoning_values)
@@ -67,37 +67,37 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
bot = self._make_bot()
bot._on_routing_update = AsyncMock()
routing = RoutingModalData(
- registered_backends=["codex"],
- current_backend="codex",
+ agents=[AgentChoice("id-codex", "codex", "codex")],
+ current_agent="id-codex",
current_routing=RoutingSettings(agent_name="codex", model="gpt-5.1", codex_agent="reviewer"),
)
bot._routing_cache["chat:user"] = {"routing": routing, "drafts": {}}
context = MessageContext(user_id="user", channel_id="chat", platform="lark", platform_specific={"is_dm": False})
await bot._handle_routing_form_submit(
- context, {"route_model:codex": "gpt-5.4", "route_effort:codex": "high"}, "routing_submit:codex"
+ context, {"route_model:id-codex": "gpt-5.4", "route_effort:id-codex": "high"}, "routing_submit:id-codex"
)
bot._on_routing_update.assert_awaited_once_with(
user_id="user",
channel_id="chat",
- backend="codex",
+ agent_id="id-codex",
variant="reviewer",
model="gpt-5.4",
reasoning_effort="high",
is_dm=False,
)
- async def test_an_options_card_saves_its_own_backend_after_another_was_opened(self):
+ async def test_an_options_card_saves_its_own_agent_after_another_was_opened(self):
bot = self._make_bot()
bot._send_card_to_channel = AsyncMock()
bot._on_routing_update = AsyncMock()
context = MessageContext(user_id="user", channel_id="chat", platform="lark", platform_specific={"is_dm": False})
await bot.open_routing_modal(trigger_id=context, channel_id="chat", routing=self._claude_routing())
- # The step-1 card stays active, so it can open a second backend's card before the first is submitted.
- await bot._handle_routing_backend_select(context, {"backend": "claude"})
+ # The step-1 card stays active, so it can open a second Agent's card before the first is submitted.
+ await bot._handle_routing_backend_select(context, {"agent": "id-claude"})
claude_card = bot._send_card_to_channel.await_args.args[1]
- await bot._handle_routing_backend_select(context, {"backend": "codex"})
+ await bot._handle_routing_backend_select(context, {"agent": "id-codex"})
elements = claude_card["body"]["elements"][0]["elements"]
button = next(element for element in elements if element["tag"] == "button")
@@ -108,7 +108,7 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
)
kwargs = bot._on_routing_update.await_args.kwargs
- self.assertEqual((kwargs["backend"], kwargs["model"]), ("claude", "claude-sonnet-4-5"))
+ self.assertEqual((kwargs["agent_id"], kwargs["model"]), ("id-claude", "claude-sonnet-4-5"))
async def test_settings_submit_binds_optional_fields_by_name(self):
bot = self._make_bot()
diff --git a/tests/test_im_backend_registration.py b/tests/test_im_backend_registration.py
index 0d6faf09d..f1e1b0732 100644
--- a/tests/test_im_backend_registration.py
+++ b/tests/test_im_backend_registration.py
@@ -12,7 +12,7 @@ import pytest
from config.v2_config import DiscordConfig, LarkConfig, SlackConfig, TelegramConfig
from config.v2_settings import RoutingSettings
-from core.modals import STORED_OPTION_VALUE, BackendRouteMenu, RouteOption, RoutingModalData
+from core.modals import STORED_OPTION_VALUE, AgentChoice, BackendRouteMenu, RouteOption, RoutingModalData
from modules.agents.catalog import display_name_for_backend
from modules.im import MessageContext
from modules.im.discord import DiscordBot
@@ -39,7 +39,11 @@ def _options(payload):
async def test_agent_picker_includes_vibey_but_native_resume_excludes_it(platform):
routing = dict(
channel_id="fixture-channel",
- routing=RoutingModalData(registered_backends=["codex", "vibey"], current_backend="vibey", current_routing=None),
+ routing=RoutingModalData(
+ agents=[AgentChoice("id-codex", "codex", "codex"), AgentChoice("id-vibey", "vibey", "vibey")],
+ current_agent="id-vibey",
+ current_routing=None,
+ ),
)
if platform == "slack":
bot = SlackBot(SlackConfig(bot_token="fixture-token"))
@@ -61,8 +65,8 @@ async def test_agent_picker_includes_vibey_but_native_resume_excludes_it(platfor
bot._send_card_to_channel = AsyncMock()
await bot.open_routing_modal(trigger_id=None, **routing)
options = list(_options(bot._send_card_to_channel.await_args.args[1]))
- vibey = next(option for option in options if option["value"] == "vibey")
- assert "Vibey" in json.dumps(vibey)
+ vibey = next(option for option in options if option["value"] == "id-vibey")
+ assert "Vibey" in json.dumps(vibey, ensure_ascii=False)
bot._controller = SimpleNamespace(agent_service=SimpleNamespace(agents={"codex": object(), "vibey": object()}))
await bot.open_resume_session_modal(
@@ -110,15 +114,16 @@ def _route(bot, backend, stored_model="model-b"):
codex_agent="reviewer" if backend == "codex" else None,
)
data = RoutingModalData(
- registered_backends=[backend, "opencode"], current_backend=backend, current_routing=stored,
+ agents=[AgentChoice(f"id-{backend}", backend, backend), AgentChoice("id-opencode", "opencode", "opencode")],
+ current_agent=f"id-{backend}",
+ current_routing=stored,
menus={backend: menu},
)
- menu.stored = data.stored_draft(backend) # as the settings handler sets it
return data, long_id
class _Form:
- """Drive one platform's routing form through its own entry points: open, change the model, save."""
+ """Drive one platform's routing form through its own entry points: open, switch Agent, change model, save."""
def __init__(self, platform, backend, stored_model="model-b"):
self.platform = platform
@@ -135,6 +140,7 @@ class _Form:
else:
self.bot = FeishuBot(LarkConfig(app_id="fixture-app", app_secret="fixture-secret"))
self.data, self.long_id = _route(self.bot, backend, stored_model)
+ self.agent_id = f"id-{backend}"
async def open(self):
bot, context = self.bot, self.context
@@ -155,9 +161,49 @@ class _Form:
else:
bot._send_card_to_channel = AsyncMock()
await bot.open_routing_modal(trigger_id=context, channel_id=context.channel_id, routing=self.data)
- await bot._handle_routing_backend_select(context, {"backend": self.backend})
+ await bot._handle_routing_backend_select(context, {"agent": self.agent_id})
self.card = bot._send_card_to_channel.await_args.args[1]
+ async def switch_agent(self, agent_id):
+ bot, context = self.bot, self.context
+ self.agent_id = agent_id
+ self.backend = self.data.agent(agent_id).backend
+ if self.platform == "slack":
+ self.view["state"] = _shown_state(self.view)
+ self.view["state"]["values"]["agent_block"]["agent_select"] = {"selected_option": {"value": agent_id}}
+ selection = parse_routing_modal_selection(
+ view=self.view, action={"action_id": "agent_select", "selected_option": {"value": agent_id}}
+ )
+ self.view = bot._build_routing_modal_view(
+ channel_id=context.channel_id, routing=self.data,
+ selected_agent=selection.selected_agent, draft=selection.draft,
+ )
+ elif self.platform == "discord":
+ select = next(c for c in self.view.children if getattr(c, "placeholder", None) == bot._t("modal.routing.selectAgent"))
+ select._values = [agent_id]
+ await select.callback(SimpleNamespace(response=SimpleNamespace(edit_message=AsyncMock())))
+ elif self.platform == "telegram":
+ index = [agent.id for agent in self.data.agent_options()].index(agent_id)
+ await bot._handle_routing_callback(context, f"tg_route:agent:{index}")
+ else:
+ await bot._handle_routing_backend_select(context, {"agent": agent_id})
+ self.card = bot._send_card_to_channel.await_args.args[1]
+
+ def default_text(self, field):
+ """The text of the Default option the form shows for ``field``."""
+ if self.platform == "slack":
+ block = next(b for b in self.view["blocks"] if str(b.get("block_id", "")).startswith(f"route_{field}:"))
+ return block["element"]["options"][0]["text"]["text"]
+ if self.platform == "discord":
+ key = {"model": "selectModel", "effort": "selectReasoningEffort"}[field]
+ select = next(c for c in self.view.children if getattr(c, "placeholder", None) == self.bot._t(f"modal.routing.{key}"))
+ return select.options[0].label
+ if self.platform == "telegram":
+ state = self.bot._routing_states[self.bot._interaction_scope_key(self.context)]
+ return self.bot._routing_picker_options(state, {"effort": "reasoning_effort"}.get(field, field))[0][0]
+ select = next(e for e in self.card["body"]["elements"][0]["elements"] if e.get("name") == f"route_{field}:{self.agent_id}")
+ return select["options"][0]["text"]["content"]
+
def offered(self, field):
"""The option values the form offers for ``field`` (variant, model or effort) right now."""
if self.platform == "slack":
@@ -172,7 +218,7 @@ class _Form:
state = self.bot._routing_states[self.bot._interaction_scope_key(self.context)]
name = {"effort": "reasoning_effort"}.get(field, field)
return [value or "__default__" for _, value in self.bot._routing_picker_options(state, name)]
- name = f"route_{field}:{self.backend}"
+ name = f"route_{field}:{self.agent_id}"
select = next(e for e in self.card["body"]["elements"][0]["elements"] if e.get("name") == name)
return [option["value"] for option in select["options"]]
@@ -184,12 +230,12 @@ class _Form:
model_block = next(key for key in self.view["state"]["values"] if key.startswith("route_model:"))
self.view["state"]["values"][model_block]["route_model"] = {"selected_option": {"value": model}}
selection = parse_routing_modal_selection(view=self.view, action={
- "action_id": "route_model", "block_id": f"route_model:{self.backend}",
+ "action_id": "route_model", "block_id": f"route_model:{self.agent_id}",
"selected_option": {"value": model},
})
self.view = bot._build_routing_modal_view(
channel_id=context.channel_id, routing=self.data,
- selected_backend=selection.selected_backend, draft=selection.draft,
+ selected_agent=selection.selected_agent, draft=selection.draft,
)
elif self.platform == "discord":
prefix = bot._t("modal.routing.selectModel")
@@ -204,7 +250,7 @@ class _Form:
else:
bot._patch_card_message = AsyncMock()
assert await bot._handle_routing_select_change(
- context, {"name": f"route_model:{self.backend}", "option": model}
+ context, {"name": f"route_model:{self.agent_id}", "option": model}
)
self.card = bot._patch_card_message.await_args.args[1]
@@ -236,7 +282,7 @@ class _Form:
)
self.saved.assert_awaited_once()
kwargs = self.saved.await_args.kwargs
- return kwargs["backend"], kwargs["variant"], kwargs["model"], kwargs["reasoning_effort"]
+ return kwargs["agent_id"], kwargs["variant"], kwargs["model"], kwargs["reasoning_effort"]
def _shown_state(view):
@@ -264,7 +310,7 @@ async def test_a_route_offers_its_backends_menu_and_saving_unchanged_keeps_it(pl
if backend == "codex":
assert form.offered("variant") == ["__default__", "builder", "reviewer"]
stored_variant = "reviewer" if backend == "codex" else None
- assert await form.save() == (backend, stored_variant, "model-b", "max")
+ assert await form.save() == (f"id-{backend}", stored_variant, "model-b", "max")
@pytest.mark.asyncio
@@ -276,7 +322,7 @@ async def test_a_model_change_offers_that_models_efforts_and_clears_the_effort(p
await form.change_model("model-a")
assert form.offered("effort") == ["__default__", "low"]
- assert await form.save() == ("vibey", None, "model-a", None)
+ assert await form.save() == ("id-vibey", None, "model-a", None)
@pytest.mark.asyncio
@@ -286,8 +332,26 @@ async def test_reselecting_a_stored_model_the_platform_cannot_carry_keeps_its_ef
form = _Form(platform, "vibey", stored_model=long_id)
await form.open()
- await form.change_model(form.data.menu("vibey").shown_value(long_id))
+ await form.change_model(form.data.menu(form.agent_id).shown_value(long_id))
# Slack hands the stand-in to the settings handler, which resolves it to the stored model.
saved_model = STORED_OPTION_VALUE if platform == "slack" else long_id
- assert await form.save() == ("vibey", None, saved_model, "max")
+ assert await form.save() == ("id-vibey", None, saved_model, "max")
+
+
[email protected]("platform", PLATFORMS)
+async def test_a_route_names_the_chosen_agent_and_default_is_that_agents_own_model(platform):
+ """The form lists Agents as the Web does, including a user Agent that shares a built-in Agent's backend."""
+ form = _Form(platform, "codex")
+ form.data.agents.append(AgentChoice("id-reviewer", "reviewer", "codex", model="model-a"))
+ await form.open()
+
+ await form.switch_agent("id-reviewer")
+
+ assert form.default_text("model").endswith("Model A") # Default · the reviewer Agent's own model
+ assert form.offered("effort") == ["__default__", "low"] # model-a's efforts, inherited with it
+ # The stored model and effort were the codex Agent's; the reviewer starts at its own Defaults.
+ agent_id, variant, model, effort = await form.save()
+ assert (agent_id, model, effort) == ("id-reviewer", None, None)
+ assert variant == "reviewer" # Codex's native agent is stored per backend, so it carries over
diff --git a/tests/test_route_menu.py b/tests/test_route_menu.py
index 40f97e528..1e18b9adf 100644
--- a/tests/test_route_menu.py
+++ b/tests/test_route_menu.py
@@ -6,7 +6,15 @@ unchanged on some surfaces and not others.
"""
from config.v2_settings import RoutingSettings
-from core.modals import STORED_OPTION_VALUE, BackendRouteMenu, RouteDraft, RouteOption, RoutingModalData
+from core.modals import (
+ STORED_OPTION_VALUE,
+ AgentChoice,
+ BackendRouteMenu,
+ RouteDraft,
+ RouteOption,
+ RoutingModalData,
+ route_option_label,
+)
def _options(*values):
@@ -60,14 +68,56 @@ def test_efforts_follow_the_model_and_keep_a_stored_effort_the_menu_omits():
assert draft.with_model("a") == draft # picking the shown model again keeps its effort
-def test_the_stored_route_shows_only_on_its_own_backend():
- routing = RoutingSettings(agent_name="codex", model="gpt-5.4", reasoning_effort="high", claude_agent="helper")
- data = RoutingModalData(registered_backends=["claude", "codex", "vibey"], current_backend="codex", current_routing=routing)
+def _agents():
+ return [
+ AgentChoice("a-codex", "codex", "codex", model="gpt-5.4", reasoning_effort="medium"),
+ AgentChoice("a-reviewer", "reviewer", "codex", model="gpt-5.5"),
+ AgentChoice("a-claude", "claude", "claude"),
+ AgentChoice("a-vibey", "vibey", "vibey"),
+ ]
- assert data.stored_draft("codex") == RouteDraft(None, "gpt-5.4", "high")
- # Another backend keeps its own native agent but not the stored backend's model or effort.
- assert data.stored_draft("claude") == RouteDraft("helper", None, None)
- assert data.stored_draft("vibey") == RouteDraft()
+
+def test_the_stored_route_shows_only_on_its_own_agent():
+ routing = RoutingSettings(
+ agent_name="codex", model="gpt-5.6", reasoning_effort="high", codex_agent="builder", claude_agent="helper"
+ )
+ data = RoutingModalData(agents=_agents(), current_agent="a-codex", current_routing=routing)
+
+ assert data.stored_draft("a-codex") == RouteDraft("builder", "gpt-5.6", "high")
+ # Another Agent starts at Default, its own; a backend's native agent is stored per backend.
+ assert data.stored_draft("a-reviewer") == RouteDraft("builder", None, None)
+ assert data.stored_draft("a-claude") == RouteDraft("helper", None, None)
+ assert data.stored_draft("a-vibey") == RouteDraft()
# A route saved by an older release with backend-specific fields reads the same.
- legacy = RoutingSettings(agent_name="codex", codex_model="gpt-5.4", codex_reasoning_effort="high")
- assert RoutingModalData(["codex"], "codex", legacy).stored_draft("codex") == RouteDraft(None, "gpt-5.4", "high")
+ legacy = RoutingSettings(agent_name="codex", codex_model="gpt-5.6", codex_reasoning_effort="high")
+ assert RoutingModalData(_agents(), "a-codex", legacy).stored_draft("a-codex") == RouteDraft(None, "gpt-5.6", "high")
+
+
+def test_default_options_inherit_the_chosen_agents_own_model_and_effort():
+ menu = BackendRouteMenu(
+ "codex",
+ models=[RouteOption("gpt-5.4", "GPT-5.4"), RouteOption("gpt-5.5", "GPT-5.5")],
+ efforts={"gpt-5.4": _options("low", "medium"), "gpt-5.5": _options("high")},
+ )
+ data = RoutingModalData(agents=_agents(), current_agent="a-codex", current_routing=None, menus={"codex": menu})
+ translate = {"common.default": "Default", "reasoning.medium": "Medium"}.get
+
+ codex, reviewer = data.menu("a-codex"), data.menu("a-reviewer")
+ # Each Agent on one backend shares its lists, but Default means that Agent's own choice.
+ assert route_option_label(translate, codex.default_option("model")) == "Default · GPT-5.4"
+ assert route_option_label(translate, codex.default_option("reasoning_effort"), effort=True) == "Default · Medium"
+ assert route_option_label(translate, reviewer.default_option("model")) == "Default · GPT-5.5"
+ assert reviewer.default_option("reasoning_effort").label == ""
+ assert _values(codex.effort_options(None, None)) == ["low", "medium"]
+ assert _values(reviewer.effort_options(None, None)) == ["high"]
+
+
+def test_the_agent_select_keeps_the_scopes_agent_within_its_cap():
+ agents = [AgentChoice(f"a{i}", f"agent-{i:02}", "vibey") for i in range(30)]
+ data = RoutingModalData(agents=agents, current_agent="a29", current_routing=None, agent_option_limit=25)
+
+ shown = data.agent_options()
+ assert len(shown) == 25 and shown[-1].id == "a29"
+ assert data.shown_agent("missing") == "a29" and data.shown_agent("a3") == "a3"
+ # Agent names have no length bound; the label every platform shows does.
+ assert len(AgentChoice("a", "n" * 5000, "vibey").label) < 100
diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.py
index f3e0e96a1..f36f9f46b 100644
--- a/tests/test_settings_handler.py
+++ b/tests/test_settings_handler.py
@@ -8,7 +8,14 @@ from unittest.mock import patch
from config.v2_settings import RoutingSettings
from core.handlers.settings_handler import SettingsHandler
-from core.modals import STORED_OPTION_VALUE, BackendRouteMenu, RouteOption, RoutingModalData, RoutingModalSelection
+from core.modals import (
+ STORED_OPTION_VALUE,
+ AgentChoice,
+ BackendRouteMenu,
+ RouteOption,
+ RoutingModalData,
+ RoutingModalSelection,
+)
from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS
from modules.im import MessageContext
@@ -17,6 +24,26 @@ def _values(options) -> list[str]:
return [option.value for option in options]
+class _AgentStore:
+ """The built-in Agent of every backend, as ``VibeAgentStore`` returns them (id ``id-<backend>``)."""
+
+ def __init__(self, *extra):
+ self.agents = [
+ SimpleNamespace(id=f"id-{backend}", name=backend, backend=backend, model=None, reasoning_effort=None,
+ enabled=True)
+ for backend in AGENT_BACKENDS
+ ] + list(extra)
+
+ def list_agents(self, *, include_disabled=True, **_kwargs):
+ return [agent for agent in self.agents if include_disabled or agent.enabled]
+
+ def require_reference_by_id(self, agent_id):
+ return next(agent for agent in self.agents if agent.id == agent_id)
+
+ def get(self, name):
+ return next((agent for agent in self.agents if agent.name == name), None)
+
+
class _StubSettingsManager:
def __init__(self, routing: RoutingSettings | None):
self.routing = routing
@@ -37,6 +64,7 @@ def _make_handler(settings_manager: _StubSettingsManager) -> tuple[SettingsHandl
config=SimpleNamespace(platform="telegram", language="en"),
im_client=SimpleNamespace(send_message=send_message),
settings_manager=settings_manager,
+ vibe_agent_store=_AgentStore(),
_get_settings_key=lambda context: "telegram::-100123",
_get_lang=lambda: "en",
)
@@ -135,6 +163,7 @@ def _make_flat_scope_handler(
settings_manager=settings_manager,
sessions=sessions,
session_handler=SimpleNamespace(get_base_session_id=lambda context: f"{platform}_58181121"),
+ vibe_agent_store=_AgentStore(),
_get_settings_key=lambda context: "58181121",
_get_session_key=lambda context: f"{platform}::user::58181121",
_get_lang=lambda: "zh",
@@ -157,7 +186,7 @@ def test_handle_routing_update_preserves_existing_codex_agent_when_omitted() ->
handler.handle_routing_update(
user_id="42",
channel_id="-100123",
- backend="codex",
+ agent_id="id-codex",
model="gpt-5.4",
reasoning_effort="high",
notify_user=False,
@@ -189,7 +218,7 @@ def test_handle_routing_update_allows_explicit_codex_agent_clear() -> None:
handler.handle_routing_update(
user_id="42",
channel_id="-100123",
- backend="codex",
+ agent_id="id-codex",
variant=None,
model="gpt-5.4",
reasoning_effort="high",
@@ -214,7 +243,7 @@ def test_handle_routing_update_handles_first_codex_save_without_existing_routing
handler.handle_routing_update(
user_id="42",
channel_id="-100123",
- backend="codex",
+ agent_id="id-codex",
model="gpt-5.4",
reasoning_effort="high",
notify_user=False,
@@ -244,7 +273,7 @@ def test_handle_routing_update_preserves_catalog_claude_effort() -> None:
handler.handle_routing_update(
user_id="42",
channel_id="-100123",
- backend="claude",
+ agent_id="id-claude",
variant="reviewer",
model="claude-future-6",
reasoning_effort="ultra",
@@ -259,31 +288,38 @@ def test_handle_routing_update_preserves_catalog_claude_effort() -> None:
send_message.assert_not_awaited()
-def test_handle_routing_update_saves_vibey_model_and_effort_on_the_vibey_route() -> None:
- settings_manager = _StubSettingsManager(RoutingSettings(agent_name="opencode", model="openai/gpt-5"))
+def test_handle_routing_update_routes_to_the_chosen_agent_with_its_overrides() -> None:
+ settings_manager = _StubSettingsManager(
+ RoutingSettings(agent_name="opencode", model="openai/gpt-5", opencode_agent="build", claude_agent="helper")
+ )
handler, send_message = _make_handler(settings_manager)
- handler.controller.vibe_agent_store = SimpleNamespace(routing_name_for_backend=lambda backend: f"{backend}-agent")
+ # A user Agent on a backend whose built-in Agent is also listed: the route names this one, not the built-in.
+ handler.controller.vibe_agent_store.agents.append(
+ SimpleNamespace(id="id-pm", name="pm-claude", backend="claude", model="claude-opus-5-5", enabled=True)
+ )
asyncio.run(
handler.handle_routing_update(
user_id="42",
channel_id="-100123",
- backend="vibey",
- model="claude-opus-5-5",
- reasoning_effort="xhigh",
+ agent_id="id-pm",
+ model="claude-sonnet-5-5",
+ reasoning_effort="high",
platform="telegram",
)
)
saved = settings_manager.saved_routing
- assert (saved.agent_name, saved.model, saved.reasoning_effort) == ("vibey-agent", "claude-opus-5-5", "xhigh")
+ assert (saved.agent_name, saved.model, saved.reasoning_effort) == ("pm-claude", "claude-sonnet-5-5", "high")
+ # Native agents stay per backend, the chosen Agent's included, since the form omitted it.
+ assert (saved.opencode_agent, saved.claude_agent) == ("build", "helper")
text = send_message.await_args.args[1]
- assert "claude-opus-5-5" in text and "xhigh" in text
+ assert "pm-claude" in text and "claude-sonnet-5-5" in text
# An opaque id of any length still yields a confirmation every platform can send.
asyncio.run(
handler.handle_routing_update(
- user_id="42", channel_id="-100123", backend="vibey", model="m" * 5000, platform="telegram",
+ user_id="42", channel_id="-100123", agent_id="id-vibey", model="m" * 5000, platform="telegram",
)
)
assert settings_manager.saved_routing.model == "m" * 5000
@@ -298,19 +334,15 @@ def test_saving_an_unchanged_slack_form_keeps_a_stored_model_slack_cannot_show()
long_id = "vendor/" + "x" * 160
settings_manager = _StubSettingsManager(RoutingSettings(agent_name="vibey", model=long_id, reasoning_effort="high"))
handler, _ = _make_handler(settings_manager)
- handler.controller.vibe_agent_store = SimpleNamespace(
- routing_name_for_backend=lambda backend: backend, get=lambda name: SimpleNamespace(backend="vibey")
- )
bot = SlackBot(SlackConfig(bot_token="fixture-token"))
bot._on_routing_update = handler.handle_routing_update
- data = RoutingModalData(["vibey"], "vibey", settings_manager.routing)
+ data = RoutingModalData([AgentChoice("id-vibey", "vibey", "vibey")], "id-vibey", settings_manager.routing)
data.menus["vibey"] = BackendRouteMenu(
"vibey",
models=[RouteOption("model-a", "Model A")],
efforts={"": [RouteOption("high", "High")]},
option_limit=bot.route_option_limit,
value_limit=bot.route_option_value_limit,
- stored=data.stored_draft("vibey"),
)
view = bot._build_routing_modal_view(channel_id="-100123", routing=data)
view["state"] = {"values": {
@@ -325,19 +357,16 @@ def test_saving_an_unchanged_slack_form_keeps_a_stored_model_slack_cannot_show()
assert (saved.agent_name, saved.model, saved.reasoning_effort) == ("vibey", long_id, "high")
-def test_a_stored_stand_in_resolves_only_against_a_stored_route_on_its_backend() -> None:
+def test_a_stored_stand_in_resolves_only_against_a_stored_route_on_its_agent() -> None:
# The form rendered while the route was on Vibey; by the time it saves, the route may be on Codex.
for stored_agent, expected in (("vibey", ("long-vibey-model", "high")), ("codex", (None, None))):
stored = RoutingSettings(agent_name=stored_agent, model=f"long-{stored_agent}-model", reasoning_effort="high")
settings_manager = _StubSettingsManager(stored)
handler, _ = _make_handler(settings_manager)
- handler.controller.vibe_agent_store = SimpleNamespace(
- routing_name_for_backend=lambda backend: backend, get=lambda name: SimpleNamespace(backend=name)
- )
asyncio.run(
handler.handle_routing_update(
- user_id="42", channel_id="-100123", backend="vibey",
+ user_id="42", channel_id="-100123", agent_id="id-vibey",
model=STORED_OPTION_VALUE, reasoning_effort=STORED_OPTION_VALUE,
notify_user=False, platform="telegram",
)
@@ -354,7 +383,7 @@ def test_handle_routing_update_warns_flat_scope_with_existing_backend_session()
handler.handle_routing_update(
user_id="58181121",
channel_id="58181121",
- backend="claude",
+ agent_id="id-claude",
variant=None,
model=None,
platform="telegram",
@@ -375,7 +404,7 @@ def test_handle_routing_update_warns_wechat_flat_scope_with_existing_backend_ses
handler.handle_routing_update(
user_id="58181121",
channel_id="58181121",
- backend="claude",
+ agent_id="id-claude",
variant=None,
model=None,
platform="wechat",
@@ -388,6 +417,24 @@ def test_handle_routing_update_warns_wechat_flat_scope_with_existing_backend_ses
assert sessions.calls == [("wechat::user::58181121", "wechat_58181121")]
+def test_handle_routing_update_warns_flat_scope_switching_to_another_agent_on_the_same_backend() -> None:
+ handler, send_message, _sessions = _make_flat_scope_handler(
+ row={"agent_name": "claude", "agent_backend": "claude", "agent_variant": "claude", "model": "", "reasoning_effort": ""}
+ )
+ handler.controller.vibe_agent_store.agents.append(
+ SimpleNamespace(id="id-pm", name="pm-claude", backend="claude", model=None, reasoning_effort=None, enabled=True)
+ )
+
+ asyncio.run(
+ handler.handle_routing_update(
+ user_id="58181121", channel_id="58181121", agent_id="id-pm", platform="telegram", is_dm=True,
+ )
+ )
+
+ # The scope's session keeps the Agent it started with, so the new one needs /new.
+ assert "请使用 /new 命令创建新会话" in send_message.await_args.args[1]
+
+
def test_handle_routing_update_does_not_warn_flat_scope_same_backend_model_change() -> None:
handler, send_message, sessions = _make_flat_scope_handler(
row={
@@ -403,7 +450,7 @@ def test_handle_routing_update_does_not_warn_flat_scope_same_backend_model_chang
handler.handle_routing_update(
user_id="58181121",
channel_id="58181121",
- backend="claude",
+ agent_id="id-claude",
variant=None,
model="claude-opus-4-1",
platform="telegram",
@@ -431,7 +478,7 @@ def test_handle_routing_update_does_not_warn_flat_scope_same_backend_reasoning_c
handler.handle_routing_update(
user_id="58181121",
channel_id="58181121",
- backend="claude",
+ agent_id="id-claude",
variant=None,
model="claude-sonnet-4-5",
reasoning_effort="high",
@@ -460,7 +507,7 @@ def test_handle_routing_update_does_not_warn_flat_scope_same_session_target() ->
handler.handle_routing_update(
user_id="58181121",
channel_id="58181121",
- backend="claude",
+ agent_id="id-claude",
variant=None,
model="claude-sonnet-4-5",
platform="telegram",
@@ -480,7 +527,7 @@ def test_handle_routing_update_does_not_warn_when_flat_scope_has_no_session() ->
handler.handle_routing_update(
user_id="58181121",
channel_id="58181121",
- backend="claude",
+ agent_id="id-claude",
variant=None,
model=None,
platform="telegram",
@@ -501,7 +548,7 @@ def test_handle_routing_update_does_not_warn_threaded_scope() -> None:
handler.handle_routing_update(
user_id="U123",
channel_id="D123",
- backend="claude",
+ agent_id="id-claude",
variant=None,
model=None,
platform="slack",
@@ -555,8 +602,9 @@ class _FakeOpenCodeAgent:
yield self.server
-def _make_routing_handler() -> tuple[SettingsHandler, _FakeOpenCodeServer]:
+def _make_routing_handler(current: str = "opencode") -> tuple[SettingsHandler, _FakeOpenCodeServer]:
server = _FakeOpenCodeServer()
+ store = _AgentStore()
controller = SimpleNamespace(
config=SimpleNamespace(
platform="slack",
@@ -567,7 +615,9 @@ def _make_routing_handler() -> tuple[SettingsHandler, _FakeOpenCodeServer]:
settings_manager=_RoutingSettingsManager(),
_get_settings_key=lambda context: "slack::D0APS47LPU2",
_get_lang=lambda: "en",
- resolve_agent_for_context=lambda context: "opencode",
+ vibe_agent_store=store,
+ # The Agent the scope runs now; tests point it elsewhere through ``controller.current``.
+ current=current,
get_cwd=lambda context: "/tmp/workspace",
agent_service=SimpleNamespace(
agents={
@@ -576,6 +626,7 @@ def _make_routing_handler() -> tuple[SettingsHandler, _FakeOpenCodeServer]:
}
),
)
+ controller.resolve_vibe_agent_for_context = lambda context, required=True: store.get(controller.current)
return SettingsHandler(controller), server
@@ -590,8 +641,9 @@ def test_gather_routing_modal_data_only_fetches_current_backend() -> None:
):
data = asyncio.run(handler._gather_routing_modal_data(context))
- assert data.current_backend == "opencode"
- assert data.registered_backends == list(AGENT_BACKENDS) # Catalog order: the built-in Avibe Agent first.
+ assert data.current_agent == "id-opencode"
+ # Every enabled Agent on a runnable backend, as the Web route picker lists them.
+ assert [agent.id for agent in data.agents] == [f"id-{backend}" for backend in AGENT_BACKENDS]
assert server.calls == [
"current_server",
"agents:/tmp/workspace",
@@ -631,9 +683,9 @@ def test_gather_routing_modal_data_fetches_selected_backend_on_modal_update() ->
), patch("vibe.api.codex_models", side_effect=AssertionError("codex should not be fetched")), patch(
"vibe.api.codex_agents", side_effect=AssertionError("codex should not be fetched")
):
- data = asyncio.run(handler._gather_routing_modal_data(context, selected_backend="claude"))
+ data = asyncio.run(handler._gather_routing_modal_data(context, selected_agent="id-claude"))
- assert data.current_backend == "opencode"
+ assert data.current_agent == "id-opencode"
assert _values(data.menus["claude"].variants) == ["reviewer"]
assert _values(data.menus["claude"].models) == ["claude-sonnet-4-6"]
assert server.calls == []
@@ -661,7 +713,6 @@ def test_gather_routing_modal_data_prefetches_all_backends_when_requested() -> N
):
data = asyncio.run(handler._gather_routing_modal_data(context, include_all_backend_data=True))
- assert data.registered_backends == list(AGENT_BACKENDS)
menus = data.menus
assert {backend: _values(menu.variants) for backend, menu in menus.items()} == {
"vibey": [], "opencode": ["build"], "claude": ["reviewer"], "codex": ["builder"],
@@ -694,6 +745,12 @@ def test_opencode_route_menu_fits_the_platforms_cap_and_is_whole_without_one() -
}
for p in range(30)
]
+ # An OpenCode Agent whose own model sits past Discord's cap, with efforts of its own.
+ providers[29]["models"]["m2"]["variants"] = {"max": {}}
+ handler.controller.vibe_agent_store.agents.append(
+ SimpleNamespace(id="id-planner", name="planner", backend="opencode", model="p29/m2", reasoning_effort=None,
+ enabled=True)
+ )
server.get_available_models = AsyncMock(return_value={"providers": providers})
context = MessageContext(user_id="U1", channel_id="D0APS47LPU2", platform="discord")
menus = {}
@@ -705,12 +762,19 @@ def test_opencode_route_menu_fits_the_platforms_cap_and_is_whole_without_one() -
capped = menus[25].model_options(None)
assert len(capped) == 24 and all("/m" in option.value for option in capped)
+ assert "p29/m2" not in {option.value for option in capped}
+ # Its Default still offers that model's efforts, not a generic ladder.
+ planner = RoutingModalData(
+ agents=[AgentChoice("id-planner", "planner", "opencode", model="p29/m2")], current_agent="id-planner",
+ current_routing=None, menus={"opencode": menus[25]},
+ )
+ assert _values(planner.menu("id-planner").effort_options(None, None)) == ["max"]
assert len(menus[None].model_options(None)) == 270
def test_gather_routing_modal_data_reads_vibey_menu_from_model_hub() -> None:
handler, server = _make_routing_handler()
- handler.controller.resolve_agent_for_context = lambda context: "vibey"
+ handler.controller.current = "vibey"
catalog = [
{"id": "model-a", "display_name": "Model A", "routeable": True, "supports_reasoning": True,
"reasoning_efforts": ["low", "high", "max"], "effort_menu": {"omitted": ["max"], "not_on": {}}},
@@ -720,23 +784,22 @@ def test_gather_routing_modal_data_reads_vibey_menu_from_model_hub() -> None:
]
read_agent_sources = AsyncMock(return_value={"backend": "vibey", "catalog_models": catalog})
handler.controller.model_hub_service = SimpleNamespace(read_agent_sources=read_agent_sources)
- handler.controller.vibe_agent_store = SimpleNamespace(
- get_builtin_default_agent_for_backend=lambda backend, enabled_only=True: SimpleNamespace(model="model-a"),
- )
- context = MessageContext(user_id="U1", channel_id="D0APS47LPU2", platform="slack")
+ # The platform's declared select caps size every menu and the Agent select.
+ handler._get_im_client = lambda context: SimpleNamespace(route_option_limit=25, route_option_value_limit=100)
+ context = MessageContext(user_id="U1", channel_id="D0APS47LPU2", platform="discord")
data = asyncio.run(handler._gather_routing_modal_data(context))
read_agent_sources.assert_awaited_once_with("vibey")
- assert data.current_backend == "vibey"
+ assert data.current_agent == "id-vibey"
menu = data.menus["vibey"]
assert menu.models == [RouteOption("model-a", "Model A"), RouteOption("model-b", "model-b")]
- # Model Hub's omitted efforts are not offered; a route without its own model inherits the Vibey Agent's.
+ # Model Hub's omitted efforts are not offered.
assert {model: _values(efforts) for model, efforts in menu.efforts.items()} == {
"model-a": ["low", "high"],
"model-b": [],
- "": ["low", "high"],
}
+ assert (menu.option_limit, menu.value_limit, data.agent_option_limit) == (25, 100, 25)
assert server.calls == []
@@ -748,7 +811,7 @@ def test_gather_routing_modal_data_hides_disabled_backends() -> None:
data = asyncio.run(handler._gather_routing_modal_data(context))
- assert data.registered_backends == ["vibey", "opencode"]
+ assert [agent.id for agent in data.agents] == ["id-vibey", "id-opencode"]
assert server.calls == [
"current_server",
"agents:/tmp/workspace",
@@ -761,7 +824,7 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_is
handler, server = _make_routing_handler()
handler.config.claude.enabled = False
context = MessageContext(user_id="U1", channel_id="D0APS47LPU2", platform="slack")
- handler.controller.resolve_agent_for_context = lambda context: "claude"
+ handler.controller.current = "claude"
with patch("vibe.api.claude_models", side_effect=AssertionError("claude should not be fetched")), patch(
"vibe.api.claude_agents", side_effect=AssertionError("claude should not be fetched")
@@ -770,9 +833,9 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_is
):
data = asyncio.run(handler._gather_routing_modal_data(context))
- # Listed first, the built-in backend is still not the fallback while another is enabled.
- assert data.current_backend == "opencode"
- assert data.registered_backends == ["vibey", "opencode", "codex"]
+ # Listed first, the built-in backend's Agent is still not the fallback while another is listed.
+ assert data.current_agent == "id-opencode"
+ assert [agent.id for agent in data.agents] == ["id-vibey", "id-opencode", "id-codex"]
assert _values(data.menus["opencode"].variants) == ["build"]
assert server.calls == [
"current_server",
@@ -782,8 +845,8 @@ def test_gather_routing_modal_data_falls_back_to_visible_backend_when_current_is
]
-def test_slack_backend_switch_back_shows_the_stored_route_not_blanks() -> None:
- """Switching the Slack modal away from the stored backend and back must not blank what saving would persist."""
+def test_slack_agent_switch_back_shows_the_stored_route_not_blanks() -> None:
+ """Switching the Slack modal away from the stored Agent and back must not blank what saving would persist."""
from config.v2_config import SlackConfig
from modules.im.slack import SlackBot
from modules.im.slack_modal import parse_routing_modal_selection
@@ -791,7 +854,7 @@ def test_slack_backend_switch_back_shows_the_stored_route_not_blanks() -> None:
handler, _server = _make_routing_handler()
routing = RoutingSettings(agent_name="vibey", model="model-b", reasoning_effort="high")
handler.settings_manager = SimpleNamespace(get_channel_routing=lambda settings_key: routing)
- handler.controller.resolve_agent_for_context = lambda context: "vibey"
+ handler.controller.current = "vibey"
catalog = [
{"id": model_id, "routeable": True, "reasoning_efforts": ["low", "high"], "effort_menu": {"omitted": []}}
for model_id in ("model-a", "model-b")
@@ -804,18 +867,19 @@ def test_slack_backend_switch_back_shows_the_stored_route_not_blanks() -> None:
bot.web_client = SimpleNamespace(views_update=AsyncMock())
handler._get_im_client = lambda context: bot
# The modal as Slack holds it after a switch to OpenCode: it has no Vibey controls.
+ agents = [AgentChoice("id-vibey", "vibey", "vibey"), AgentChoice("id-opencode", "opencode", "opencode")]
view = bot._build_routing_modal_view(
channel_id="D0APS47LPU2",
- routing=RoutingModalData(registered_backends=["vibey", "opencode"], current_backend="vibey", current_routing=routing),
- selected_backend="opencode",
+ routing=RoutingModalData(agents=agents, current_agent="id-vibey", current_routing=routing),
+ selected_agent="id-opencode",
)
view["state"] = {"values": {
block["block_id"]: {block["element"]["action_id"]: {"selected_option": block["element"]["initial_option"]}}
for block in view["blocks"] if block["type"] == "input"
}}
- view["state"]["values"]["backend_block"]["backend_select"] = {"selected_option": {"value": "vibey"}}
+ view["state"]["values"]["agent_block"]["agent_select"] = {"selected_option": {"value": "id-vibey"}}
selection = parse_routing_modal_selection(
- view=view, action={"action_id": "backend_select", "selected_option": {"value": "vibey"}}
+ view=view, action={"action_id": "agent_select", "selected_option": {"value": "id-vibey"}}
)
asyncio.run(
@@ -831,20 +895,20 @@ def test_slack_backend_switch_back_shows_the_stored_route_not_blanks() -> None:
block["element"]["initial_option"]["value"]
for block in updated["blocks"] if block["type"] == "input"
}
- assert (shown["route_model:vibey"], shown["route_effort:vibey"]) == ("model-b", "high")
+ assert (shown["route_model:id-vibey"], shown["route_effort:id-vibey"]) == ("model-b", "high")
-def test_handle_routing_modal_update_uses_visible_current_backend() -> None:
+def test_handle_routing_modal_update_uses_the_visible_current_agent() -> None:
handler, _server = _make_routing_handler()
handler.config.claude.enabled = False
- handler.controller.resolve_agent_for_context = lambda context: "claude"
+ handler.controller.current = "claude"
update_calls = []
async def _update_routing_modal(**kwargs):
update_calls.append(kwargs)
handler._get_im_client = lambda context: SimpleNamespace(update_routing_modal=_update_routing_modal)
- selection = RoutingModalSelection(selected_backend="opencode")
+ selection = RoutingModalSelection(selected_agent="id-opencode")
asyncio.run(
handler.handle_routing_modal_update(
@@ -858,5 +922,5 @@ def test_handle_routing_modal_update_uses_visible_current_backend() -> None:
)
assert len(update_calls) == 1
- assert update_calls[0]["routing"].current_backend == "opencode"
- assert update_calls[0]["selected_backend"] == "opencode"
+ assert update_calls[0]["routing"].current_agent == "id-opencode"
+ assert update_calls[0]["selected_agent"] == "id-opencode"
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index c1262241e..0a37e232c 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -20,7 +20,7 @@ from core.processing_indicator import (
STOPPED_REACTION_EMOJI,
)
from core.message_context import resolve_context_thread_id
-from core.modals import RoutingModalData
+from core.modals import AgentChoice, RoutingModalData
from modules.agents.native_sessions import NativeResumeSession
from modules.agents.catalog import AGENT_BACKENDS
from modules.im import InlineButton, InlineKeyboard, MessageContext
@@ -1315,17 +1315,19 @@ def test_resume_callback_submits_selected_session() -> None:
)
-def _routing_state(context, registered, backend):
+def _routing_state(context, names, current):
+ """A routing form listing one Agent per name; a name that is no backend is a user Agent on Claude Code."""
from modules.im.telegram import _TelegramRoutingState
+ agents = [AgentChoice(f"id-{name}", name, name if name in AGENT_BACKENDS else "claude") for name in names]
return _TelegramRoutingState(
message_id="88",
channel_id=context.channel_id,
thread_id=None,
user_id=context.user_id,
is_dm=False,
- routing=RoutingModalData(registered_backends=list(registered), current_backend=backend, current_routing=None),
- backend=backend,
+ routing=RoutingModalData(agents=agents, current_agent=f"id-{current}", current_routing=None),
+ agent=f"id-{current}",
)
@@ -1339,17 +1341,18 @@ def _routing_context() -> MessageContext:
)
-def test_routing_state_marks_current_backend_in_first_row() -> None:
+def test_routing_state_marks_current_agent_in_first_row() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
- _, keyboard = bot._render_routing_state(_routing_state(_routing_context(), ROUTING_BACKENDS, "claude"))
+ _, keyboard = bot._render_routing_state(_routing_state(_routing_context(), ROUTING_BACKENDS, "opencode"))
+ # Agent names are free text, so the buttons carry list positions within Telegram's 64-byte callback data.
assert [button.callback_data for button in keyboard.buttons[0]] == [
- "tg_route:backend:vibey",
- "tg_route:backend:opencode",
- "tg_route:backend:claude",
+ "tg_route:agent:0",
+ "tg_route:agent:1",
+ "tg_route:agent:2",
]
- assert keyboard.buttons[0][2].text.startswith("☑️ ")
+ assert keyboard.buttons[0][1].text == "☑️ opencode"
def test_routing_summary_bounds_an_unbounded_model_label() -> None:
@@ -1367,57 +1370,45 @@ def test_routing_summary_bounds_an_unbounded_model_label() -> None:
assert all(len(button.text) <= 40 for row in keyboard.buttons for button in row)
-def test_routing_callback_backend_switches_without_nested_picker() -> None:
+def test_routing_callback_agent_switches_without_nested_picker() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = _routing_context()
bot._routing_states[bot._interaction_scope_key(context)] = _routing_state(context, ROUTING_BACKENDS, "opencode")
with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)) as edit_mock:
- asyncio.run(bot._handle_routing_callback(context, "tg_route:backend:claude"))
+ asyncio.run(bot._handle_routing_callback(context, "tg_route:agent:2"))
state = bot._routing_states[bot._interaction_scope_key(context)]
- assert state.backend == "claude"
+ assert state.agent == f"id-{ROUTING_BACKENDS[2]}"
assert state.picker_field is None
edit_mock.assert_awaited_once()
-def _with_extra(extra_backend):
- return [*ROUTING_BACKENDS, *([] if extra_backend in ROUTING_BACKENDS else [extra_backend])]
-
-
[email protected]("extra_backend", ["vibey", "extra"])
-def test_routing_state_keeps_backend_picker_entry_for_extra_backends(extra_backend) -> None:
+def test_routing_state_keeps_agent_picker_entry_for_more_agents() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
- text, keyboard = bot._render_routing_state(_routing_state(_routing_context(), _with_extra(extra_backend), extra_backend))
- if extra_backend == "vibey":
- assert "Vibey" in text
+ text, keyboard = bot._render_routing_state(_routing_state(_routing_context(), [*ROUTING_BACKENDS, "pm"], "pm"))
- assert [button.callback_data for button in keyboard.buttons[0]] == [
- "tg_route:backend:vibey",
- "tg_route:backend:opencode",
- "tg_route:backend:claude",
- ]
- assert keyboard.buttons[1][0].callback_data == "tg_route:field:backend"
+ assert "pm · Claude Code" in text
+ assert len(keyboard.buttons[0]) == 3
+ assert keyboard.buttons[1][0].callback_data == "tg_route:field:agent"
[email protected]("extra_backend", ["vibey", "extra"])
-def test_routing_callback_backend_picker_can_select_extra_backend(extra_backend) -> None:
+def test_routing_callback_agent_picker_can_select_an_agent_past_the_first_row() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = _routing_context()
bot._routing_states[bot._interaction_scope_key(context)] = _routing_state(
- context, _with_extra(extra_backend), "opencode"
+ context, [*ROUTING_BACKENDS, "pm"], "opencode"
)
with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)) as edit_mock:
- asyncio.run(bot._handle_routing_callback(context, "tg_route:field:backend"))
+ asyncio.run(bot._handle_routing_callback(context, "tg_route:field:agent"))
state = bot._routing_states[bot._interaction_scope_key(context)]
- asyncio.run(bot._handle_routing_callback(
- context, f"tg_route:option:{state.registered_backends.index(extra_backend)}",
- ))
+ values = [value for _, value in bot._routing_picker_options(state)]
+ asyncio.run(bot._handle_routing_callback(context, f"tg_route:option:{values.index('id-pm')}"))
state = bot._routing_states[bot._interaction_scope_key(context)]
- assert state.backend == extra_backend
+ assert state.agent == "id-pm"
assert state.picker_field is None
assert edit_mock.await_count == 2
diff --git a/tests/test_vibey_backend_registration.py b/tests/test_vibey_backend_registration.py
index 983cc9b91..c070420c9 100644
--- a/tests/test_vibey_backend_registration.py
+++ b/tests/test_vibey_backend_registration.py
@@ -431,11 +431,11 @@ async def test_an_rc1_vibey_left_empty_starts_at_the_first_upgraded_start(tmp_pa
@pytest.mark.parametrize("name_taken", [False, True])
-def test_choosing_the_built_in_backend_in_an_im_picker_routes_to_its_agent(tmp_path, sqlite_db_factory, name_taken):
- """An IM picker chooses a backend; the routing it saves names that backend's built-in Agent.
+def test_an_im_picker_routes_to_exactly_the_agent_it_lists(tmp_path, sqlite_db_factory, name_taken):
+ """An IM picker lists Agents and saves the one chosen, by id, so a name collision cannot redirect it.
- While a user's Agent holds ``vibey`` the built-in takes the next free name, so saving the id
- would route the channel to that user's Agent instead of the built-in.
+ While a user's Agent holds ``vibey`` the built-in takes the next free name; both are listed, and
+ each routes the channel to itself.
"""
from core.handlers.settings_handler import SettingsHandler
@@ -468,14 +468,19 @@ def test_choosing_the_built_in_backend_in_an_im_picker_routes_to_its_agent(tmp_p
handler._get_settings_key = lambda context: context.channel_id
handler._get_settings_manager = lambda context: settings_manager
- for backend, expected in (("vibey", built_in.name), ("claude", "claude")):
+ controller.get_cwd = lambda _context: str(tmp_path)
+ context = MessageContext(user_id="U1", channel_id="C-test", platform="slack")
+ listed = {agent.name: agent for agent in asyncio.run(handler._gather_routing_modal_data(context)).agents}
+ expected = {built_in.name: "vibey", "claude": "claude", **({"vibey": "claude"} if name_taken else {})}
+ assert set(listed) == set(expected)
+
+ for name, backend in expected.items():
asyncio.run(handler.handle_routing_update(
- user_id="U1", channel_id="C-test", backend=backend,
+ user_id="U1", channel_id="C-test", agent_id=listed[name].id,
notify_user=False, platform="slack",
))
- assert saved["C-test"].agent_name == expected
- context = MessageContext(user_id="U1", channel_id="C-test", platform="slack")
- assert controller.resolve_vibe_agent_for_context(context).name == expected
+ assert saved["C-test"].agent_name == name
+ assert controller.resolve_vibe_agent_for_context(context).name == name
assert controller.resolve_agent_for_context(context) == backend
finally:
store.close()
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index a0812e419..f3174c1d2 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -593,7 +593,7 @@
"messageTypes": "Message types",
"mentionPolicy": "Mention policy",
"language": "Language",
- "backend": "Backend",
+ "agent": "Agent",
"backendAgent": "{backend} agent",
"model": "Model",
"reasoningEffort": "Reasoning effort"
@@ -674,17 +674,16 @@
},
"routing": {
"title": "Agent Settings",
- "currentBackend": "Current Backend:",
- "backend": "Backend",
- "selectBackend": "Select backend",
- "backendSettings": "{backend} Settings",
+ "currentAgent": "Current Agent:",
+ "agent": "Agent",
+ "selectAgent": "Select agent",
"backendAgent": "{backend} Agent",
"selectBackendAgent": "Select {backend} agent",
"model": "Model",
"selectModel": "Select model",
"reasoningEffort": "Reasoning Effort (Thinking Mode)",
"selectReasoningEffort": "Select reasoning effort",
- "tip": "Select (Default) to use the backend's configured defaults."
+ "tip": "Select (Default) to use the Agent's own model and reasoning effort."
}
},
"command": {
@@ -813,9 +812,9 @@
"routing": {
"slackOnly": "🤖 Agent switching is currently only available in Slack. Use Slack Agent Settings to configure routing.",
"introTitle": "Agent & Model Settings",
- "introDesc": "Configure which backend to use for this channel.",
+ "introDesc": "Choose which Agent this channel uses.",
+ "noAgents": "No Agent is available for this channel.",
"label": {
- "backend": "Backend",
"agent": "Agent",
"model": "Model",
"reasoningEffort": "Reasoning Effort"
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 11edd3311..5904581a3 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -593,7 +593,7 @@
"messageTypes": "消息类型",
"mentionPolicy": "提及策略",
"language": "语言",
- "backend": "后端",
+ "agent": "Agent",
"backendAgent": "{backend} Agent",
"model": "模型",
"reasoningEffort": "推理强度"
@@ -674,17 +674,16 @@
},
"routing": {
"title": "Agent 设置",
- "currentBackend": "当前后端:",
- "backend": "后端",
- "selectBackend": "选择后端",
- "backendSettings": "{backend} 设置",
+ "currentAgent": "当前 Agent:",
+ "agent": "Agent",
+ "selectAgent": "选择 Agent",
"backendAgent": "{backend} Agent",
"selectBackendAgent": "选择 {backend} Agent",
"model": "模型",
"selectModel": "选择模型",
"reasoningEffort": "推理强度(思考模式)",
"selectReasoningEffort": "选择推理强度",
- "tip": "选择“(默认)”以使用后端的配置默认值。"
+ "tip": "选择“(默认)”以使用该 Agent 自身的模型和推理强度。"
}
},
"command": {
@@ -813,9 +812,9 @@
"routing": {
"slackOnly": "🤖 Agent 切换目前仅在 Slack 可用。请使用 Slack Agent 设置进行配置。",
"introTitle": "Agent 与模型设置",
- "introDesc": "配置该频道使用的后端。",
+ "introDesc": "选择该频道使用的 Agent。",
+ "noAgents": "该频道没有可用的 Agent。",
"label": {
- "backend": "后端",
"agent": "Agent",
"model": "模型",
"reasoningEffort": "推理强度"