Open-source SEO, GEO, and marketing skills for AI agents.
feat(notfair-cmo): per-turn model selector fed by the provider's list
Yuting Zhong4d2b4b841738
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsxindex c16f6301..6901f560 100644--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx@@ -1,5 +1,6 @@import { notFound } from "next/navigation";import { getProject } from "@/server/db/projects";+import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/registry";import { resolveAgentBySlug } from "@/server/agent-meta";import {buildPendingSessionKey,@@ -92,6 +93,11 @@ export default async function AgentChatThreadPage({// render an MCP server's brand favicon next to its tool calls.// Mapping is by server key, so the resource_url is the brand domain// we feed faviconV2.+ // Provider-fed model list for the composer's selector (codex reads its+ // account-scoped cache; claude uses its documented tier aliases).+ const modelOptions = await requireAdapter(+ project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,+ ).listModels();const mcpCatalog = getMcpCatalog(project.slug).map((m) => ({key: m.key,display_name: m.display_name,@@ -135,6 +141,7 @@ export default async function AgentChatThreadPage({initialByteOffset={initialByteOffset}autoKickoff={autoKickoff}mcpCatalog={mcpCatalog}+ modelOptions={modelOptions}/></div></div>diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsxindex 02592ea1..4f136851 100644--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx@@ -1,6 +1,7 @@import { notFound } from "next/navigation";import { AgentTaskWorkspace } from "@/components/agent-task-workspace";+import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/registry";import { getProject } from "@/server/db/projects";import { getMcpCatalog } from "@/server/mcp-catalog";import { resolveAgentBySlug } from "@/server/agent-meta";@@ -83,6 +84,11 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {const tasks = listTasksByAgent(agentFullId);const proposedCount = tasks.filter((t) => t.status === "proposed").length;const attentionByTask = attentionByTaskForAgent(project.slug, agentFullId);+ // Provider-fed model list for the composer's selector (codex reads its+ // account-scoped cache; claude uses its documented tier aliases).+ const modelOptions = await requireAdapter(+ project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,+ ).listModels();// Brand-favicon lookup table for MCP tool calls in the transcript.const mcpCatalog = getMcpCatalog(project.slug).map((m) => ({key: m.key,@@ -101,6 +107,7 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {proposedCount={proposedCount}attentionByTask={attentionByTask}mcpCatalog={mcpCatalog}+ modelOptions={modelOptions}/>);}diff --git a/notfair-cmo/src/app/api/chat/route.ts b/notfair-cmo/src/app/api/chat/route.tsindex 909d5d40..e9ccbe45 100644--- a/notfair-cmo/src/app/api/chat/route.ts+++ b/notfair-cmo/src/app/api/chat/route.ts@@ -36,6 +36,12 @@ type ChatPostBody = {* mid-run are rejected with 409.*/task_id?: string;+ /**+ * Per-turn model override from the composer's model selector. Must be+ * one of HARNESS_MODEL_OPTIONS for the project's adapter — anything+ * else is a 400 (values become CLI spawn args, so no passthrough).+ */+ model?: string;};export async function POST(request: Request) {@@ -66,6 +72,20 @@ export async function POST(request: Request) {);}+ // Whitelist the model against the adapter's provider-fed list — the+ // value becomes a CLI spawn arg, so arbitrary client strings never+ // pass through unchecked.+ const model = body.model?.trim() || null;+ if (model) {+ const available = await requireAdapter(project.harness_adapter).listModels();+ if (!available.some((m) => m.value === model)) {+ return NextResponse.json(+ { error: `Unknown model '${model}' for adapter '${project.harness_adapter}'` },+ { status: 400 },+ );+ }+ }+const taskId = body.task_id?.trim();if (taskId) {const existing = getTask(taskId);@@ -138,6 +158,7 @@ export async function POST(request: Request) {message: body.message,threadId: session.id,harnessSessionId: session.harness_session_id,+ model,signal: noAbort.signal,})) {if (evt.kind === "session") {diff --git a/notfair-cmo/src/components/agent-task-workspace.tsx b/notfair-cmo/src/components/agent-task-workspace.tsxindex 3951162a..2525dd5c 100644--- a/notfair-cmo/src/components/agent-task-workspace.tsx+++ b/notfair-cmo/src/components/agent-task-workspace.tsx@@ -84,6 +84,9 @@ type Props = {/** task_id → count of pending questions/approvals waiting on the user.* Rows in the rail show the Slack-style red badge when > 0. */attentionByTask?: Record<string, number>;+ /** Composer model choices for this project's harness — forwarded to+ * LiveTranscript's selector. */+ modelOptions?: Array<{ value: string; label: string }>;/** MCP catalog forwarded to the per-task LiveTranscript so tool calls* that resolve to an MCP server render the server's brand favicon. */mcpCatalog?: McpCatalogEntryLite[];@@ -99,6 +102,7 @@ export function AgentTaskWorkspace({proposedCount,attentionByTask = {},mcpCatalog,+ modelOptions,}: Props) {const router = useRouter();const search = useSearchParams();@@ -216,6 +220,7 @@ export function AgentTaskWorkspace({agentDisplayName={agentDisplayName}taskById={taskById}mcpCatalog={mcpCatalog}+ modelOptions={modelOptions}/></div></>@@ -237,6 +242,7 @@ function SelectedTaskPanel({agentDisplayName,taskById,mcpCatalog,+ modelOptions,}: {selected: SelectedTaskBundle;projectSlug: string;@@ -244,6 +250,7 @@ function SelectedTaskPanel({agentDisplayName: string;taskById: Map<string, Task>;mcpCatalog?: McpCatalogEntryLite[];+ modelOptions?: Array<{ value: string; label: string }>;}) {const router = useRouter();const isInFlight = TASK_IN_FLIGHT.includes(selected.task.status);@@ -369,6 +376,7 @@ function SelectedTaskPanel({kickoffMessage={selected.kickoff?.message}taskId={selected.kickoff?.taskId}mcpCatalog={mcpCatalog}+ modelOptions={modelOptions}// The brief lives INSIDE the scrollable history: scroll to the// top of the conversation and the full brief card is there,// always expanded — it no longer eats header space.diff --git a/notfair-cmo/src/components/live-transcript.test.tsx b/notfair-cmo/src/components/live-transcript.test.tsxindex ee03ab41..3576dda7 100644--- a/notfair-cmo/src/components/live-transcript.test.tsx+++ b/notfair-cmo/src/components/live-transcript.test.tsx@@ -395,6 +395,59 @@ describe("LiveTranscript composer", () => {expect(screen.queryByText(/^Starting$/)).not.toBeInTheDocument();});+ it("model dropdown lists all models next to send and includes the pick in the send body", async () => {+ window.localStorage.clear();+ render(+ <LiveTranscript+ {...defaultProps({+ threadId: "t-model",+ modelOptions: [+ { value: "opus", label: "Opus" },+ { value: "sonnet", label: "Sonnet" },+ ],+ })}+ />,+ );+ const trigger = screen.getByRole("button", { name: /model/i });+ expect(trigger).toHaveTextContent("Default");+ // Radix menus open on pointerdown → click.+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });+ fireEvent.click(trigger);+ // Every available model + the Default reset are in the dropdown.+ const items = await screen.findAllByRole("menuitemradio");+ expect(items.map((i) => i.textContent)).toEqual([+ "Default",+ "Opus",+ "Sonnet",+ ]);+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Opus" }));+ expect(trigger).toHaveTextContent("Opus");+ // Persisted per project+agent so the choice sticks across visits.+ expect(+ window.localStorage.getItem("notfair-cmo:model:demo:cmo"),+ ).toBe("opus");++ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "hi" } });+ fireEvent.keyDown(textarea, { key: "Enter" });+ await vi.waitFor(() => {+ const f = global.fetch as ReturnType<typeof vi.fn>;+ const chatCall = f.mock.calls.find(+ ([u]) => typeof u === "string" && u.includes("/api/chat"),+ );+ expect(chatCall).toBeTruthy();+ const body = JSON.parse((chatCall![1] as RequestInit).body as string);+ expect(body.model).toBe("opus");+ });+ });++ it("renders no model selector when modelOptions are absent", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-no-model" })} />);+ expect(+ screen.queryByRole("button", { name: /model/i }),+ ).not.toBeInTheDocument();+ });+it("submitting Shift+Enter inserts a newline and does NOT send", () => {render(<LiveTranscript {...defaultProps({ threadId: "t-shift" })} />);const textarea = screen.getByRole("textbox");diff --git a/notfair-cmo/src/components/live-transcript.tsx b/notfair-cmo/src/components/live-transcript.tsxindex be8b9594..fff9d5a6 100644--- a/notfair-cmo/src/components/live-transcript.tsx+++ b/notfair-cmo/src/components/live-transcript.tsx@@ -13,6 +13,7 @@ import {AlertCircle,ArrowUp,CheckCircle2,+ ChevronDown,ChevronRight,Edit3,FileText,@@ -26,6 +27,13 @@ import {import { toast } from "sonner";import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";import { Markdown } from "@/components/markdown";import { brandDomain } from "@/components/mcp-icon";import { RunningDot } from "@/components/running-dot";@@ -147,6 +155,13 @@ type Props = {* scrolls with the conversation instead of eating header space.*/leadingContent?: React.ReactNode;+ /**+ * Models the composer's selector offers for this project's harness+ * (from HARNESS_MODEL_OPTIONS, passed down by the server page). A+ * "Default" choice (no override) is always prepended. Omitted/empty =+ * no selector rendered.+ */+ modelOptions?: Array<{ value: string; label: string }>;};/** Module-level guard so React StrictMode dev double-mounts don't double-fire. */@@ -168,9 +183,30 @@ export function LiveTranscript({taskId,mcpCatalog,leadingContent,+ modelOptions = [],}: Props) {const router = useRouter();const [events, setEvents] = useState<TranscriptEvent[]>(initialEvents);++ // Composer model override. "" = harness default (no flag). Persisted+ // per project+agent in localStorage; loaded after mount so SSR and the+ // first client render agree (no hydration mismatch).+ const modelStorageKey = `notfair-cmo:model:${projectSlug}:${agentSlug}`;+ const [model, setModel] = useState("");+ useEffect(() => {+ const stored = window.localStorage.getItem(modelStorageKey);+ if (stored && modelOptions.some((m) => m.value === stored)) {+ setModel(stored);+ }+ // modelOptions is a fresh array per render from the server page —+ // key its identity by content to avoid effect churn.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [modelStorageKey, JSON.stringify(modelOptions)]);+ function onPickModel(value: string) {+ setModel(value);+ if (value) window.localStorage.setItem(modelStorageKey, value);+ else window.localStorage.removeItem(modelStorageKey);+ }const [byteOffset, setByteOffset] = useState(initialByteOffset);const [input, setInput] = useState("");const [sendingChat, setSendingChat] = useState(false);@@ -510,6 +546,7 @@ export function LiveTranscript({sessionId: threadId,sessionKey,...(includeTaskId ? { task_id: taskId } : {}),+ ...(model ? { model } : {}),}),signal: ctrl.signal,});@@ -599,7 +636,7 @@ export function LiveTranscript({abortRef.current = null;}},- [agentSlug, input, pollOnce, projectSlug, router, sendingChat, sessionKey, taskId, threadId],+ [agentSlug, input, model, pollOnce, projectSlug, router, sendingChat, sessionKey, taskId, threadId],);// ── Auto-kickoff for FIRST_TURN-style flows. ────────────────────────@@ -768,7 +805,43 @@ export function LiveTranscript({rows={1}className="block max-h-52 w-full resize-none bg-transparent px-4 pt-3.5 text-sm placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"/>- <div className="flex items-center justify-end px-2.5 pb-2.5 pt-1.5">+ <div className="flex items-center justify-end gap-1.5 px-2.5 pb-2.5 pt-1.5">+ {/* Model picker sits right next to the send button (Codex+ placement): quiet "<model> ⌄" text trigger, dropdown of+ every available model opening above the composer. */}+ {modelOptions.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label="Model"+ disabled={composerDisabled || sendingChat}+ className="inline-flex max-w-44 items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"+ >+ <span className="truncate">+ {modelOptions.find((m) => m.value === model)?.label ??+ "Default"}+ </span>+ <ChevronDown className="size-3 shrink-0" aria-hidden />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" side="top">+ <DropdownMenuRadioGroup+ value={model}+ onValueChange={onPickModel}+ >+ <DropdownMenuRadioItem value="">+ Default+ </DropdownMenuRadioItem>+ {modelOptions.map((m) => (+ <DropdownMenuRadioItem key={m.value} value={m.value}>+ {m.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ )}{sendingChat ? (<Buttontype="button"diff --git a/notfair-cmo/src/server/adapters/claude-code-local/execute.ts b/notfair-cmo/src/server/adapters/claude-code-local/execute.tsindex 1277a194..22acda69 100644--- a/notfair-cmo/src/server/adapters/claude-code-local/execute.ts+++ b/notfair-cmo/src/server/adapters/claude-code-local/execute.ts@@ -38,6 +38,10 @@ export async function* executeClaudeCodeLocal("text","--verbose",];+ // Composer model override — whitelisted by the chat route.+ if (ctx.model) {+ args.push("--model", ctx.model);+ }if (identityMd.trim().length > 0) {args.push("--append-system-prompt", identityMd);}diff --git a/notfair-cmo/src/server/adapters/claude-code-local/index.ts b/notfair-cmo/src/server/adapters/claude-code-local/index.tsindex e9317cab..95fc322c 100644--- a/notfair-cmo/src/server/adapters/claude-code-local/index.ts+++ b/notfair-cmo/src/server/adapters/claude-code-local/index.ts@@ -9,6 +9,7 @@ import type {McpUnregistrationSpec,} from "../types";import { executeClaudeCodeLocal } from "./execute";+import { listClaudeCodeModels } from "./models";import { provisionClaudeCodeAgent } from "./provision";import { testClaudeCodeLocalEnvironment } from "./test";import { registerClaudeCodeMcp, unregisterClaudeCodeMcp } from "./mcp";@@ -24,6 +25,7 @@ function workspaceDirFor(agentId: string): string {export const claudeCodeLocalAdapter: HarnessAdapter = {id: "claude-code-local",testEnvironment: testClaudeCodeLocalEnvironment,+ listModels: listClaudeCodeModels,execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void> {return executeClaudeCodeLocal(ctx);},diff --git a/notfair-cmo/src/server/adapters/claude-code-local/models.ts b/notfair-cmo/src/server/adapters/claude-code-local/models.tsnew file mode 100644index 00000000..fd636555--- /dev/null+++ b/notfair-cmo/src/server/adapters/claude-code-local/models.ts@@ -0,0 +1,22 @@+import type { HarnessModelOption } from "../types";++/**+ * Model listing for Claude Code.+ *+ * Unlike codex there is no provider-fed cache to read: the claude CLI+ * exposes no "list models" command, and its account-scoped picker state+ * isn't persisted anywhere stable. What IS stable is the CLI's alias+ * surface — `claude --help` documents tier aliases that always resolve+ * to the newest model of each tier, so this list doesn't go stale on+ * point releases. Revisit if the CLI ever ships model enumeration.+ */+const ALIAS_TIERS: HarnessModelOption[] = [+ { value: "fable", label: "Fable" },+ { value: "opus", label: "Opus" },+ { value: "sonnet", label: "Sonnet" },+ { value: "haiku", label: "Haiku" },+];++export async function listClaudeCodeModels(): Promise<HarnessModelOption[]> {+ return ALIAS_TIERS;+}diff --git a/notfair-cmo/src/server/adapters/codex-local/execute.ts b/notfair-cmo/src/server/adapters/codex-local/execute.tsindex 8b45163c..636e740e 100644--- a/notfair-cmo/src/server/adapters/codex-local/execute.ts+++ b/notfair-cmo/src/server/adapters/codex-local/execute.ts@@ -40,6 +40,10 @@ export async function* executeCodexLocal("--skip-git-repo-check","--dangerously-bypass-approvals-and-sandbox",];+ // Composer model override — whitelisted by the chat route.+ if (ctx.model) {+ args.push("-m", ctx.model);+ }// Resume only when we have a real codex thread id from a prior turn.// notfair-cmo's session UUID is not a codex thread id — passing it woulddiff --git a/notfair-cmo/src/server/adapters/codex-local/index.ts b/notfair-cmo/src/server/adapters/codex-local/index.tsindex e61cec47..2ab67dc1 100644--- a/notfair-cmo/src/server/adapters/codex-local/index.ts+++ b/notfair-cmo/src/server/adapters/codex-local/index.ts@@ -7,6 +7,7 @@ import type {McpUnregistrationSpec,} from "../types";import { executeCodexLocal } from "./execute";+import { listCodexModels } from "./models";import { provisionCodexAgent } from "./provision";import { testCodexLocalEnvironment } from "./test";import { registerCodexMcp, unregisterCodexMcp } from "./mcp";@@ -14,6 +15,7 @@ import { registerCodexMcp, unregisterCodexMcp } from "./mcp";export const codexLocalAdapter: HarnessAdapter = {id: "codex-local",testEnvironment: testCodexLocalEnvironment,+ listModels: listCodexModels,execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void> {return executeCodexLocal(ctx);},diff --git a/notfair-cmo/src/server/adapters/codex-local/mcp.ts b/notfair-cmo/src/server/adapters/codex-local/mcp.tsindex 85e8960b..463442b3 100644--- a/notfair-cmo/src/server/adapters/codex-local/mcp.ts+++ b/notfair-cmo/src/server/adapters/codex-local/mcp.ts@@ -28,7 +28,7 @@ import type { McpRegistrationSpec } from "../types";* We rewrite the [mcp_servers.*] sections under our namespace prefix; we* never touch user-installed servers outside our prefix.*/-function codexConfigDir(): string {+export function codexConfigDir(): string {return process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");}diff --git a/notfair-cmo/src/server/adapters/codex-local/models.test.ts b/notfair-cmo/src/server/adapters/codex-local/models.test.tsnew file mode 100644index 00000000..7a7f466d--- /dev/null+++ b/notfair-cmo/src/server/adapters/codex-local/models.test.ts@@ -0,0 +1,58 @@+import { mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { listCodexModels } from "./models";++async function writeCache(content: unknown): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), "codex-models-"));+ const file = join(dir, "models_cache.json");+ await writeFile(+ file,+ typeof content === "string" ? content : JSON.stringify(content),+ );+ return file;+}++describe("listCodexModels", () => {+ it("maps visible models from the provider cache, sorted by priority", async () => {+ const file = await writeCache({+ models: [+ { slug: "gpt-5.4", display_name: "GPT-5.4", visibility: "list", priority: 16 },+ { slug: "gpt-5.5", display_name: "GPT-5.5", visibility: "list", priority: 7 },+ { slug: "codex-auto-review", display_name: "Codex Auto Review", visibility: "hide", priority: 43 },+ { slug: "gpt-5.4-mini", display_name: "GPT-5.4-Mini", visibility: "list", priority: 23 },+ ],+ });+ expect(await listCodexModels(file)).toEqual([+ { value: "gpt-5.5", label: "GPT-5.5" },+ { value: "gpt-5.4", label: "GPT-5.4" },+ { value: "gpt-5.4-mini", label: "GPT-5.4-Mini" },+ ]);+ });++ it("falls back to slug when display_name is missing", async () => {+ const file = await writeCache({+ models: [{ slug: "gpt-9", visibility: "list", priority: 1 }],+ });+ expect(await listCodexModels(file)).toEqual([+ { value: "gpt-9", label: "gpt-9" },+ ]);+ });++ it("returns the static fallback when the cache file is missing", async () => {+ const models = await listCodexModels("/nonexistent/models_cache.json");+ expect(models.length).toBeGreaterThan(0);+ expect(models[0]!.value).toBe("gpt-5.5");+ });++ it("returns the static fallback on malformed JSON or an empty list", async () => {+ expect(await listCodexModels(await writeCache("not-json{{{"))).toEqual(+ await listCodexModels("/nonexistent"),+ );+ expect(await listCodexModels(await writeCache({ models: [] }))).toEqual(+ await listCodexModels("/nonexistent"),+ );+ });+});diff --git a/notfair-cmo/src/server/adapters/codex-local/models.ts b/notfair-cmo/src/server/adapters/codex-local/models.tsnew file mode 100644index 00000000..6118b4b0--- /dev/null+++ b/notfair-cmo/src/server/adapters/codex-local/models.ts@@ -0,0 +1,63 @@+import { readFile } from "node:fs/promises";+import { join } from "node:path";++import type { HarnessModelOption } from "../types";+import { codexConfigDir } from "./mcp";++/**+ * Model discovery for Codex — read the PROVIDER's list, don't hardcode.+ *+ * The codex CLI has no "list models" command, but its TUI fetches the+ * account-scoped model list from OpenAI and caches it at+ * `~/.codex/models_cache.json` (slug, display_name, visibility,+ * priority, …). We read that cache: it's the same source the user's own+ * `/model` picker shows, refreshed whenever they run codex.+ *+ * Entries with `visibility: "hide"` are internal (e.g. codex-auto-review)+ * and excluded. Sorted by the cache's own `priority` (ascending — that's+ * the order the TUI shows).+ *+ * Fallback: when the cache is missing/unreadable (fresh install that has+ * never run the TUI), return a minimal static list so the selector still+ * works. Never throws.+ */++type CachedModel = {+ slug?: unknown;+ display_name?: unknown;+ visibility?: unknown;+ priority?: unknown;+};++const FALLBACK: HarnessModelOption[] = [+ { value: "gpt-5.5", label: "GPT-5.5" },+ { value: "gpt-5.4", label: "GPT-5.4" },+];++export async function listCodexModels(+ cacheFile: string = join(codexConfigDir(), "models_cache.json"),+): Promise<HarnessModelOption[]> {+ try {+ const raw = await readFile(cacheFile, "utf8");+ const parsed = JSON.parse(raw) as { models?: CachedModel[] };+ const models = (parsed.models ?? [])+ .filter(+ (m): m is CachedModel & { slug: string } =>+ typeof m.slug === "string" &&+ m.slug.length > 0 &&+ m.visibility !== "hide",+ )+ .sort(+ (a, b) =>+ (typeof a.priority === "number" ? a.priority : Number.MAX_SAFE_INTEGER) -+ (typeof b.priority === "number" ? b.priority : Number.MAX_SAFE_INTEGER),+ )+ .map<HarnessModelOption>((m) => ({+ value: m.slug,+ label: typeof m.display_name === "string" && m.display_name ? m.display_name : m.slug,+ }));+ return models.length > 0 ? models : FALLBACK;+ } catch {+ return FALLBACK;+ }+}diff --git a/notfair-cmo/src/server/adapters/types.ts b/notfair-cmo/src/server/adapters/types.tsindex df22e055..6210a1c7 100644--- a/notfair-cmo/src/server/adapters/types.ts+++ b/notfair-cmo/src/server/adapters/types.ts@@ -84,6 +84,14 @@ export interface HarnessExecuteContext {* `--resume`, codex `exec resume`). Null on the first turn of a thread.*/harnessSessionId?: string | null;+ /**+ * Per-turn model override from the composer's model selector. When set,+ * adapters pass it to their CLI's model flag (`claude --model`,+ * `codex exec -m`). Absent/null = the CLI's own default. Values are+ * whitelisted against HARNESS_MODEL_OPTIONS by the chat route before+ * they reach the adapter.+ */+ model?: string | null;/** Optional cancellation. When aborted the adapter kills its subprocess. */signal?: AbortSignal;}@@ -118,11 +126,27 @@ export type HarnessEvent =*/| { kind: "session"; harnessSessionId: string };+/** One selectable model for the composer's model dropdown. */+export interface HarnessModelOption {+ /** Identifier passed verbatim to the CLI's model flag. */+ value: string;+ /** Human label for the dropdown. */+ label: string;+}+export interface HarnessAdapter {readonly id: HarnessAdapterId;testEnvironment(): Promise<HarnessEnvironmentHealth>;+ /**+ * Models the user can pick for a turn. Sourced from the provider where+ * the harness exposes one (codex caches its account-scoped list in+ * ~/.codex/models_cache.json); falls back to a small static list when+ * discovery fails. Never throws.+ */+ listModels(): Promise<HarnessModelOption[]>;+execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void>;provisionAgent(spec: AgentProvisionSpec): Promise<void>;