diff --git a/docs/buzz-help.md b/docs/buzz-help.md index e137c73a51..c086690a8d 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, 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. - **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..65cd49a425 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -159,6 +159,26 @@ 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, Codex and Goose Model menus with `ctx.agents.registerModelRouter(router)`. +An agent on a route runs with `route:` as its model, but no copy of its +settings stores that. Its synced settings revision keeps the route beside +`settings`, as `"modelRoute": ""`, with an empty `model`, and its saved +record keeps it beside `config` the same way. A catalog share keeps it as +`model_route` and an exported snapshot as `modelRoute`, with no `model`. Older +versions run the harness's default. A model saved by an older version takes +the agent off the route. 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 ask for the conversation's earlier messages +(`request.history()`) and for what Buzz already holds about the turn +(`request.context()`): what started it, the agent's instructions, skills and +workspace, attached files, and the conversation's last routed pick with when +that turn ended. Buzz runs no git or GitHub calls for either. 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.test.tsx b/src/bundled/agents/AgentCreateDialog.test.tsx index d7862a47c4..fcec79873d 100644 --- a/src/bundled/agents/AgentCreateDialog.test.tsx +++ b/src/bundled/agents/AgentCreateDialog.test.tsx @@ -42,6 +42,10 @@ import { uploadAvatar, } from "../../features/profiles/avatar-upload"; import { CHECK_MS } from "../../features/agents/recommended"; +import { + resetModelRoutesForTests, + setModelRouters, +} from "../../features/agents/model-routes"; import { AgentCreateDialog } from "./AgentCreateDialog"; import { BuilderlabLogoIcon, @@ -2252,6 +2256,44 @@ describe("Recommended setup", () => { ); }); + it("starts Custom on the Automatic route when a plugin offers one", async () => { + setModelRouters([ + { + id: "test", + routes: (id) => + id === "codex" + ? { + routes: [{ id: "auto-a", label: "Auto A" }], + automatic: "auto-a", + } + : undefined, + select: async () => undefined, + }, + ]); + try { + const { agents, dialog, user } = setup([echo, goose, codex]); + await inspectModel(user, dialog, "Auto A"); + await chooseCustom(user, dialog); + expect(harnessSelect(dialog)).toHaveTextContent("Codex"); + await user.type(within(dialog).getByLabelText("Name"), "Agent A"); + await user.click(createButton()); + // The route, not the candidate it would have started on. + expect(agents.create).toHaveBeenCalledWith( + expect.objectContaining({ + type: "test/codex", + config: { + notes: "start", + instructions: "Be brief.", + model: "route:auto-a", + effort: "", + }, + }), + ); + } finally { + resetModelRoutesForTests(); + } + }); + it("lets the owner choose manually while the pick is still running, even with one harness", async () => { let finish = (_ready: boolean) => {}; const slow = harness( diff --git a/src/bundled/agents/AgentCreateDialog.tsx b/src/bundled/agents/AgentCreateDialog.tsx index dc5dc9c90d..6898c4b0f7 100644 --- a/src/bundled/agents/AgentCreateDialog.tsx +++ b/src/bundled/agents/AgentCreateDialog.tsx @@ -19,8 +19,14 @@ import { import { AISettings, Checking, + RouteLine, UsesLine, } from "../../features/agents/AISettings"; +import { + activeRoute, + routeModel, + useModelRoutes, +} from "../../features/agents/model-routes"; import { bounded, followRecommended, @@ -357,6 +363,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"; @@ -458,15 +467,20 @@ export function AgentCreateDialog({ // While the pick runs, its effect takes the harness once known. if (on && pick && pick.type.key !== type?.key) chooseModel(pick.type, carried(pick.type)); - // Manual starts from what Automatic picked. - if (!on && pick && pick.type.key === type?.key) + // Manual starts from what Automatic picked: its route, when a plugin + // offers one, on the candidate's provider. + if (!on && pick && pick.type.key === type?.key) { + const picked = followRecommended( + withRecommended(config as object), + config as { model: string; effort: string }, + pick.candidate, + ); setConfig( - followRecommended( - withRecommended(config as object), - config as { model: string; effort: string }, - pick.candidate, - ), + automaticRoute + ? { ...picked, model: routeModel(automaticRoute.id), effort: "" } + : picked, ); + } }; // Automatic has nothing to create with until, and unless, a pick is found. const waiting = automatic && !type?.remote && !pick; @@ -805,7 +819,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..f06a764db2 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, @@ -1277,6 +1284,7 @@ export class ClaudeRuntime { channelId, model, effort, + route: chooseModel, synced, team, workingUntil, @@ -1632,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( @@ -1986,6 +1995,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/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/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 25e52cb92a..92c3537850 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 +1635,7 @@ export function createTabs({ {...runsOnDetails( { title: "Claude", icon: ClaudeLogoIcon }, resolved, + automaticRoute, )} onChange={(on) => // Manual starts from the recommendation it ran on. @@ -1599,7 +1643,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.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 0e474a60d0..2b0781f8d2 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 { routeFor } from "../../features/agents/model-routes"; import { composeBase, sectionsKey, @@ -210,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 @@ -1106,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; @@ -1154,6 +1161,10 @@ 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. + // 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 } : { @@ -2620,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 @@ -3404,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/codex/tabs.tsx b/src/bundled/codex/tabs.tsx index de6b52acb9..d65ed11a61 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,10 @@ 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"); + // 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); @@ -1689,6 +1710,7 @@ export function createTabs(
)} setDraft(offRecommended({ ...draft, effort })) } @@ -1760,6 +1791,7 @@ export function createTabs( {...runsOnDetails( { title: "Codex", icon: CodexLogoIcon }, resolved, + automaticRoute, )} onChange={(on) => // Manual starts from the recommendation it ran on. @@ -1767,7 +1799,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/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..79c6f533b8 100644 --- a/src/bundled/goose/runtime.test.ts +++ b/src/bundled/goose/runtime.test.ts @@ -1440,6 +1440,109 @@ 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", + }; + 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( + (data) => + data.includes('"method":"session/set_config_option"') && + data.includes('"o3"'), + ), + ).toBe(true); + 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("keeps an idle session for a message while its model route chooses", async () => { + const { deliver, goose } = setup({ scope: "channel", hold: true }); + const config = { + ...DEFAULT_CONFIG, + scope: "channel", + model: "route:auto-balanced", + }; + void deliver(message("1", "@Gander first"), { + config, + route: async () => ({ model: "o3" }), + }); + await vi.waitFor(() => expect(goose()?.turns).toHaveLength(1)); + goose()?.turns[0]?.finish(); + // A slow choice for the next message, and a quick one after it. + let choose!: (pick: { model: string }) => void; + const slow = vi.fn( + () => + new Promise<{ model: string }>((resolve) => { + choose = resolve; + }), + ); + void deliver(message("2", "@Gander second"), { config, route: slow }); + await vi.waitFor(() => expect(slow).toHaveBeenCalledTimes(1)); + void deliver(message("3", "@Gander third"), { config }); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(goose()?.turns).toHaveLength(1); + choose({ model: "o3" }); + await vi.waitFor(() => expect(goose()?.turns.length).toBeGreaterThan(1)); + expect(JSON.stringify(goose()?.turns[1])).toContain("@Gander second"); + expect(JSON.stringify(goose()?.turns[1]?.text)).not.toContain( + "@Gander third", + ); + for (const turn of goose()?.turns ?? []) turn.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..219845c5c1 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, @@ -647,6 +648,7 @@ export class GooseRuntime { team, model, effort, + route: chooseModel, synced, workingUntil, current, @@ -910,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; @@ -940,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 @@ -1872,7 +1882,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), + ), ) } > diff --git a/src/features/agent-harness/acp/agent-sessions.ts b/src/features/agent-harness/acp/agent-sessions.ts index 1af2149268..da6043d8b3 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, @@ -283,6 +283,9 @@ export class AgentSessions { >(); /** Conversations `exclusive` holds, which messages wait for. */ private readonly held = new Map(); + /** Conversations whose idle session a message keeps while its model route + * chooses, so one that comes meanwhile does not go first. */ + private readonly choosing = new Map>(); /** Conversations whose last held work left a session not yet retired. */ private readonly outliving = new Map(); /** Holds waiting their turn, by conversation, which `interrupt` ends. */ @@ -367,7 +370,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 +388,7 @@ export class AgentSessions { model, effort, kept, + route, ...activity }: Readonly<{ current?: () => boolean; @@ -393,79 +399,122 @@ export class AgentSessions { model?: string; effort?: string; kept?: string; + route?: TurnRoute; }> & ActivityReceipt = {}, ): Promise { - for (;;) { - if (current && !current()) return { ok: true, undelivered: true }; - if (this.disposed) return { ...this.stopped, undelivered: true }; - // One that arrives while `exclusive` holds the conversation waits. - const held = this.held.get(key); - if (held) { - try { - await abortable(held.done, signal); - } catch { - return this.late; + // This message's hold on an idle session while its route chooses: kept + // until it sends the turn, opens a session or gives up. + let release: (() => void) | undefined; + try { + for (;;) { + if (current && !current()) return { ok: true, undelivered: true }; + if (this.disposed) return { ...this.stopped, undelivered: true }; + // One that arrives while `exclusive` holds the conversation waits. + const held = this.held.get(key); + if (held) { + try { + await abortable(held.done, signal); + } catch { + return this.late; + } + continue; } - continue; - } - // Or while a session held work left running has yet to exit. - const outliving = this.outliving.get(key); - if (outliving) { - if (outliving.failed) - return { ok: false, error: this.unconfirmed, undelivered: true }; - try { - await abortable( - Promise.race([outliving.settled, this.stopping]), - signal, - ); - } catch { - return this.late; + // Or while a session held work left running has yet to exit. + const outliving = this.outliving.get(key); + if (outliving) { + if (outliving.failed) + return { ok: false, error: this.unconfirmed, undelivered: true }; + try { + await abortable( + Promise.race([outliving.settled, this.stopping]), + signal, + ); + } catch { + return this.late; + } + continue; } - continue; - } - // A message that arrives while its conversation's session opens uses it. - const opening = this.opening.get(key); - if (opening) { - // The session stays shared; only this message gives up on it. - try { - await abortable( - opening.catch(() => undefined), - signal, - ); - } catch { - return this.late; + // A message that arrives while its conversation's session opens uses it. + const opening = this.opening.get(key); + if (opening) { + // The session stays shared; only this message gives up on it. + try { + await abortable( + opening.catch(() => undefined), + signal, + ); + } catch { + return this.late; + } + continue; } - continue; - } - const live = this.live.get(key); - if (!live) break; - if ( - !live.session.open || - (!live.session.busy && (this.stale(live) || this.leveled(live, effort))) - ) { - this.drop(key, live); - break; - } - // A harness that cannot take a new prompt in place needs a new session. - if (!live.session.busy && !live.process.repromptable) { - const { systemPrompt } = await this.options.launch(key); - if (this.live.get(key) !== live) continue; - if (systemPrompt !== live.systemPrompt) { - this.drop(key, live); + // Or while another message chooses its model for the idle session. + const choosing = this.choosing.get(key); + if (choosing && !release) { + try { + await abortable(choosing, signal); + } catch { + return this.late; + } + continue; + } + 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) { + if (!release) { + let done!: () => void; + const held = new Promise((resolve) => { + done = resolve; + }); + this.choosing.set(key, held); + release = () => { + if (this.choosing.get(key) === held) this.choosing.delete(key); + done(); + }; + } + 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))) + ) { + this.drop(key, live); + break; + } + // A harness that cannot take a new prompt in place needs a new session. + if (!live.session.busy && !live.process.repromptable) { + const { systemPrompt } = await this.options.launch(key); + if (this.live.get(key) !== live) continue; + if (systemPrompt !== live.systemPrompt) { + this.drop(key, live); + continue; + } + } + return this.answer( + key, + live, + seen, + text, + { ...activity, ...(current ? { current } : {}) }, + model, + effort, + kept, + route, + ); } - return this.answer( - key, - live, - seen, - text, - { ...activity, ...(current ? { current } : {}) }, - model, - effort, - kept, - ); + } finally { + // Sending made the session busy, so a message waiting now queues + // behind this one. One that goes on to open a session reserves it + // below before a waiting one resumes. + release?.(); } // Reserved before anything is awaited, so a message that comes meanwhile // waits for this session instead of opening another. @@ -506,6 +555,7 @@ export class AgentSessions { model, effort, kept, + route, ), }; })(); @@ -1116,6 +1166,7 @@ export class AgentSessions { model: string | undefined, effort?: string, kept?: string, + route?: TurnRoute, ) { const sent = live.session.send( text, @@ -1129,6 +1180,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/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..a6a9f8805f 100644 --- a/src/features/agents/ModelFamilyMenu.tsx +++ b/src/features/agents/ModelFamilyMenu.tsx @@ -4,6 +4,7 @@ import { CaretDownIcon, CheckIcon, LightningIcon, + ArrowsSplitIcon, } from "../../shared/design-system/icons"; import { Button } from "../../shared/design-system/ui/Button"; import { ChoiceRow } from "../../shared/design-system/ui/ChoiceRow"; @@ -118,20 +119,25 @@ 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]); } 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. - 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 && ( @@ -185,7 +191,15 @@ export function ModelFamilyMenu({ {leading} )} - {modelLogo(modelFamily(selected), "buzz-select-leading")} + {selected.route ? ( +