A desktop coding agent with free access to frontier models.
TypeScript
feat(subagents): run a sub-agent on a model the user names in their message (#63)
Anurag Pappulacafb2003f0fc
diff --git a/apps/server/src/omnirush-subagent-model.test.ts b/apps/server/src/omnirush-subagent-model.test.tsindex fe3cabd2..5b1aa569 100644--- a/apps/server/src/omnirush-subagent-model.test.ts+++ b/apps/server/src/omnirush-subagent-model.test.ts@@ -13,6 +13,7 @@ import {sanitizeSubagentModelSetting,subagentFallbackNote,subagentModelSettingPath,+ subagentSettingFor,writeSubagentModelSetting,} from "./omnirush-subagent-model.js";import type { ServerConfig } from "./types.js";@@ -67,6 +68,26 @@ describe("nearest effort", () => {});describe("resolve a sub-agent prompt", () => {+ test("a model the user named for a sub-agent replaces the pick and is checked like one", () => {+ const stored = { model: "gpt-6-sol", effort: "high" } as const;+ expect(subagentSettingFor(stored, null)).toEqual(stored);+ // Its own effort wins; without one the setting's effort applies.+ expect(subagentSettingFor(stored, { providerID: "omnirush", modelID: "meta-muse-spark", variant: "low" })).toEqual({ model: "meta-muse-spark", effort: "low" });+ expect(subagentSettingFor(stored, { providerID: "omnirush", modelID: "meta-muse-spark", variant: null })).toEqual({ model: "meta-muse-spark", effort: "high" });+ expect(subagentSettingFor({ model: null, effort: null }, { providerID: "omnirush", modelID: "gpt-6-sol" })).toEqual({ model: "gpt-6-sol", effort: null });+ // Another provider's model needs no omnirush.ai checks: kept as the engine started it.+ expect(subagentSettingFor(stored, { providerID: "anthropic", modelID: "claude-x" })).toBeNull();++ // Resolved like a pick: served, it runs; not in the account's catalog, the main model runs instead.+ const named = subagentSettingFor(stored, { providerID: "omnirush", modelID: "meta-muse-spark", variant: "low" })!;+ expect(resolveSubagentModel({ setting: named, catalog, gateway: true, inherited: { ...astra, variant: "max" }, main: { ...astra, variant: "max" } }).model)+ .toEqual({ providerID: "omnirush", modelID: "meta-muse-spark" });+ const unknown = subagentSettingFor(stored, { providerID: "omnirush", modelID: "not-served-model" })!;+ const resolved = resolveSubagentModel({ setting: unknown, catalog, gateway: true, inherited: astra, main: astra });+ expect(resolved.model).toEqual({ providerID: "omnirush", modelID: "gpt-6-astra" });+ expect(resolved.fallback?.reason).toBe("not_in_catalog");+ });+test("untouched setting changes nothing", () => {expect(resolveSubagentModel({setting: { model: null, effort: null },diff --git a/apps/server/src/omnirush-subagent-model.ts b/apps/server/src/omnirush-subagent-model.tsindex 6b452892..09b4eb60 100644--- a/apps/server/src/omnirush-subagent-model.ts+++ b/apps/server/src/omnirush-subagent-model.ts@@ -289,6 +289,22 @@ export function resolveSubagentModel(input: {return resolution;}+/**+ * The setting a sub-agent resolves with. A model the user's own message named+ * for this sub-agent (`requested`, vetted by the swarm plugin) replaces the+ * stored pick, and is checked exactly like one: catalog, refusals, fallback.+ * Its effort is the one the user named with it, else the setting's. A named+ * model of another provider needs no omnirush.ai checks: null keeps it.+ */+export function subagentSettingFor(+ stored: SubagentModelSetting,+ requested: (EngineModelRef & { variant?: string | null }) | null,+): SubagentModelSetting | null {+ if (!requested) return stored;+ if (requested.providerID !== OMNIRUSH_PROVIDER_ID || !MODEL_ID.test(requested.modelID)) return null;+ return { model: requested.modelID, effort: parseSubagentEffort(requested.variant) ?? stored.effort };+}+/** A readable note for a sub-agent session that runs on the main model instead of the picked one. */export function subagentFallbackNote(fallback: NonNullable<SubagentModelResolution["fallback"]> | { requestedName: string; usedName: string; reason: string }): string {const why = fallback.reason === "not_in_catalog"diff --git a/apps/server/src/omnirush-swarm.ts b/apps/server/src/omnirush-swarm.tsindex 2c1dda31..9ad7a2f6 100644--- a/apps/server/src/omnirush-swarm.ts+++ b/apps/server/src/omnirush-swarm.ts@@ -46,6 +46,42 @@ export const SUBAGENT_ROOT_SESSION_HEADER = "x-omnirush-subagent-root";/** The session upload trace event recording that a sub-agent ran on the main model instead of the picked one. */export const SUBAGENT_MODEL_FALLBACK_TRACE = "subagent.model_fallback";+/** A model the user's text can name: its id and, from the catalog, its display name. */+export type NameableModel = { id: string; name?: string | null };++/**+ * The models the user's text names, by id or display name, as words of their+ * own. Case and separators (space, "-", "_") do not matter, so "GPT 6 Sol",+ * "gpt-6-sol" and "gpt 6 sol" all name gpt-6-sol. A mention inside a longer+ * model's mention names only the longer model ("GPT 6 Sol Mini" is not+ * GPT 6 Sol), and "gpt-6" alone names neither. A task's own model runs over+ * the sub-agent setting only when the user's latest message names it.+ */+export function modelsNamedIn(text: string | null | undefined, models: readonly NameableModel[]): Set<string> {+ const named = new Set<string>();+ if (typeof text !== "string" || !text) return named;+ const spans: Array<{ id: string; start: number; end: number }> = [];+ for (const model of models) {+ for (const label of [model.id, model.name]) {+ const words = typeof label === "string" ? label.split(/[\s_-]+/).filter(Boolean) : [];+ if (!words.length) continue;+ const body = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\s_-]*");+ const pattern = new RegExp(`(?<![A-Za-z0-9._-])${body}(?![A-Za-z0-9_]|[-.][A-Za-z0-9])`, "gi");+ for (const match of text.matchAll(pattern)) spans.push({ id: model.id, start: match.index, end: match.index + match[0].length });+ }+ }+ for (const span of spans) {+ const inside = spans.some((other) => other.id !== span.id && other.start <= span.start && other.end >= span.end && other.end - other.start > span.end - span.start);+ if (!inside) named.add(span.id);+ }+ return named;+}++/** Whether the user's text names the model id `id` (no catalog: its id only). */+export function textNamesModel(text: string | null | undefined, id: string): boolean {+ return Boolean(id) && modelsNamedIn(text, [{ id }]).has(id);+}+/*** The folder omnirush.ai keeps its own workspace files in, relative to the* workspace root. Only the board and its archive are kept out of git therediff --git a/apps/server/src/opencode-plugins/omnirush-engine2.ts b/apps/server/src/opencode-plugins/omnirush-engine2.tsindex 5c5f1856..f8c039a2 100644--- a/apps/server/src/opencode-plugins/omnirush-engine2.ts+++ b/apps/server/src/opencode-plugins/omnirush-engine2.ts@@ -175,6 +175,14 @@ function messagesForV1(messages: unknown[]): { v1: Rec[]; restore: (edited: Rec[type ModelInfo = Rec & { id: string; providerID: string };+/** The subagent tool's `model` parameter as offered: the swarm plugin keeps it only when the user named it. */+const SUBAGENT_MODEL_DESCRIPTION = [+ "Leave this out unless the user's own message asks for a particular model for the sub-agent.",+ 'Then pass the model the user named, as "omnirush/<model id>", or "omnirush/<model id>#<effort>" when they also named an effort.',+ "A model id is its display name in lowercase with dashes for spaces (a model shown as \"Some Model 2\" has the id some-model-2).",+ "It is used only when the user's latest message names that model, by id or display name; otherwise the sub-agent runs on the user's sub-agent model setting.",+].join(" ");+export default {id: "omnirush",async setup(ctx: any) {@@ -296,22 +304,24 @@ export default {// ---- tool calls --------------------------------------------------------// Sub-agents run in the foreground, as the 1.x task tool did (the swarm counts running// sub-agents and the task result carries the sub-agent's answer).+ // A call's own `model` is kept here: the swarm plugin's tool.execute.before (below) keeps it only+ // when the user's own message names that model, and drops it otherwise, so the sub-agent runs on+ // the app's sub-agent setting (or the caller's model), as with the 1.x task tool.await ctx.tool.hook("execute.before", async (event: any) => {if (event.tool !== "subagent" || !isRec(event.input)) return;- // The sub-agent's model comes from the app's sub-agent setting (or the caller's), as with- // the 1.x task tool, never from the model's own pick.- const { model: _model, background: _background, ...input } = event.input;+ const { background: _background, ...input } = event.input;event.input = input;});- // …so the subagent tool is offered without its `model` and `background` parameters.+ // …so the subagent tool is offered without `background`, and with `model` for a model the user asks for.await ctx.session.hook("context", async (event: any) => {const input = event?.tools?.subagent?.input;if (!isRec(input) || !isRec(input.properties)) return;- const { model: _model, background: _background, ...properties } = input.properties as Rec;+ const { background: _background, ...properties } = input.properties as Rec;+ if (isRec(properties.model)) properties.model = { ...properties.model, description: SUBAGENT_MODEL_DESCRIPTION };event.tools.subagent.input = {...input,properties,- ...(Array.isArray(input.required) ? { required: input.required.filter((key: unknown) => key !== "model" && key !== "background") } : {}),+ ...(Array.isArray(input.required) ? { required: input.required.filter((key: unknown) => key !== "background") } : {}),};});const before = hooks("tool.execute.before");diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts b/apps/server/src/opencode-plugins/omnirush-swarm.test.tsindex e8407e52..f1bfb9c6 100644--- a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts+++ b/apps/server/src/opencode-plugins/omnirush-swarm.test.ts@@ -18,6 +18,8 @@ import {OMNIRUSH_SWARM_MAX_PER_TURN,OMNIRUSH_SWARM_MAX_RUNNING,OMNIRUSH_SWARM_SKILL_NAME,+ modelsNamedIn,+ textNamesModel,OMNIRUSH_TASK_TOOL_NOTE,omnirushSubagentNote,} from "../omnirush-swarm.js";@@ -431,6 +433,13 @@ describe("omnirush swarm plugin: sub-agent model and effort", () => {else process.env.OMNIRUSH_POLICY_TOKEN = saved.token;});+ /** The account's catalog as the server knows it: ids and display names. */+ const testCatalog = [+ { id: "gpt-6-astra", name: "GPT 6 Astra" },+ { id: "gpt-6-luna", name: "GPT 6 Luna" },+ { id: "gpt-6-luna-mini", name: "GPT 6 Luna Mini" },+ { id: "omni-fast", name: "Omni Turbo" },+ ];async function withServer(answer: (body: Record<string, unknown>) => unknown, fallbacks: unknown[] = []) {const resolves: Resolve[] = [];const server = Bun.serve({@@ -443,6 +452,10 @@ describe("omnirush swarm plugin: sub-agent model and effort", () => {resolves.push({ body });return Response.json(answer(body));}+ if (url.pathname === "/omnirush/subagent-model/named") {+ const body = (await request.json()) as { text: string; model: string };+ return Response.json({ named: modelsNamedIn(body.text, [...testCatalog, { id: body.model }]).has(body.model) });+ }if (url.pathname === "/omnirush/subagent-model/fallbacks") return Response.json({ fallbacks });return new Response("not found", { status: 404 });},@@ -453,18 +466,31 @@ describe("omnirush swarm plugin: sub-agent model and effort", () => {const titles: Record<string, string> = { ses_child: "Research (@general subagent)" };const directory = await mkdtemp(join(tmpdir(), "omnirush-swarm-model-"));dirs.push(directory);- const parents: Record<string, string | null> = { ses_main: null, ses_child: "ses_main", ses_grand: "ses_child" };+ const parents: Record<string, string | null> = { ses_main: null, ses_child: "ses_main", ses_grand: "ses_child", ses_other: "ses_main" };+ /** What the user typed last in the main session (the only session with a user). */+ const user = { text: "" };+ /** The model each session's record names (the 2.x engine's `{ id, providerID }`). */+ const sessionModels: Record<string, unknown> = {};const client = {session: {- get: async ({ path }: { path: { id: string } }) => ({ data: { id: path.id, parentID: parents[path.id] ?? undefined, title: titles[path.id] } }),+ get: async ({ path }: { path: { id: string } }) => ({ data: { id: path.id, parentID: parents[path.id] ?? undefined, title: titles[path.id], model: sessionModels[path.id] } }),update: async ({ path, body }: { path: { id: string }; body: { title: string } }) => {titles[path.id] = body.title;return { data: {} };},+ messages: async ({ path }: { path: { id: string } }) => ({+ data: path.id === "ses_main"+ ? [+ { info: { role: "user" }, parts: [{ type: "text", text: "earlier: use gpt-6-luna" }] },+ { info: { role: "assistant" }, parts: [{ type: "text", text: "gpt-6-astra is the one" }] },+ { info: { role: "user" }, parts: [{ type: "text", text: user.text }, { type: "text", text: "gpt-6-nova", synthetic: true }] },+ ]+ : [],+ }),},};const hooks = await OmniRushSwarm({ client, directory });- return { hooks, resolves, titles };+ return { hooks, resolves, titles, user, sessionModels };}const cleanupServers: Array<() => void> = [];afterEach(() => {@@ -559,6 +585,117 @@ describe("omnirush swarm plugin: sub-agent model and effort", () => {expect(titles.ses_child).toContain("· ran on GPT 6 Astra: GPT 6 Sol was refused by omnirush.ai");});+ test("a task's own model runs only when the user's latest message names it, and resolves in place of the setting", async () => {+ // The server echoes a requested model, else answers with the setting's pick (GPT 6 Sol).+ const { hooks, resolves, user } = await withServer((body) => {+ const requested = body.requested as { modelID: string; variant?: string | null } | undefined;+ return requested+ ? { model: { providerID: "omnirush", modelID: requested.modelID }, variant: requested.variant ?? "high" }+ : { model: { providerID: "omnirush", modelID: "gpt-6-sol" }, variant: "high" };+ });+ const task = async (sessionID: string, model: unknown) => {+ const output = { args: { description: "Research", prompt: "look", subagent_type: "general", ...(model === undefined ? {} : { model }) } as Record<string, unknown> };+ await hooks["tool.execute.before"]({ tool: "task", sessionID, callID: `call_${Math.random()}` }, output);+ return output.args.model;+ };+ const main = { providerID: "omnirush", modelID: "gpt-6-astra", variant: "max" };++ // Not named in the latest user message (an earlier message, the agent's text and synthetic parts do not count): dropped.+ user.text = "please research this with a sub-agent";+ await prompt(hooks, "ses_main", main);+ expect(await task("ses_main", "omnirush/gpt-6-luna")).toBeUndefined();+ expect(await task("ses_main", "omnirush/gpt-6-nova")).toBeUndefined();+ expect(await prompt(hooks, "ses_child", main)).toEqual({ providerID: "omnirush", modelID: "gpt-6-sol", variant: "high" });+ expect(resolves.at(-1)!.body.requested).toBeUndefined();++ // Named: kept (a bare id is an omnirush.ai model), and the sub-agent it starts resolves that model.+ user.text = "Use a sub-agent on GPT-6-Luna#low for this";+ await prompt(hooks, "ses_main", main);+ expect(await task("ses_main", "gpt-6-luna#low")).toBe("omnirush/gpt-6-luna#low");+ const luna = { providerID: "omnirush", modelID: "gpt-6-luna", variant: "low" };+ expect(await prompt(hooks, "ses_other", luna)).toEqual(luna);+ expect(resolves.at(-1)!.body.requested).toEqual(luna);+ // Its later prompts keep it; a sibling that inherited the main model still gets the setting.+ expect(await prompt(hooks, "ses_other", luna)).toEqual(luna);+ expect(resolves.at(-1)!.body.requested).toEqual(luna);+ expect(await prompt(hooks, "ses_child", main)).toEqual({ providerID: "omnirush", modelID: "gpt-6-sol", variant: "high" });++ // The display name the app shows counts too; a longer model's name names only that model.+ user.text = "Launch two reviewers: one on GPT 6 Astra and the other on gpt 6 luna";+ await prompt(hooks, "ses_main", main);+ expect(await task("ses_main", "omnirush/gpt-6-astra")).toBe("omnirush/gpt-6-astra");+ expect(await task("ses_main", "omnirush/gpt-6-luna")).toBe("omnirush/gpt-6-luna");+ user.text = "one reviewer on GPT 6 Luna Mini";+ await prompt(hooks, "ses_main", main);+ expect(await task("ses_main", "omnirush/gpt-6-luna")).toBeUndefined();+ expect(await task("ses_main", "omnirush/gpt-6-luna-mini")).toBe("omnirush/gpt-6-luna-mini");+ // A display name unlike its id counts through the account's catalog.+ user.text = "one reviewer on Omni Turbo";+ await prompt(hooks, "ses_main", main);+ expect(await task("ses_main", "omnirush/omni-fast")).toBe("omnirush/omni-fast");+ // Without the server (no catalog) only the id counts, in any spacing: "GPT 6 Astra" still names+ // gpt-6-astra, but "Omni Turbo" no longer names omni-fast.+ const url = process.env.OMNIRUSH_SERVER_URL;+ process.env.OMNIRUSH_SERVER_URL = "http://127.0.0.1:9";+ user.text = "one on GPT 6 Astra, one on Omni Turbo";+ await prompt(hooks, "ses_main", main);+ expect(await task("ses_main", "omnirush/gpt-6-astra")).toBe("omnirush/gpt-6-astra");+ expect(await task("ses_main", "omnirush/omni-fast")).toBeUndefined();+ process.env.OMNIRUSH_SERVER_URL = url;++ // A sub-agent's own task call never keeps a model (it has no user), nor does a malformed one.+ expect(await task("ses_child", "omnirush/gpt-6-luna")).toBeUndefined();+ expect(await task("ses_main", "not a model id")).toBeUndefined();+ expect(await task("ses_main", 42)).toBeUndefined();+ expect(await task("ses_main", undefined)).toBeUndefined();+ });++ test("a finished task names the model its sub-agent really ran on, not the call's dropped model", async () => {+ const { hooks, user, sessionModels } = await withServer(() => ({}));+ user.text = "research this with a sub-agent";+ await prompt(hooks, "ses_main", { providerID: "omnirush", modelID: "gpt-6-astra" });+ const args: Record<string, unknown> = { description: "Research", prompt: "look", subagent_type: "general", model: "omnirush/gpt-6-sol" };+ await hooks["tool.execute.before"]({ tool: "task", sessionID: "ses_main", callID: "call_x" }, { args });+ expect(args.model).toBeUndefined();+ sessionModels.ses_child = { id: "gpt-6-astra", providerID: "omnirush", variant: "default" };+ await prompt(hooks, "ses_child", { providerID: "omnirush", modelID: "gpt-6-astra" });+ // The adapter's guess (the call's own model) is replaced by the session's model.+ const output = { output: "<task>done</task>", metadata: { sessionId: "ses_child", model: { providerID: "omnirush", modelID: "gpt-6-sol" } } as Record<string, unknown> };+ await hooks["tool.execute.after"]({ tool: "task", callID: "call_x" }, output);+ expect(output.metadata.model).toEqual({ providerID: "omnirush", modelID: "gpt-6-astra" });+ });++ test("a message names catalog models by id or display name, as whole words", () => {+ const catalog = [+ { id: "gpt-6-sol", name: "GPT 6 Sol" },+ { id: "gpt-6-sol-mini", name: "GPT 6 Sol Mini" },+ { id: "gpt-5.6-sol", name: "GPT-5.6 Sol" },+ { id: "gpt-6-astra", name: "GPT 6 Astra" },+ ];+ const named = (text: string) => [...modelsNamedIn(text, catalog)].sort();+ expect(named("one reviewer on GPT 6 Astra and the other on GPT 6 Sol")).toEqual(["gpt-6-astra", "gpt-6-sol"]);+ expect(named("use gpt 6 sol")).toEqual(["gpt-6-sol"]);+ expect(named("use GPT_6_SOL please")).toEqual(["gpt-6-sol"]);+ expect(named("use GPT 6 Sol Mini")).toEqual(["gpt-6-sol-mini"]);+ expect(named("use gpt-6-sol-mini")).toEqual(["gpt-6-sol-mini"]);+ expect(named("try GPT-5.6 Sol, then gpt-5.6-sol")).toEqual(["gpt-5.6-sol"]);+ expect(named("use gpt-6 for this")).toEqual([]);+ expect(named("the solution uses astra-like ideas")).toEqual([]);+ expect(named("")).toEqual([]);+ });++ test("a model id is named only as a word of its own", () => {+ expect(textNamesModel("use gpt-6-astra please", "gpt-6-astra")).toBe(true);+ expect(textNamesModel("Use GPT-6-Astra.", "gpt-6-astra")).toBe(true);+ expect(textNamesModel("(gpt-6-astra)", "gpt-6-astra")).toBe(true);+ expect(textNamesModel("use gpt-6-astra-mini", "gpt-6-astra")).toBe(false);+ expect(textNamesModel("use gpt-6", "gpt-6-astra")).toBe(false);+ expect(textNamesModel("use my-gpt-6-astra", "gpt-6-astra")).toBe(false);+ expect(textNamesModel("use gpt-6-astra.2", "gpt-6-astra")).toBe(false);+ expect(textNamesModel("", "gpt-6-astra")).toBe(false);+ expect(textNamesModel(null, "gpt-6-astra")).toBe(false);+ });+test("with the setting untouched or no server, sub-agent prompts stay exactly as the engine made them", async () => {const { hooks } = await withServer(() => ({}));await prompt(hooks, "ses_main", { providerID: "omnirush", modelID: "gpt-6-astra", variant: "max" });diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.ts b/apps/server/src/opencode-plugins/omnirush-swarm.tsindex a420b241..0abba71e 100644--- a/apps/server/src/opencode-plugins/omnirush-swarm.ts+++ b/apps/server/src/opencode-plugins/omnirush-swarm.ts@@ -78,6 +78,7 @@ import {omnirushSubagentNote,omnirushSwarmSubagentNote,OMNIRUSH_TASK_TOOL_NOTE,+ textNamesModel,} from "../omnirush-swarm.js";type SessionInfo = { id?: unknown; parentID?: unknown; title?: unknown };@@ -86,6 +87,7 @@ type SwarmClient = {session?: {get?: (input: { path: { id: string } }) => Promise<{ data?: SessionInfo } | undefined>;update?: (input: { path: { id: string }; body: { title: string } }) => Promise<unknown>;+ messages?: (input: { path: { id: string } }) => Promise<{ data?: unknown } | undefined>;};};type ModelChoice = { providerID: string; modelID: string; variant?: string | null };@@ -152,6 +154,29 @@ function modelChoice(value: unknown): ModelChoice | null {return { providerID, modelID, variant: typeof value.variant === "string" && value.variant ? value.variant : null };}+/** A task's `model` argument: "providerID/modelID", "providerID/modelID#variant", or a bare omnirush.ai model id. */+function modelArgument(value: unknown): ModelChoice | null {+ if (typeof value !== "string") return null;+ const match = /^(?:([A-Za-z0-9._-]{1,128})\/)?([A-Za-z0-9][A-Za-z0-9._:-]{0,127})(?:#([A-Za-z0-9._-]{1,32}))?$/.exec(value.trim());+ if (!match) return null;+ return { providerID: match[1] ?? "omnirush", modelID: match[2]!, variant: match[3] ?? null };+}++/** The text the user typed in the session's latest user message (synthetic parts left out). */+function latestUserText(messages: unknown): string | null {+ if (!Array.isArray(messages)) return null;+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (!record(message) || !record(message.info) || message.info.role !== "user") continue;+ const parts = Array.isArray(message.parts) ? message.parts : [];+ return parts+ .filter((part): part is Record<string, unknown> => record(part) && part.type === "text" && part.synthetic !== true && typeof part.text === "string")+ .map((part) => part.text as string)+ .join("\n");+ }+ return null;+}+function resolution(value: unknown): Resolution | null {if (!record(value) || !record(value.model)) return null;const model = modelChoice(value.model);@@ -296,6 +321,10 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:const notes = new Map<string, { model: ModelChoice; fallback: Resolution["fallback"] | null; at: number }>();/** Sub-agent sessions whose title already carries the fallback note. */const titled = new Set<string>();+ /** Main session id -> the task models ("provider/model") its user's latest message named this turn. */+ const named = new Map<string, Set<string>>();+ /** Sub-agent session id -> the model the user named for it, resolved in place of the setting. */+ const requestedModels = new Map<string, ModelChoice>();/** Main sessions running a swarm: their tree loaded the swarm skill or wrote the board. */const swarms = new Set<string>();/** Sessions the engine reports busy (any layer). */@@ -371,12 +400,20 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:if (!message || !serverBase() || !serverToken()) return;const inherited = modelChoice(message.model) ?? fallbackModel;if (!inherited) return;- const { root } = await locate(sessionId);+ const { root, depth } = await locate(sessionId);+ // A first-layer sub-agent the engine started on a model the user named (vetTaskModel) runs on it,+ // resolved in place of the setting; it keeps it for its later prompts.+ let requested = requestedModels.get(sessionId);+ if (!requested && depth === 1 && named.get(root)?.has(`${inherited.providerID}/${inherited.modelID}`)) {+ requested = inherited;+ remember(requestedModels, sessionId, requested, MAX_TRACKED_SESSIONS);+ }const answer = resolution(await serverJson("/omnirush/subagent-model/resolve", {sessionId,rootSessionId: root,inherited,main: mainModels.get(root) ?? null,+ ...(requested ? { requested } : {}),}));if (!answer?.model) {overrides.delete(sessionId);@@ -402,6 +439,51 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:if (answer.fallback) await noteOnTitle(sessionId, fallbackNote(answer.fallback));};+ /** The model a session runs on, as its session record names it; null when unknown. */+ const sessionModel = async (sessionId: string): Promise<{ providerID: string; modelID: string } | null> => {+ try {+ const info: unknown = (await input?.client?.session?.get?.({ path: { id: sessionId } }))?.data;+ const model = record(info) && record(info.model) ? info.model : null;+ if (!model) return null;+ const modelID = typeof model.id === "string" ? model.id : typeof model.modelID === "string" ? model.modelID : "";+ const providerID = typeof model.providerID === "string" ? model.providerID : "";+ return modelID && providerID ? { providerID, modelID } : null;+ } catch {+ return null;+ }+ };++ /**+ * A task's own `model` runs only when the user's latest message in the main+ * session names that model (by id or catalog name); otherwise it is dropped and the sub-agent+ * setting decides, as when the tool offered no model. Sub-agents have no+ * user, so their own task calls never keep one. Kept models are written as+ * "provider/model[#variant]" (a bare id is an omnirush.ai model).+ */+ const vetTaskModel = async (sessionId: string, args: Record<string, unknown>) => {+ if (!("model" in args)) return;+ const wanted = modelArgument(args.model);+ delete args.model;+ if (!wanted) return;+ const { root, depth } = await locate(sessionId);+ if (depth > 0) return;+ let text: string | null = null;+ try {+ text = latestUserText((await input?.client?.session?.messages?.({ path: { id: root } }))?.data);+ } catch {+ return;+ }+ // The server knows the account's catalog, so "GPT 6 Sol" names gpt-6-sol there;+ // without it, only the id itself counts.+ const answer = text ? await serverJson("/omnirush/subagent-model/named", { text, model: wanted.modelID }) : null;+ const userNamed = record(answer) && typeof answer.named === "boolean" ? answer.named : textNamesModel(text, wanted.modelID);+ if (!userNamed) return;+ args.model = `${wanted.providerID}/${wanted.modelID}${wanted.variant ? `#${wanted.variant}` : ""}`;+ const models = named.get(root) ?? new Set<string>();+ models.add(`${wanted.providerID}/${wanted.modelID}`);+ remember(named, root, models, MAX_TRACKED_TREES);+ };+const finish = (callId: unknown) => {if (typeof callId !== "string") return;const root = calls.get(callId);@@ -567,6 +649,8 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:}const tree = trees.get(message.sessionID);if (tree) tree.started = 0;+ // A new user message decides afresh which task models it names.+ named.delete(message.sessionID);const main = modelChoice(output?.message?.model) ?? inputModel;if (main) remember(mainModels, message.sessionID, main, MAX_TRACKED_TREES);},@@ -596,6 +680,8 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:return;}if (call.tool !== "task") return;+ const taskArgs = output?.args;+ if (record(taskArgs)) await vetTaskModel(call.sessionID, taskArgs);const { root } = await locate(call.sessionID);const tree = treeOf(root);const now = Date.now();@@ -637,7 +723,13 @@ export const OmniRushSwarm = async (input?: { client?: SwarmClient; directory?:const child = metadata && typeof metadata.sessionId === "string" ? metadata.sessionId : null;if (!child || !metadata) return;const note = notes.get(child);- if (!note) return;+ if (!note) {+ // No pick changed its model: name the one the child session really ran on. The call's+ // own `model` is no guide, since vetTaskModel may have dropped it.+ const ran = await sessionModel(child);+ if (ran) metadata.model = ran;+ return;+ }metadata.model = { providerID: note.model.providerID, modelID: note.model.modelID };if (note.model.variant) metadata.variant = note.model.variant;let fallback: { requested: string; requestedName: string; used: string; usedName: string; reason: string } | null = note.fallback ?? null;diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex d46af66f..f09c8272 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -181,10 +181,12 @@ import {resolveSubagentModel,sanitizeSubagentModelSetting,subagentModelRefusals,+ subagentSettingFor,writeSubagentModelSetting,type EngineModelRef,type SubagentModelSetting,} from "./omnirush-subagent-model.js";+import { modelsNamedIn } from "./omnirush-swarm.js";import { findManagedEngineWorkspace } from "./workspaces.js";import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";@@ -3687,12 +3689,24 @@ function createRoutes(return jsonResponse({ ok: true, setting: saved });});+ // Whether the user's message names a model a task asked for, by id or by its catalog name+ // (the swarm plugin keeps the task's model only then).+ addRoute(routes, "POST", "/omnirush/subagent-model/named", "policy", async (ctx) => {+ const body = await readJsonBody(ctx.request);+ const model = typeof body.model === "string" ? body.model.trim() : "";+ const text = typeof body.text === "string" ? body.text.slice(0, 100_000) : "";+ if (!model) throw new ApiError(400, "invalid_payload", "model is required");+ const catalog = await readOmniRushModelCatalog(config);+ const models = [...catalog.map((entry) => ({ id: entry.id, name: entry.display_name })), { id: model }];+ return jsonResponse({ named: modelsNamedIn(text, models).has(model) });+ });+addRoute(routes, "POST", "/omnirush/subagent-model/resolve", "policy", async (ctx) => {const body = await readJsonBody(ctx.request);const inherited = engineModelRef(body.inherited);if (!inherited) throw new ApiError(400, "invalid_payload", "inherited model is required");- const setting = await readSubagentModelSetting(config);- if (!setting.model && !setting.effort) return jsonResponse({});+ const setting = subagentSettingFor(await readSubagentModelSetting(config), engineModelRef(body.requested));+ if (!setting || (!setting.model && !setting.effort)) return jsonResponse({});const refusals = subagentModelRefusals(config);const resolution = resolveSubagentModel({setting,