Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(ai): add dynamic free provider discovery

Rahmanea708512dc98
diff --git a/app/api/models/providers/route.ts b/app/api/models/providers/route.ts
new file mode 100644
index 00000000..d4b9e273
--- /dev/null
+++ b/app/api/models/providers/route.ts
@@ -0,0 +1,20 @@
+import { NextRequest, NextResponse } from "next/server";
+import { requireSession } from "@/lib/auth/require-session";
+import { listProviderSummaries, providerSummariesFromCatalog } from "@/lib/models/discovery.js";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export async function GET(req: NextRequest) {
+ if (!(await requireSession("owner"))) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+ const freeOnly = req.nextUrl.searchParams.get("free") === "1";
+ try {
+ return NextResponse.json({ providers: await listProviderSummaries({ freeOnly }) });
+ } catch {
+ // Keep every endpoint-pinned provider connectable even on a cold offline box,
+ // but advertise no free models without catalog pricing evidence.
+ return NextResponse.json({ providers: providerSummariesFromCatalog({}, { freeOnly }) });
+ }
+}
diff --git a/app/api/models/route.test.ts b/app/api/models/route.test.ts
new file mode 100644
index 00000000..b88b1fbe
--- /dev/null
+++ b/app/api/models/route.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const listModels = vi.fn();
+const readOAuthBundle = vi.fn();
+const writeOAuthBundle = vi.fn();
+const codexModels = vi.fn();
+const ensureFreshCodex = vi.fn();
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: vi.fn(async () => true) }));
+vi.mock("@/lib/models", () => ({ listModels: (...args: unknown[]) => listModels(...args) }));
+vi.mock("@/lib/config/store", () => ({
+ readOAuthBundle: (...args: unknown[]) => readOAuthBundle(...args),
+ writeOAuthBundle: (...args: unknown[]) => writeOAuthBundle(...args),
+}));
+vi.mock("@/lib/ai/oauth/codex", () => ({
+ codexModels: (...args: unknown[]) => codexModels(...args),
+ ensureFreshCodex: (...args: unknown[]) => ensureFreshCodex(...args),
+}));
+
+describe("/api/models dynamic pricing and provider mapping", () => {
+ beforeEach(() => {
+ listModels.mockReset().mockResolvedValue([
+ {
+ ref: "zhipuai/glm-free",
+ provider: "zhipuai",
+ name: "GLM Free",
+ cost: { input: 0, output: 0 },
+ limit: { context: 128000 },
+ tool_call: true,
+ reasoning: true,
+ },
+ {
+ ref: "zhipuai/glm-paid",
+ provider: "zhipuai",
+ name: "GLM Paid",
+ cost: { input: 1, output: 2 },
+ tool_call: true,
+ },
+ {
+ ref: "zhipuai/glm-unknown",
+ provider: "zhipuai",
+ name: "GLM Unknown",
+ tool_call: true,
+ },
+ ]);
+ readOAuthBundle.mockReset().mockResolvedValue(null);
+ writeOAuthBundle.mockReset();
+ codexModels.mockReset();
+ ensureFreshCodex.mockReset();
+ });
+
+ it("maps a runtime provider through catalogId and preserves the runtime slug in results", async () => {
+ const { GET } = await import("./route");
+ const res = await GET(new NextRequest("http://localhost/api/models?provider=glm"));
+ const body = await res.json();
+ expect(body.models).toHaveLength(3);
+ expect(body.models[0]).toMatchObject({
+ provider: "glm",
+ ref: "glm/glm-free",
+ id: "glm-free",
+ free: true,
+ agentReady: true,
+ });
+ expect(body.models.find((m: { id: string }) => m.id === "glm-unknown")).toMatchObject({ free: false });
+ });
+
+ it("free=1 returns only explicit zero-input and zero-output models", async () => {
+ const { GET } = await import("./route");
+ const res = await GET(new NextRequest("http://localhost/api/models?provider=glm&free=1"));
+ const body = await res.json();
+ expect(body.models.map((m: { id: string }) => m.id)).toEqual(["glm-free"]);
+ });
+});
diff --git a/app/api/models/route.ts b/app/api/models/route.ts
index 15f3dde3..c51c3fb8 100644
--- a/app/api/models/route.ts
+++ b/app/api/models/route.ts
@@ -1,29 +1,25 @@
import { NextRequest, NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
import { listModels } from "@/lib/models";
+import { isFreeModel, providerCatalogId } from "@/lib/models/discovery.js";
import { readOAuthBundle, writeOAuthBundle } from "@/lib/config/store";
import { codexModels, ensureFreshCodex } from "@/lib/ai/oauth/codex";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-// Model catalog for the Settings → AI picker + the Browse dialog, sourced from the
-// models.dev cache (offline-tolerant: stale cache or empty on a cold offline box).
-// Session-gated. ?provider=<slug> filters to one provider to keep the payload small.
-// Each row carries capability/pricing meta (context, cost, tools, reasoning); the
-// model field stays free-text so an id not in the catalog still works.
+// Model catalog for Settings → AI + CLI pickers, sourced from the models.dev cache.
+// ?provider=<runtime-slug> applies the registry's catalogId mapping.
+// ?free=1 keeps only models with explicit zero input AND output cost.
export async function GET(req: NextRequest) {
if (!(await requireSession("owner"))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const provider = req.nextUrl.searchParams.get("provider");
+ const freeOnly = req.nextUrl.searchParams.get("free") === "1";
- // An OAuth provider's models come from the ACCOUNT, not from models.dev. Its slug
- // ("openai-codex") is local to mso and models.dev has never heard of it, so the
- // filter below matched nothing and the picker came up empty the moment ChatGPT auth
- // was connected — the account's own list had been fetched during OAuth and thrown
- // away. Nothing from the bundle but model IDs is ever returned: the access token
- // stays in the 0600 host file and only ever leaves as an Authorization header.
+ // OAuth account models are account-scoped rather than models.dev-scoped. Their
+ // pricing is unknown here, so they are never advertised as free.
if (provider === "openai-codex") {
const bundle = await readOAuthBundle(provider);
if (!bundle) return NextResponse.json({ models: [] });
@@ -32,32 +28,47 @@ export async function GET(req: NextRequest) {
fresh = await ensureFreshCodex(bundle);
if (fresh !== bundle) await writeOAuthBundle(provider, fresh);
} catch {
- // Refresh failed (revoked/offline) — fall through and let the call below fail
- // to an empty list rather than 500 the settings page.
+ // Revoked/offline refresh degrades to an empty catalog rather than breaking Settings.
}
+ if (freeOnly) return NextResponse.json({ models: [] });
const ids = await codexModels(fresh);
return NextResponse.json({
- models: ids.map((id) => ({ ref: `${provider}/${id}`, provider, id, name: id })),
+ models: ids.map((id) => ({
+ ref: `${provider}/${id}`,
+ provider,
+ id,
+ name: id,
+ free: false,
+ agentReady: true,
+ })),
});
}
try {
const all = await listModels();
- const models = (provider ? all.filter((m) => m.provider === provider) : all).map((m) => ({
- ref: m.ref,
- provider: m.provider,
- // model id = ref minus the "provider/" prefix (ids may contain "/").
- id: m.ref.slice(m.provider.length + 1),
- name: m.name,
- context: m.limit?.context,
- inputCost: m.cost?.input,
- outputCost: m.cost?.output,
- tools: !!m.tool_call,
- reasoning: !!m.reasoning,
- vision: Array.isArray(m.modalities?.input) ? m.modalities.input.includes("image") : false,
- }));
+ const catalogId = provider ? providerCatalogId(provider) : null;
+ const models = all
+ .filter((m) => (!provider || m.provider === catalogId) && (!freeOnly || isFreeModel(m)))
+ .map((m) => {
+ const id = m.ref.slice(m.provider.length + 1);
+ const runtimeProvider = provider || m.provider;
+ return {
+ ref: `${runtimeProvider}/${id}`,
+ provider: runtimeProvider,
+ id,
+ name: m.name,
+ context: m.limit?.context,
+ inputCost: m.cost?.input,
+ outputCost: m.cost?.output,
+ tools: !!m.tool_call,
+ free: isFreeModel(m),
+ agentReady: !!m.tool_call,
+ reasoning: !!m.reasoning,
+ vision: Array.isArray(m.modalities?.input) ? m.modalities.input.includes("image") : false,
+ };
+ });
return NextResponse.json({ models });
} catch {
- return NextResponse.json({ models: [] }); // offline + no cache → the UI just loses suggestions
+ return NextResponse.json({ models: [] });
}
}
diff --git a/app/install/page.test.ts b/app/install/page.test.ts
index 0de58273..5e28fa68 100644
--- a/app/install/page.test.ts
+++ b/app/install/page.test.ts
@@ -8,8 +8,10 @@ describe("public install guide", () => {
it("documents the terminal onboarding that the one-line installer actually runs", () => {
expect(source).toContain("Complete terminal onboarding");
expect(source).toContain("mso onboard");
- expect(source).toContain("OpenAI ChatGPT OAuth");
+ expect(source).toContain("OpenAI ChatGPT uses its separate device OAuth path");
+ expect(source).toContain("OpenCode Zen");
expect(source).toContain("OpenRouter");
+ expect(source).toContain("marked FREE");
});
it("documents an immediately resolvable CLI and the curated skill market", () => {
diff --git a/app/install/page.tsx b/app/install/page.tsx
index e2026062..b89aecf7 100644
--- a/app/install/page.tsx
+++ b/app/install/page.tsx
@@ -33,7 +33,7 @@ const STEPS = [
{
n: 2,
title: "Complete terminal onboarding",
- body: "On a fresh interactive install, the same command opens /dev/tty after the service is healthy. Choose an Alfa provider (OpenAI ChatGPT OAuth or supported API-key providers including OpenRouter), a response preset, optional Hermes/OpenClaw installs, and reviewed skills. If no terminal exists, nothing hangs: run `mso onboard` later.",
+ body: "On a fresh interactive install, the same command opens /dev/tty after the service is healthy. Connect an Alfa AI platform from MSO's live supported-provider catalog, where explicitly zero-cost agent-capable models are marked FREE; OpenCode Zen and OpenRouter are supported API-key platforms, while OpenAI ChatGPT uses its separate device OAuth path. Then choose a model, response preset, optional Hermes/OpenClaw installs, and reviewed skills. If no terminal exists, nothing hangs: run `mso onboard` later.",
code: "mso onboard\nmso skills available\nmso skills install ponytail caveman rtk -y",
note: "`-y` is available for a safe non-interactive install, but it does not silently connect accounts, install managed apps, or trust community skills you did not select.",
},
diff --git a/bin/mso-update-offline.test.ts b/bin/mso-update-offline.test.ts
index 00c1d785..01f8116e 100644
--- a/bin/mso-update-offline.test.ts
+++ b/bin/mso-update-offline.test.ts
@@ -31,6 +31,7 @@ function fixture() {
"bin/mso",
"scripts/mso-update",
"scripts/mso-cli-agent.sh",
+ "scripts/cli/ai-provider-catalog.sh",
"scripts/cli/runtime.sh",
"scripts/cli/service.sh",
"scripts/cli/transport.sh",
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d0c92cc5..bcc83bc9 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `ai` add dynamic free provider discovery
- `workflows` maximize script and search automation
## 2026-09-15
diff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.md
index e746b388..4cb24825 100644
--- a/docs/INFRASTRUCTURE-PROVIDERS.md
+++ b/docs/INFRASTRUCTURE-PROVIDERS.md
@@ -20,6 +20,8 @@ mso agent # explicit alias
mso --continue # resume latest durable Agent session
mso --resume <query> # resume by @name/index/id/short-id/title
mso models # configure AI provider/API/OAuth connections
+mso models free # live providers with explicit zero-cost, agent-ready models
+mso models free opencode # inspect OpenCode Zen models currently marked zero-cost
mso models add openai-codex # connect ChatGPT subscription OAuth without switching model
mso model # choose active model from connected providers
mso model list # list models selectable from the active provider
@@ -39,8 +41,7 @@ When no AI provider is connected, bare `mso` opens the provider manager first an
picker. If credentials already exist but the selection is unusable, only the model picker runs.
Both interactive surfaces use the same native picker: **↑/↓** navigate, typing filters, **Enter**
selects, and **Esc** cancels. Provider/model selection never falls back to a numbered prompt.
-The connection choices are OpenAI ChatGPT/Codex device OAuth plus the built-in API-key providers documented in
-[`INSTALL.md`](./INSTALL.md).
+The API-key provider choices are discovered dynamically from MSO's endpoint-pinned provider registry and model catalog; free-capable providers are annotated from explicit zero-cost pricing. OpenAI ChatGPT/Codex remains a separate device-OAuth choice. See [`INSTALL.md`](./INSTALL.md).
Infrastructure secrets belong only in `mso provider set ...` hidden prompts/private provider state;
do not commit them or paste real values into model prompts. Environment-shaped examples are placeholders
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 1042274c..cdef4527 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -125,16 +125,19 @@ production runtime itself, still bound to loopback, before proving the authentic
runtime is reported as a runtime problem — it is not misreported as a device-approval failure. API keys are read with terminal echo
disabled and posted from stdin; they are not placed in the CLI/curl argv.
-The current provider choices are OpenAI ChatGPT/Codex device OAuth, plus API-key providers
-Anthropic, OpenAI Platform, OpenRouter, Google, Groq, xAI, DeepSeek and Mistral. OpenRouter
-is an API-key integration here, not OAuth. The OpenAI OAuth path is the ChatGPT consumer
-Codex backend; it is separate from OpenAI Platform API keys and separate again from MSO's
-ChatGPT MCP OAuth.
-
-After onboarding, use the two AI commands deliberately: `mso models` manages provider/API/OAuth
-connections without changing the active model; `mso model` selects a model from providers that are
-already connected. `mso models test` validates the currently selected connection (including the
-ChatGPT/Codex subscription path), while `mso model list [provider]` shows selectable model IDs.
+The provider picker is loaded dynamically from MSO's pinned provider registry plus the cached
+`models.dev` catalog instead of a fixed eight-provider menu. Providers with at least one model whose
+catalog price explicitly reports both input and output cost as zero **and** supports tool calls are shown
+as free-capable. Unknown/missing pricing is never treated as free. OpenCode Zen is a pinned
+OpenAI-compatible API-key provider (`https://opencode.ai/zen/v1`); OpenRouter remains an API-key
+integration. OpenAI ChatGPT/Codex keeps its separate device OAuth path. A FREE label describes model
+token pricing only: provider account/key requirements and rate limits can still apply.
+
+After onboarding, use the AI commands deliberately: `mso models` manages provider/API/OAuth
+connections without changing the active model; `mso models free [provider]` reads the live zero-cost
+catalog; `mso model` selects a model from providers that are already connected. `mso models test`
+validates the currently selected connection (including the ChatGPT/Codex subscription path), while
+`mso model list [provider]` shows selectable model IDs.
Interactive `mso model` / `mso models` menus are arrow-key pickers: **↑/↓** moves, typing filters,
**Enter** selects, and **Esc** cancels; numeric provider/model prompts are not part of the UX.
Agent sessions are durable: `mso --continue` resumes the latest session and
diff --git a/docs/MODELS-INTEGRATION.md b/docs/MODELS-INTEGRATION.md
index 9537b2ce..f0ca85fd 100644
--- a/docs/MODELS-INTEGRATION.md
+++ b/docs/MODELS-INTEGRATION.md
@@ -11,10 +11,14 @@ Alfa's server-side selection and credentials live in private host state (normall
`~/.mso/config.json`, mode `0600`). Built-in environment variables remain fallback inputs.
Credentials are not compiled into the client bundle.
-The current provider picker covers the common built-ins (Anthropic, OpenAI, OpenRouter,
-Google, Groq, xAI, DeepSeek and Mistral) and can use the vendored model registry for a
-broader catalog. Custom providers can define a base URL and OpenAI- or
-Anthropic-compatible protocol; custom URLs are SSRF-checked before use.
+The provider picker is dynamic over MSO's supported, endpoint-pinned provider registry and the
+cached `models.dev` capability/pricing catalog. The same provider summaries drive terminal onboarding,
+`mso models`, and Settings → AI. A model is marked **FREE** only when numeric `cost.input` and
+`cost.output` are both explicitly `0`; missing pricing is not free. For Alfa onboarding, the provider's
+free-capable count is further restricted to tool-call-capable models. OpenCode Zen is a built-in pinned
+OpenAI-compatible provider at `https://opencode.ai/zen/v1`; its model list is not hardcoded. Custom
+providers can still define a base URL and OpenAI- or Anthropic-compatible protocol; custom URLs are
+SSRF-checked before use.
## 2. Streaming architecture
diff --git a/frontend/slices/os-settings/components/ai-provider-options.test.ts b/frontend/slices/os-settings/components/ai-provider-options.test.ts
new file mode 100644
index 00000000..cafe0bf8
--- /dev/null
+++ b/frontend/slices/os-settings/components/ai-provider-options.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import { groupProviderOptions, suggestedProviderModel, type ProviderSummary } from "./ai-provider-options";
+
+const rows: ProviderSummary[] = [
+ { id: "paid", name: "Paid", catalogId: "paid", modelCount: 3, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "free", name: "Free", catalogId: "free", modelCount: 5, freeModelCount: 2, freeAgentModelCount: 1, recommendedFreeModel: "agent-free" },
+];
+
+describe("AI provider options", () => {
+ it("separates providers with agent-ready free models from other providers", () => {
+ const grouped = groupProviderOptions(rows);
+ expect(grouped.free.map((row) => row.id)).toEqual(["free"]);
+ expect(grouped.other.map((row) => row.id)).toEqual(["paid"]);
+ });
+
+ it("prefers the live recommended free model and otherwise preserves the caller fallback", () => {
+ expect(suggestedProviderModel(rows, "free", "fallback")).toBe("agent-free");
+ expect(suggestedProviderModel(rows, "paid", "fallback")).toBe("fallback");
+ });
+});
diff --git a/frontend/slices/os-settings/components/ai-provider-options.ts b/frontend/slices/os-settings/components/ai-provider-options.ts
new file mode 100644
index 00000000..3624348f
--- /dev/null
+++ b/frontend/slices/os-settings/components/ai-provider-options.ts
@@ -0,0 +1,33 @@
+export type ProviderSummary = {
+ id: string;
+ name: string;
+ catalogId: string;
+ modelCount: number;
+ freeModelCount: number;
+ freeAgentModelCount: number;
+ recommendedFreeModel: string | null;
+};
+
+// Offline fallback only. The live /api/models/providers catalog is the primary source.
+export const FALLBACK_PROVIDER_OPTIONS: ProviderSummary[] = [
+ { id: "opencode", name: "OpenCode Zen", catalogId: "opencode", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "anthropic", name: "Anthropic", catalogId: "anthropic", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "openai", name: "OpenAI Platform", catalogId: "openai", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "openrouter", name: "OpenRouter", catalogId: "openrouter", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "google", name: "Google Gemini", catalogId: "google", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "groq", name: "Groq", catalogId: "groq", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "xai", name: "xAI", catalogId: "xai", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "deepseek", name: "DeepSeek", catalogId: "deepseek", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+ { id: "mistral", name: "Mistral", catalogId: "mistral", modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0, recommendedFreeModel: null },
+];
+
+export function groupProviderOptions(rows: ProviderSummary[]) {
+ return {
+ free: rows.filter((row) => row.freeAgentModelCount > 0),
+ other: rows.filter((row) => row.freeAgentModelCount === 0),
+ };
+}
+
+export function suggestedProviderModel(rows: ProviderSummary[], provider: string, fallback = ""): string {
+ return rows.find((row) => row.id === provider)?.recommendedFreeModel || fallback;
+}
diff --git a/frontend/slices/os-settings/components/ai-provider-select.tsx b/frontend/slices/os-settings/components/ai-provider-select.tsx
new file mode 100644
index 00000000..3bf4a152
--- /dev/null
+++ b/frontend/slices/os-settings/components/ai-provider-select.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import {
+ Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue,
+} from "@/components/ui/select";
+import { groupProviderOptions, type ProviderSummary } from "./ai-provider-options";
+import { type ConnectedProvider } from "./provider-list";
+
+export function AiProviderSelect({
+ value,
+ options,
+ connectedExtras,
+ onChange,
+}: {
+ value: string;
+ options: ProviderSummary[];
+ connectedExtras: ConnectedProvider[];
+ onChange: (value: string) => void;
+}) {
+ const groups = groupProviderOptions(options);
+ const selected = options.find((row) => row.id === value);
+ return (
+ <div className="space-y-1.5">
+ <Select value={value} onValueChange={onChange}>
+ <SelectTrigger className="sm:w-64"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {groups.free.length > 0 && (
+ <SelectGroup>
+ <SelectLabel>Free AI available</SelectLabel>
+ {groups.free.map((row) => (
+ <SelectItem key={row.id} value={row.id}>
+ {row.name} · {row.freeAgentModelCount} free agent-ready
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ )}
+ {groups.other.length > 0 && (
+ <SelectGroup>
+ <SelectLabel>Other providers</SelectLabel>
+ {groups.other.map((row) => <SelectItem key={row.id} value={row.id}>{row.name}</SelectItem>)}
+ </SelectGroup>
+ )}
+ {connectedExtras.length > 0 && (
+ <SelectGroup>
+ <SelectLabel>Connected</SelectLabel>
+ {connectedExtras.map((row) => (
+ <SelectItem key={row.id} value={row.id}>
+ {row.id}{row.kind === "oauth" ? " (OAuth)" : row.kind === "custom" ? " (Custom)" : ""}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ )}
+ </SelectContent>
+ </Select>
+ {selected && selected.freeAgentModelCount > 0 && (
+ <p className="text-xs text-muted-foreground">
+ {selected.freeAgentModelCount} agent-ready free model{selected.freeAgentModelCount === 1 ? "" : "s"} currently reported.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/slices/os-settings/components/ai-section.tsx b/frontend/slices/os-settings/components/ai-section.tsx
index 05a21da8..e556b1d1 100644
--- a/frontend/slices/os-settings/components/ai-section.tsx
+++ b/frontend/slices/os-settings/components/ai-section.tsx
@@ -4,39 +4,35 @@ import { useCallback, useEffect, useState } from "react";
import { Sparkles, Check } from "lucide-react";
import { toast } from "@/features/appshell";
import { Input } from "@/components/ui/input";
-import {
- Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue,
-} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { SettingsSection, SettingsRow, SettingsBlock } from "@/features/shell-settings";
import { DEFAULT_MODELS } from "@/lib/models/defaults";
import { type ConnectedProvider } from "./provider-list";
import { ProviderManage } from "./provider-manage";
import { ModelCatalog } from "./model-catalog";
+import { AiProviderSelect } from "./ai-provider-select";
+import {
+ FALLBACK_PROVIDER_OPTIONS,
+ suggestedProviderModel,
+ type ProviderSummary,
+} from "./ai-provider-options";
type Cfg = { hasApiKey: boolean; apiKeyMasked: string; model: string; provider?: string; providers?: ConnectedProvider[] };
-type CatModel = { ref: string; provider: string; id: string };
+type CatModel = { ref: string; provider: string; id: string; free?: boolean; agentReady?: boolean };
-// Curated built-in BYOK providers (the @rahmanef/models registry wires ~35; these
-// are the common ones with nice labels/hints). Any other endpoint → "Add custom
-// provider" below. Non-Anthropic providers stream through the openai-protocol adapter.
-const BUILTINS: { slug: string; label: string; keyHint: string }[] = [
- { slug: "anthropic", label: "Anthropic (Claude)", keyHint: "sk-ant-…" },
- { slug: "openai", label: "OpenAI (GPT)", keyHint: "sk-…" },
- { slug: "openrouter", label: "OpenRouter", keyHint: "sk-or-…" },
- { slug: "google", label: "Google (Gemini)", keyHint: "AIza…" },
- { slug: "groq", label: "Groq", keyHint: "gsk_…" },
- { slug: "xai", label: "xAI (Grok)", keyHint: "xai-…" },
- { slug: "deepseek", label: "DeepSeek", keyHint: "sk-…" },
- { slug: "mistral", label: "Mistral", keyHint: "…" },
-];
+// Presentation hints only. Provider availability itself comes from /api/models/providers.
+const KEY_HINTS: Record<string, string> = {
+ anthropic: "sk-ant-…",
+ openai: "sk-…",
+ openrouter: "sk-or-…",
+ google: "AIza…",
+ groq: "gsk_…",
+ xai: "xai-…",
+};
-// Sensible default model per built-in so switching provider never leaves a stale
-// cross-provider model id (e.g. anthropic's default paired with openai).
-// BYOK config for the Alfa assistant. Raw keys are write-only from here — GET
-// /api/config returns only masked previews. Empty key on save keeps the stored one.
export function AiSection() {
const [cfg, setCfg] = useState<Cfg | null>(null);
+ const [providerOptions, setProviderOptions] = useState<ProviderSummary[]>(FALLBACK_PROVIDER_OPTIONS);
const [provider, setProvider] = useState("anthropic");
const [key, setKey] = useState("");
const [model, setModel] = useState("");
@@ -59,6 +55,7 @@ export function AiSection() {
setProvider(c.provider || "anthropic");
setModel(c.model || DEFAULT_MODELS[c.provider || "anthropic"] || "");
}, []);
+
const load = useCallback(async () => {
const c = await fetchCfg();
if (c) applyCfg(c);
@@ -67,23 +64,33 @@ export function AiSection() {
useEffect(() => {
let alive = true;
fetchCfg().then((c) => alive && c && applyCfg(c));
+ fetch("/api/models/providers", { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : { providers: [] }))
+ .then((body) => {
+ if (!alive) return;
+ const rows = (body.providers ?? []) as ProviderSummary[];
+ if (rows.length) setProviderOptions(rows);
+ })
+ .catch(() => undefined);
return () => {
alive = false;
};
}, [fetchCfg, applyCfg]);
- // Model suggestions for the picked provider (models.dev catalog); free-text field
- // so it always works offline.
+ // Model suggestions use the same endpoint as CLI. Explicit-free, agent-ready
+ // rows are presentation-sorted first; this does not change the saved provider/model.
useEffect(() => {
let alive = true;
fetch(`/api/models?provider=${encodeURIComponent(provider)}`, { cache: "no-store" })
.then((r) => (r.ok ? r.json() : { models: [] }))
.then((d) => {
if (!alive) return;
- const rows = (d.models ?? []) as CatModel[];
+ const rows = ((d.models ?? []) as CatModel[]).sort((a, b) =>
+ Number(!!b.free && !!b.agentReady) - Number(!!a.free && !!a.agentReady)
+ || Number(!!b.free) - Number(!!a.free)
+ || a.id.localeCompare(b.id),
+ );
setCatalog(rows);
- // Providers with no static default (OAuth ones, whose ids are account-scoped)
- // would otherwise leave the field blank. Take the account's first real model.
setModel((current) => current || rows[0]?.id || "");
})
.catch(() => alive && setCatalog([]));
@@ -92,13 +99,15 @@ export function AiSection() {
};
}, [provider]);
- const extraProviders = (cfg?.providers ?? []).filter((p) => p.kind === "custom" || p.kind === "oauth");
+ const liveIds = new Set(providerOptions.map((row) => row.id));
+ const extraProviders = (cfg?.providers ?? []).filter((p) => !liveIds.has(p.id));
const selectedMeta = (cfg?.providers ?? []).find((p) => p.id === provider);
+ const selectedProvider = providerOptions.find((p) => p.id === provider);
const isCustom = selectedMeta?.kind === "custom";
const isOAuth = selectedMeta?.kind === "oauth";
- const prov = BUILTINS.find((p) => p.slug === provider);
const onSavedProvider = provider === cfg?.provider;
const customModels = selectedMeta?.models ?? [];
+ const providerLabel = selectedProvider?.name || provider;
async function onSave() {
setBusy(true);
@@ -147,57 +156,37 @@ export function AiSection() {
title="AI (Alfa)"
footnote={
<>
- Bring your own key (stored server-side, never shown again). Built-ins use a pasted key — there
- is no “sign in with OpenAI” for the platform API. Add any OpenAI-compatible or Anthropic-Messages
- endpoint below. If the key is empty, the matching server env var (e.g. <code>ANTHROPIC_API_KEY</code>) is used.
+ Provider/model availability is discovered dynamically while runtime endpoints remain pinned by MSO. Keys are stored server-side and never shown again.
+ Free means the live model catalog explicitly reports $0 input and $0 output token cost; an account/API key and provider rate limits may still apply.
</>
}
>
<SettingsRow label="Provider">
- <Select
+ <AiProviderSelect
value={provider}
- onValueChange={(v) => {
+ options={providerOptions}
+ connectedExtras={extraProviders}
+ onChange={(v) => {
setProvider(v);
- // OAuth providers have no static default worth having — their model ids
- // are account-scoped. The catalog effect below refills `model` from the
- // account's own first entry; clearing here avoids briefly showing a
- // literal the backend would reject.
- setModel(DEFAULT_MODELS[v] ?? "");
- setTest(null); // drop any stale connection-test result for the old provider
+ const connected = (cfg?.providers ?? []).find((entry) => entry.id === v);
+ const fallback = DEFAULT_MODELS[v] || connected?.models?.[0] || "";
+ setModel(suggestedProviderModel(providerOptions, v, fallback));
+ setTest(null);
}}
- >
- <SelectTrigger className="sm:w-56">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {BUILTINS.map((p) => (
- <SelectItem key={p.slug} value={p.slug}>{p.label}</SelectItem>
- ))}
- {extraProviders.length > 0 && (
- <SelectGroup>
- <SelectLabel>Connected</SelectLabel>
- {extraProviders.map((p) => (
- <SelectItem key={p.id} value={p.id}>
- {p.id}{p.kind === "oauth" ? " (OAuth)" : ""}
- </SelectItem>
- ))}
- </SelectGroup>
- )}
- </SelectContent>
- </Select>
+ />
</SettingsRow>
{isOAuth ? (
<SettingsRow label="Auth">
<span className="text-sm text-muted-foreground">Signed in via OAuth — no key needed</span>
</SettingsRow>
) : (
- <SettingsRow label={`${isCustom ? provider : prov?.label ?? "Provider"} key`}>
+ <SettingsRow label={`${isCustom ? provider : providerLabel} key`}>
<Input
type="password"
value={key}
onChange={(e) => setKey(e.target.value)}
- placeholder={onSavedProvider && cfg?.hasApiKey ? cfg.apiKeyMasked : (prov?.keyHint ?? "API key")}
- className="sm:w-56"
+ placeholder={onSavedProvider && cfg?.hasApiKey ? cfg.apiKeyMasked : (KEY_HINTS[provider] ?? "API key")}
+ className="sm:w-64"
/>
</SettingsRow>
)}
@@ -207,8 +196,8 @@ export function AiSection() {
list="ai-model-suggestions"
value={model}
onChange={(e) => setModel(e.target.value)}
- placeholder={(onSavedProvider && cfg?.model) || DEFAULT_MODELS[provider] || "model id"}
- className="sm:w-56"
+ placeholder={(onSavedProvider && cfg?.model) || DEFAULT_MODELS[provider] || selectedProvider?.recommendedFreeModel || "model id"}
+ className="sm:w-64"
/>
<ModelCatalog provider={provider} value={model} onPick={setModel} />
</div>
diff --git a/frontend/slices/os-settings/components/model-catalog-utils.test.ts b/frontend/slices/os-settings/components/model-catalog-utils.test.ts
index 9c428095..1e32db75 100644
--- a/frontend/slices/os-settings/components/model-catalog-utils.test.ts
+++ b/frontend/slices/os-settings/components/model-catalog-utils.test.ts
@@ -2,20 +2,28 @@ import { describe, expect, it } from "vitest";
import { filterAndSortModels, type CatModel } from "./model-catalog-utils";
const models: CatModel[] = [
+ { ref: "free", id: "free-agent", context: 256000, inputCost: 0, outputCost: 0, free: true, agentReady: true, tools: true },
{ ref: "a", id: "cheap-tools", context: 128000, inputCost: 0.1, outputCost: 0.2, tools: true },
{ ref: "b", id: "expensive-vision", context: 1000000, inputCost: 10, outputCost: 30, vision: true },
{ ref: "c", id: "reasoner", context: 64000, inputCost: 1, outputCost: 1, reasoning: true },
+ { ref: "unknown", id: "unknown-price", context: 128000, tools: true, free: false },
];
+const none = { free: false, tools: false, reasoning: false, vision: false, minContext: 0 };
+
describe("model catalog filters", () => {
it("filters by capabilities and context", () => {
- const got = filterAndSortModels(models, "", { tools: true, reasoning: false, vision: false, minContext: 128000 }, "best");
- expect(got.map((m) => m.id)).toEqual(["cheap-tools"]);
+ const got = filterAndSortModels(models, "", { ...none, tools: true, minContext: 128000 }, "best");
+ expect(got.map((m) => m.id)).toEqual(expect.arrayContaining(["free-agent", "cheap-tools", "unknown-price"]));
+ });
+
+ it("filters Free using the server-provided strict free flag", () => {
+ expect(filterAndSortModels(models, "", { ...none, free: true }, "price").map((m) => m.id)).toEqual(["free-agent"]);
});
- it("sorts by price and best value", () => {
- const filters = { tools: false, reasoning: false, vision: false, minContext: 0 };
- expect(filterAndSortModels(models, "", filters, "price")[0].id).toBe("cheap-tools");
- expect(filterAndSortModels(models, "", filters, "best")[0].id).toBe("cheap-tools");
+ it("sorts explicit zero-cost models first by price without treating unknown cost as free", () => {
+ const sorted = filterAndSortModels(models, "", none, "price");
+ expect(sorted[0].id).toBe("free-agent");
+ expect(sorted.find((m) => m.id === "unknown-price")?.free).toBe(false);
});
});
diff --git a/frontend/slices/os-settings/components/model-catalog-utils.ts b/frontend/slices/os-settings/components/model-catalog-utils.ts
index 39eae435..113a0b17 100644
--- a/frontend/slices/os-settings/components/model-catalog-utils.ts
+++ b/frontend/slices/os-settings/components/model-catalog-utils.ts
@@ -6,11 +6,14 @@ export type CatModel = {
inputCost?: number;
outputCost?: number;
tools?: boolean;
+ free?: boolean;
+ agentReady?: boolean;
reasoning?: boolean;
vision?: boolean;
};
export type ModelFilters = {
+ free: boolean;
tools: boolean;
reasoning: boolean;
vision: boolean;
@@ -29,6 +32,7 @@ export function filterAndSortModels(models: CatModel[], query: string, filters:
const q = query.trim().toLowerCase();
const pass = (m: CatModel) =>
(!q || m.id.toLowerCase().includes(q) || (m.name ?? "").toLowerCase().includes(q)) &&
+ (!filters.free || m.free === true) &&
(!filters.tools || !!m.tools) &&
(!filters.reasoning || !!m.reasoning) &&
(!filters.vision || !!m.vision) &&
@@ -36,9 +40,9 @@ export function filterAndSortModels(models: CatModel[], query: string, filters:
const score = (m: CatModel) => modelPower(m) / Math.max(modelCost(m), 0.01);
return models.filter(pass).sort((a, b) => {
- if (sort === "price") return modelCost(a) - modelCost(b);
- if (sort === "capability") return modelPower(b) - modelPower(a);
- if (sort === "context") return (b.context ?? 0) - (a.context ?? 0);
- return score(b) - score(a);
+ if (sort === "price") return modelCost(a) - modelCost(b) || Number(!!b.agentReady) - Number(!!a.agentReady) || a.id.localeCompare(b.id);
+ if (sort === "capability") return modelPower(b) - modelPower(a) || a.id.localeCompare(b.id);
+ if (sort === "context") return (b.context ?? 0) - (a.context ?? 0) || a.id.localeCompare(b.id);
+ return score(b) - score(a) || Number(!!b.free) - Number(!!a.free) || a.id.localeCompare(b.id);
});
}
diff --git a/frontend/slices/os-settings/components/model-catalog.tsx b/frontend/slices/os-settings/components/model-catalog.tsx
index e3f0dee3..5acf1c23 100644
--- a/frontend/slices/os-settings/components/model-catalog.tsx
+++ b/frontend/slices/os-settings/components/model-catalog.tsx
@@ -9,15 +9,15 @@ import { filterAndSortModels, type CatModel, type ModelFilters, type ModelSort }
const fmtCtx = (n?: number) => (!n ? "—" : n >= 1e6 ? `${n / 1e6}M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : `${n}`);
const fmtCost = (n?: number) => (n == null ? "—" : `$${n}`);
-// Searchable model browser over the models.dev catalog for the selected provider,
-// showing context window · $/M input+output · tool/reasoning/vision support. Pick →
-// sets the model id in the parent. Empty for custom/OAuth providers (not in the catalog).
+// Searchable browser over the same live model catalog used by CLI onboarding.
+// `free` is server-derived only from explicit zero input+output pricing; unknown
+// pricing never receives the badge or passes the Free filter.
export function ModelCatalog({ provider, value, onPick }: { provider: string; value: string; onPick: (id: string) => void }) {
const [open, setOpen] = useState(false);
const [q, setQ] = useState("");
const [models, setModels] = useState<CatModel[]>([]);
const [sort, setSort] = useState<ModelSort>("best");
- const [filters, setFilters] = useState<ModelFilters>({ tools: false, reasoning: false, vision: false, minContext: 0 });
+ const [filters, setFilters] = useState<ModelFilters>({ free: false, tools: false, reasoning: false, vision: false, minContext: 0 });
useEffect(() => {
if (!open) return;
@@ -32,7 +32,7 @@ export function ModelCatalog({ provider, value, onPick }: { provider: string; va
}, [open, provider]);
const filtered = useMemo(() => filterAndSortModels(models, q, filters, sort), [models, q, filters, sort]);
- const toggle = (key: "tools" | "reasoning" | "vision") => setFilters((f) => ({ ...f, [key]: !f[key] }));
+ const toggle = (key: "free" | "tools" | "reasoning" | "vision") => setFilters((f) => ({ ...f, [key]: !f[key] }));
return (
<>
@@ -56,12 +56,18 @@ export function ModelCatalog({ provider, value, onPick }: { provider: string; va
<option value={128000}>128K+ context</option>
<option value={1000000}>1M+ context</option>
</select>
+ <Filter checked={filters.free} label="Free" onChange={() => toggle("free")} />
<Filter checked={filters.tools} label="Tools" onChange={() => toggle("tools")} />
<Filter checked={filters.reasoning} label="Reasoning" onChange={() => toggle("reasoning")} />
<Filter checked={filters.vision} label="Vision" onChange={() => toggle("vision")} />
</div>
+ {models.some((model) => model.free) && (
+ <p className="text-xs leading-5 text-muted-foreground">
+ Free = the live catalog reports $0 input and $0 output token cost. Provider account/API key and rate limits may still apply.
+ </p>
+ )}
{filtered.length === 0 ? (
- <p className="py-8 text-center text-sm text-muted-foreground">No catalog for this provider.</p>
+ <p className="py-8 text-center text-sm text-muted-foreground">No models match these filters.</p>
) : (
<div className="space-y-1 pr-3">
{filtered.map((m) => (
@@ -76,6 +82,7 @@ export function ModelCatalog({ provider, value, onPick }: { provider: string; va
>
<div className="flex w-full flex-wrap items-center gap-2">
<span className="font-medium">{m.name || m.id}</span>
+ {m.free && <Badge emphasis>FREE</Badge>}
{m.tools && <Badge>tools</Badge>}
{m.reasoning && <Badge>reasoning</Badge>}
{m.vision && <Badge>vision</Badge>}
@@ -96,8 +103,8 @@ export function ModelCatalog({ provider, value, onPick }: { provider: string; va
);
}
-function Badge({ children }: { children: React.ReactNode }) {
- return <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{children}</span>;
+function Badge({ children, emphasis = false }: { children: React.ReactNode; emphasis?: boolean }) {
+ return <span className={emphasis ? "rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold text-primary" : "rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground"}>{children}</span>;
}
function Filter({ checked, label, onChange }: { checked: boolean; label: string; onChange: () => void }) {
diff --git a/lib/models/discovery.js b/lib/models/discovery.js
new file mode 100644
index 00000000..0e113f6d
--- /dev/null
+++ b/lib/models/discovery.js
@@ -0,0 +1,56 @@
+import { getCatalog } from './catalog.js'
+import { PROVIDERS } from './registry.js'
+
+/** A model is free only when the catalog explicitly reports zero input AND output cost. */
+export function isFreeModel(model) {
+ const input = model?.cost?.input
+ const output = model?.cost?.output
+ return Number.isFinite(input) && Number.isFinite(output) && input === 0 && output === 0
+}
+
+/** Runtime provider ids stay pinned to MSO's registry; models.dev may use a different catalog id. */
+export function providerCatalogId(provider) {
+ return PROVIDERS[provider]?.catalogId || provider
+}
+
+export function runtimeProviderModels(catalog, provider) {
+ const catalogId = providerCatalogId(provider)
+ const row = catalog?.[catalogId]
+ if (!row || typeof row !== 'object' || Array.isArray(row)) return []
+ return Object.entries(row.models || {})
+ .filter(([, model]) => model && typeof model === 'object' && !Array.isArray(model))
+ .map(([id, model]) => ({ id, model }))
+ .sort((a, b) => a.id.localeCompare(b.id))
+}
+
+export function summarizeProvider(catalog, provider) {
+ const catalogId = providerCatalogId(provider)
+ const catalogProvider = catalog?.[catalogId]
+ const models = runtimeProviderModels(catalog, provider)
+ const free = models.filter(({ model }) => isFreeModel(model))
+ const freeAgent = free.filter(({ model }) => model.tool_call === true)
+ return {
+ id: provider,
+ name: typeof catalogProvider?.name === 'string' && catalogProvider.name.trim() ? catalogProvider.name : provider,
+ catalogId,
+ modelCount: models.length,
+ freeModelCount: free.length,
+ freeAgentModelCount: freeAgent.length,
+ recommendedFreeModel: (freeAgent[0] || free[0])?.id || null,
+ }
+}
+
+export function providerSummariesFromCatalog(catalog, { freeOnly = false } = {}) {
+ const rows = Object.keys(PROVIDERS).map((provider) => summarizeProvider(catalog, provider))
+ const filtered = freeOnly ? rows.filter((row) => row.freeAgentModelCount > 0) : rows
+ return filtered.sort((a, b) =>
+ (b.freeAgentModelCount > 0 ? 1 : 0) - (a.freeAgentModelCount > 0 ? 1 : 0)
+ || b.freeAgentModelCount - a.freeAgentModelCount
+ || a.name.localeCompare(b.name)
+ || a.id.localeCompare(b.id),
+ )
+}
+
+export async function listProviderSummaries(options = {}) {
+ return providerSummariesFromCatalog(await getCatalog(), options)
+}
diff --git a/lib/models/discovery.test.ts b/lib/models/discovery.test.ts
new file mode 100644
index 00000000..d8066c7b
--- /dev/null
+++ b/lib/models/discovery.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+import { PROVIDERS } from "./registry.js";
+import {
+ isFreeModel,
+ providerCatalogId,
+ providerSummariesFromCatalog,
+ runtimeProviderModels,
+} from "./discovery.js";
+
+describe("dynamic provider discovery", () => {
+ it("only treats explicit numeric zero input+output pricing as free", () => {
+ expect(isFreeModel({ cost: { input: 0, output: 0 } })).toBe(true);
+ expect(isFreeModel({ cost: { input: 0, output: 1 } })).toBe(false);
+ expect(isFreeModel({ cost: { input: 0 } })).toBe(false);
+ expect(isFreeModel({})).toBe(false);
+ expect(isFreeModel({ cost: { input: "0", output: "0" } })).toBe(false);
+ });
+
+ it("uses registry catalogId mappings instead of assuming runtime id equals catalog id", () => {
+ expect(providerCatalogId("glm")).toBe("zhipuai");
+ expect(providerCatalogId("vercel-gateway")).toBe("vercel");
+ const catalog = { zhipuai: { models: { "glm-test": { cost: { input: 0, output: 0 }, tool_call: true } } } };
+ expect(runtimeProviderModels(catalog, "glm").map((row) => row.id)).toEqual(["glm-test"]);
+ });
+
+ it("summarizes free and agent-ready free models without guessing unknown prices", () => {
+ const catalog = {
+ opencode: {
+ name: "OpenCode Zen",
+ models: {
+ paid: { cost: { input: 1, output: 2 }, tool_call: true },
+ "z-free": { cost: { input: 0, output: 0 }, tool_call: false },
+ "a-free-agent": { cost: { input: 0, output: 0 }, tool_call: true },
+ unknown: { tool_call: true },
+ },
+ },
+ };
+ const row = providerSummariesFromCatalog(catalog).find((p) => p.id === "opencode");
+ expect(row).toMatchObject({
+ name: "OpenCode Zen",
+ modelCount: 4,
+ freeModelCount: 2,
+ freeAgentModelCount: 1,
+ recommendedFreeModel: "a-free-agent",
+ });
+ });
+
+ it("keeps pinned providers discoverable offline without claiming they are free", () => {
+ const rows = providerSummariesFromCatalog({});
+ expect(rows.find((row) => row.id === "opencode")).toMatchObject({ modelCount: 0, freeModelCount: 0, freeAgentModelCount: 0 });
+ expect(providerSummariesFromCatalog({}, { freeOnly: true })).toEqual([]);
+ });
+
+ it("registers OpenCode Zen as a pinned OpenAI-compatible provider", () => {
+ expect(PROVIDERS.opencode).toMatchObject({
+ baseUrl: "https://opencode.ai/zen/v1",
+ protocol: "openai",
+ catalogId: "opencode",
+ });
+ expect(PROVIDERS.opencode.envVars).toContain("OPENCODE_API_KEY");
+ });
+});
diff --git a/lib/models/registry.js b/lib/models/registry.js
index 1f955ed2..54b89bc5 100644
--- a/lib/models/registry.js
+++ b/lib/models/registry.js
@@ -8,6 +8,7 @@ export const PROVIDERS = {
anthropic: { baseUrl: 'https://api.anthropic.com', protocol: 'anthropic', envVars: ['ANTHROPIC_API_KEY'], catalogId: 'anthropic' },
google: { baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai', protocol: 'openai', envVars: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'], catalogId: 'google' },
openrouter: { baseUrl: 'https://openrouter.ai/api/v1', protocol: 'openai', envVars: ['OPENROUTER_API_KEY'], catalogId: 'openrouter' },
+ opencode: { baseUrl: 'https://opencode.ai/zen/v1', protocol: 'openai', envVars: ['OPENCODE_API_KEY'], catalogId: 'opencode' },
groq: { baseUrl: 'https://api.groq.com/openai/v1', protocol: 'openai', envVars: ['GROQ_API_KEY'], catalogId: 'groq' },
deepseek: { baseUrl: 'https://api.deepseek.com', protocol: 'openai', envVars: ['DEEPSEEK_API_KEY'], catalogId: 'deepseek' },
xai: { baseUrl: 'https://api.x.ai/v1', protocol: 'openai', envVars: ['XAI_API_KEY'], catalogId: 'xai' },
diff --git a/lib/onboard-contract.test.ts b/lib/onboard-contract.test.ts
index 00ddaccc..e0759d02 100644
--- a/lib/onboard-contract.test.ts
+++ b/lib/onboard-contract.test.ts
@@ -10,6 +10,8 @@ const cli = [
fs.readFileSync(path.join(__dirname, "../bin/mso"), "utf8"),
fs.readFileSync(path.join(__dirname, "../scripts/cli/onboarding.sh"), "utf8"),
fs.readFileSync(path.join(__dirname, "../scripts/cli/onboarding-ai.sh"), "utf8"),
+ fs.readFileSync(path.join(__dirname, "../scripts/mso-cli-agent.sh"), "utf8"),
+ fs.readFileSync(path.join(__dirname, "../scripts/cli/ai-provider-catalog.sh"), "utf8"),
fs.readFileSync(path.join(__dirname, "../scripts/cli/transport.sh"), "utf8"),
].join("\n");
@@ -26,10 +28,14 @@ describe("terminal onboarding contract", () => {
expect(cli).toContain('secret_post "/api/config" "$body"');
});
- it("documents OAuth separately from API-key providers", () => {
- expect(cli).toContain("OpenAI ChatGPT OAuth (Codex consumer backend; no API key)");
- expect(cli).toContain("OpenRouter API key");
- expect(cli).toContain("OpenAI Platform API key");
+ it("discovers AI platforms dynamically while keeping OAuth and API-key auth distinct", () => {
+ expect(cli).toContain('jget "/api/models/providers"');
+ expect(cli).toContain('tui_select "Connect AI platform"');
+ expect(cli).toContain("OpenAI ChatGPT");
+ expect(cli).toContain("Subscription · device OAuth");
+ expect(cli).toContain("OpenCode Zen");
+ expect(cli).toContain('tty_secret "Paste $provider API key: "');
+ expect(cli).toContain("FREE means the live catalog explicitly reports zero input + output token cost");
});
it("keeps -y minimal instead of selecting external accounts or installs", () => {
diff --git a/scripts/cli/ai-provider-catalog.sh b/scripts/cli/ai-provider-catalog.sh
new file mode 100755
index 00000000..4992e1c4
--- /dev/null
+++ b/scripts/cli/ai-provider-catalog.sh
@@ -0,0 +1,100 @@
+#!/usr/bin/env bash
+# Dynamic AI provider/model discovery helpers shared by onboarding and `mso models`.
+# Sourced by scripts/mso-cli-agent.sh after HTTP/TTY transport helpers are available.
+# Pricing is presentation metadata only: FREE means explicit zero input + output cost.
+
+known_ai_provider_picker_rows() {
+ cat <<'ROWS'
+openai-codex OpenAI ChatGPT ChatGPT subscription · device OAuth
+opencode OpenCode Zen API key · dynamic free models when available
+anthropic Anthropic API key
+openai OpenAI Platform API key
+openrouter OpenRouter API key · multi-model router
+google Google Gemini API key
+groq Groq API key
+xai xAI API key
+deepseek DeepSeek API key
+mistral Mistral API key
+custom Custom provider OpenAI/Anthropic-compatible endpoint
+ROWS
+}
+
+ai_provider_catalog() {
+ jget "/api/models/providers"
+}
+
+dynamic_ai_provider_picker_rows() {
+ local data="${1:-}" active="${2:-}"
+ [ -n "$data" ] || data=$(ai_provider_catalog 2>/dev/null || true)
+ if ! jq -e '.providers | length > 0' <<<"$data" >/dev/null 2>&1; then
+ known_ai_provider_picker_rows
+ return
+ fi
+ jq -r --arg active "$active" '.providers[] |
+ [
+ .id,
+ (.name // .id),
+ (if (.freeAgentModelCount // 0) > 0
+ then "FREE · " + ((.freeAgentModelCount // 0)|tostring) + " agent-ready · " + ((.modelCount // 0)|tostring) + " models"
+ else ((.modelCount // 0)|tostring) + " models · API key"
+ end),
+ (if .id == $active then "current" else "" end)
+ ] | @tsv' <<<"$data"
+ printf 'openai-codex OpenAI ChatGPT Subscription · device OAuth %s\n' "$([ "$active" = openai-codex ] && printf current || true)"
+ printf 'custom Custom provider OpenAI/Anthropic-compatible endpoint \n'
+}
+
+ai_provider_supported() {
+ local provider="$1" data
+ data=$(ai_provider_catalog 2>/dev/null || true)
+ if jq -e '.providers | length > 0' <<<"$data" >/dev/null 2>&1; then
+ jq -e --arg p "$provider" 'any(.providers[]?; .id == $p)' <<<"$data" >/dev/null 2>&1
+ return
+ fi
+ known_ai_provider_picker_rows | cut -f1 | grep -Fxq "$provider"
+}
+
+model_picker_rows() {
+ local data="$1" current="${2-}"
+ jq -r --arg current "$current" '.models
+ | sort_by(if (.free == true and .agentReady == true) then 0 elif .free == true then 1 else 2 end, .id)
+ | .[] |
+ [
+ .id,
+ .id,
+ ((if .free == true then "FREE · " else "" end)
+ + (if (.context // 0) > 0 then "ctx " + ((.context // 0)|tostring) else "ctx —" end)
+ + " · tools " + (if .tools then "yes" else "—" end)
+ + " · reasoning " + (if .reasoning then "yes" else "—" end)),
+ (if .id==$current then "current" else "" end)
+ ] | @tsv' <<<"$data"
+}
+
+print_free_ai_options() {
+ local provider="${1:-}" data
+ if [ -n "$provider" ]; then
+ data=$(jget "/api/models?provider=$(enc "$provider")&free=1")
+ if ! jq -e '.models | length > 0' <<<"$data" >/dev/null 2>&1; then
+ echo "No explicitly zero-cost models currently reported for $provider."
+ return 1
+ fi
+ printf '%-36s %-7s %-10s %-8s %s\n' 'MODEL' 'AGENT' 'CONTEXT' 'REASON' 'NAME'
+ jq -r '.models | sort_by(if .agentReady then 0 else 1 end, .id) | .[] |
+ [.id,(if .agentReady then "yes" else "—" end),((.context // 0)|tostring),(if .reasoning then "yes" else "—" end),(.name // .id)] | @tsv' <<<"$data" |
+ while IFS=$'\t' read -r id agent context reasoning name; do
+ [ "$context" = 0 ] && context="—"
+ printf '%-36s %-7s %-10s %-8s %s\n' "${id:0:36}" "$agent" "$context" "$reasoning" "${name:0:45}"
+ done
+ return
+ fi
+ data=$(jget "/api/models/providers?free=1")
+ if ! jq -e '.providers | length > 0' <<<"$data" >/dev/null 2>&1; then
+ echo "No provider currently reports explicitly zero-cost, agent-ready models."
+ return 1
+ fi
+ echo "Free AI providers (live catalog; provider account/key and rate limits may still apply)"
+ jq -r '.providers[] | [.id,(.name // .id),(.freeAgentModelCount|tostring),(.freeModelCount|tostring),(.recommendedFreeModel // "—")] | @tsv' <<<"$data" |
+ while IFS=$'\t' read -r id name agent_count free_count recommended; do
+ printf ' %-18s %-24s %3s agent-ready / %3s free %s\n' "$id" "${name:0:24}" "$agent_count" "$free_count" "$recommended"
+ done
+}
diff --git a/scripts/cli/onboarding-ai.sh b/scripts/cli/onboarding-ai.sh
index d4d705da..5cd98424 100644
--- a/scripts/cli/onboarding-ai.sh
+++ b/scripts/cli/onboarding-ai.sh
@@ -1,63 +1,41 @@
#!/usr/bin/env bash
-# Guided AI provider setup, using the shared private TTY/transport helpers.
+# Guided AI setup. Provider/model discovery is shared with `mso models` and the Web UI.
onboard_ai() {
- local yes="$1" choice provider key body response interval code url poll
+ local yes="$1" provider cfg data model rc
if [ "$yes" = 1 ]; then
echo " -- AI provider skipped (-y keeps external accounts unconfigured)"
return
fi
+
echo
echo "AI for Alfa"
- echo " 0) Skip for now"
- echo " 1) OpenAI ChatGPT OAuth (Codex consumer backend; no API key)"
- echo " 2) Anthropic API key"
- echo " 3) OpenAI Platform API key"
- echo " 4) OpenRouter API key"
- echo " 5) Google Gemini API key"
- echo " 6) Groq API key"
- echo " 7) xAI API key"
- echo " 8) DeepSeek API key"
- echo " 9) Mistral API key"
- tty_line "Choose [0]: " 0; choice="$REPLY"
- case "$choice" in
- 0|'') echo " -- skipped"; return ;;
- 1)
- response=$(jpost "/api/oauth/openai" '{"action":"start"}')
- code=$(jq -r '.userCode // empty' <<<"$response")
- url=$(jq -r '.verificationUrl // empty' <<<"$response")
- interval=$(jq -r '.intervalMs // 5000' <<<"$response")
- [ -n "$code" ] && [ -n "$url" ] || die "OpenAI OAuth did not return a device code"
- echo
- echo "Open this URL in any browser: $url"
- echo "Enter code: $code"
- echo "Waiting for authorization (Ctrl-C cancels this local wait; it does not expose the code)..."
- while true; do
- poll_seconds=$((interval / 1000))
- [ "$poll_seconds" -gt 2 ] || poll_seconds=3
- sleep "$poll_seconds"
- poll=$(jpost "/api/oauth/openai" '{"action":"poll"}')
- if [ "$(jq -r '.ok // false' <<<"$poll")" = true ]; then
- echo " ✓ OpenAI connected as $(jq -r '.slug' <<<"$poll")"
- return
- fi
- [ "$(jq -r '.pending // false' <<<"$poll")" = true ] || die "OpenAI OAuth failed: $poll"
- tty_print "."
- done ;;
- 2) provider=anthropic ;;
- 3) provider=openai ;;
- 4) provider=openrouter ;;
- 5) provider=google ;;
- 6) provider=groq ;;
- 7) provider=xai ;;
- 8) provider=deepseek ;;
- 9) provider=mistral ;;
- *) echo " ! unknown choice; skipped"; return ;;
- esac
- echo " $provider uses an API key here (not OAuth). The key is never placed in argv."
- tty_secret "Paste $provider API key: "; key="$REPLY"
- [ -n "$key" ] || { echo " -- empty key; skipped"; return; }
- body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body)
- secret_post "/api/config" "$body" >/dev/null
- unset key body REPLY
- echo " ✓ $provider configured for Alfa"
+ echo " Provider/model availability is loaded dynamically. FREE means the live catalog explicitly reports zero input + output token cost."
+ echo " A provider account/API key and provider rate limits may still apply."
+
+ provider=$(
+ {
+ printf 'skip\tSkip for now\tConfigure later with mso models\t\n'
+ dynamic_ai_provider_picker_rows "" ""
+ } | tui_select "Connect AI platform" "skip"
+ ) || {
+ rc=$?
+ [ "$rc" -eq 130 ] && { echo " -- skipped"; return 0; }
+ return "$rc"
+ }
+ [ "$provider" != skip ] || { echo " -- skipped"; return; }
+
+ configure_ai_provider "$provider"
+ cfg=$(ai_model_config)
+ data=$(ai_model_catalog "$provider" "$cfg")
+ if ! jq -e '.models | length > 0' <<<"$data" >/dev/null 2>&1; then
+ echo " ✓ $provider connected; no model catalog is available right now. Choose one later with: mso model"
+ return
+ fi
+
+ model=$(model_picker_rows "$data" "" | tui_select "Choose Alfa model · $provider" "") || {
+ rc=$?
+ [ "$rc" -eq 130 ] && { echo " ✓ $provider connected; model selection skipped"; return 0; }
+ return "$rc"
+ }
+ select_model_ref "$provider/$model"
}
diff --git a/scripts/mso-cli-agent.sh b/scripts/mso-cli-agent.sh
index a7caf1ad..8f93a211 100755
--- a/scripts/mso-cli-agent.sh
+++ b/scripts/mso-cli-agent.sh
@@ -88,33 +88,11 @@ connected_ai_provider_picker_rows() {
done < <(connected_ai_provider_ids "$cfg")
}
-known_ai_provider_picker_rows() {
- cat <<'ROWS'
-openai-codex openai-codex ChatGPT subscription · device OAuth
-anthropic anthropic API key
-openai openai OpenAI Platform API key
-openrouter openrouter API key · multi-model router
-google google Gemini API key
-groq groq API key
-xai xai API key
-deepseek deepseek API key
-mistral mistral API key
-custom custom OpenAI/Anthropic-compatible endpoint
-ROWS
-}
+# Keep provider/model catalog discovery modular: the main agent CLI owns orchestration,
+# while this slice owns live provider/free-model presentation.
+# shellcheck source=cli/ai-provider-catalog.sh
+source "$ROOT/scripts/cli/ai-provider-catalog.sh"
-model_picker_rows() {
- local data="$1" current="${2-}"
- jq -r --arg current "$current" '.models[] |
- [
- .id,
- .id,
- ((if (.context // 0) > 0 then "ctx " + ((.context // 0)|tostring) else "ctx —" end)
- + " · tools " + (if .tools then "yes" else "—" end)
- + " · reasoning " + (if .reasoning then "yes" else "—" end)),
- (if .id==$current then "current" else "" end)
- ] | @tsv' <<<"$data"
-}
picker_cancelled() { echo " — selection cancelled"; }
@@ -162,6 +140,7 @@ print_model_catalog() {
done
}
+
configure_oauth_provider() {
local provider="$1" response code url interval poll
[ "$provider" = "openai-codex" ] || die "OAuth provider not supported yet: $provider"
@@ -208,8 +187,7 @@ configure_ai_provider() {
unset key body REPLY
echo " ✓ custom provider configured; active model unchanged"
return ;;
- anthropic|openai|openrouter|google|groq|xai|deepseek|mistral) ;;
- *) die "provider must be: openai-codex anthropic openai openrouter google groq xai deepseek mistral custom" ;;
+ *) ai_provider_supported "$provider" || die "unknown/unsupported AI provider '$provider'; run: mso models free or mso models add" ;;
esac
tty_ok || die "provider setup needs an interactive terminal"
tty_secret "Paste $provider API key: "; key="$REPLY"; [ -n "$key" ] || die "empty API key"
@@ -289,10 +267,11 @@ run_models() {
cfg=$(ai_model_config)
case "$sub" in
status|list) print_ai_providers "$cfg" ;;
+ free) print_free_ai_options "${2:-}" ;;
add|auth)
provider="${2-}"
if [ -z "$provider" ] && tty_ok; then
- provider=$(known_ai_provider_picker_rows | tui_select "Connect AI provider" "openai-codex") || {
+ provider=$(dynamic_ai_provider_picker_rows "" "" | tui_select "Connect AI platform" "") || {
rc=$?; [ "$rc" -eq 130 ] && { picker_cancelled; return 0; }; return "$rc";
}
fi
@@ -320,6 +299,7 @@ run_models() {
action=$(cat <<'ROWS' | tui_select "AI provider/auth manager" "done"
done Done Return to MSO Agent
add Add / authenticate provider API key, OAuth, or custom endpoint
+free Free AI options Live zero-cost, agent-ready provider/model catalog
remove Remove provider Forget one stored provider credential
catalog Browse model catalog Inspect models for a connected provider
test Test active connection Validate the selected provider/model
@@ -328,10 +308,11 @@ ROWS
case "$action" in
done) return ;;
add)
- provider=$(known_ai_provider_picker_rows | tui_select "Connect AI provider" "openai-codex") || {
+ provider=$(dynamic_ai_provider_picker_rows "" "" | tui_select "Connect AI platform" "") || {
rc=$?; [ "$rc" -eq 130 ] && continue; return "$rc";
}
configure_ai_provider "$provider" ;;
+ free) echo; print_free_ai_options || true ;;
remove)
if ! connected_ai_provider_ids "$cfg" | grep -q .; then echo " · no connected providers to remove"; continue; fi
provider=$(connected_ai_provider_picker_rows "$cfg" "" | tui_select "Remove AI provider" "") || {
@@ -347,7 +328,7 @@ ROWS
test) echo; jpost "/api/models/test" | jq . ;;
esac
done ;;
- *) die "usage: mso models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]" ;;
+ *) die "usage: mso models [status|list|free [provider]|add|auth <provider>|rm <provider>|catalog [provider]|test]" ;;
esac
}
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index d1818857..0159e88e 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -9,6 +9,10 @@ const agentCli = fs.readFileSync(
path.join(__dirname, "mso-cli-agent.sh"),
"utf8",
);
+const providerCatalogCli = fs.readFileSync(
+ path.join(root, "scripts/cli/ai-provider-catalog.sh"),
+ "utf8",
+);
const configRoute = fs.readFileSync(
path.join(root, "app/api/config/route.ts"),
"utf8",
@@ -26,7 +30,7 @@ const picker = fs.readFileSync(
"utf8",
);
-const all = [cli, commandOwner, agentCli, configRoute, oauthRoute, slash, picker].join("\n");
+const all = [cli, commandOwner, agentCli, providerCatalogCli, configRoute, oauthRoute, slash, picker].join("\n");
describe("MSO model/provider/session CLI contract", () => {
it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
@@ -58,6 +62,14 @@ describe("MSO model/provider/session CLI contract", () => {
expect(picker).toContain("nextPickerIndex");
});
+ it("shares a dynamic free-provider catalog between connect and model discovery", () => {
+ expect(providerCatalogCli).toContain('jget "/api/models/providers"');
+ expect(agentCli).toContain('tui_select "Connect AI platform"');
+ expect(agentCli).toContain('free) print_free_ai_options');
+ expect(providerCatalogCli).toContain('FREE · ');
+ expect(providerCatalogCli).toContain('provider account/key and rate limits may still apply');
+ });
+
it("supports explicit and slash-containing model IDs without losing provider intent", () => {
expect(agentCli).toContain("Model IDs themselves may contain slashes");
expect(agentCli).toContain("mso model set <provider> <model>");