Skip to content

🙌 OpenHands: AI-Driven Development

feat(agent-profiles): choose a Model Router per profile (#18685)

simonrosenberg3bf5e85c01dc
diff --git a/.pr/profile-router-default-note.png b/.pr/profile-router-default-note.png
new file mode 100644
index 0000000000..3509aa8c59
Binary files /dev/null and b/.pr/profile-router-default-note.png differ
diff --git a/.pr/profile-router-first.png b/.pr/profile-router-first.png
new file mode 100644
index 0000000000..6de248c608
Binary files /dev/null and b/.pr/profile-router-first.png differ
diff --git a/.pr/profile-router-missing.png b/.pr/profile-router-missing.png
new file mode 100644
index 0000000000..be7e1ff1be
Binary files /dev/null and b/.pr/profile-router-missing.png differ
diff --git a/.pr/profile-router.png b/.pr/profile-router.png
new file mode 100644
index 0000000000..5783ade61c
Binary files /dev/null and b/.pr/profile-router.png differ
diff --git a/__tests__/api/agent-profiles-service/profile-field-support.test.ts b/__tests__/api/agent-profiles-service/profile-field-support.test.ts
index 21f23a18b5..724b026e70 100644
--- a/__tests__/api/agent-profiles-service/profile-field-support.test.ts
+++ b/__tests__/api/agent-profiles-service/profile-field-support.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import {
agentProfileSupportsInstructions,
+ agentProfileSupportsRouter,
agentProfileSupportsSecretRefs,
agentProfileSupportsSkills,
agentProfileSupportsTools,
@@ -17,6 +18,7 @@ describe.each([
["agentProfileSupportsInstructions", agentProfileSupportsInstructions],
["agentProfileSupportsTools", agentProfileSupportsTools],
["agentProfileSupportsSkills", agentProfileSupportsSkills],
+ ["agentProfileSupportsRouter", agentProfileSupportsRouter],
])("%s", (_name, supports) => {
it("is offered on a local backend", () => {
mockBackendKind.mockReturnValue("local");
diff --git a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx
index 4a1ec17469..44e9ed7b07 100644
--- a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx
+++ b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx
@@ -277,6 +277,8 @@ describe("AgentProfilesLocalView save mapping", () => {
tool_concurrency_limit: 4,
mcp_server_refs: ["github"],
disabled_skills: ["deploy-checklist"],
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "fast-router",
};
vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
name: "default",
@@ -319,6 +321,9 @@ describe("AgentProfilesLocalView save mapping", () => {
// The editor's Condenser and Verification sections open on these.
condenser: { kind: "NoOpCondenserSettings" },
verification: { critic_enabled: true },
+ // The editor's Model Router section opens on these.
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "fast-router",
});
await user.click(screen.getByTestId("save-agent-profile-btn"));
@@ -341,6 +346,8 @@ describe("AgentProfilesLocalView save mapping", () => {
tool_concurrency_limit: 4,
mcp_server_refs: ["github"],
disabled_skills: ["deploy-checklist"],
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "fast-router",
});
expect(profile).not.toHaveProperty("id");
expect(profile).not.toHaveProperty("name");
diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsx
index 69dbf684e3..604977afdf 100644
--- a/__tests__/routes/agent-settings.test.tsx
+++ b/__tests__/routes/agent-settings.test.tsx
@@ -11,6 +11,7 @@ import {
import SettingsService from "#/api/settings-service/settings-service.api";
import { SecretsService } from "#/api/secrets-service";
import SkillsService from "#/api/skills-service";
+import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
import { Settings, SkillInfo } from "#/types/settings";
import {
@@ -55,11 +56,13 @@ const CLAUDE_MODELS = [
const profileSupportsSecretRefsMock = vi.hoisted(() => vi.fn(() => true));
const profileSupportsInstructionsMock = vi.hoisted(() => vi.fn(() => false));
const profileSupportsSkillsMock = vi.hoisted(() => vi.fn(() => true));
+const profileSupportsRouterMock = vi.hoisted(() => vi.fn(() => true));
vi.mock("#/api/agent-profiles-service/profile-field-support", () => ({
agentProfileSupportsSecretRefs: () => profileSupportsSecretRefsMock(),
agentProfileSupportsInstructions: () => profileSupportsInstructionsMock(),
agentProfileSupportsSkills: () => profileSupportsSkillsMock(),
agentProfileSupportsTools: () => true,
+ agentProfileSupportsRouter: () => profileSupportsRouterMock(),
}));
// The secret picker lists the user's saved secrets; stub the query so these
@@ -1669,6 +1672,154 @@ describe("AgentSettingsScreen — condenser and verification", () => {
});
});
+describe("AgentSettingsScreen — Model Router", () => {
+ const WITH_ROUTER = {
+ agent_kind: "openhands",
+ mcp_server_refs: null,
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "fast-router",
+ };
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ profileSupportsRouterMock.mockReturnValue(true);
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());
+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);
+ vi.spyOn(MetaProfilesService, "listMetaProfiles").mockResolvedValue({
+ meta_profiles: [
+ { name: "fast-router", classifier_model: null, num_classes: 2 },
+ { name: "pro-router", classifier_model: null, num_classes: 3 },
+ ],
+ active_meta_profile: null,
+ });
+ acpAuthStatusMock.mockReturnValue({
+ status: "unknown",
+ isChecking: false,
+ isSupported: true,
+ });
+ acpModelDiscoveryMock.mockReturnValue(NO_DISCOVERY);
+ });
+
+ async function choose(
+ user: ReturnType<typeof userEvent.setup>,
+ name: string,
+ ) {
+ const combo = screen.getByTestId("agent-settings-router-select");
+ combo.focus();
+ await user.keyboard("{ArrowDown}");
+ await user.click(await screen.findByRole("option", { name }));
+ }
+
+ it("opens on the profile's router and saves a change to it", async () => {
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: WITH_ROUTER,
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId("agent-settings-router-select")).toHaveValue(
+ "fast-router",
+ ),
+ );
+ expect(control().isDirty).toBe(false);
+
+ const user = userEvent.setup();
+ await choose(user, "pro-router");
+ await waitFor(() => expect(control().isDirty).toBe(true));
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ enable_classify_and_switch_llm_tool: true,
+ meta_profile_ref: "pro-router",
+ });
+
+ await choose(user, "SETTINGS$AGENT_PROFILE_ROUTER_OFF");
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ enable_classify_and_switch_llm_tool: false,
+ meta_profile_ref: null,
+ });
+ });
+
+ it("leaves the stored router alone when saving other changes", async () => {
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: WITH_ROUTER,
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId("agent-settings-router-select")).toHaveValue(
+ "fast-router",
+ ),
+ );
+
+ const fields = control().buildAgentProfileFields();
+ expect(fields).not.toHaveProperty("enable_classify_and_switch_llm_tool");
+ expect(fields).not.toHaveProperty("meta_profile_ref");
+ });
+
+ it("shows a router left on without a name as the first saved router and keeps it", async () => {
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: { ...WITH_ROUTER, meta_profile_ref: null },
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId("agent-settings-router-select")).toHaveValue(
+ "SETTINGS$AGENT_PROFILE_ROUTER_FIRST",
+ ),
+ );
+ expect(
+ screen.queryByTestId("agent-settings-router-dangling"),
+ ).not.toBeInTheDocument();
+ expect(control().isDirty).toBe(false);
+ expect(control().buildAgentProfileFields()).not.toHaveProperty(
+ "enable_classify_and_switch_llm_tool",
+ );
+
+ const user = userEvent.setup();
+ await choose(user, "SETTINGS$AGENT_PROFILE_ROUTER_OFF");
+ await waitFor(() => expect(control().isDirty).toBe(true));
+ expect(control().buildAgentProfileFields()).toMatchObject({
+ enable_classify_and_switch_llm_tool: false,
+ meta_profile_ref: null,
+ });
+ });
+
+ it("is not offered on Cloud, which keeps routers per organization", async () => {
+ profileSupportsRouterMock.mockReturnValue(false);
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: WITH_ROUTER,
+ });
+ await screen.findByTestId("agent-settings-screen");
+
+ expect(
+ screen.queryByTestId("agent-settings-router"),
+ ).not.toBeInTheDocument();
+ expect(control().buildAgentProfileFields()).not.toHaveProperty(
+ "meta_profile_ref",
+ );
+ });
+
+ it("warns about a router that no longer exists, which would fail the launch", async () => {
+ renderAgentSettingsScreen({
+ agentSettingsOverride: { ...WITH_ROUTER, meta_profile_ref: "gone" },
+ });
+
+ expect(
+ await screen.findByTestId("agent-settings-router-dangling"),
+ ).toHaveTextContent("SETTINGS$AGENT_PROFILE_ROUTER_DANGLING");
+ });
+
+ it("points the default profile to the Model Router page", async () => {
+ const { control } = renderAgentSettingsScreen({
+ agentSettingsOverride: WITH_ROUTER,
+ isDefaultProfile: true,
+ });
+
+ expect(
+ await screen.findByTestId("agent-settings-router-default-profile"),
+ ).toHaveTextContent("SETTINGS$AGENT_PROFILE_ROUTER_DEFAULT_PROFILE");
+ expect(
+ screen.queryByTestId("agent-settings-router-select"),
+ ).not.toBeInTheDocument();
+ expect(control().buildAgentProfileFields()).not.toHaveProperty(
+ "meta_profile_ref",
+ );
+ });
+});
+
describe("AgentSettingsScreen — system prompt", () => {
beforeEach(() => {
vi.restoreAllMocks();
diff --git a/src/api/agent-profiles-service/profile-field-support.ts b/src/api/agent-profiles-service/profile-field-support.ts
index 939830accb..d36d54941b 100644
--- a/src/api/agent-profiles-service/profile-field-support.ts
+++ b/src/api/agent-profiles-service/profile-field-support.ts
@@ -19,3 +19,8 @@ export function agentProfileSupportsTools(): boolean {
export function agentProfileSupportsSkills(): boolean {
return getActiveBackend().backend.kind !== "cloud";
}
+
+/** Local only: cloud backends keep routers in the organization's store. */
+export function agentProfileSupportsRouter(): boolean {
+ return getActiveBackend().backend.kind !== "cloud";
+}
diff --git a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx
index 51ed0233cd..e54648fc7b 100644
--- a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx
+++ b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx
@@ -61,9 +61,16 @@ function toAgentSettingsOverride(
acp_model: profile.acp_model ?? "",
};
}
+ const stored = profile as typeof profile & {
+ enable_classify_and_switch_llm_tool?: boolean;
+ meta_profile_ref?: string | null;
+ };
return {
agent_kind: "openhands",
mcp_server_refs: profile.mcp_server_refs ?? null,
+ enable_classify_and_switch_llm_tool:
+ stored.enable_classify_and_switch_llm_tool ?? false,
+ meta_profile_ref: stored.meta_profile_ref ?? null,
tools: (profile.tools as SettingsValue) ?? null,
tool_concurrency_limit: profile.tool_concurrency_limit,
secret_refs: secretRefs,
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index fd588e3529..61ec038a64 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -52360,5 +52360,95 @@
"uk": "Типовий профіль завжди запускається з глобальними налаштуваннями конденсатора та верифікації. Щоб вибрати власні, створіть іменований профіль.",
"ca": "El perfil predeterminat sempre s’inicia amb la configuració global del condensador i la verificació. Crea un perfil amb nom per triar-ne la seva.",
"id": "Profil default selalu diluncurkan dengan pengaturan Condenser dan Verifikasi global. Buat profil bernama untuk memilih pengaturannya sendiri."
+ },
+ "SETTINGS$AGENT_PROFILE_ROUTER_OFF": {
+ "en": "Off",
+ "ja": "オフ",
+ "zh-CN": "关闭",
+ "zh-TW": "關閉",
+ "ko-KR": "끄기",
+ "no": "Av",
+ "it": "Disattivato",
+ "pt": "Desligado",
+ "es": "Desactivado",
+ "ar": "إيقاف",
+ "fr": "Désactivé",
+ "tr": "Kapalı",
+ "de": "Aus",
+ "uk": "Вимкнено",
+ "ca": "Desactivat",
+ "id": "Nonaktif"
+ },
+ "SETTINGS$AGENT_PROFILE_ROUTER_HINT": {
+ "en": "With a router selected, this agent can route each task to one of your LLM profiles. Routers are managed on the Model Router page.",
+ "ja": "ルーターを選択すると、このエージェントは各タスクをいずれかの LLM プロファイルに振り分けられます。ルーターはモデルルーターのページで管理します。",
+ "zh-CN": "选择路由器后,此代理可以将每个任务路由到你的某个 LLM 配置文件。路由器在“模型路由器”页面中管理。",
+ "zh-TW": "選擇路由器後,此代理可以將每個任務路由到你的某個 LLM 設定檔。路由器在「模型路由器」頁面中管理。",
+ "ko-KR": "라우터를 선택하면 이 에이전트는 각 작업을 LLM 프로필 중 하나로 라우팅할 수 있습니다. 라우터는 모델 라우터 페이지에서 관리합니다.",
+ "no": "Med en ruter valgt kan denne agenten sende hver oppgave til en av LLM-profilene dine. Rutere administreres på siden Modellruter.",
+ "it": "Con un router selezionato, questo agente può indirizzare ogni attività a uno dei tuoi profili LLM. I router si gestiscono nella pagina Router dei modelli.",
+ "pt": "Com um roteador selecionado, este agente pode encaminhar cada tarefa para um dos seus perfis de LLM. Os roteadores são gerenciados na página Roteador de modelos.",
+ "es": "Con un enrutador seleccionado, este agente puede dirigir cada tarea a uno de tus perfiles de LLM. Los enrutadores se gestionan en la página Enrutador de modelos.",
+ "ar": "عند اختيار موجّه، يمكن لهذا الوكيل توجيه كل مهمة إلى أحد ملفات LLM الخاصة بك. تُدار الموجّهات في صفحة موجّه النماذج.",
+ "fr": "Avec un routeur sélectionné, cet agent peut diriger chaque tâche vers l'un de vos profils LLM. Les routeurs se gèrent sur la page Routeur de modèles.",
+ "tr": "Bir yönlendirici seçildiğinde bu ajan her görevi LLM profillerinizden birine yönlendirebilir. Yönlendiriciler Model yönlendirici sayfasında yönetilir.",
+ "de": "Mit einem ausgewählten Router kann dieser Agent jede Aufgabe an eines Ihrer LLM-Profile weiterleiten. Router werden auf der Seite Modell-Router verwaltet.",
+ "uk": "Якщо вибрано маршрутизатор, цей агент може спрямовувати кожне завдання до одного з ваших профілів LLM. Маршрутизатори керуються на сторінці «Маршрутизатор моделей».",
+ "ca": "Amb un encaminador seleccionat, aquest agent pot dirigir cada tasca a un dels teus perfils de LLM. Els encaminadors es gestionen a la pàgina Encaminador de models.",
+ "id": "Dengan router dipilih, agen ini dapat mengarahkan setiap tugas ke salah satu profil LLM Anda. Router dikelola di halaman Model Router."
+ },
+ "SETTINGS$AGENT_PROFILE_ROUTER_DANGLING": {
+ "en": "{{name}} no longer exists. Saving with it selected will stop this agent from starting. Choose another router or turn it off.",
+ "ja": "{{name}} は存在しなくなりました。選択したまま保存すると、このエージェントは起動できなくなります。別のルーターを選ぶか、オフにしてください。",
+ "zh-CN": "{{name}} 已不存在。保持选中并保存会导致此代理无法启动。请选择其他路由器或将其关闭。",
+ "zh-TW": "{{name}} 已不存在。保持選取並儲存會導致此代理無法啟動。請選擇其他路由器或將其關閉。",
+ "ko-KR": "{{name}}이(가) 더 이상 존재하지 않습니다. 선택한 상태로 저장하면 이 에이전트를 시작할 수 없습니다. 다른 라우터를 선택하거나 끄세요.",
+ "no": "{{name}} finnes ikke lenger. Lagrer du med den valgt, kan ikke denne agenten starte. Velg en annen ruter eller slå den av.",
+ "it": "{{name}} non esiste più. Salvando con questo selezionato, l'agente non potrà avviarsi. Scegli un altro router o disattivalo.",
+ "pt": "{{name}} não existe mais. Salvar com ele selecionado impedirá este agente de iniciar. Escolha outro roteador ou desligue-o.",
+ "es": "{{name}} ya no existe. Guardar con él seleccionado impedirá que este agente se inicie. Elige otro enrutador o desactívalo.",
+ "ar": "لم يعد {{name}} موجودًا. سيمنع الحفظ مع تحديده هذا الوكيل من البدء. اختر موجّهًا آخر أو أوقفه.",
+ "fr": "{{name}} n'existe plus. Enregistrer avec ce routeur sélectionné empêchera cet agent de démarrer. Choisissez un autre routeur ou désactivez-le.",
+ "tr": "{{name}} artık mevcut değil. Seçili olarak kaydetmek bu ajanın başlamasını engeller. Başka bir yönlendirici seçin veya kapatın.",
+ "de": "{{name}} existiert nicht mehr. Wenn Sie damit speichern, kann dieser Agent nicht starten. Wählen Sie einen anderen Router oder schalten Sie ihn aus.",
+ "uk": "{{name}} більше не існує. Якщо зберегти з ним, цей агент не зможе запуститися. Виберіть інший маршрутизатор або вимкніть його.",
+ "ca": "{{name}} ja no existeix. Desar-lo seleccionat impedirà que aquest agent s'iniciï. Tria un altre encaminador o desactiva'l.",
+ "id": "{{name}} sudah tidak ada. Menyimpan dengan pilihan ini akan membuat agen gagal dimulai. Pilih router lain atau matikan."
+ },
+ "SETTINGS$AGENT_PROFILE_ROUTER_DEFAULT_PROFILE": {
+ "en": "The default profile always launches with the router chosen on the Model Router page. Create a named profile to choose its own.",
+ "ja": "デフォルトのプロファイルは常にモデルルーターのページで選んだルーターで起動します。独自に選ぶには、名前付きのプロファイルを作成してください。",
+ "zh-CN": "默认配置文件始终使用在“模型路由器”页面中选择的路由器启动。如需单独选择,请创建一个命名配置文件。",
+ "zh-TW": "預設設定檔一律以「模型路由器」頁面中選擇的路由器啟動。若要單獨選擇,請建立具名設定檔。",
+ "ko-KR": "기본 프로필은 항상 모델 라우터 페이지에서 선택한 라우터로 시작됩니다. 따로 선택하려면 이름이 있는 프로필을 만드세요.",
+ "no": "Standardprofilen starter alltid med ruteren som er valgt på siden Modellruter. Opprett en navngitt profil for å velge en egen.",
+ "it": "Il profilo predefinito si avvia sempre con il router scelto nella pagina Router dei modelli. Crea un profilo con nome per sceglierne uno proprio.",
+ "pt": "O perfil padrão sempre inicia com o roteador escolhido na página Roteador de modelos. Crie um perfil com nome para escolher o seu.",
+ "es": "El perfil predeterminado siempre se inicia con el enrutador elegido en la página Enrutador de modelos. Crea un perfil con nombre para elegir el suyo.",
+ "ar": "يبدأ الملف الشخصي الافتراضي دائمًا بالموجّه المختار في صفحة موجّه النماذج. أنشئ ملفًا شخصيًا باسم لاختيار موجّهه الخاص.",
+ "fr": "Le profil par défaut démarre toujours avec le routeur choisi sur la page Routeur de modèles. Créez un profil nommé pour choisir le sien.",
+ "tr": "Varsayılan profil her zaman Model yönlendirici sayfasında seçilen yönlendiriciyle başlar. Kendi yönlendiricisini seçmek için adlandırılmış bir profil oluşturun.",
+ "de": "Das Standardprofil startet immer mit dem Router, der auf der Seite Modell-Router ausgewählt ist. Erstellen Sie ein benanntes Profil, um einen eigenen zu wählen.",
+ "uk": "Типовий профіль завжди запускається з маршрутизатором, вибраним на сторінці «Маршрутизатор моделей». Щоб вибрати власний, створіть іменований профіль.",
+ "ca": "El perfil predeterminat sempre s'inicia amb l'encaminador triat a la pàgina Encaminador de models. Crea un perfil amb nom per triar-ne un de propi.",
+ "id": "Profil default selalu diluncurkan dengan router yang dipilih di halaman Model Router. Buat profil bernama untuk memilih router sendiri."
+ },
+ "SETTINGS$AGENT_PROFILE_ROUTER_FIRST": {
+ "en": "Alphabetically first router",
+ "ja": "名前順で最初のルーター",
+ "zh-CN": "按名称排序的第一个路由器",
+ "zh-TW": "依名稱排序的第一個路由器",
+ "ko-KR": "이름순 첫 번째 라우터",
+ "no": "Første ruter alfabetisk",
+ "it": "Primo router in ordine alfabetico",
+ "pt": "Primeiro roteador em ordem alfabética",
+ "es": "Primer enrutador por orden alfabético",
+ "ar": "أول موجّه أبجديًا",
+ "fr": "Premier routeur par ordre alphabétique",
+ "tr": "Alfabetik olarak ilk yönlendirici",
+ "de": "Alphabetisch erster Router",
+ "uk": "Перший маршрутизатор за алфавітом",
+ "ca": "Primer encaminador per ordre alfabètic",
+ "id": "Router pertama menurut abjad"
}
}
diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsx
index c665dd670a..87b157cbf4 100644
--- a/src/routes/agent-settings.tsx
+++ b/src/routes/agent-settings.tsx
@@ -70,6 +70,7 @@ import {
toProfileSkillFields,
type SkillEnablement,
} from "#/utils/skill-enablement";
+import { useMetaProfiles } from "#/hooks/query/use-meta-profiles";
import { flattenMcpConfig } from "#/utils/mcp-installed-servers";
import { parseMcpConfig } from "#/utils/mcp-config";
import {
@@ -77,6 +78,7 @@ import {
agentProfileSupportsInstructions,
agentProfileSupportsSkills,
agentProfileSupportsTools,
+ agentProfileSupportsRouter,
} from "#/api/agent-profiles-service/profile-field-support";
import { useSearchSecrets } from "#/hooks/query/use-get-secrets";
@@ -100,6 +102,9 @@ type AgentSettingsSnapshot = {
};
const TOOL_CONCURRENCY_FIELD_KEY = "tool_concurrency_limit";
+// Not valid meta-profile names, so they can't collide with one.
+const ROUTER_OFF_KEY = "__off__";
+const ROUTER_FIRST_KEY = "__first__";
const MCP_SERVER_REFS_KEY = "mcp_server_refs";
const SECRET_REFS_KEY = "secret_refs";
const TOOLS_KEY = "tools";
@@ -173,6 +178,8 @@ export type AgentProfileFieldsDraft =
public_skills?: string[];
disabled_skills?: string[];
tools?: ProfileToolSpec[] | null;
+ enable_classify_and_switch_llm_tool?: boolean;
+ meta_profile_ref?: string | null;
persona?: string | null;
system_message_suffix?: string | null;
condenser?: Record<string, SettingsValue>;
@@ -213,6 +220,8 @@ export interface AgentProfileFieldsInput {
toolParams?: Record<string, Record<string, SettingsValue>>;
/** Whether the tool catalog loaded; `tools` is only written then. */
toolCatalogLoaded?: boolean;
+ /** The Model Router to store: a meta-profile name, null for none, undefined to keep it. */
+ router?: string | null;
systemPromptMode: SystemPromptMode;
systemPromptText: string;
/** False when the section is hidden, so neither prompt field is written. */
@@ -261,6 +270,7 @@ export function buildAgentProfileFields(
selectedTools = [],
toolParams = {},
toolCatalogLoaded = false,
+ router,
systemPromptMode,
systemPromptText,
systemPromptEditable,
@@ -313,6 +323,10 @@ export function buildAgentProfileFields(
params: toolParams,
});
}
+ if (router !== undefined) {
+ fields.enable_classify_and_switch_llm_tool = router !== null;
+ fields.meta_profile_ref = router;
+ }
if (toolConcurrencyField) {
// Reuse the schema-driven coercion/validation; throws on bad input.
const coerced = coerceFieldValue(toolConcurrencyField, toolConcurrency);
@@ -850,6 +864,34 @@ export function AgentSettingsScreen({
if (!control.isDirty && storedBehavior[section]) return undefined;
return fromBehaviorFormValues(schema, section, control.values);
};
+ // --- Model Router (OpenHands; stored on the profile) ---
+ // `default` launches with the router chosen on the Model Router page instead.
+ const routerSupported = agentProfileSupportsRouter();
+ const routerEditable = routerSupported && !isDefaultProfile;
+ const { data: metaProfilesData } = useMetaProfiles({
+ enabled: routerEditable,
+ });
+ // On without a name means the server picks the alphabetically first router.
+ let initialRouter: string | null = null;
+ if (agentSettingsOverride?.enable_classify_and_switch_llm_tool === true) {
+ initialRouter =
+ typeof agentSettingsOverride.meta_profile_ref === "string"
+ ? agentSettingsOverride.meta_profile_ref
+ : ROUTER_FIRST_KEY;
+ }
+ const [router, setRouter] = useState<string | null>(initialRouter);
+ useEffect(() => {
+ setRouter(initialRouter);
+ }, [initialRouter]);
+ const routerNames = (metaProfilesData?.meta_profiles ?? []).map(
+ ({ name }) => name,
+ );
+ // A router that no longer exists fails the launch, so keep it visible.
+ const routerDangling =
+ router !== null &&
+ router !== ROUTER_FIRST_KEY &&
+ !!metaProfilesData &&
+ !routerNames.includes(router);
// --- Save control ---
// Ref-backed so the exposed builder/credential fns read the freshest state at
@@ -881,6 +923,7 @@ export function AgentSettingsScreen({
const secretScopeDirty =
secretsMode !== initialSecretRefs.mode ||
!sameScopeSelection(orderedSelectedSecrets, initialSecretRefs.selected);
+ const routerDirty = routerEditable && router !== initialRouter;
const toolSelectionDirty =
toolsMode !== initialTools.mode ||
(toolsMode === "custom" &&
@@ -906,7 +949,8 @@ export function AgentSettingsScreen({
isCustomAcpModel !== loadedSnapshot.isCustomAcpModel
: toolConcurrency !== initialToolConcurrency ||
systemPromptDirty ||
- behaviorDirty);
+ behaviorDirty ||
+ routerDirty);
const credentialsDirty = acpCredentialForm.isDirty;
const isAnyDirty =
settingsDirty ||
@@ -1026,6 +1070,7 @@ export function AgentSettingsScreen({
selectedTools: orderedSelectedTools,
toolParams: initialTools.params,
toolCatalogLoaded,
+ router: routerDirty ? router : undefined,
systemPromptMode,
systemPromptText,
systemPromptEditable: showSystemPrompt,
@@ -1168,6 +1213,69 @@ export function AgentSettingsScreen({
</div>
) : null}
+ {!isAcp && routerSupported ? (
+ <div
+ className="flex flex-col gap-2.5"
+ data-testid="agent-settings-router"
+ >
+ <Typography.Text className="text-sm">
+ {t(I18nKey.SETTINGS$NAV_META_LLM)}
+ </Typography.Text>
+ {routerEditable ? (
+ <>
+ <SettingsDropdownInput
+ testId="agent-settings-router-select"
+ name="agent-router"
+ label=""
+ items={[
+ {
+ key: ROUTER_OFF_KEY,
+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_OFF),
+ },
+ ...(initialRouter === ROUTER_FIRST_KEY
+ ? [
+ {
+ key: ROUTER_FIRST_KEY,
+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_FIRST),
+ },
+ ]
+ : []),
+ ...[
+ ...routerNames,
+ ...(routerDangling && router ? [router] : []),
+ ].map((name) => ({ key: name, label: name })),
+ ]}
+ selectedKey={router ?? ROUTER_OFF_KEY}
+ isDisabled={isSaving}
+ onSelectionChange={(key) => {
+ if (key === null || key === undefined) return;
+ setRouter(key === ROUTER_OFF_KEY ? null : String(key));
+ }}
+ />
+ {routerDangling ? (
+ <Typography.Text
+ testId="agent-settings-router-dangling"
+ className="text-xs text-danger"
+ >
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_DANGLING, {
+ name: router,
+ })}
+ </Typography.Text>
+ ) : null}
+ <Typography.Text className="text-xs text-tertiary-alt">
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_HINT)}
+ </Typography.Text>
+ </>
+ ) : (
+ <Typography.Text
+ testId="agent-settings-router-default-profile"
+ className="text-xs text-tertiary-alt"
+ >
+ {t(I18nKey.SETTINGS$AGENT_PROFILE_ROUTER_DEFAULT_PROFILE)}
+ </Typography.Text>
+ )}
+ </div>
+ ) : null}
{!isAcp && toolConcurrencyField ? (
<SchemaField
field={toolConcurrencyField}