From 5b90609022ce2cf52accf1a3bf85e52db67ffc21 Mon Sep 17 00:00:00 2001 From: Atish Patel Date: Fri, 20 Nov 2026 15:13:34 -0600 Subject: [PATCH 01/14] feat(agents): let bundled plugins offer model routes A bundled plugin can now register a model router with ctx.agents.registerModelRouter. For each harness it offers routes (such as "Auto Balanced") that appear beside Default in the Model menu, an optional initial route for new Custom agents, an optional route for Automatic agents, and an exclusive switch that hides the harness's own models. An agent on a route saves its model as route:. For each turn started while the conversation is idle, the host asks the router for a model and thinking level, given the prompt, the thread's earlier messages and the harness's own models. A steering message reuses the conversation's last pick, so a running turn's prompt cache is kept. An explicit per-message pick wins; a failure, a 30-second timeout or an unlisted model uses the route's fallback, and a route whose plugin is off runs on the default. The turn's activity says which model the route chose and why. Claude Code and Codex support routes: route: never reaches their CLIs, Thinking shows Auto, and summaries name the route. Co-authored-by: Worker Bee (Opus) <4a3bc7fd57a7b2c126e4f3d3462dd16f375242e1c176b4b3f25ca93e3edb6a84@buzz.block.builderlab.xyz> Signed-off-by: Atish Patel --- docs/buzz-help.md | 5 + docs/configuration.md | 9 + src/bundled/agents/AgentCreateDialog.tsx | 26 +- src/bundled/agents/AgentsPage.test.tsx | 1 + src/bundled/claude-code/index.ts | 15 +- src/bundled/claude-code/runtime.ts | 13 +- src/bundled/claude-code/tabs.tsx | 70 +++- src/bundled/codex/config.ts | 8 +- src/bundled/codex/index.ts | 15 +- src/bundled/codex/runtime.ts | 4 + src/bundled/codex/tabs.tsx | 60 +++- src/features/agents/AISettings.tsx | 33 +- src/features/agents/CreateModelChoices.tsx | 4 + src/features/agents/ModelFamilyMenu.tsx | 34 +- src/features/agents/ModelPicker.test.tsx | 104 +++++- src/features/agents/ModelPicker.tsx | 57 +++- src/features/agents/model-routes.test.ts | 290 ++++++++++++++++ src/features/agents/model-routes.ts | 377 +++++++++++++++++++++ src/features/agents/runner.ts | 38 ++- src/features/agents/service.test.ts | 69 ++++ src/features/agents/service.ts | 180 +++++++++- 21 files changed, 1357 insertions(+), 55 deletions(-) create mode 100644 src/features/agents/model-routes.test.ts create mode 100644 src/features/agents/model-routes.ts diff --git a/docs/buzz-help.md b/docs/buzz-help.md index e137c73a51..bfeab45815 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -163,6 +163,11 @@ if that desktop app is up and running. accounts or permissions. - **Sessions.** By default an agent starts a fresh conversation for each thread. Its settings can make it one per channel or one per community. +- **Auto models.** Some builds add choices such as **Auto Balanced** to the + Model menu of Claude Code and Codex agents. Before each new turn, the build + picks a model and thinking level for that message, and the turn's activity + says which and why. A message sent while the agent is working keeps its + model, and a model chosen beside Send still wins. - **While it works**, the agent shows typing dots, and you can stop it. If it can't finish, it says why and offers **Retry**. - **Your default agent** (your Bestie) answers new chats and `ask:` searches. diff --git a/docs/configuration.md b/docs/configuration.md index 508c78760f..69bc3cdda9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -159,6 +159,15 @@ A bundled plugin can replace the setup per launch with `ctx.agents.recommend(source)`, for example per team. Buzz waits up to five seconds for it, then falls back to `BUZZ_RECOMMENDED_AGENT`, so set both. +A bundled plugin can also add **model routes**, such as "Auto Balanced", to the +Claude Code and Codex Model menus with `ctx.agents.registerModelRouter(router)`. +An agent on a route saves `route:` as its model. Before each turn it starts +while idle in a conversation, Buzz asks `router.select` for one of the +harness's models and a thinking level. A turn that steers a running one keeps +its pick, and a failure or no answer within 30 seconds uses the route's +fallback. The router can also choose the route new agents and Automatic agents +use. See `src/features/agents/model-routes.ts`. + ## Federated identity build input A build trusts a compiled list of sign-in servers. Each community is matched by diff --git a/src/bundled/agents/AgentCreateDialog.tsx b/src/bundled/agents/AgentCreateDialog.tsx index dc5dc9c90d..402a628c8f 100644 --- a/src/bundled/agents/AgentCreateDialog.tsx +++ b/src/bundled/agents/AgentCreateDialog.tsx @@ -19,8 +19,13 @@ import { import { AISettings, Checking, + RouteLine, UsesLine, } from "../../features/agents/AISettings"; +import { + activeRoute, + useModelRoutes, +} from "../../features/agents/model-routes"; import { bounded, followRecommended, @@ -357,6 +362,9 @@ export function AgentCreateDialog({ const [asked, setAsked] = useState(0); const recommendation = useRecommendedPick(types, recommendable, asked); const { pick } = recommendation.status === "found" ? recommendation : {}; + // A plugin's route that Automatic runs on for the pick's harness. + useModelRoutes(pick?.type.id ?? ""); + const automaticRoute = pick && activeRoute(pick.type.id, "", true); // No local harness can run an Automatic agent here: one thing to set up. const nothingSetUp = automatic && recommendable && recommendation.status === "none"; @@ -805,7 +813,7 @@ export function AgentCreateDialog({ + ) : ( + pick && ( + + ) ) } > diff --git a/src/bundled/agents/AgentsPage.test.tsx b/src/bundled/agents/AgentsPage.test.tsx index fcf147461b..a763423582 100644 --- a/src/bundled/agents/AgentsPage.test.tsx +++ b/src/bundled/agents/AgentsPage.test.tsx @@ -526,6 +526,7 @@ function setup( controlAttention: () => {}, recommend: () => {}, gatewayHarnesses: () => {}, + registerModelRouter: () => {}, registerSessionRouter: () => {}, registerExecution: () => {}, bindExecution: async () => {}, diff --git a/src/bundled/claude-code/index.ts b/src/bundled/claude-code/index.ts index 5c9825d78b..d64743551b 100644 --- a/src/bundled/claude-code/index.ts +++ b/src/bundled/claude-code/index.ts @@ -15,6 +15,7 @@ import { ClaudeLogoIcon } from "../../shared/design-system/icons"; import { claudeRun, TYPE_ID } from "./run"; import { followRecommended, + onAutomatic, recommendedRun, } from "../../features/agents/recommended"; import type { AgentHandle } from "../../features/agents/service"; @@ -25,6 +26,7 @@ import { ClaudeRuntime, type Config, config, DEFAULT_CONFIG } from "./runtime"; import { ClaudeSetup, withScript } from "./setup"; import { createTabs } from "./tabs"; import { targetKey } from "../../features/navigation/targets"; +import { activeRoute, routeLabel } from "../../features/agents/model-routes"; import type { ClaudeConnection } from "./ClaudeSettings"; import { readUsage } from "./usage"; import { usageOn } from "../../features/agents/standalone-sessions"; @@ -296,12 +298,19 @@ export const apply: PluginModule["apply"] = (ctx) => { { id: "thinking", label: "Thinking", isOverride: Boolean(effort) }, ]; }, - summary: (agent) => - followRecommended( + summary: (agent) => { + const { model } = followRecommended( agent.config, config(agent.config), recommended.current(), - ).model || "Claude", + ); + return ( + activeRoute(TYPE_ID, model, onAutomatic(agent.config, TYPE_ID)) + ?.label ?? + routeLabel(TYPE_ID, model) ?? + (model || "Claude") + ); + }, ...(spawn && readFile && { usage: async (agent, { since, signal }) => { diff --git a/src/bundled/claude-code/runtime.ts b/src/bundled/claude-code/runtime.ts index dcf4c86dbf..1d3c2c5b10 100644 --- a/src/bundled/claude-code/runtime.ts +++ b/src/bundled/claude-code/runtime.ts @@ -16,6 +16,7 @@ import { } from "../../features/agent-harness/session-scope"; import { protectionTranscript } from "./protection-transcript"; import { compactAt } from "../../features/agents/compact-at"; +import { launchModel, routeOf } from "../../features/agents/model-routes"; import type { PRESET } from "../../features/agents/recommended"; import { fileStore } from "../../features/agents/state"; import type { AgentExecution } from "../../features/agents/execution"; @@ -271,9 +272,11 @@ type Entry = { * compaction. */ const where = ({ workspace, model, effort, ...config }: Config) => { const tokens = compactAt(config.compactAt); + // A saved model route picks per turn; the process starts on the default. + const launch = launchModel(model.trim()); return { cwd: workspace, - ...(model.trim() ? { model: model.trim() } : {}), + ...(launch ? { model: launch } : {}), ...(effort ? { effort } : {}), ...(tokens ? { compactAt: tokens } : {}), }; @@ -761,7 +764,8 @@ export class ClaudeRuntime { /** `models`, saying whether Claude itself lists the current model. */ private async catalog(agent: AgentKey) { const entry = this.agents.get(agent); - const configured = entry?.config.model.trim(); + const saved = entry?.config.model.trim(); + const configured = saved && launchModel(saved); const { models: listed, model: reported, @@ -781,6 +785,9 @@ export class ClaudeRuntime { ...resting(offeredEfforts), }; }); + // A saved route is the current choice; the agents service lists it. + if (saved && routeOf(saved)) + return { current: saved, models, listed: true }; const current = offered.find( (model) => own === model.value || own === model.resolvedModel, @@ -1986,6 +1993,8 @@ export class ClaudeRuntime { private async refusal(agent: AgentKey, kept: string | undefined) { if (!kept) return undefined; const { current, models, listed } = await this.catalog(agent); + // A route picks its own effort each turn. + if (routeOf(current)) return undefined; const own = models.find((model) => model.id === current); // A model Claude doesn't list has no levels to check the effort against. if (!listed || !own) diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 25e52cb92a..2641ffb419 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -39,6 +39,14 @@ import { Dialog } from "../../shared/design-system/ui/Dialog"; import { useToastNotification } from "../../shared/design-system/ui/Toast"; import { Accordion } from "../../shared/design-system/ui/Accordion"; import { ModelPicker } from "../../features/agents/ModelPicker"; +import { + activeRoute, + routeLabel, + routeModel, + routeOf, + useInitialRoute, + useModelRoutes, +} from "../../features/agents/model-routes"; import { AISettings, runsOnDetails } from "../../features/agents/AISettings"; import { CompactionField } from "../../features/agents/Compaction"; import { withCompactAt } from "../../features/agents/compact-at"; @@ -474,6 +482,12 @@ export function createTabs({ defaults.subscribe, defaults.snapshot, ); + useInitialRoute( + "claude-code", + !props.agent && !onRecommended(config), + current.model, + (model) => onChange({ ...current, model, effort: "" }), + ); const ready = state.status?.state === "ready" && !state.running && @@ -508,6 +522,7 @@ export function createTabs({ return ( level.id === current.effort) + !routeOf(model) && + (state.models.length === 0 || + efforts.some((level) => level.id === current.effort)) ? current.effort : "", }); @@ -598,15 +614,17 @@ export function createTabs({ state.models, current.effort, ); + const routed = Boolean(routeOf(model)); return ( setDraft(offRecommended({ ...draft, effort })) @@ -1592,6 +1632,7 @@ export function createTabs({ {...runsOnDetails( { title: "Claude", icon: ClaudeLogoIcon }, resolved, + automaticRoute, )} onChange={(on) => // Manual starts from the recommendation it ran on. @@ -1599,7 +1640,14 @@ export function createTabs({ on ? readConfig(withRecommended(draft)) : offRecommended( - followRecommended(draft, draft, resolved), + // Or from its Automatic route. + automaticRoute + ? { + ...draft, + model: routeModel(automaticRoute.id), + effort: "", + } + : followRecommended(draft, draft, resolved), ), ) } diff --git a/src/bundled/codex/config.ts b/src/bundled/codex/config.ts index 9bc2196a97..7688854028 100644 --- a/src/bundled/codex/config.ts +++ b/src/bundled/codex/config.ts @@ -3,6 +3,7 @@ import { type SessionScope, } from "../../features/agent-harness/session-scope"; import { compactAt } from "../../features/agents/compact-at"; +import { launchModel } from "../../features/agents/model-routes"; import { PRESET } from "../../features/agents/recommended"; export type Config = { @@ -31,9 +32,12 @@ export type Model = { defaultReasoningEffort: string; supportedReasoningEfforts: { reasoningEffort: string; description: string }[]; }; -/** Buzz owns model preferences; an unset choice follows Codex's recommendation. */ +/** Buzz owns model preferences; an unset choice follows Codex's + * recommendation, as does a saved model route outside the turn it picks. */ export function resolveModel(selected: string, models: readonly Model[]) { - return selected || models.find((model) => model.isDefault)?.model; + return ( + launchModel(selected) || models.find((model) => model.isDefault)?.model + ); } /** A turn uses the first supported choice, then the selected model's default. */ export function resolveEffort( diff --git a/src/bundled/codex/index.ts b/src/bundled/codex/index.ts index 5396784ede..074e3dc555 100644 --- a/src/bundled/codex/index.ts +++ b/src/bundled/codex/index.ts @@ -16,8 +16,10 @@ import { reviewModel } from "./security-review"; import { candidatesFor, followRecommended, + onAutomatic, recommendationReady, } from "../../features/agents/recommended"; +import { activeRoute, routeLabel } from "../../features/agents/model-routes"; import { AppServer, listModels } from "./rpc"; import { CODEX_ROUTES, HARNESS } from "./gateway"; /** How often Buzz's copy of Codex looks for a new release. */ @@ -273,12 +275,19 @@ export const apply: PluginModule["apply"] = (ctx) => { ]; }, migrationWarning: "Any commands Codex left running will stop.", - summary: (agent) => - followRecommended( + summary: (agent) => { + const { model } = followRecommended( agent.config, config(agent.config), providerController.recommended(), - ).model || "Codex", + ); + return ( + activeRoute(TYPE_ID, model, onAutomatic(agent.config, TYPE_ID)) + ?.label ?? + routeLabel(TYPE_ID, model) ?? + (model || "Codex") + ); + }, recommends: (candidate) => providerController.recommends(candidate), ...(spawn && readFile && { diff --git a/src/bundled/codex/runtime.ts b/src/bundled/codex/runtime.ts index 0e474a60d0..d2b4f457e5 100644 --- a/src/bundled/codex/runtime.ts +++ b/src/bundled/codex/runtime.ts @@ -35,6 +35,7 @@ import { wakeLands, } from "../../features/agent-harness/plugin-wake"; import { compactAt } from "../../features/agents/compact-at"; +import { routeOf } from "../../features/agents/model-routes"; import { composeBase, sectionsKey, @@ -1154,6 +1155,9 @@ export class CodexRuntime { }); // A configured model this Codex does not list still leaves the // listed ones to pick, so the picker stays. + // A saved route is the current choice; the agents service lists it. + if (routeOf(settings.model)) + return { current: settings.model, models: offered, sendDefaults: true }; return !model || models.some((row) => row.model === model) ? { current: model ?? "", models: offered, sendDefaults: true } : { diff --git a/src/bundled/codex/tabs.tsx b/src/bundled/codex/tabs.tsx index de6b52acb9..74827f7d5d 100644 --- a/src/bundled/codex/tabs.tsx +++ b/src/bundled/codex/tabs.tsx @@ -37,6 +37,13 @@ import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; import { AgentInstructions } from "../../features/agents/AgentInstructions"; import { CreateModelChoices } from "../../features/agents/CreateModelChoices"; import { ModelPicker } from "../../features/agents/ModelPicker"; +import { + activeRoute, + routeModel, + routeOf, + useInitialRoute, + useModelRoutes, +} from "../../features/agents/model-routes"; import { AISettings, runsOnDetails } from "../../features/agents/AISettings"; import { CompactionField } from "../../features/agents/Compaction"; import { withCompactAt } from "../../features/agents/compact-at"; @@ -894,6 +901,12 @@ export function createTabs( : status?.state === "signed-out" || error === SIGN_IN_ERROR ? "login" : undefined; + useInitialRoute( + "codex", + !agent && !onRecommended(config), + current.model, + (model) => onChange(readConfig({ ...current, model, effort: "" })), + ); const ready = !step && !checking && @@ -943,6 +956,7 @@ export function createTabs(
onChange(readConfig({ ...current, effort }))} /> ); @@ -1603,6 +1620,9 @@ export function createTabs( }, [agent.config]); // Inert in a build that recommends nothing for Codex. const following = onRecommended(draft) && candidatesFor("codex").length > 0; + // The route Automatic runs on, while a plugin offers one. + useModelRoutes("codex"); + const automaticRoute = activeRoute("codex", "", true); // A remote target runs Recommended on its own default. const resolved = bound ? null : provider.recommended(); const effective = provider.resolve({ ...draft, effort: "" }, !!bound); @@ -1689,6 +1709,7 @@ export function createTabs(
)} setDraft(offRecommended({ ...draft, effort })) } @@ -1760,6 +1790,7 @@ export function createTabs( {...runsOnDetails( { title: "Codex", icon: CodexLogoIcon }, resolved, + automaticRoute, )} onChange={(on) => // Manual starts from the recommendation it ran on. @@ -1767,7 +1798,14 @@ export function createTabs( on ? readConfig(withRecommended(draft)) : offRecommended( - followRecommended(draft, draft, resolved), + // Or from its Automatic route. + automaticRoute + ? { + ...draft, + model: routeModel(automaticRoute.id), + effort: "", + } + : followRecommended(draft, draft, resolved), ), ) } diff --git a/src/features/agents/AISettings.tsx b/src/features/agents/AISettings.tsx index a0d56152e3..5ff5c07b55 100644 --- a/src/features/agents/AISettings.tsx +++ b/src/features/agents/AISettings.tsx @@ -8,6 +8,7 @@ import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; import { Select } from "../../shared/design-system/ui/Select"; import { SettingsGroupExpand } from "../../shared/design-system/ui/SettingsGroup"; import { type RecommendedCandidate, recommendedSetup } from "./recommended"; +import type { ModelRoute } from "./model-routes"; const effortLabel = (effort: string) => effort === "xhigh" @@ -104,11 +105,41 @@ export function Checking() { ); } -/** Keep pending/default status visible; settled model details belong in the menu. */ +/** A plugin's model route that Automatic runs on, in place of one model. */ +export function RouteLine({ + icon: Icon, + title, + route, +}: Readonly<{ icon: Mark; title: string; route: ModelRoute }>) { + const value = route.description + ? `${route.label} · ${route.description}` + : route.label; + return ( + + {Icon && ( + + )} + {title}:{" "} + {value} + + ); +} + +/** Keep pending/default status visible; settled model details belong in the + * menu. `route` is the harness's Automatic model route, when a plugin offers + * one: it picks each turn's model, with `resolved` as its fallback. */ export function runsOnDetails( type: Readonly<{ title: string; icon?: Mark }>, resolved: RecommendedCandidate | null | undefined, + route?: ModelRoute, ) { + if (route) + return { + modelName: route.label, + model: , + }; if (resolved === undefined) return { summary: }; if (resolved) { return { diff --git a/src/features/agents/CreateModelChoices.tsx b/src/features/agents/CreateModelChoices.tsx index 0908b9a5c8..468c9eafa3 100644 --- a/src/features/agents/CreateModelChoices.tsx +++ b/src/features/agents/CreateModelChoices.tsx @@ -3,6 +3,7 @@ import { ModelPicker, type ModelChoice } from "./ModelPicker"; /** Compact model field; catalogs and config changes stay with the type. */ export function CreateModelChoices({ + harness, showEffort = true, effort, effortLabel, @@ -20,6 +21,8 @@ export function CreateModelChoices({ error, retry, }: { + /** The agent type's id: its plugins' model routes join the menu. */ + harness?: string | undefined; showEffort?: boolean; effort?: string | undefined; effortLabel?: string | undefined; @@ -44,6 +47,7 @@ export function CreateModelChoices({ {...(showEffort && onEffortChange ? { effort, effortLabel, onEffortChange } : {})} + harness={harness} includeDefault={includeDefault} defaultModel={defaultModel} appearance={modelAppearance ?? "outlined"} diff --git a/src/features/agents/ModelFamilyMenu.tsx b/src/features/agents/ModelFamilyMenu.tsx index 1f9ef1b027..bfcdead10f 100644 --- a/src/features/agents/ModelFamilyMenu.tsx +++ b/src/features/agents/ModelFamilyMenu.tsx @@ -118,8 +118,11 @@ export function ModelFamilyMenu({ onChange(id: string): void; onCustom?: (() => void) | undefined; }) { + // Routes are listed on their own up front, beside Default, not in a family. + const routes = models.filter((model) => model.route); const families = new Map(); for (const model of models) { + if (model.route) continue; const family = modelFamily(model); families.set(family, [...(families.get(family) ?? []), model]); } @@ -129,9 +132,9 @@ export function ModelFamilyMenu({ // Fast models get their own section up front, so the quick choices are one // click away; they stay in their families too. A catalog of only fast (or // no fast) models gains nothing from a separate section. - const fastModels = models.filter((model) => model.fast); + const fastModels = models.filter((model) => model.fast && !model.route); const fastSection = - fastModels.length > 0 && fastModels.length < models.length; + fastModels.length > 0 && fastModels.length < models.length - routes.length; const selectedLabel = `${selected.label}${selected.fast ? " · Fast" : ""}${valueSuffix ?? (inherited && selected.description ? ` · ${selected.description}` : "")}`; const choiceRow = (model: ModelChoice, inFastSection: boolean) => { const leading = inFastSection && hasFamilyLogos && ( @@ -228,6 +231,33 @@ export function ModelFamilyMenu({ )} + {routes.length > 0 && ( + <> + onChange(id)} + > + {routes.map((model) => ( + + {hasFamilyLogos && ( + + ))} + + {families.size > 0 && } + + )} {fastSection && ( <> diff --git a/src/features/agents/ModelPicker.test.tsx b/src/features/agents/ModelPicker.test.tsx index 67590fc722..59ad622ba6 100644 --- a/src/features/agents/ModelPicker.test.tsx +++ b/src/features/agents/ModelPicker.test.tsx @@ -11,6 +11,11 @@ import userEvent from "@testing-library/user-event"; import { afterEach, expect, it, vi } from "vitest"; import { StrictMode, useState } from "react"; import { ModelPicker, type ModelChoice } from "./ModelPicker"; +import { + type ModelRouter, + resetModelRoutesForTests, + setModelRouters, +} from "./model-routes"; import { DeepSeekLogoIcon, GrokLogoIcon, @@ -21,7 +26,10 @@ import { GoogleLogoIcon, } from "../../shared/design-system/icons"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + resetModelRoutesForTests(); +}); it.each([ ["Gemini 3 Pro", "Gemini", GoogleLogoIcon], @@ -996,3 +1004,97 @@ it.each([false, true])( expect(onChange).not.toHaveBeenCalled(); }, ); + +const routes = (exclusive = false): ModelRouter => ({ + id: "test", + routes: (harness) => + harness === "claude-code" + ? { + routes: [ + { + id: "auto-balanced", + label: "Auto Balanced", + description: "Opus, Sonnet", + }, + { id: "auto-premium", label: "Auto Premium" }, + ], + exclusive, + } + : undefined, + select: async () => undefined, +}); + +it.each([false, true])( + "lists a harness's model routes beside Default (grouped: %s)", + async (groupByFamily) => { + setModelRouters([routes()]); + const user = userEvent.setup(); + const onChange = vi.fn(); + render( + , + ); + const trigger = groupByFamily + ? screen.getByRole("button", { name: /^Model:/ }) + : control(); + expect(trigger).toHaveTextContent("Auto Balanced"); + await user.click(trigger); + const role = groupByFamily ? "menuitemradio" : "option"; + const rows = await screen.findAllByRole(role); + expect(rows.slice(0, 3).map((row) => row.textContent)).toEqual([ + expect.stringContaining("Default"), + expect.stringContaining("Auto Balanced"), + expect.stringContaining("Auto Premium"), + ]); + await user.click(screen.getByRole(role, { name: /Auto Premium/ })); + expect(onChange).toHaveBeenCalledExactlyOnceWith("route:auto-premium"); + }, +); + +it("shows only routes and the pinned model when the routes are exclusive", async () => { + setModelRouters([routes(true)]); + const user = userEvent.setup(); + render( + , + ); + await user.click(control()); + expect( + (await screen.findAllByRole("option")).map((row) => row.textContent), + ).toEqual([ + "Default", + "Auto BalancedOpus, Sonnet", + "Auto Premium", + "Claude Opus", + ]); +}); + +it("names a saved route whose plugin is off", () => { + render( + , + ); + expect(control()).toHaveTextContent("Unavailable route"); +}); diff --git a/src/features/agents/ModelPicker.tsx b/src/features/agents/ModelPicker.tsx index cac70c1a32..6647ca5bf6 100644 --- a/src/features/agents/ModelPicker.tsx +++ b/src/features/agents/ModelPicker.tsx @@ -25,6 +25,7 @@ import { Input } from "../../shared/design-system/ui/Input"; import { ModelFamilyMenu } from "./ModelFamilyMenu"; import { formatModelChoices } from "./formatModelDisplayName"; import { Select } from "../../shared/design-system/ui/Select"; +import { routeModel, routeOf, useModelRoutes } from "./model-routes"; export type ModelChoice = Readonly<{ /** The model ID saved in the type's config. */ @@ -40,6 +41,9 @@ export type ModelChoice = Readonly<{ efforts?: readonly { id: string; label: string }[]; effortScope?: string; loadEfforts?: () => Promise; + /** A plugin's model route, e.g. Auto Balanced: listed first, beside + * Default, and it picks the model and effort of each turn itself. */ + route?: boolean; }>; const CUSTOM_MODEL_ACTION: ModelChoice = { @@ -155,7 +159,7 @@ export function ModelPicker({ effort, effortLabel, onEffortChange, - models, + models: catalog, allowCustomModel = false, value, defaultLabel, @@ -169,7 +173,10 @@ export function ModelPicker({ appearance = "outlined", includeDefault = true, description, + harness, }: { + /** The agent type's id: its plugins' model routes join the menu. */ + harness?: string | undefined; label?: string; resetLabel?: string; groupByFamily?: boolean; @@ -199,6 +206,27 @@ export function ModelPicker({ }) { const [customModel, setCustomModel] = useState(null); const control = useRef(null); + const offered = useModelRoutes(harness ?? ""); + // Routes come first; an exclusive harness shows only them and the agent's + // own pinned model. + const routed = harness !== undefined && offered.routes.length > 0; + const own = catalog.filter( + (model) => + !routeOf(model.id) && + (!routed || !offered.exclusive || model.id === value), + ); + const models: readonly ModelChoice[] = routed + ? [ + ...offered.routes.map((route) => ({ + id: routeModel(route.id), + label: route.label, + description: route.description, + route: true, + })), + ...own, + ] + : catalog; + // Default stays when no own model is offered: it is the harness's own. const defaultChoice = models.find((model) => model.id === defaultModel); const efforts = models.find( (model) => model.id === (value || defaultModel), @@ -210,12 +238,24 @@ export function ModelPicker({ // A named model is always a pin, even when it currently matches Default. const listed: ModelChoice[] = [...models]; if (value && !listed.some((model) => model.id === value)) - listed.push({ - id: value, - label: value, - description: allowCustomModel ? "Custom model" : "Unavailable model", - unlisted: true, - }); + listed.push( + routeOf(value) + ? { + id: value, + label: "Unavailable route", + description: "Runs on the default model", + unlisted: true, + route: true, + } + : { + id: value, + label: value, + description: allowCustomModel + ? "Custom model" + : "Unavailable model", + unlisted: true, + }, + ); // The default takes part in telling names apart, even when it is not a row. const [formattedDefault = fallback, ...shownListed] = formatModelChoices( [fallback, ...listed], @@ -259,7 +299,8 @@ export function ModelPicker({ appearance={appearance} resetLabel={resetLabel} effort={effort} - effortLabel={effortLabel} + // A route picks each turn's effort itself. + effortLabel={routeOf(value) ? undefined : effortLabel} onEffortChange={onEffortChange} inherited={!discovering && inherited} valueSuffix={discovering ? undefined : valueSuffix} diff --git a/src/features/agents/model-routes.test.ts b/src/features/agents/model-routes.test.ts new file mode 100644 index 0000000000..264bedc56d --- /dev/null +++ b/src/features/agents/model-routes.test.ts @@ -0,0 +1,290 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { + activeRoute, + initialModel, + launchModel, + type ModelRouter, + resetModelRoutesForTests, + routeLabel, + routeOf, + routesFor, + routeTurn, + setModelRouters, + withRoutes, +} from "./model-routes"; +import type { Model } from "./service"; + +afterEach(() => { + resetModelRoutesForTests(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +const MODELS: readonly Model[] = [ + { + id: "opus", + label: "Opus", + efforts: [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High" }, + ], + }, + { id: "sonnet", label: "Sonnet", efforts: [{ id: "high", label: "High" }] }, +]; + +function router( + select: ModelRouter["select"] = async () => ({ + model: "sonnet", + effort: "high", + rationale: "Small task", + }), + overrides: Partial & object> = {}, +): ModelRouter { + return { + id: "test", + routes: (harness) => + harness === "claude-code" + ? { + routes: [ + { + id: "auto-balanced", + label: "Auto Balanced", + description: "Opus, Sonnet", + fallback: { model: "opus", effort: "high" }, + }, + { id: "auto-premium", label: "Auto Premium" }, + ], + initial: "auto-balanced", + automatic: "auto-premium", + ...overrides, + } + : undefined, + select, + }; +} + +const turn = ( + overrides: Partial[0]> = {}, +): Parameters[0] => ({ + harness: "claude-code", + pick: {}, + current: "route:auto-balanced", + automatic: false, + models: MODELS, + busy: false, + request: { + agent: { pubkey: "a".repeat(64), name: "Agent" }, + prompt: "Fix a typo", + history: async () => [], + }, + signal: new AbortController().signal, + ...overrides, +}); + +it("reads route ids from saved models and keeps them off the command line", () => { + expect(routeOf("route:auto-balanced")).toBe("auto-balanced"); + expect(routeOf(" route:x ")).toBe("x"); + expect(routeOf("route:")).toBeUndefined(); + expect(routeOf("opus")).toBeUndefined(); + expect(launchModel("route:auto-balanced")).toBe(""); + expect(launchModel("opus")).toBe("opus"); +}); + +it("lists a harness's routes from the active routers, first id wins", () => { + expect(routesFor("claude-code").routes).toEqual([]); + const second: ModelRouter = { + id: "second", + routes: () => ({ + routes: [ + { id: "auto-balanced", label: "Duplicate" }, + { id: "Bad Id", label: "Rejected" }, + { id: "auto-fast", label: "Auto Fast" }, + ], + initial: "auto-balanced", + exclusive: true, + }), + select: async () => undefined, + }; + setModelRouters([router(), second]); + const routes = routesFor("claude-code"); + expect(routes.routes.map((route) => route.label)).toEqual([ + "Auto Balanced", + "Auto Premium", + "Auto Fast", + ]); + expect(routes.initial).toBe("auto-balanced"); + expect(routes.exclusive).toBe(true); + expect(routesFor("codex").routes.map((route) => route.label)).toEqual([ + "Duplicate", + "Auto Fast", + ]); + expect(initialModel("claude-code")).toBe("route:auto-balanced"); + expect(routeLabel("claude-code", "route:auto-premium")).toBe("Auto Premium"); + expect(routeLabel("claude-code", "route:gone")).toBe("Unavailable route"); + expect(routeLabel("claude-code", "opus")).toBeUndefined(); + expect(activeRoute("claude-code", "opus", true)?.id).toBe("auto-premium"); + expect(activeRoute("claude-code", "route:auto-balanced", false)?.id).toBe( + "auto-balanced", + ); +}); + +it("re-reads routes when a router says they changed", () => { + let label = "Auto Balanced"; + let notify = () => {}; + setModelRouters([ + { + id: "test", + routes: () => ({ routes: [{ id: "auto", label }] }), + subscribe: (listener) => { + notify = listener; + return () => {}; + }, + select: async () => undefined, + }, + ]); + expect(routesFor("codex").routes[0]?.label).toBe("Auto Balanced"); + label = "Auto Renamed"; + expect(routesFor("codex").routes[0]?.label).toBe("Auto Balanced"); + notify(); + expect(routesFor("codex").routes[0]?.label).toBe("Auto Renamed"); +}); + +it("puts routes first in a model list and hides others only when exclusive", () => { + setModelRouters([router()]); + const models = { current: "opus", models: MODELS }; + expect(withRoutes("claude-code", models).models.map(({ id }) => id)).toEqual([ + "route:auto-balanced", + "route:auto-premium", + "opus", + "sonnet", + ]); + expect(withRoutes("codex", models)).toBe(models); + resetModelRoutesForTests(); + setModelRouters([router(undefined, { exclusive: true })]); + expect(withRoutes("claude-code", models).models.map(({ id }) => id)).toEqual([ + "route:auto-balanced", + "route:auto-premium", + "opus", + ]); +}); + +it("asks the saved route's router for an idle turn's model and effort", async () => { + const select = vi.fn(async () => ({ + model: "sonnet", + effort: "high", + rationale: "Small task", + })); + setModelRouters([router(select)]); + await expect(routeTurn(turn())).resolves.toEqual({ + model: "sonnet", + effort: "high", + routed: { + route: expect.objectContaining({ id: "auto-balanced" }), + rationale: "Small task", + }, + }); + expect(select).toHaveBeenCalledWith( + expect.objectContaining({ + harness: "claude-code", + route: "auto-balanced", + prompt: "Fix a typo", + models: MODELS, + }), + ); +}); + +it("lets an explicit model pick win and keeps a running turn's pick", async () => { + const select = vi.fn(async () => ({ + model: "sonnet", + })); + setModelRouters([router(select)]); + await expect(routeTurn(turn({ pick: { model: "opus" } }))).resolves.toEqual({ + model: "opus", + }); + await expect( + routeTurn(turn({ busy: true, last: { model: "opus", effort: "medium" } })), + ).resolves.toEqual({ + model: "opus", + effort: "medium", + routed: { + route: expect.objectContaining({ id: "auto-balanced" }), + kept: true, + }, + }); + expect(select).not.toHaveBeenCalled(); +}); + +it("routes a per-message route pick and Automatic's route", async () => { + const select = vi.fn(async () => ({ + model: "opus", + })); + setModelRouters([router(select)]); + await routeTurn( + turn({ current: "opus", pick: { model: "route:auto-premium" } }), + ); + await routeTurn(turn({ current: "opus", automatic: true })); + expect(select.mock.calls.map(([request]) => request.route)).toEqual([ + "auto-premium", + "auto-premium", + ]); + await expect(routeTurn(turn({ current: "opus" }))).resolves.toEqual({}); +}); + +it("drops an effort the chosen model doesn't list", async () => { + setModelRouters([router(async () => ({ model: "sonnet", effort: "low" }))]); + await expect(routeTurn(turn())).resolves.toMatchObject({ + model: "sonnet", + }); + expect((await routeTurn(turn())).effort).toBeUndefined(); +}); + +it("falls back when the router fails, answers late or picks an unlisted model", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const fallback = { + model: "opus", + effort: "high", + routed: { + route: expect.objectContaining({ id: "auto-balanced" }), + fallback: true, + }, + }; + setModelRouters([ + router(async () => { + throw new Error("down"); + }), + ]); + await expect(routeTurn(turn())).resolves.toEqual(fallback); + resetModelRoutesForTests(); + setModelRouters([router(async () => ({ model: "haiku" }))]); + await expect(routeTurn(turn())).resolves.toEqual(fallback); + resetModelRoutesForTests(); + vi.useFakeTimers(); + setModelRouters([router(() => new Promise(() => {}))]); + const late = routeTurn(turn()); + await vi.advanceTimersByTimeAsync(30_000); + await expect(late).resolves.toEqual(fallback); +}); + +it("falls back to Automatic's recommendation without a pick", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + setModelRouters([router(async () => undefined)]); + await expect(routeTurn(turn({ automatic: true }))).resolves.toEqual({ + routed: { + route: expect.objectContaining({ id: "auto-premium" }), + fallback: true, + }, + }); +}); + +it("runs a saved route on the harness default while its plugin is off", async () => { + await expect(routeTurn(turn())).resolves.toEqual({}); + await expect(routeTurn(turn({ current: "opus" }))).resolves.toEqual({}); +}); + +it("stops when the turn is cancelled", async () => { + const controller = new AbortController(); + setModelRouters([router(() => new Promise(() => {}))]); + const routed = routeTurn(turn({ signal: controller.signal })); + controller.abort(new Error("cancelled")); + await expect(routed).rejects.toThrow("cancelled"); +}); diff --git a/src/features/agents/model-routes.ts b/src/features/agents/model-routes.ts new file mode 100644 index 0000000000..41ae235adb --- /dev/null +++ b/src/features/agents/model-routes.ts @@ -0,0 +1,377 @@ +// Model routes: choices such as "Auto Balanced" that a bundled plugin adds to +// a harness's Model menu (`Agents.registerModelRouter`). An agent saves a +// route as its model, `route:`. Each turn it starts while idle in that +// conversation asks the plugin's router which of the harness's own models and +// effort levels to run it on; a message that steers a running turn keeps that +// turn's choice, so the session's prompt cache stays warm. The choice reaches +// the harness as the turn's model and effort picks (`Delivery.model`, +// `Delivery.effort`), as a per-message pick does: no harness ever runs a +// route id, and launches its process on its own default (`launchModel`). +// +// - `routes(harness)` lists a harness's routes, the one new agents start on +// (`initial`), the one agents on Automatic use (`automatic`), and whether +// the menu shows only routes (`exclusive`). +// - `select(request)` answers with one of `request.models` and, optionally, +// one of its efforts. A failure, a late answer or a model the harness +// doesn't list runs the route's `fallback`, else the harness's default. +// - An owner's explicit model pick for a message wins over the route. +// - A saved route whose plugin is off runs on the harness's default. +import { useEffect, useRef, useSyncExternalStore } from "react"; +import type { Model, Models } from "./service"; + +export const ROUTE_PREFIX = "route:"; +/** The longest a turn waits for a router before it runs the fallback. */ +export const ROUTE_TIMEOUT_MS = 30_000; + +/** The model value an agent saves for route `id`. */ +export const routeModel = (id: string) => `${ROUTE_PREFIX}${id}`; +/** The route id a saved model names, if it names one. */ +export function routeOf(model: string | undefined) { + const value = model?.trim(); + return value?.startsWith(ROUTE_PREFIX) + ? value.slice(ROUTE_PREFIX.length) || undefined + : undefined; +} +/** The model a harness starts its process on: each turn on a route runs + * on its own pick, so the process starts on the harness's default. */ +export const launchModel = (model: string) => (routeOf(model) ? "" : model); + +export type ModelRoute = Readonly<{ + /** Lowercase letters, digits, `.`, `_` and `-`. */ + id: string; + /** The menu's name for it, e.g. `Auto Balanced`. */ + label: string; + /** A short line under the label, e.g. the models it chooses between. */ + description?: string; + /** What a turn runs on when the router can't answer. */ + fallback?: Readonly<{ model: string; effort?: string }>; +}>; +export type HarnessRoutes = Readonly<{ + routes: readonly ModelRoute[]; + /** The route new agents of the harness start on. */ + initial?: string; + /** The route agents on Automatic use, with the recommended model as the + * fallback. */ + automatic?: string; + /** The Model menu offers only routes (and an agent's current model). */ + exclusive?: boolean; +}>; +export type RouteMessage = Readonly<{ + pubkey: string; + content: string; + /** Unix seconds. */ + createdAt: number; +}>; +export type ModelRouteRequest = Readonly<{ + /** The agent type's id, e.g. `claude-code` or `codex`. */ + harness: string; + route: string; + agent: Readonly<{ pubkey: string; name: string }>; + /** The text of the message or wake that starts the turn. */ + prompt: string; + /** Earlier messages in the turn's thread, oldest first; read only when + * asked, at most once. Empty outside a thread. */ + history(): Promise; + /** The harness's own models for the agent, each with its effort levels. */ + models: readonly Model[]; + signal: AbortSignal; +}>; +export type ModelRouteChoice = Readonly<{ + model: string; + effort?: string; + rationale?: string; +}>; +export type ModelRouter = Readonly<{ + id: string; + routes(harness: string): HarnessRoutes | undefined; + /** Tells `listener` when `routes` may answer differently. */ + subscribe?(listener: () => void): () => void; + select(request: ModelRouteRequest): Promise; +}>; + +const ROUTE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const EMPTY: HarnessRoutes = Object.freeze({ routes: Object.freeze([]) }); + +// The active routers, kept here so every model menu can read them without a +// service in its props, as `recommended.ts` keeps this launch's setup. +let routers: readonly ModelRouter[] = []; +let stops: (() => void)[] = []; +let cache = new Map< + string, + Readonly<{ routes: HarnessRoutes; owners: ReadonlyMap }> +>(); +const listeners = new Set<() => void>(); +const changed = () => { + cache = new Map(); + for (const listener of listeners) listener(); +}; + +/** Replaces the active routers (AgentsService, as plugins start and stop). */ +export function setModelRouters(next: readonly ModelRouter[]) { + for (const stop of stops) stop(); + routers = next; + stops = next.flatMap((router) => { + try { + return router.subscribe ? [router.subscribe(changed)] : []; + } catch (error) { + console.warn(`Model router ${router.id} could not subscribe`, error); + return []; + } + }); + changed(); +} + +/** The routes for `harness`, checked: the first router to offer a route id + * keeps it. The same object until the routers change. */ +export function routesFor(harness: string): HarnessRoutes { + return resolved(harness).routes; +} +function resolved(harness: string) { + const cached = cache.get(harness); + if (cached) return cached; + const routes: ModelRoute[] = []; + const owners = new Map(); + let initial: string | undefined; + let automatic: string | undefined; + let exclusive = false; + for (const router of routers) { + let offered: HarnessRoutes | undefined; + try { + offered = router.routes(harness); + } catch (error) { + console.warn(`Model router ${router.id} could not list routes`, error); + } + for (const route of offered?.routes ?? []) { + if ( + !ROUTE_ID.test(route?.id ?? "") || + typeof route.label !== "string" || + !route.label.trim() || + owners.has(route.id) + ) + continue; + owners.set(route.id, router); + routes.push( + Object.freeze({ + id: route.id, + label: route.label.trim(), + ...(route.description?.trim() && { + description: route.description.trim(), + }), + ...(route.fallback?.model && { + fallback: Object.freeze({ ...route.fallback }), + }), + }), + ); + } + const mine = (id: string | undefined) => + id && owners.get(id) === router ? id : undefined; + initial ??= mine(offered?.initial); + automatic ??= mine(offered?.automatic); + exclusive ||= routes.length > 0 && offered?.exclusive === true; + } + const result: HarnessRoutes = routes.length + ? Object.freeze({ + routes: Object.freeze(routes), + ...(initial && { initial }), + ...(automatic && { automatic }), + ...(exclusive && { exclusive }), + }) + : EMPTY; + const entry = Object.freeze({ routes: result, owners }); + cache.set(harness, entry); + return entry; +} +export function subscribeRoutes(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} +/** The routes for `harness`, rendering again when they change. */ +export function useModelRoutes(harness: string) { + return useSyncExternalStore( + subscribeRoutes, + () => routesFor(harness), + () => routesFor(harness), + ); +} +/** The model a new agent of `harness` starts on: its initial route, or "". */ +export const initialModel = (harness: string) => { + const { initial } = routesFor(harness); + return initial ? routeModel(initial) : ""; +}; +/** Starts a new agent's blank model on the harness's initial route, once: + * a later choice of Default stays. `active` is false for an existing agent + * or one on Automatic. */ +export function useInitialRoute( + harness: string, + active: boolean, + model: string, + apply: (model: string) => void, +) { + const { initial } = useModelRoutes(harness); + const done = useRef(false); + useEffect(() => { + if (done.current || !active || !initial) return; + done.current = true; + if (!model.trim()) apply(routeModel(initial)); + }, [active, apply, initial, model]); +} +/** The route a saved model names, while a router offers it. */ +export const routeFor = (harness: string, model: string | undefined) => { + const id = routeOf(model); + return id + ? routesFor(harness).routes.find((route) => route.id === id) + : undefined; +}; +/** A display name for a saved model that names a route. */ +export const routeLabel = (harness: string, model: string | undefined) => + routeOf(model) + ? (routeFor(harness, model)?.label ?? "Unavailable route") + : undefined; +/** The route an agent runs on, if any: on Automatic, the harness's + * Automatic route; otherwise the route its saved model names. */ +export const activeRoute = ( + harness: string, + model: string | undefined, + automatic: boolean, +) => { + if (!automatic) return routeFor(harness, model); + const { automatic: id, routes } = routesFor(harness); + return id ? routes.find((route) => route.id === id) : undefined; +}; + +/** `models` with the harness's routes first, for pickers such as the + * composer's; the harness's own rows for a route are replaced, and an + * exclusive harness's other own models are left out. */ +export function withRoutes(harness: string, models: Models): Models { + const { routes, exclusive } = routesFor(harness); + // An exclusive menu keeps only the agent's current own model, if any. + const own = models.models.filter( + (model) => + !routeOf(model.id) && (!exclusive || model.id === models.current), + ); + if (!routes.length && own.length === models.models.length) return models; + return { + ...models, + models: [ + ...routes.map((route) => ({ + id: routeModel(route.id), + label: route.label, + efforts: [], + })), + ...own, + ], + }; +} + +export type TurnPick = Readonly<{ model?: string; effort?: string }>; +export type RoutedPick = TurnPick & + Readonly<{ + /** What chose the pick, for the turn's activity. */ + routed?: Readonly<{ + route: ModelRoute; + rationale?: string; + /** The router didn't answer usably. */ + fallback?: true; + /** A steer kept the running turn's pick. */ + kept?: true; + }>; + }>; + +/** A pick of one of `models`, with an effort that model lists. */ +function listed( + models: readonly Model[], + choice: TurnPick | undefined, +): TurnPick | undefined { + const model = models.find((item) => item.id === choice?.model); + if (!model) return undefined; + return { + model: model.id, + ...(choice?.effort && + model.efforts.some((level) => level.id === choice.effort) && { + effort: choice.effort, + }), + }; +} + +/** The pick a turn runs on: `pick`, the owner's for this message, unless + * the agent runs on a route (saved, picked for this message, or Automatic's), + * in which case the route's router chooses, or the running turn's pick is + * kept when the turn will steer (`busy`). */ +export async function routeTurn( + input: Readonly<{ + harness: string; + pick: TurnPick; + /** The model the agent runs on without a pick (`Models.current`). */ + current: string; + automatic: boolean; + models: readonly Model[]; + /** The conversation has a turn running, which this one steers into. */ + busy: boolean; + /** The pick of the conversation's latest routed turn. */ + last?: TurnPick | undefined; + request: Omit; + signal: AbortSignal; + }>, +): Promise { + const { harness, pick } = input; + if (pick.model && !routeOf(pick.model)) return pick; + const { routes, owners } = resolved(harness); + const id = + routeOf(pick.model) ?? + (input.automatic ? routes.automatic : routeOf(input.current)); + if (!id) return pick; + const route = routes.routes.find((item) => item.id === id); + const router = owners.get(id); + // The route's plugin is off, or no longer offers it. + if (!route || !router) return {}; + if (input.busy) return { ...input.last, routed: { route, kept: true } }; + const own = input.models.filter((model) => !routeOf(model.id)); + const late = new AbortController(); + const timer = setTimeout( + () => late.abort(new Error("The model router took too long")), + ROUTE_TIMEOUT_MS, + ); + const signal = AbortSignal.any([input.signal, late.signal]); + let choice: ModelRouteChoice | undefined; + try { + // A router that ignores the signal still can't hold the turn past it. + choice = await new Promise( + (resolve, reject) => { + signal.throwIfAborted(); + signal.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + router + .select({ ...input.request, harness, route: id, models: own, signal }) + .then(resolve, reject); + }, + ); + } catch (error) { + input.signal.throwIfAborted(); + console.warn(`Model route ${id} could not choose a model`, error); + } finally { + clearTimeout(timer); + } + input.signal.throwIfAborted(); + const chosen = listed(own, choice); + if (chosen) + return { + ...chosen, + routed: { + route, + ...(choice?.rationale && { rationale: choice.rationale }), + }, + }; + if (choice) + console.warn(`Model route ${id} chose a model this harness doesn't list`); + // Automatic's recommended model runs without a pick. + const fallback = input.automatic ? undefined : listed(own, route.fallback); + return { ...fallback, routed: { route, fallback: true } }; +} + +/** Clears the routers between tests. */ +export function resetModelRoutesForTests() { + setModelRouters([]); +} diff --git a/src/features/agents/runner.ts b/src/features/agents/runner.ts index ce6ac64a78..f42b27c642 100644 --- a/src/features/agents/runner.ts +++ b/src/features/agents/runner.ts @@ -30,9 +30,11 @@ import type { TeamUpdateInput, AgentHandoff, RegisteredAgentType, + SessionPlace, Trigger, Agents, } from "./service"; +import type { RoutedPick } from "./model-routes"; import type { LocalAgentActivity, WorkOutcome } from "./local-activity"; import type { MentionRefusal } from "./owner-attestation"; import { threadReference } from "../relay/thread-reference"; @@ -607,6 +609,16 @@ export type RunnerHost = { progress(key: AgentKey, progress: TimerProgress): void; /** The team sections of its prompt; empty without a team. */ team(key: AgentKey): string; + /** The model and effort a turn starts with, given the owner's `pick` + * for it: a model route's choice when the agent runs on one. */ + route?( + agent: Agent, + type: RegisteredAgentType, + trigger: Trigger, + place: SessionPlace | undefined, + pick: Readonly<{ model?: string; effort?: string }>, + signal: AbortSignal, + ): Promise; /** What its next run starts with, from this device's storage only. */ start(agent: Agent): Start | Promise>; prepareSession?( @@ -3497,7 +3509,31 @@ export class AgentRunners { anchor, signal, ); - const pick = await pickFor(job.trigger, agent, type); + const owned = await pickFor(job.trigger, agent, type); + const result: RoutedPick = + (await this.host.route?.( + agent, + type, + trigger, + trigger.type === "mention" + ? { + channelId: job.channelId ?? channelOf(trigger.event) ?? "", + root: + threadReference(trigger.event)?.rootId ?? trigger.event.id, + } + : anchor && { + channelId: anchor.channel, + ...(anchor.root ? { root: anchor.root } : {}), + }, + owned, + signal, + )) ?? owned; + const { routed, ...pick } = result; + // The turn's activity says what its route chose, and why. + if (routed && !routed.kept) + job.work?.notice( + `${routed.route.label}${routed.fallback ? " fell back to" : " chose"} ${pick.model || "the default model"}${pick.effort ? ` · ${pick.effort}` : ""}${routed.rationale ? `: ${routed.rationale}` : ""}`, + ); const start = await this.host.start(agent); if (!start.ok) throw new Error(start.reason); const team = this.host.team(agent.key); diff --git a/src/features/agents/service.test.ts b/src/features/agents/service.test.ts index 675b0383ae..876732cbcf 100644 --- a/src/features/agents/service.test.ts +++ b/src/features/agents/service.test.ts @@ -4227,6 +4227,75 @@ it("passes the model and effort its owner asked for, and no other", async () => ]); }); +it("asks a model route for an idle turn's model and keeps it for a steer", async () => { + let state: "idle" | "active" = "idle"; + const { service, run, emit, ctx } = await setup({ + sessionControls: { state: () => state, run: async () => {} }, + }); + await service.create({ type: "example/echo", name: "Echo" }); + const select = vi.fn(async () => ({ + model: "deep", + effort: "max", + rationale: "Hard task", + })); + ctx + .extend({ + pluginOwner: bundledOwner( + Object.freeze({ id: "org.example", revision: "bundled" }), + ), + }) + .agents.registerModelRouter({ + id: "router", + routes: (harness) => + harness === "echo" + ? { routes: [{ id: "auto", label: "Auto" }] } + : undefined, + select, + }); + const asked = (id: string, ...tags: string[][]) => + event(id, { + pubkey: viewer, + tags: [["h", channel], ["p", bot], ["model", bot, "route:auto"], ...tags], + }); + const first = asked("1d1e"); + emit({ events: [first] }); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + expect(select).toHaveBeenCalledWith( + expect.objectContaining({ + harness: "echo", + route: "auto", + models: [ + expect.objectContaining({ id: "fast" }), + expect.objectContaining({ id: "deep" }), + ], + }), + ); + expect(run.mock.calls[0]?.[0]).toMatchObject({ + model: "deep", + effort: "max", + }); + // The conversation now has a turn running: the next message steers it. + state = "active"; + emit({ events: [asked("57ee", ["e", first.id, "", "reply"])] }); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(2)); + expect(select).toHaveBeenCalledTimes(1); + expect(run.mock.calls[1]?.[0]).toMatchObject({ + model: "deep", + effort: "max", + }); +}); + +it("lists model routes only from bundled plugins", async () => { + const { plugin } = await setup(); + expect(() => + plugin.agents.registerModelRouter({ + id: "router", + routes: () => undefined, + select: async () => undefined, + }), + ).toThrow(); +}); + it("ignores the model and effort asked of an agent on Automatic", async () => { // A synthetic recommendation for the example type. setRuntimeRecommendation({ diff --git a/src/features/agents/service.ts b/src/features/agents/service.ts index 3d64a0f650..34786fc23e 100644 --- a/src/features/agents/service.ts +++ b/src/features/agents/service.ts @@ -80,6 +80,7 @@ import { awaitRecommendation, candidatesFor, offRecommended, + onAutomatic, onRecommended, pickRecommendedSurely, recommendationFinal, @@ -198,6 +199,16 @@ import { } from "../relay/events"; import { relayPartition } from "../relay/partition"; import { threadReference } from "../relay/thread-reference"; +import { + type ModelRouter, + type RoutedPick, + type RouteMessage, + routesFor, + routeTurn, + setModelRouters, + type TurnPick, + withRoutes, +} from "./model-routes"; import { channelTabs } from "../../bundled/channels/useChannelTabState"; import type { RelayData } from "../relay/service"; import type { RelaySession } from "../relay/session"; @@ -1662,6 +1673,24 @@ export type ModelSettings = Readonly<{ * it, and leaving it out keeps it. */ export type NoteChange = Readonly<{ note?: PluginNote | null }>; const MODEL_FIELDS = ["model", "provider", "effort"] as const; +/** Conversations whose latest routed pick is kept for their steers. */ +const ROUTED_PICKS = 512; +/** Earlier thread messages a model router may read. */ +const ROUTE_HISTORY = 20; +/** The most prompt text a model router is given. */ +const ROUTE_PROMPT_CHARS = 16_000; +/** What a turn asks, as a model router reads it. */ +function promptOf(trigger: Trigger) { + const text = + trigger.type === "mention" || trigger.type === "watch" + ? trigger.event.content + : trigger.type === "catch-up" + ? trigger.events.map(({ event }) => event.content).join("\n\n") + : trigger.type === "timer" + ? trigger.timer.prompt + : trigger.text; + return text.slice(-ROUTE_PROMPT_CHARS); +} export type Agents = { readonly invocationSubthreads?: true; readonly invocationIntentVersion?: 1; @@ -1754,6 +1783,12 @@ export type Agents = { * a launch is asked; later calls are ignored. With no plugin calling it * once bundled plugins have started, the access check's list stands. */ gatewayHarnesses(source: GatewayHarnessSource): void; + /** Bundled plugins only: adds model routes, such as "Auto Balanced", to + * harnesses' Model menus, and chooses the model and effort of each turn an + * agent on one starts while idle in its conversation (model-routes.ts). + * Its `select` is given the turn's prompt, so only the build's own plugins + * may route. It lasts while the plugin is on. */ + registerModelRouter(router: ModelRouter): void; // Bundled plugins only, like `recommend`: the building blocks for a plugin // that moves agents onto Automatic. /** Whether plugin start-up is over (each plugin started, or failed), the @@ -2523,6 +2558,14 @@ export class AgentsService extends Service implements Agents { } private readonly contributions; private readonly tabContributions; + private readonly modelRouters; + /** Each conversation's latest routed pick, which a steer keeps. */ + private readonly routedPicks = new Map(); + /** Each registered type's own `models`, before routes are added, by key. */ + private readonly ownModels = new Map< + string, + (agent: Agent) => Promise + >(); private readonly attentionControls; private readonly addedTools; private readonly operationNames = new Set(); @@ -2695,6 +2738,16 @@ export class AgentsService extends Service implements Agents { this.addedTools = createContributions(ctx); this.addedInstructions = createContributions(ctx); this.attentionSources = createContributions(ctx); + this.modelRouters = createContributions(ctx); + ctx.effect(() => { + const publish = () => setModelRouters(this.modelRouters.snapshot()); + const stop = this.modelRouters.subscribe(publish); + publish(); + return () => { + stop(); + setModelRouters([]); + }; + }); // Agents on Automatic follow this launch's setup once it is final. void awaitRecommendation((signal) => this.recommendedAnswer(signal)).then( () => { @@ -2828,6 +2881,8 @@ export class AgentsService extends Service implements Agents { nativePlacement, pinNativePlacement, ), + route: (agent, type, trigger, place, pick, signal) => + this.routedPick(agent, type, trigger, place, pick, signal), prepareSession: async (agent, type, trigger, placement, signal) => { if ( !type.sessionAdmission || @@ -3738,14 +3793,26 @@ export class AgentsService extends Service implements Agents { const voice = (type as unknown as AgentType).voice; const models = type.models; const pluginId = this.ctx.pluginOwner?.id; + const own = + models && + (async (agent: Agent) => { + await this.checkExecution(agent.key, agent.type); + return models(agent); + }); + if (own && pluginId) { + const key = `${pluginId}/${type.id}`; + this.ownModels.set(key, own as (agent: Agent) => Promise); + this.ctx.effect(() => () => { + if (this.ownModels.get(key) === (own as unknown)) + this.ownModels.delete(key); + }); + } this.contributions.register(this.ctx, { ...type, ...(skillFolders && { skillFolders }), - ...(models && { - models: async (agent: Agent) => { - await this.checkExecution(agent.key, agent.type); - return models(agent); - }, + ...(own && { + models: async (agent: Agent) => + withRoutes(type.id, await own(agent)), }), ...(voice ? { @@ -3905,6 +3972,109 @@ export class AgentsService extends Service implements Agents { ended.abort(); } } + registerModelRouter(router: ModelRouter) { + this.bundledCaller("registerModelRouter"); + if ( + !router || + typeof router.id !== "string" || + typeof router.routes !== "function" || + typeof router.select !== "function" || + (router.subscribe !== undefined && typeof router.subscribe !== "function") + ) + throw new Error("A model router needs an id, routes and select"); + this.modelRouters.register(this.ctx, router); + } + /** The pick a turn starts with: `pick`, unless the agent runs on a model + * route, whose router chooses unless the turn steers a running one. */ + private async routedPick( + agent: Agent, + type: RegisteredAgentType, + trigger: Trigger, + place: SessionPlace | undefined, + pick: TurnPick, + signal: AbortSignal, + ): Promise { + const models = this.ownModels.get(type.key) ?? type.models; + if (!routesFor(type.id).routes.length || !models) return pick; + let offered: Models; + try { + offered = await models(agent); + } catch (error) { + console.warn(`Agent type ${type.key} could not list its models`, error); + return pick; + } + const conversation = place && this.sessionPlace(agent, type, place); + const key = + conversation && + JSON.stringify([ + agent.key, + conversation.channelId, + conversation.root ?? "", + conversation.community === true, + ]); + const state = place ? this.sessionState(agent.key, place) : "idle"; + let history: Promise | undefined; + const routed = await routeTurn({ + harness: type.id, + pick, + current: offered.current, + automatic: onAutomatic(agent.config, type.id), + models: offered.models, + busy: state === "active" || state === "compacting", + last: key ? this.routedPicks.get(key) : undefined, + request: { + agent: { pubkey: agent.pubkey, name: agent.name }, + prompt: promptOf(trigger), + history: () => + (history ??= this.routeHistory(agent, trigger, place, signal)), + }, + signal, + }); + if (key && routed.routed && !routed.routed.kept) { + this.routedPicks.delete(key); + this.routedPicks.set(key, { + ...(routed.model ? { model: routed.model } : {}), + ...(routed.effort ? { effort: routed.effort } : {}), + }); + if (this.routedPicks.size > ROUTED_PICKS) + this.routedPicks.delete(this.routedPicks.keys().next().value as string); + } + return routed; + } + /** The thread before a routed turn's message, oldest first: at most + * ROUTE_HISTORY messages, read once and only if its router asks. */ + private async routeHistory( + agent: Agent, + trigger: Trigger, + place: SessionPlace | undefined, + signal: AbortSignal, + ): Promise { + const reads = ownerReads(this.relay(agent.key), agent.pubkey); + const root = place?.root; + if (!reads || !place || !root) return []; + const current = trigger.type === "mention" ? trigger.event.id : undefined; + const events = await reads.read( + [ + { ids: [root], "#h": [place.channelId], limit: 1 }, + { + kinds: [9, 40002], + "#h": [place.channelId], + "#e": [root], + limit: ROUTE_HISTORY, + }, + ], + signal, + ); + return [...new Map(events.map((event) => [event.id, event])).values()] + .filter((event) => event.id !== current) + .sort((a, b) => a.created_at - b.created_at) + .slice(-ROUTE_HISTORY) + .map((event) => ({ + pubkey: event.pubkey, + content: event.content, + createdAt: event.created_at, + })); + } /** The calling plugin's id; throws unless it is bundled. */ private bundledCaller(what: string) { const owner = this.ctx.pluginOwner; From 20e62574f7c211f3b6f53f7c3092f11cfe613178 Mon Sep 17 00:00:00 2001 From: Atish Patel Date: Mon, 23 Nov 2026 09:22:57 -0600 Subject: [PATCH 02/14] feat(goose): offer model routes in Goose's Model menu Goose agents can save a plugin's model route, as Claude Code and Codex agents can. The process starts on the provider's default, each turn runs on the route's pick from the provider's own models, Thinking shows Auto, and Automatic agents use the harness's Automatic route. Signed-off-by: Atish Patel --- docs/buzz-help.md | 2 +- docs/configuration.md | 2 +- src/bundled/goose/index.ts | 7 +++- src/bundled/goose/runtime.test.ts | 32 ++++++++++++++ src/bundled/goose/runtime.ts | 4 +- src/bundled/goose/setup.test.ts | 17 ++++++++ src/bundled/goose/setup.ts | 8 +++- src/bundled/goose/tabs.tsx | 70 ++++++++++++++++++++++++++----- 8 files changed, 125 insertions(+), 17 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index bfeab45815..c086690a8d 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -164,7 +164,7 @@ if that desktop app is up and running. - **Sessions.** By default an agent starts a fresh conversation for each thread. Its settings can make it one per channel or one per community. - **Auto models.** Some builds add choices such as **Auto Balanced** to the - Model menu of Claude Code and Codex agents. Before each new turn, the build + Model menu of Claude Code, Codex and Goose agents. Before each new turn, the build picks a model and thinking level for that message, and the turn's activity says which and why. A message sent while the agent is working keeps its model, and a model chosen beside Send still wins. diff --git a/docs/configuration.md b/docs/configuration.md index 69bc3cdda9..49936abdab 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -160,7 +160,7 @@ A bundled plugin can replace the setup per launch with seconds for it, then falls back to `BUZZ_RECOMMENDED_AGENT`, so set both. A bundled plugin can also add **model routes**, such as "Auto Balanced", to the -Claude Code and Codex Model menus with `ctx.agents.registerModelRouter(router)`. +Claude Code, Codex and Goose Model menus with `ctx.agents.registerModelRouter(router)`. An agent on a route saves `route:` as its model. Before each turn it starts while idle in a conversation, Buzz asks `router.select` for one of the harness's models and a thinking level. A turn that steers a running one keeps diff --git a/src/bundled/goose/index.ts b/src/bundled/goose/index.ts index 2f34ace6d8..1e4097d7ab 100644 --- a/src/bundled/goose/index.ts +++ b/src/bundled/goose/index.ts @@ -18,9 +18,11 @@ import { } from "./runtime"; import { type RecommendedCandidate, + onAutomatic, onRecommended, recommendedRun, } from "../../features/agents/recommended"; +import { activeRoute, routeLabel } from "../../features/agents/model-routes"; import { REQUEST_TIMEOUT_MS } from "./goose"; import { gooseRun } from "./run"; import { readModelSettings } from "../../features/agents/model-settings"; @@ -198,7 +200,10 @@ export const apply: PluginModule["apply"] = (ctx) => { }, summary: (agent) => { const { model, provider } = running(agent.config, recommended.current()); - return [provider, model].filter(Boolean).join(" · ") || "Goose"; + const route = + activeRoute(TYPE_ID, model, onAutomatic(agent.config, TYPE_ID)) + ?.label ?? routeLabel(TYPE_ID, model); + return [provider, route ?? model].filter(Boolean).join(" · ") || "Goose"; }, sessions: { ready: (agentKey) => runtime.listed(agentKey), diff --git a/src/bundled/goose/runtime.test.ts b/src/bundled/goose/runtime.test.ts index d498a99065..a1aaac0474 100644 --- a/src/bundled/goose/runtime.test.ts +++ b/src/bundled/goose/runtime.test.ts @@ -1440,6 +1440,38 @@ describe("GooseRuntime", () => { expect(turn).not.toContain("create a new worktree"); }); + it("starts an agent on a model route on its provider's default, and runs each turn on its pick", async () => { + const written: string[] = []; + const { deliver, goose } = setup({ + wrap: (spawn) => async (id, options) => { + const process = await spawn(id, options); + return { + ...process, + write: (data: string) => { + written.push(data); + return process.write(data); + }, + }; + }, + }); + const config = { + ...DEFAULT_CONFIG, + provider: "openai", + model: "route:auto-balanced", + }; + await deliver(message("1", "@Gander go"), { config, model: "o3" }); + await vi.waitFor(() => expect(goose()?.turns).toHaveLength(1)); + expect(written.some((data) => data.includes("route:"))).toBe(false); + expect( + written.some( + (data) => + data.includes('"method":"session/set_config_option"') && + data.includes('"o3"'), + ), + ).toBe(true); + goose()?.turns[0]?.finish(); + }); + it("reads a queued turn's Canvas with the working location its own turn's prompt has", async () => { const { agent, deliver, goose } = setup({ solo: new Set([channel]), diff --git a/src/bundled/goose/runtime.ts b/src/bundled/goose/runtime.ts index e254d95022..9fc4504573 100644 --- a/src/bundled/goose/runtime.ts +++ b/src/bundled/goose/runtime.ts @@ -45,6 +45,7 @@ import { type TurnResult, } from "../../features/agents/service"; import { compactAt } from "../../features/agents/compact-at"; +import { launchModel } from "../../features/agents/model-routes"; import { workflowOf } from "../../features/agents/owner-attestation"; import { agentFolders, @@ -1872,7 +1873,8 @@ export class GooseRuntime { private choice(entry: Entry) { return { provider: entry.config.provider.trim(), - model: entry.config.model.trim(), + // A saved model route picks per turn; the process starts on the default. + model: launchModel(entry.config.model.trim()), effort: entry.config.effort, }; } diff --git a/src/bundled/goose/setup.test.ts b/src/bundled/goose/setup.test.ts index 5874c66379..f644bbb670 100644 --- a/src/bundled/goose/setup.test.ts +++ b/src/bundled/goose/setup.test.ts @@ -713,6 +713,23 @@ describe("GooseSetup", () => { }); }); + it("offers an agent on a model route its provider's own models", async () => { + const { setup: configured } = setup({ + saved: new Map([["anthropic", new Set(["ANTHROPIC_API_KEY"])]]), + }); + await expect( + configured.picks({ provider: "anthropic", model: "route:auto-balanced" }), + ).resolves.toEqual({ + current: "route:auto-balanced", + // No row for the route itself, and none for the provider's default + // model the provider doesn't list. + models: [ + { id: "claude-opus-5-5", label: "claude-opus-5-5", efforts: [] }, + { id: "claude-haiku-5-5", label: "claude-haiku-5-5", efforts: [] }, + ], + }); + }); + it("saves a provider's fields into goose and reads the list again", async () => { const saved = new Map>(); const { fake, setup: goose } = setup({ saved }); diff --git a/src/bundled/goose/setup.ts b/src/bundled/goose/setup.ts index b3dcab710a..7547ab11b6 100644 --- a/src/bundled/goose/setup.ts +++ b/src/bundled/goose/setup.ts @@ -4,6 +4,7 @@ // into Buzz. import type { ModelChoice } from "../../features/agents/ModelPicker"; import { withProviderWords } from "../../features/agents/failure-words"; +import { routeOf } from "../../features/agents/model-routes"; import type { ProtectedSpawn, ReviewPrompt, @@ -279,9 +280,12 @@ export class GooseSetup { // A provider not set up offers only the model the agent names. const ready = Boolean(id && !listed?.needs); const offered = ready ? await this.models(id ?? "") : []; - // A model its provider does not list is still the one it runs on. + // A model its provider does not list is still the one it runs on; a + // saved route is the current choice, and the agents service lists it. const named = - !current || offered.some((model) => model.id === current) + !current || + routeOf(current) || + offered.some((model) => model.id === current) ? offered : [{ id: current, label: current }, ...offered]; // Without levels a model offers no slider, so a failed read costs only it. diff --git a/src/bundled/goose/tabs.tsx b/src/bundled/goose/tabs.tsx index dd5a0940de..5a82f9af0b 100644 --- a/src/bundled/goose/tabs.tsx +++ b/src/bundled/goose/tabs.tsx @@ -36,6 +36,13 @@ import { type ModelChoice, ModelPicker, } from "../../features/agents/ModelPicker"; +import { + activeRoute, + routeModel, + routeOf, + useInitialRoute, + useModelRoutes, +} from "../../features/agents/model-routes"; import { OpenedConversation, useOpenTranscript, @@ -567,6 +574,7 @@ export function createTabs({ {!hideModel && provider && (provider.configured || rows) && ( ) { + // A route picks each turn's level itself. + const routed = Boolean(routeOf(choice.model)); const [efforts, retry] = useRead( - () => setup.efforts(choice), + () => + routed + ? Promise.resolve({ current: "", levels: [] }) + : setup.efforts(choice), `${choice.provider}\u0000${choice.model.trim()}:${revision}`, ); const failed = @@ -703,13 +716,20 @@ export function createTabs({ variant={compact ? "compact" : "preference"} {...(compact && { align: "end" as const })} value={value} - {...(!value + {...(routed ? { - valueLabel: fallback ?? "Default", - ...(compact && fallback ? { valueSuffix: " · Default" } : {}), + valueLabel: "Auto", + ...(!compact && { + description: "Chosen for each conversation's turns", + }), } - : {})} - disabled={disabled} + : !value + ? { + valueLabel: fallback ?? "Default", + ...(compact && fallback ? { valueSuffix: " · Default" } : {}), + } + : {})} + disabled={routed || disabled} {...(failed && !compact ? { description: failed } : {})} groups={[ { @@ -1220,6 +1240,7 @@ export function createTabs({ } function CreateModel({ + agent, config, onChange, onReadyChange, @@ -1230,6 +1251,12 @@ export function createTabs({ // A pick here takes the agent off Recommended, from what it runs on. const resolved = useRecommended(onRecommended(config)); const current = offRecommended(running(config, resolved)); + useInitialRoute( + "goose", + !agent && !onRecommended(config), + current.model, + (model) => onChange({ ...current, model, effort: "" }), + ); const [open, setOpen] = useState(false); const [listing, reload] = useRead(() => setup.providers(), "providers"); const provider = current.provider || listing.value?.defaults.provider || ""; @@ -1254,7 +1281,7 @@ export function createTabs({ useEffect(() => onReadyChange?.(ready), [onReadyChange, ready]); const [thinking] = useRead( () => - provider && selectedModel + provider && selectedModel && !routeOf(selectedModel) ? setup.efforts({ provider, model: selectedModel }) : Promise.resolve({ current: "", levels: [] }), `${provider}\u0000${selectedModel}`, @@ -1289,6 +1316,7 @@ export function createTabs({ > 0; const resolved = useRecommended(following); + // The route Automatic runs on, while a plugin offers one. + useModelRoutes("goose"); + const automaticRoute = activeRoute("goose", "", true); const manual = ( <> {settingsHost?.typeControl?.(configChanged)} @@ -1413,7 +1444,14 @@ export function createTabs({ rows value={draft} onChange={(choice) => - setDraft(offRecommended({ ...draft, ...choice })) + setDraft( + offRecommended({ + ...draft, + ...choice, + // A route picks each turn's level itself. + ...(routeOf(choice.model) ? { effort: "" } : {}), + }), + ) } /> - // Manual starts from the recommendation it ran on. + // Manual starts from the recommendation it ran on, or + // from its Automatic route on that provider. setDraft( on ? readConfig(withRecommended(draft)) - : offRecommended(running(draft, resolved)), + : offRecommended( + automaticRoute + ? { + ...running(draft, resolved), + model: routeModel(automaticRoute.id), + effort: "", + } + : running(draft, resolved), + ), ) } > From 86bc7ae4c73e68b49a7ad1affadc43940631bc3a Mon Sep 17 00:00:00 2001 From: Atish Patel Date: Mon, 23 Nov 2026 09:29:45 -0600 Subject: [PATCH 03/14] fix(agents): offer no model routes on remote execution targets A bound or hosted agent runs on its target's models, which this device can't list, so its Model menus offer no routes and its turns are never routed. Signed-off-by: Atish Patel --- src/bundled/claude-code/tabs.tsx | 9 ++++++--- src/bundled/codex/tabs.tsx | 7 ++++--- src/features/agents/service.ts | 2 ++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 2641ffb419..92c3537850 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -522,7 +522,7 @@ export function createTabs({ return ( 0; // The route Automatic runs on, while a plugin offers one. useModelRoutes("claude-code"); - const automaticRoute = activeRoute("claude-code", "", true); + // A remote target runs on its own models: no routes there. + const automaticRoute = remote + ? undefined + : activeRoute("claude-code", "", true); const found = useRecommended(following); // A remote target runs Recommended on its own default. const resolved = remote ? null : found; @@ -1521,7 +1524,7 @@ export function createTabs({ const modelControl = ( <> 0; // The route Automatic runs on, while a plugin offers one. useModelRoutes("codex"); - const automaticRoute = activeRoute("codex", "", true); + // A remote target runs on its own models: no routes there. + const automaticRoute = bound ? undefined : activeRoute("codex", "", true); // A remote target runs Recommended on its own default. const resolved = bound ? null : provider.recommended(); const effective = provider.resolve({ ...draft, effort: "" }, !!bound); @@ -1709,7 +1710,7 @@ export function createTabs( )} { const models = this.ownModels.get(type.key) ?? type.models; + // Hosted, or on another execution target, it runs on that one's models. + if (agent.place === "hosted" || agent.executionBinding) return pick; if (!routesFor(type.id).routes.length || !models) return pick; let offered: Models; try { From 85e068cf09de30421523a30ffbe461855e4881da Mon Sep 17 00:00:00 2001 From: Atish Patel Date: Mon, 23 Nov 2026 10:20:27 -0600 Subject: [PATCH 04/14] Choose a model route's pick where the harness starts a turn The harness now asks a lazy Delivery.route only where a delivery starts a new turn (Claude when its process is idle, Codex as its job starts, Goose as its session starts or pumps a queued turn), never for a steer. The owner's mention authority is checked before the router sees the prompt, standalone watch and timer wakes are not routed, Stop works while the route chooses, and the thread history read ends with the choice. Codex shows a saved route no router offers as its default. Co-authored-by: Worker Bee (Opus) <4a3bc7fd57a7b2c126e4f3d3462dd16f375242e1c176b4b3f25ca93e3edb6a84@buzz.block.builderlab.xyz> Signed-off-by: Atish Patel --- src/bundled/claude-code/runtime.ts | 2 + src/bundled/claude-code/sessions.test.ts | 30 ++++ src/bundled/claude-code/sessions.ts | 11 ++ src/bundled/codex/runtime.test.ts | 30 ++++ src/bundled/codex/runtime.ts | 36 ++++- src/bundled/goose/runtime.test.ts | 38 ++++- src/bundled/goose/runtime.ts | 11 +- .../agent-harness/acp/agent-sessions.ts | 21 ++- src/features/agent-harness/acp/session.ts | 29 +++- src/features/agents/model-routes.test.ts | 41 ++++-- src/features/agents/model-routes.ts | 76 ++++++---- src/features/agents/runner.ts | 98 +++++++++---- src/features/agents/service.test.ts | 99 ++++++++++--- src/features/agents/service.ts | 132 +++++++++++------- 14 files changed, 508 insertions(+), 146 deletions(-) diff --git a/src/bundled/claude-code/runtime.ts b/src/bundled/claude-code/runtime.ts index 1d3c2c5b10..f06a764db2 100644 --- a/src/bundled/claude-code/runtime.ts +++ b/src/bundled/claude-code/runtime.ts @@ -1284,6 +1284,7 @@ export class ClaudeRuntime { channelId, model, effort, + route: chooseModel, synced, team, workingUntil, @@ -1639,6 +1640,7 @@ export class ClaudeRuntime { ...(model ? { model } : {}), ...(effort ? { effort } : {}), }, + ...(chooseModel ? { route: chooseModel } : {}), admit, // Mentions already show the host's fallback under the request. ...this.turnAttribution( diff --git a/src/bundled/claude-code/sessions.test.ts b/src/bundled/claude-code/sessions.test.ts index 3b8d13981c..b854bd7d8b 100644 --- a/src/bundled/claude-code/sessions.test.ts +++ b/src/bundled/claude-code/sessions.test.ts @@ -884,6 +884,36 @@ it("runs a turn with the model and effort it was delivered with, starting over i expect(fresh?.efforts).toEqual(["low", "high"]); }); +it("asks a model route for a new turn's pick, and not for a steer", async () => { + const { pool, claudes } = sessions({ hold: true }); + const route = vi.fn(async () => ({ model: "haiku", effort: "low" })); + const first = pool.deliver("c/root", "first", 1, { route }); + await flush(); + const process = claudes()[0]; + if (!process) throw new Error("no process"); + const steer = vi.fn(async () => ({ model: "sonnet" })); + const second = pool.deliver("c/root", "plain", 2, { + steer: "steer", + route: steer, + }); + await flush(); + expect(process.prompts).toEqual(["first", "steer"]); + expect(process.models).toEqual(["haiku", "haiku"]); + expect(route).toHaveBeenCalledTimes(1); + expect(steer).not.toHaveBeenCalled(); + process.finish(); + await expect(first).resolves.toEqual({ ok: true }); + await expect(second).resolves.toEqual({ ok: true }); +}); + +it("sends nothing when a model route's choice was stopped", async () => { + const { pool, claudes } = sessions(); + await expect( + pool.deliver("c/root", "hello", 1, { route: async () => undefined }), + ).resolves.toEqual({ ok: true, undelivered: true }); + expect(claudes().flatMap((process) => process.prompts)).toEqual([]); +}); + it("runs any number of conversations at once", async () => { const { pool, live } = sessions({ hold: true }); for (let index = 0; index < 12; index++) diff --git a/src/bundled/claude-code/sessions.ts b/src/bundled/claude-code/sessions.ts index d0e402afc3..fa19e19e58 100644 --- a/src/bundled/claude-code/sessions.ts +++ b/src/bundled/claude-code/sessions.ts @@ -110,6 +110,10 @@ type DeliveryOptions = Readonly<{ refresh?: (fresh?: boolean) => Promise; fresh?: () => Promise; pick?: TurnPick; + /** Chooses `pick` for a turn this message starts, asked once a process + * would take it as a new turn (`Delivery.route`); a steer asks nothing. + * Undefined sends nothing. */ + route?: () => Promise; /** The thread whose history was supplied to a shared channel session. */ contextRoot?: string; /** Rejects a turn the current settings can't start, asked after every @@ -362,6 +366,7 @@ export class AgentSessions { refresh, fresh, pick = {}, + route, contextRoot, admit, attribute, @@ -414,6 +419,12 @@ export class AgentSessions { } if (attribute && !live.process.busy) await this.attribute(key, live, attribute); + // Its model route chooses for a new turn only. + if (route && !live.process.busy) { + const chosen = await route(); + if (!chosen) return { ok: true, undelivered: true }; + pick = chosen; + } if (current && !current()) return { ok: true, undelivered: true }; if (this.disposed) return { ok: false, error: "Claude was stopped", undelivered: true }; diff --git a/src/bundled/codex/runtime.test.ts b/src/bundled/codex/runtime.test.ts index 879acce109..5d57c82669 100644 --- a/src/bundled/codex/runtime.test.ts +++ b/src/bundled/codex/runtime.test.ts @@ -3181,6 +3181,36 @@ it("starts a turn on the model its owner picked, at an effort that model support { model: "test-model", effort: "low" }, ]); }); +it("starts a routed turn on its route's choice, and nothing when it was stopped", async () => { + const f = fixture(); + const route = vi.fn(async () => ({ model: "deep-model", effort: "xhigh" })); + await f.runtime.run({ ...f.delivery("@Codex", "a".repeat(64)), route }); + await vi.waitFor(() => expect(f.starts()).toHaveLength(1)); + expect(route).toHaveBeenCalledTimes(1); + expect(f.starts()[0]?.params).toMatchObject({ + model: "deep-model", + effort: "xhigh", + }); + const stopped = vi.fn(async () => undefined); + await f.runtime.run({ + ...f.delivery("@Codex", "b".repeat(64)), + route: stopped, + }); + await vi.waitFor(() => expect(stopped).toHaveBeenCalled()); + await f.runtime.run(f.delivery("@Codex next", "c".repeat(64))); + await vi.waitFor(() => expect(f.starts()).toHaveLength(2)); + // The next turn Codex starts is the plain one. + expect(JSON.stringify(f.starts()[1]?.params)).toContain("@Codex next"); +}); +it("shows a saved route no router offers as Codex's default", async () => { + const f = fixture(); + const agent = { + key: pubkey, + pubkey, + config: { workspace: "/tmp/codex-test", model: "route:gone" }, + } as Agent; + expect((await f.runtime.preview(agent)).current).toBe("test-model"); +}); it("runs a mid-turn pick that differs from the running turn as the next turn instead of steering", async () => { const f = fixture(); const settings = (wire: Wire) => { diff --git a/src/bundled/codex/runtime.ts b/src/bundled/codex/runtime.ts index d2b4f457e5..2b0781f8d2 100644 --- a/src/bundled/codex/runtime.ts +++ b/src/bundled/codex/runtime.ts @@ -35,7 +35,7 @@ import { wakeLands, } from "../../features/agent-harness/plugin-wake"; import { compactAt } from "../../features/agents/compact-at"; -import { routeOf } from "../../features/agents/model-routes"; +import { routeFor } from "../../features/agents/model-routes"; import { composeBase, sectionsKey, @@ -211,6 +211,9 @@ type Request = { /** The model and effort the owner picked for this turn. */ model?: string; effort?: string; + /** Chooses them as the turn this request starts begins + * (`Delivery.route`); one that steers asks nothing. */ + route?: Delivery["route"]; /** The synced settings in `settings`. */ synced?: Delivery["synced"]; /** Called once a final send answers this request, or one steered after it @@ -1107,10 +1110,13 @@ export class CodexRuntime { throw new Error("The protected agent has no live policy binding"); handle?.protection?.assertAvailable(); const settings = this.resolveConfig(agent.config); + // A saved route is current only while a router offers it. + const routed = routeFor("codex", settings.model) !== undefined; const key = JSON.stringify([ settings.model, settings.effort, handle?.protection?.key, + routed, ]); const existing = this.previews.get(agent.key); if (existing?.key === key) return existing.ready; @@ -1156,7 +1162,8 @@ export class CodexRuntime { // A configured model this Codex does not list still leaves the // listed ones to pick, so the picker stays. // A saved route is the current choice; the agents service lists it. - if (routeOf(settings.model)) + // One no router offers runs on Codex's default, which is current. + if (routed) return { current: settings.model, models: offered, sendDefaults: true }; return !model || models.some((row) => row.model === model) ? { current: model ?? "", models: offered, sendDefaults: true } @@ -2624,6 +2631,7 @@ export class CodexRuntime { ...(toolRoot ? { toolRoot } : {}), ...(delivery.model ? { model: delivery.model } : {}), ...(delivery.effort ? { effort: delivery.effort } : {}), + ...(delivery.route ? { route: delivery.route } : {}), ...(delivery.synced ? { synced: delivery.synced } : {}), activityScope: topLevel ? channelId @@ -3408,6 +3416,30 @@ export class CodexRuntime { request.answered(); return; } + // Its model route chooses as the turn begins; messages behind it + // steer in on that choice. + if (request.route) { + let chosen: Awaited>>; + try { + chosen = await request.route(); + } finally { + delete request.route; + } + if (!chosen) { + request.answered(true); + return; + } + if (chosen.model) request.model = chosen.model; + if (chosen.effort) request.effort = chosen.effort; + if (entry.abort.signal.aborted) { + request.failActivity("Codex was stopped"); + return; + } + if (request.current && !request.current()) { + request.answered(); + return; + } + } try { await entry.after; // A rerun waits for the retired Huddle seat to let go of the lane. diff --git a/src/bundled/goose/runtime.test.ts b/src/bundled/goose/runtime.test.ts index a1aaac0474..6d0285f250 100644 --- a/src/bundled/goose/runtime.test.ts +++ b/src/bundled/goose/runtime.test.ts @@ -1459,8 +1459,10 @@ describe("GooseRuntime", () => { provider: "openai", model: "route:auto-balanced", }; - await deliver(message("1", "@Gander go"), { config, model: "o3" }); + const route = vi.fn(async () => ({ model: "o3" })); + await deliver(message("1", "@Gander go"), { config, route }); await vi.waitFor(() => expect(goose()?.turns).toHaveLength(1)); + expect(route).toHaveBeenCalledTimes(1); expect(written.some((data) => data.includes("route:"))).toBe(false); expect( written.some( @@ -1472,6 +1474,40 @@ describe("GooseRuntime", () => { goose()?.turns[0]?.finish(); }); + it("sends nothing when its model route's choice was stopped", async () => { + const { deliver, goose } = setup(); + const config = { ...DEFAULT_CONFIG, model: "route:auto-balanced" }; + const route = vi.fn(async () => undefined); + await deliver(message("1", "@Gander go"), { config, route }); + await vi.waitFor(() => expect(route).toHaveBeenCalledTimes(1)); + await deliver(message("2", "@Gander next"), { config }); + await vi.waitFor(() => expect(goose()?.turns).toHaveLength(1)); + // The first turn Goose sees is the plain one. + expect(JSON.stringify(goose()?.turns[0])).toContain("@Gander next"); + }); + + it("asks no model route for a message that steers a running turn", async () => { + const { deliver, goose } = setup({ scope: "channel", hold: true }); + const config = { + ...DEFAULT_CONFIG, + scope: "channel", + model: "route:auto-balanced", + }; + const first = vi.fn(async () => ({ model: "o3" })); + await deliver(message("1", "@Gander first"), { config, route: first }); + await vi.waitFor(() => expect(goose()?.turns).toHaveLength(1)); + const steer = vi.fn(async () => ({ model: "o4" })); + await deliver(message("2", "@Gander second"), { config, route: steer }); + await vi.waitFor(() => + expect(goose()?.turns[0]?.steered).toEqual([ + expect.stringContaining("@Gander second"), + ]), + ); + expect(first).toHaveBeenCalledTimes(1); + expect(steer).not.toHaveBeenCalled(); + goose()?.turns[0]?.finish(); + }); + it("reads a queued turn's Canvas with the working location its own turn's prompt has", async () => { const { agent, deliver, goose } = setup({ solo: new Set([channel]), diff --git a/src/bundled/goose/runtime.ts b/src/bundled/goose/runtime.ts index 9fc4504573..219845c5c1 100644 --- a/src/bundled/goose/runtime.ts +++ b/src/bundled/goose/runtime.ts @@ -648,6 +648,7 @@ export class GooseRuntime { team, model, effort, + route: chooseModel, synced, workingUntil, current, @@ -911,13 +912,20 @@ export class GooseRuntime { ...(model ? { model } : {}), ...(effort ? { effort } : {}), // A pick runs on its own level; a synced one is checked. - ...(synced?.effort && !model && !effort + ...(synced?.effort && !model && !effort && !chooseModel ? { kept: synced.effort } : {}), }; if (gateway) { + // A forwarded turn always starts one: its route chooses now. + const chosen = chooseModel ? await chooseModel() : {}; + if (!chosen) { + delivered = Promise.resolve({ ok: true, undelivered: true }); + return; + } delivered = this.forwarded(entry, agent.key, key, gateway, { ...options, + ...chosen, activity: { ...activity, current: valid }, prompt: async (fresh) => { if (!valid()) return undefined; @@ -941,6 +949,7 @@ export class GooseRuntime { } delivered = entry.sessions.deliver(key, text, shown, { ...options, + ...(chooseModel ? { route: chooseModel } : {}), ...activity, ...(wake ? { current } : {}), // Built again as it is handed over: a wake, to read what is diff --git a/src/features/agent-harness/acp/agent-sessions.ts b/src/features/agent-harness/acp/agent-sessions.ts index 1af2149268..8c020bbb80 100644 --- a/src/features/agent-harness/acp/agent-sessions.ts +++ b/src/features/agent-harness/acp/agent-sessions.ts @@ -10,7 +10,7 @@ import { absoluteWorkspace } from "../../../bundled/codex/config"; import type { SessionAction } from "../../agents/service"; import type { AcpProcess } from "./process"; -import type { AcpSession } from "./session"; +import type { AcpSession, TurnRoute } from "./session"; import { codeOf, errorMessage } from "./steps"; import type { ActivityReceipt, @@ -367,7 +367,9 @@ export class AgentSessions { * takes that name; * `model`, one of the agent's * provider's, and `effort`, one of its thinking levels, are what its turn - * runs on, and `kept`, a synced level, one it must run on. Once `signal` aborts, it stops + * runs on, and `kept`, a synced level, one it must run on; `route` + * chooses them instead for a turn it starts (`Delivery.route`). Once + * `signal` aborts, it stops * waiting for a session to open, which is then kept for the next message, * and sends nothing. */ async deliver( @@ -383,6 +385,7 @@ export class AgentSessions { model, effort, kept, + route, ...activity }: Readonly<{ current?: () => boolean; @@ -393,6 +396,7 @@ export class AgentSessions { model?: string; effort?: string; kept?: string; + route?: TurnRoute; }> & ActivityReceipt = {}, ): Promise { @@ -440,6 +444,15 @@ export class AgentSessions { } const live = this.live.get(key); if (!live) break; + // A turn on an idle session is chosen now, so its level is checked as + // a picked one is; a busy session's queue asks once the turn starts. + if (route && live.session.open && !live.session.busy) { + const chosen = await route(); + if (!chosen) return { ok: true, undelivered: true }; + ({ model, effort } = chosen); + route = undefined; + continue; + } if ( !live.session.open || (!live.session.busy && (this.stale(live) || this.leveled(live, effort))) @@ -465,6 +478,7 @@ export class AgentSessions { model, effort, kept, + route, ); } // Reserved before anything is awaited, so a message that comes meanwhile @@ -506,6 +520,7 @@ export class AgentSessions { model, effort, kept, + route, ), }; })(); @@ -1116,6 +1131,7 @@ export class AgentSessions { model: string | undefined, effort?: string, kept?: string, + route?: TurnRoute, ) { const sent = live.session.send( text, @@ -1129,6 +1145,7 @@ export class AgentSessions { model, effort, kept, + route, ); // A final Buzz send can answer before the harness finishes its model work. void live.session.idle().then(() => { diff --git a/src/features/agent-harness/acp/session.ts b/src/features/agent-harness/acp/session.ts index 20359de536..3f675ad00c 100644 --- a/src/features/agent-harness/acp/session.ts +++ b/src/features/agent-harness/acp/session.ts @@ -12,6 +12,11 @@ type Waiter = (settled: Settled) => void; /** A session's settings, as `session/new` and `session/set_config_option` * return them. */ +/** Chooses a turn's model and effort as it starts (`Delivery.route`); + * undefined sends nothing. */ +export type TurnRoute = () => Promise< + Readonly<{ model?: string; effort?: string }> | undefined +>; export type ConfigOptions = { configOptions?: { category?: string | null; @@ -70,6 +75,7 @@ export class AcpSession { waiter?: Waiter; delivered?: () => void; accepted?: () => void; + route?: TurnRoute; }[] = []; /** The model the running turn runs on; empty is its provider's default. */ private model = ""; @@ -163,6 +169,8 @@ export class AcpSession { effort?: string, /** A synced level the turn must run on, or it fails before its prompt. */ kept?: string, + /** Chooses `model` and `effort` as a turn for this message starts. */ + route?: TurnRoute, ): Promise { if (this.closed) return Promise.resolve({ ok: false, error: "The session was closed" }); @@ -184,7 +192,7 @@ export class AcpSession { (!model || model === this.model) && (!effort || effort === this.level) ) - void this.steer(text, activity, waiter, model, effort, kept); + void this.steer(text, activity, waiter, model, effort, kept, route); else { this.queue.push({ text, @@ -196,6 +204,7 @@ export class AcpSession { ...(model ? { model } : {}), ...(effort ? { effort } : {}), ...(kept ? { kept } : {}), + ...(route ? { route } : {}), }); this.acknowledge(activity, waiter, true); void this.pump(); @@ -323,6 +332,7 @@ export class AcpSession { model?: string, effort?: string, kept?: string, + route?: TurnRoute, ) { this.steering.add(waiter); const prior = this.steered; @@ -380,8 +390,9 @@ export class AcpSession { waiter, ...(model ? { model } : {}), ...(effort ? { effort } : {}), - // As a turn of its own, it is checked like any other. + // As a turn of its own, it is checked and routed like any other. ...(kept ? { kept } : {}), + ...(route ? { route } : {}), }); this.acknowledge(activity, waiter, true); } @@ -439,13 +450,25 @@ export class AcpSession { waiter, delivered, accepted, + route, } = this.queue.shift() ?? { text: "", }; let sent = false; try { await this.beforeTurn?.(); - await this.select(model, effort); + // A model route chooses as its turn starts. + const chosen = route ? await route() : { model, effort }; + if (!chosen) { + if (waiter) this.discard(waiter); + continue; + } + // A level can't be cleared in place, so a routed turn that names + // none runs on, and records, the one the session has. + await this.select( + chosen.model, + chosen.effort || (route ? this.level || undefined : undefined), + ); // A harness may ignore a level its model lacks, and keep one across // a model switch without its being set again. if (kept && !this.levels.includes(kept)) diff --git a/src/features/agents/model-routes.test.ts b/src/features/agents/model-routes.test.ts index 264bedc56d..e71a415446 100644 --- a/src/features/agents/model-routes.test.ts +++ b/src/features/agents/model-routes.test.ts @@ -9,6 +9,7 @@ import { routeOf, routesFor, routeTurn, + turnRoute, setModelRouters, withRoutes, } from "./model-routes"; @@ -71,7 +72,6 @@ const turn = ( current: "route:auto-balanced", automatic: false, models: MODELS, - busy: false, request: { agent: { pubkey: "a".repeat(64), name: "Agent" }, prompt: "Fix a typo", @@ -193,27 +193,44 @@ it("asks the saved route's router for an idle turn's model and effort", async () ); }); -it("lets an explicit model pick win and keeps a running turn's pick", async () => { +it("lets an explicit model pick win", async () => { const select = vi.fn(async () => ({ model: "sonnet", })); setModelRouters([router(select)]); + expect( + turnRoute({ + harness: "claude-code", + pick: { model: "opus" }, + current: "route:auto-balanced", + automatic: false, + }), + ).toBeUndefined(); await expect(routeTurn(turn({ pick: { model: "opus" } }))).resolves.toEqual({ model: "opus", }); - await expect( - routeTurn(turn({ busy: true, last: { model: "opus", effort: "medium" } })), - ).resolves.toEqual({ - model: "opus", - effort: "medium", - routed: { - route: expect.objectContaining({ id: "auto-balanced" }), - kept: true, - }, - }); expect(select).not.toHaveBeenCalled(); }); +it("reads the thread once, ending the read with the choice", async () => { + const read = vi.fn(async (_signal: AbortSignal) => [ + { pubkey: "b".repeat(64), content: "Earlier", createdAt: 1 }, + ]); + let signal: AbortSignal | undefined; + setModelRouters([ + router(async (request) => { + await request.history(); + await request.history(); + signal = request.signal; + return { model: "sonnet" }; + }), + ]); + await routeTurn(turn({ request: { ...turn().request, history: read } })); + expect(read).toHaveBeenCalledTimes(1); + expect(read.mock.calls[0]?.[0]).toBe(signal); + expect(signal?.aborted).toBe(true); +}); + it("routes a per-message route pick and Automatic's route", async () => { const select = vi.fn(async () => ({ model: "opus", diff --git a/src/features/agents/model-routes.ts b/src/features/agents/model-routes.ts index 41ae235adb..cecbe018e0 100644 --- a/src/features/agents/model-routes.ts +++ b/src/features/agents/model-routes.ts @@ -1,12 +1,12 @@ // Model routes: choices such as "Auto Balanced" that a bundled plugin adds to // a harness's Model menu (`Agents.registerModelRouter`). An agent saves a -// route as its model, `route:`. Each turn it starts while idle in that -// conversation asks the plugin's router which of the harness's own models and -// effort levels to run it on; a message that steers a running turn keeps that -// turn's choice, so the session's prompt cache stays warm. The choice reaches -// the harness as the turn's model and effort picks (`Delivery.model`, -// `Delivery.effort`), as a per-message pick does: no harness ever runs a -// route id, and launches its process on its own default (`launchModel`). +// route as its model, `route:`. Each turn it starts asks the plugin's +// router which of the harness's own models and effort levels to run it on: +// the harness calls `Delivery.route` where a delivery starts a turn, and runs +// that turn on its answer as on a per-message pick. A message that steers a +// running turn asks nothing and keeps that turn's choice, so the session's +// prompt cache stays warm. No harness ever runs a route id, and each launches +// its process on its own default (`launchModel`). // // - `routes(harness)` lists a harness's routes, the one new agents start on // (`initial`), the one agents on Automatic use (`automatic`), and whether @@ -274,8 +274,6 @@ export type RoutedPick = TurnPick & rationale?: string; /** The router didn't answer usably. */ fallback?: true; - /** A steer kept the running turn's pick. */ - kept?: true; }>; }>; @@ -295,38 +293,54 @@ function listed( }; } -/** The pick a turn runs on: `pick`, the owner's for this message, unless - * the agent runs on a route (saved, picked for this message, or Automatic's), - * in which case the route's router chooses, or the running turn's pick is - * kept when the turn will steer (`busy`). */ -export async function routeTurn( +/** The route a turn runs on, if any: one picked for its message, or, without + * an explicit model pick, Automatic's or the saved one (`current`). */ +export function turnRoute( input: Readonly<{ harness: string; pick: TurnPick; /** The model the agent runs on without a pick (`Models.current`). */ current: string; automatic: boolean; + }>, +) { + const { pick } = input; + if (pick.model && !routeOf(pick.model)) return undefined; + return ( + routeOf(pick.model) ?? + (input.automatic + ? routesFor(input.harness).automatic + : routeOf(input.current)) + ); +} + +/** The pick a turn starts with: `pick`, the owner's for this message, unless + * the agent runs on a route (`turnRoute`), whose router chooses. */ +export async function routeTurn( + input: Readonly<{ + harness: string; + pick: TurnPick; + current: string; + automatic: boolean; models: readonly Model[]; - /** The conversation has a turn running, which this one steers into. */ - busy: boolean; - /** The pick of the conversation's latest routed turn. */ - last?: TurnPick | undefined; - request: Omit; + request: Omit< + ModelRouteRequest, + "route" | "models" | "harness" | "signal" | "history" + > & { + /** Read with the selection's own signal, which ends with it. */ + history(signal: AbortSignal): Promise; + }; signal: AbortSignal; }>, ): Promise { const { harness, pick } = input; - if (pick.model && !routeOf(pick.model)) return pick; - const { routes, owners } = resolved(harness); - const id = - routeOf(pick.model) ?? - (input.automatic ? routes.automatic : routeOf(input.current)); + const id = turnRoute(input); if (!id) return pick; + const { routes, owners } = resolved(harness); const route = routes.routes.find((item) => item.id === id); const router = owners.get(id); // The route's plugin is off, or no longer offers it. if (!route || !router) return {}; - if (input.busy) return { ...input.last, routed: { route, kept: true } }; const own = input.models.filter((model) => !routeOf(model.id)); const late = new AbortController(); const timer = setTimeout( @@ -334,6 +348,7 @@ export async function routeTurn( ROUTE_TIMEOUT_MS, ); const signal = AbortSignal.any([input.signal, late.signal]); + let history: Promise | undefined; let choice: ModelRouteChoice | undefined; try { // A router that ignores the signal still can't hold the turn past it. @@ -344,7 +359,14 @@ export async function routeTurn( once: true, }); router - .select({ ...input.request, harness, route: id, models: own, signal }) + .select({ + ...input.request, + history: () => (history ??= input.request.history(signal)), + harness, + route: id, + models: own, + signal, + }) .then(resolve, reject); }, ); @@ -353,6 +375,8 @@ export async function routeTurn( console.warn(`Model route ${id} could not choose a model`, error); } finally { clearTimeout(timer); + // Ends any read of the thread the router left running. + if (!late.signal.aborted) late.abort(new Error("The model route chose")); } input.signal.throwIfAborted(); const chosen = listed(own, choice); diff --git a/src/features/agents/runner.ts b/src/features/agents/runner.ts index f42b27c642..1bebe4d06e 100644 --- a/src/features/agents/runner.ts +++ b/src/features/agents/runner.ts @@ -34,7 +34,7 @@ import type { Trigger, Agents, } from "./service"; -import type { RoutedPick } from "./model-routes"; +import type { RoutedPick, TurnPick } from "./model-routes"; import type { LocalAgentActivity, WorkOutcome } from "./local-activity"; import type { MentionRefusal } from "./owner-attestation"; import { threadReference } from "../relay/thread-reference"; @@ -609,8 +609,8 @@ export type RunnerHost = { progress(key: AgentKey, progress: TimerProgress): void; /** The team sections of its prompt; empty without a team. */ team(key: AgentKey): string; - /** The model and effort a turn starts with, given the owner's `pick` - * for it: a model route's choice when the agent runs on one. */ + /** When the agent runs on a model route for this turn, given the owner's + * `pick` for it: what chooses the model and effort of a turn it starts. */ route?( agent: Agent, type: RegisteredAgentType, @@ -618,7 +618,7 @@ export type RunnerHost = { place: SessionPlace | undefined, pick: Readonly<{ model?: string; effort?: string }>, signal: AbortSignal, - ): Promise; + ): Promise<((signal: AbortSignal) => Promise) | undefined>; /** What its next run starts with, from this device's storage only. */ start(agent: Agent): Start | Promise>; prepareSession?( @@ -3510,30 +3510,64 @@ export class AgentRunners { signal, ); const owned = await pickFor(job.trigger, agent, type); - const result: RoutedPick = - (await this.host.route?.( - agent, - type, - trigger, - trigger.type === "mention" - ? { - channelId: job.channelId ?? channelOf(trigger.event) ?? "", - root: - threadReference(trigger.event)?.rootId ?? trigger.event.id, - } - : anchor && { - channelId: anchor.channel, - ...(anchor.root ? { root: anchor.root } : {}), - }, - owned, - signal, - )) ?? owned; - const { routed, ...pick } = result; - // The turn's activity says what its route chose, and why. - if (routed && !routed.kept) - job.work?.notice( - `${routed.route.label}${routed.fallback ? " fell back to" : " chose"} ${pick.model || "the default model"}${pick.effort ? ` · ${pick.effort}` : ""}${routed.rationale ? `: ${routed.rationale}` : ""}`, - ); + // A watch or timer run as a standalone turn keeps its own picks: the + // harness starts it on its default, so no route chooses for it. + const runsAlone = !addressed(trigger) && !anchor && !!type.runOnce; + const choose = runsAlone + ? undefined + : await this.host.route?.( + agent, + type, + trigger, + trigger.type === "mention" + ? { + channelId: job.channelId ?? channelOf(trigger.event) ?? "", + root: + threadReference(trigger.event)?.rootId ?? trigger.event.id, + } + : anchor && { + channelId: anchor.channel, + ...(anchor.root ? { root: anchor.root } : {}), + }, + owned, + signal, + ); + // The harness's Stop for this request, once it offers one. + let harnessStop: (() => Promise) | undefined; + let selecting = false; + let chosen: Promise | undefined; + // Asked by the harness as the turn starts, once: Stop meanwhile ends + // the choice, and the request with it. + const route = + choose && + (() => + (chosen ??= (async () => { + const stop = new AbortController(); + selecting = true; + job.work?.interruptible(async () => { + stop.abort(new Error("The owner stopped the request")); + await harnessStop?.().catch(() => {}); + }); + try { + const { routed, ...pick } = await choose( + AbortSignal.any([lifetime, stop.signal]), + ); + // The turn's activity says what its route chose, and why. + if (routed) + job.work?.notice( + `${routed.route.label}${routed.fallback ? " fell back to" : " chose"} ${pick.model || "the default model"}${pick.effort ? ` · ${pick.effort}` : ""}${routed.rationale ? `: ${routed.rationale}` : ""}`, + ); + return pick; + } catch (error) { + if (stop.signal.aborted) return undefined; + throw error; + } finally { + selecting = false; + if (harnessStop) job.work?.interruptible(harnessStop); + } + })())); + // A route's pick is the turn's, chosen as it starts. + const pick = route ? {} : owned; const start = await this.host.start(agent); if (!start.ok) throw new Error(start.reason); const team = this.host.team(agent.key); @@ -3603,6 +3637,7 @@ export class AgentRunners { revisions: start.revisions, ...(start.synced && { synced: start.synced }), ...pick, + ...(route ? { route } : {}), ...(team ? { team } : {}), signal, ...(job.guardedWake ? { accepted: job.guardedWake.accepted } : {}), @@ -3616,8 +3651,11 @@ export class AgentRunners { void admission?.then((admitted) => admitted?.acknowledged()); }, superseded: () => job.work?.supersede(), - interruptible: (stop: () => Promise) => - job.work?.interruptible(stop), + interruptible: (stop: () => Promise) => { + harnessStop = stop; + // While a route chooses, its Stop calls this one too. + if (!selecting) job.work?.interruptible(stop); + }, step: (tool: string, target?: string) => job.work?.step(tool, target), } diff --git a/src/features/agents/service.test.ts b/src/features/agents/service.test.ts index 876732cbcf..b6a5bb287f 100644 --- a/src/features/agents/service.test.ts +++ b/src/features/agents/service.test.ts @@ -4227,11 +4227,8 @@ it("passes the model and effort its owner asked for, and no other", async () => ]); }); -it("asks a model route for an idle turn's model and keeps it for a steer", async () => { - let state: "idle" | "active" = "idle"; - const { service, run, emit, ctx } = await setup({ - sessionControls: { state: () => state, run: async () => {} }, - }); +it("lets the harness ask a model route as its turn starts, once", async () => { + const { service, run, emit, ctx } = await setup(); await service.create({ type: "example/echo", name: "Echo" }); const select = vi.fn(async () => ({ model: "deep", @@ -4252,14 +4249,31 @@ it("asks a model route for an idle turn's model and keeps it for a steer", async : undefined, select, }); - const asked = (id: string, ...tags: string[][]) => + const asked = (id: string, pubkey: string) => event(id, { - pubkey: viewer, - tags: [["h", channel], ["p", bot], ["model", bot, "route:auto"], ...tags], + pubkey, + tags: [ + ["h", channel], + ["p", bot], + ["model", bot, "route:auto"], + ], }); - const first = asked("1d1e"); - emit({ events: [first] }); + emit({ events: [asked("1d1e", viewer)] }); await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + const delivery = run.mock.calls[0]?.[0]; + // Nothing is chosen until the harness starts a turn: a steer never asks. + expect(delivery?.model).toBeUndefined(); + expect(delivery?.effort).toBeUndefined(); + expect(select).not.toHaveBeenCalled(); + await expect(delivery?.route?.()).resolves.toEqual({ + model: "deep", + effort: "max", + }); + await expect(delivery?.route?.()).resolves.toEqual({ + model: "deep", + effort: "max", + }); + expect(select).toHaveBeenCalledTimes(1); expect(select).toHaveBeenCalledWith( expect.objectContaining({ harness: "echo", @@ -4270,19 +4284,62 @@ it("asks a model route for an idle turn's model and keeps it for a steer", async ], }), ); - expect(run.mock.calls[0]?.[0]).toMatchObject({ - model: "deep", - effort: "max", - }); - // The conversation now has a turn running: the next message steers it. - state = "active"; - emit({ events: [asked("57ee", ["e", first.id, "", "reply"])] }); + // Anyone else's mention never reaches the router. + emit({ events: [asked("57ee", "f".repeat(64))] }); await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(2)); - expect(select).toHaveBeenCalledTimes(1); - expect(run.mock.calls[1]?.[0]).toMatchObject({ - model: "deep", - effort: "max", + expect(run.mock.calls[1]?.[0]?.route).toBeUndefined(); +}); + +it("lets the owner stop a model route while it chooses, running nothing", async () => { + const { service, run, emit, ctx, activity } = await setup(); + await service.create({ type: "example/echo", name: "Echo" }); + let asked: AbortSignal | undefined; + const select = vi.fn( + ({ signal }: { signal: AbortSignal }) => + new Promise((_, reject) => { + asked = signal; + signal.addEventListener("abort", () => reject(signal.reason)); + }), + ); + ctx + .extend({ + pluginOwner: bundledOwner( + Object.freeze({ id: "org.example", revision: "bundled" }), + ), + }) + .agents.registerModelRouter({ + id: "router", + routes: (harness) => + harness === "echo" + ? { routes: [{ id: "auto", label: "Auto" }] } + : undefined, + select, + }); + // As a harness does, it asks the route as its turn starts. + let choosing: Promise | undefined; + run.mockImplementationOnce(async ({ route }) => { + choosing = route?.(); + await choosing; + }); + emit({ + events: [ + event("1d1e", { + pubkey: viewer, + tags: [ + ["h", channel], + ["p", bot], + ["model", bot, "route:auto"], + ], + }), + ], }); + await vi.waitFor(() => expect(select).toHaveBeenCalled()); + const work = activity.reader.work()[0]; + if (!work) throw new Error("no work"); + expect(work.stoppable).toBe(true); + await activity.reader.interrupt?.(work); + await expect(choosing).resolves.toBeUndefined(); + expect(asked?.aborted).toBe(true); }); it("lists model routes only from bundled plugins", async () => { diff --git a/src/features/agents/service.ts b/src/features/agents/service.ts index e18b99f656..dfeffad089 100644 --- a/src/features/agents/service.ts +++ b/src/features/agents/service.ts @@ -116,7 +116,12 @@ import { type AgentHookContext, type AgentHookDispatchOptions, } from "./hooks"; -import { ownerReads, readyOwnerReads, type AgentReads } from "./reads"; +import { + ownerReads, + readyOwnerReads, + workflowMarked, + type AgentReads, +} from "./reads"; import { AgentInbox } from "./inbox"; import { createToolOperation, type AgentToolProvider } from "./tool-operation"; import { @@ -203,12 +208,15 @@ import { type ModelRouter, type RoutedPick, type RouteMessage, + routeOf, routesFor, routeTurn, setModelRouters, type TurnPick, + turnRoute, withRoutes, } from "./model-routes"; +import { fromOwner as ownerSent, workflowOf } from "./owner-attestation"; import { channelTabs } from "../../bundled/channels/useChannelTabState"; import type { RelayData } from "../relay/service"; import type { RelaySession } from "../relay/session"; @@ -961,6 +969,14 @@ export type Delivery = Readonly<{ /** The effort level the owner asked for in the triggering message: one of * that model's `efforts`. Absent means the agent's own default. */ effort?: string; + /** Set when the agent runs on a model route, which chooses the model and + * effort of a turn this delivery starts; `model` and `effort` are then + * absent. Call it where the delivery starts a turn, including one put off + * while the session compacts, never where it steers a running turn, which + * keeps its own picks. It answers once, the same on every call; undefined + * means the owner stopped the request while it chose, so nothing runs. + * Without a call the turn runs on the agent's own default. */ + route?: () => Promise; /** A section for each team the agent is on, with the team's name, roster and * instructions, to follow the agent's own instructions. Absent without one. */ team?: string; @@ -1673,8 +1689,6 @@ export type ModelSettings = Readonly<{ * it, and leaving it out keeps it. */ export type NoteChange = Readonly<{ note?: PluginNote | null }>; const MODEL_FIELDS = ["model", "provider", "effort"] as const; -/** Conversations whose latest routed pick is kept for their steers. */ -const ROUTED_PICKS = 512; /** Earlier thread messages a model router may read. */ const ROUTE_HISTORY = 20; /** The most prompt text a model router is given. */ @@ -2559,8 +2573,6 @@ export class AgentsService extends Service implements Agents { private readonly contributions; private readonly tabContributions; private readonly modelRouters; - /** Each conversation's latest routed pick, which a steer keeps. */ - private readonly routedPicks = new Map(); /** Each registered type's own `models`, before routes are added, by key. */ private readonly ownModels = new Map< string, @@ -2882,7 +2894,7 @@ export class AgentsService extends Service implements Agents { pinNativePlacement, ), route: (agent, type, trigger, place, pick, signal) => - this.routedPick(agent, type, trigger, place, pick, signal), + this.modelRoute(agent, type, trigger, place, pick, signal), prepareSession: async (agent, type, trigger, placement, signal) => { if ( !type.sessionAdmission || @@ -3984,64 +3996,88 @@ export class AgentsService extends Service implements Agents { throw new Error("A model router needs an id, routes and select"); this.modelRouters.register(this.ctx, router); } - /** The pick a turn starts with: `pick`, unless the agent runs on a model - * route, whose router chooses unless the turn steers a running one. */ - private async routedPick( + /** How a turn's model is chosen when the agent runs on a model route: + * undefined when `pick` holds (no route, an explicit model pick, an agent + * that runs elsewhere, or a mention its owner didn't send). */ + private async modelRoute( agent: Agent, type: RegisteredAgentType, trigger: Trigger, place: SessionPlace | undefined, pick: TurnPick, signal: AbortSignal, - ): Promise { + ): Promise<((signal: AbortSignal) => Promise) | undefined> { const models = this.ownModels.get(type.key) ?? type.models; // Hosted, or on another execution target, it runs on that one's models. - if (agent.place === "hosted" || agent.executionBinding) return pick; - if (!routesFor(type.id).routes.length || !models) return pick; + if (agent.place === "hosted" || agent.executionBinding) return undefined; + if (!routesFor(type.id).routes.length || !models) return undefined; + if (pick.model && !routeOf(pick.model)) return undefined; + // The router reads the prompt and the thread: only for a mention the + // harness will act on. + if ( + trigger.type === "mention" && + !(await this.ownerMention(agent, trigger.event, place?.channelId, signal)) + ) + return undefined; let offered: Models; try { offered = await models(agent); } catch (error) { console.warn(`Agent type ${type.key} could not list its models`, error); - return pick; + return undefined; } - const conversation = place && this.sessionPlace(agent, type, place); - const key = - conversation && - JSON.stringify([ - agent.key, - conversation.channelId, - conversation.root ?? "", - conversation.community === true, - ]); - const state = place ? this.sessionState(agent.key, place) : "idle"; - let history: Promise | undefined; - const routed = await routeTurn({ - harness: type.id, - pick, - current: offered.current, - automatic: onAutomatic(agent.config, type.id), - models: offered.models, - busy: state === "active" || state === "compacting", - last: key ? this.routedPicks.get(key) : undefined, - request: { - agent: { pubkey: agent.pubkey, name: agent.name }, - prompt: promptOf(trigger), - history: () => - (history ??= this.routeHistory(agent, trigger, place, signal)), - }, - signal, - }); - if (key && routed.routed && !routed.routed.kept) { - this.routedPicks.delete(key); - this.routedPicks.set(key, { - ...(routed.model ? { model: routed.model } : {}), - ...(routed.effort ? { effort: routed.effort } : {}), + const automatic = onAutomatic(agent.config, type.id); + if ( + !turnRoute({ + harness: type.id, + pick, + current: offered.current, + automatic, + }) + ) + return undefined; + return (selection) => + routeTurn({ + harness: type.id, + pick, + current: offered.current, + automatic, + models: offered.models, + request: { + agent: { pubkey: agent.pubkey, name: agent.name }, + prompt: promptOf(trigger), + history: (read) => this.routeHistory(agent, trigger, place, read), + }, + signal: selection, }); - if (this.routedPicks.size > ROUTED_PICKS) - this.routedPicks.delete(this.routedPicks.keys().next().value as string); + } + /** Whether `event` directs the agent as its owner's, as every harness + * checks before it acts on a mention. */ + private async ownerMention( + agent: Agent, + event: RelayEvent, + channelId: string | undefined, + signal: AbortSignal, + ) { + const relay = this.relay(agent.key); + try { + // A workflow's mention waits out a reconnect, as the harness's does. + const reads = workflowMarked(event, agent.owner) + ? await readyOwnerReads(relay, agent, signal, channelId) + : ownerReads(relay, agent.pubkey); + return await ownerSent( + event, + agent.owner, + workflowOf(reads, agent.pubkey), + ); + } catch (error) { + signal.throwIfAborted(); + console.warn( + "A mention's owner could not be checked for its route", + error, + ); + return false; } - return routed; } /** The thread before a routed turn's message, oldest first: at most * ROUTE_HISTORY messages, read once and only if its router asks. */ From d32ad74bf46805aee9e72a9931ec4f5753cbe7c0 Mon Sep 17 00:00:00 2001 From: Atish Patel Date: Mon, 23 Nov 2026 14:25:09 -0600 Subject: [PATCH 05/14] Show a route's latest pick and mark routes with sparkles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The composer's model card shows what an agent's route chose for its latest turn on this device ("Latest turn: Sonnet 5.5 · High"), with the route's rationale on hover. Route rows and a selected route carry a sparkles mark in the model menus, and the turn activity names the chosen model and effort by their labels instead of their ids. Co-authored-by: Worker Bee (Opus) <4a3bc7fd57a7b2c126e4f3d3462dd16f375242e1c176b4b3f25ca93e3edb6a84@buzz.block.builderlab.xyz> Signed-off-by: Atish Patel --- src/features/agents/ModelFamilyMenu.tsx | 24 +++++-- src/features/agents/model-routes.test.ts | 3 + src/features/agents/model-routes.ts | 63 ++++++++++++++++++- src/features/agents/runner.ts | 2 +- src/features/agents/service.ts | 8 ++- .../ComposerModels.recommended.test.tsx | 45 ++++++++++++- src/features/messages/ComposerModels.tsx | 31 ++++++++- 7 files changed, 162 insertions(+), 14 deletions(-) diff --git a/src/features/agents/ModelFamilyMenu.tsx b/src/features/agents/ModelFamilyMenu.tsx index bfcdead10f..6e4d742b95 100644 --- a/src/features/agents/ModelFamilyMenu.tsx +++ b/src/features/agents/ModelFamilyMenu.tsx @@ -4,6 +4,7 @@ import { CaretDownIcon, CheckIcon, LightningIcon, + SparklesIcon, } from "../../shared/design-system/icons"; import { Button } from "../../shared/design-system/ui/Button"; import { ChoiceRow } from "../../shared/design-system/ui/ChoiceRow"; @@ -129,6 +130,8 @@ export function ModelFamilyMenu({ const hasFamilyLogos = [...families.keys()].some((family) => modelLogo(family), ); + // Routes' marks need the leading column too. + const leadingColumn = hasFamilyLogos || routes.length > 0; // Fast models get their own section up front, so the quick choices are one // click away; they stay in their families too. A catalog of only fast (or // no fast) models gains nothing from a separate section. @@ -188,7 +191,15 @@ export function ModelFamilyMenu({ {leading} )} - {modelLogo(modelFamily(selected), "buzz-select-leading")} + {selected.route ? ( +