refactor(provider-core): expose model metadata through a ModelCatalog port (#17417)

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-09 09:15:21 -07:00
1 parent a6698271a4
commit 2c1915b319
14 files changed
+579 -449

No files matched your search

@@ -1,8 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { hasValidClaudeManifestAdapters } from "./ClaudeModelManifest.ts";
import type { ModelManifestData } from "./ModelManifest.ts";
import { resolveProviderCatalog, type ModelManifestData } from "./ModelManifest.ts";
import {
formatClaudeVersionUpgradeMessage,
normalizeClaudeCatalogEffort,
@@ -71,11 +71,17 @@ const manifest = (): ModelManifestData => ({
},
});
const CLAUDE = ProviderDriverKind.make("claudeAgent");
/** Resolves Claude's catalog the way the driver does: through its manifest catalog entry. */
const catalogFromManifest = (data: ModelManifestData) =>
resolveClaudeModelCatalog(resolveProviderCatalog(data, CLAUDE) ?? undefined);
describe("Claude model catalog", () => {
it("resolves capacity from selected options and fixed catalog windows without guessing custom models", () => {
const source = manifest();
const profile = source.providers!.claudeAgent!.profiles.synthetic!;
const catalog = resolveClaudeModelCatalog({
const catalog = catalogFromManifest({
...source,
providers: {
claudeAgent: {
@@ -121,7 +127,7 @@ describe("Claude model catalog", () => {
});
it("filters models at runtime-version boundaries and derives the upgrade message", () => {
const catalog = resolveClaudeModelCatalog(manifest());
const catalog = catalogFromManifest(manifest());
assert.deepStrictEqual(resolveClaudeModelsForVersion(catalog, "3.1.9"), []);
assert.deepStrictEqual(
resolveClaudeModelsForVersion(catalog, "3.2.0").map((model) => model.slug),
@@ -157,7 +163,7 @@ describe("Claude model catalog", () => {
},
},
};
const catalog = resolveClaudeModelCatalog(input);
const catalog = catalogFromManifest(input);
assert.strictEqual(resolveClaudeModelSlug(catalog, "synthetic"), "claude-synthetic-next");
assert.strictEqual(
resolveClaudeModelSlug(catalog, "claude-synthetic-next"),
@@ -195,7 +201,7 @@ describe("Claude model catalog", () => {
});
it("appends custom models with their own descriptors and keeps bare slugs opaque", () => {
const catalog = scopeClaudeModelCatalog(resolveClaudeModelCatalog(manifest()), [
const catalog = scopeClaudeModelCatalog(catalogFromManifest(manifest()), [
"synthetic",
{
slug: "claude-custom-tuned",
+21 -12
View File
@@ -21,11 +21,8 @@ import {
decodeClaudeModelAdapter,
decodeClaudeProfileAdapter,
} from "./ClaudeModelManifest.ts";
import {
BUNDLED_MODEL_MANIFEST,
type ModelManifestData,
resolveProviderCatalog,
} from "./ModelManifest.ts";
import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
import { BUNDLED_MODEL_MANIFEST, resolveProviderCatalog } from "./ModelManifest.ts";
const CLAUDE = ProviderDriverKind.make("claudeAgent");
const EMPTY_CAPABILITIES: ModelCapabilities = { optionDescriptors: [] };
@@ -40,8 +37,9 @@ export interface ClaudeModelCatalog {
readonly models: ReadonlyArray<ClaudeCatalogModel>;
}
function tryResolveClaudeModelCatalog(manifest: ModelManifestData): ClaudeModelCatalog | null {
const resolved = resolveProviderCatalog(manifest, CLAUDE);
function tryResolveClaudeModelCatalog(
resolved: ModelCatalog.ProviderCatalog | undefined,
): ClaudeModelCatalog | null {
if (!resolved) return null;
const models: Array<ClaudeCatalogModel> = [];
@@ -50,7 +48,7 @@ function tryResolveClaudeModelCatalog(manifest: ModelManifestData): ClaudeModelC
const adapter = decodeClaudeModelAdapter(entry.adapter ?? {});
if (Option.isNone(profile) || Option.isNone(adapter)) return null;
models.push({
model: entry.model,
model: ModelCatalog.catalogServerModel(resolved, entry),
runtime: profile.value.claudeCode ?? {},
compatibility: adapter.value.claudeCode ?? {},
});
@@ -61,16 +59,27 @@ function tryResolveClaudeModelCatalog(manifest: ModelManifestData): ClaudeModelC
};
}
export function resolveClaudeModelCatalog(manifest: ModelManifestData): ClaudeModelCatalog {
const BUNDLED_CLAUDE_PROVIDER_CATALOG =
resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, CLAUDE) ?? undefined;
/**
* Claude's built-in catalog from its manifest entry, falling back to the
* bundled entry when the current one is missing or has invalid adapters.
*/
export function resolveClaudeModelCatalog(
catalog: ModelCatalog.ProviderCatalog | undefined,
): ClaudeModelCatalog {
return (
tryResolveClaudeModelCatalog(manifest) ??
tryResolveClaudeModelCatalog(BUNDLED_MODEL_MANIFEST) ?? {
tryResolveClaudeModelCatalog(catalog) ??
tryResolveClaudeModelCatalog(BUNDLED_CLAUDE_PROVIDER_CATALOG) ?? {
models: [],
}
);
}
export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog(BUNDLED_MODEL_MANIFEST);
export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog(
BUNDLED_CLAUDE_PROVIDER_CATALOG,
);
/**
* Scope the catalog to one instance's settings: custom model slugs stay opaque
@@ -52,7 +52,7 @@ import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeL
import { ProviderDriverError } from "../Errors.ts";
import { makeAntigravityProvider } from "../AntigravityProvider.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import * as ModelManifest from "../ModelManifest.ts";
import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
@@ -73,7 +73,7 @@ export type AntigravityDriverEnv =
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| ModelManifest.ModelManifest
| ModelCatalog.ModelCatalog
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers;
@@ -93,7 +93,8 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
const selfInvocation = yield* resolveSelfInvocation();
const installation = yield* AntigravityInstallation.AntigravityInstallation;
const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const modelManifest = yield* ModelManifest.ModelManifest;
const modelCatalog = yield* ModelCatalog.ModelCatalog;
const currentCatalog = modelCatalog.current(DRIVER);
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
const settings = { ...config, enabled } satisfies AntigravitySettings;
@@ -146,10 +147,8 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
continuationGroupKey: continuationIdentity.continuationKey,
});
const classifyModels = (draft: ServerProviderDraft) =>
modelManifest.current.pipe(
Effect.map((manifest) =>
stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER)),
),
currentCatalog.pipe(
Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),
);
const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
@@ -336,7 +335,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
// and version. The response below is synthetic: only agentInfo.version
// is read from it. Sessions and manual refreshes still spawn.
const probe = Effect.gen(function* () {
yield* modelManifest.refreshInBackground;
yield* modelCatalog.refreshInBackground;
if (authConfigIssue !== null) {
return yield* new ProviderSetupError({
instanceId,
@@ -393,9 +392,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
}),
),
);
const defaultModel = modelManifest.current.pipe(
Effect.map((manifest) => ModelManifest.manifestDefaultModel(manifest, DRIVER)),
);
const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
const orchestrationAdapter = yield* makeAntigravityAdapterV2({
instanceId,
selfInvocation,
@@ -43,7 +43,7 @@ import {
probeClaudeWorkspaceSnapshot,
} from "../ClaudeProvider.ts";
import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
import * as ModelManifest from "../ModelManifest.ts";
import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
import {
defaultProviderContinuationIdentity,
@@ -100,7 +100,7 @@ export type ClaudeDriverEnv =
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| ModelManifest.ModelManifest
| ModelCatalog.ModelCatalog
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig;
@@ -122,8 +122,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
const httpClient = yield* HttpClient.HttpClient;
const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
const host = yield* ProviderHost;
const modelManifest = yield* ModelManifest.ModelManifest;
const modelCatalog = modelManifest.current.pipe(Effect.map(resolveClaudeModelCatalog));
const catalogService = yield* ModelCatalog.ModelCatalog;
const modelCatalog = catalogService
.current(DRIVER_KIND)
.pipe(Effect.map(resolveClaudeModelCatalog));
const processEnv = mergeProviderInstanceEnvironment(environment);
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
@@ -208,16 +210,16 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
// Start the TTL-gated refresh without delaying provider readiness. The
// next check observes a remote manifest after the background fetch lands.
const checkProvider = modelManifest.refreshInBackground.pipe(
const checkProvider = catalogService.refreshInBackground.pipe(
Effect.andThen(
modelManifest.current.pipe(
Effect.flatMap((manifest) =>
modelCatalog.pipe(
Effect.flatMap((catalog) =>
checkClaudeProviderStatus(
effectiveConfig,
() => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
processEnv,
cwd,
resolveClaudeModelCatalog(manifest),
catalog,
scopedLimitNames,
(version) =>
ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
@@ -242,10 +244,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
streamSettings: snapshotSettings.streamSettings,
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
initialSnapshot: (settings) =>
modelManifest.current.pipe(
Effect.flatMap((manifest) =>
makePendingClaudeProvider(settings.provider, resolveClaudeModelCatalog(manifest)),
),
modelCatalog.pipe(
Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),
Effect.map(stampIdentity),
),
checkProvider,
+10 -10
View File
@@ -49,7 +49,8 @@ import {
} from "../CodexProvider.ts";
import { resolveCodexLaunchArgs } from "../codexLaunchArgs.ts";
import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
import * as ModelManifest from "../ModelManifest.ts";
import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
import { applyCodexModelCatalog } from "../codexModelCatalog.ts";
import type { ProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver";
import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
@@ -114,7 +115,7 @@ export type CodexDriverEnv =
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| ModelManifest.ModelManifest
| ModelCatalog.ModelCatalog
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers
| ServerConfig.ServerConfig
@@ -147,7 +148,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
const pathService = yield* Path.Path;
const httpClient = yield* HttpClient.HttpClient;
const host = yield* ProviderHost;
const modelManifest = yield* ModelManifest.ModelManifest;
const modelCatalog = yield* ModelCatalog.ModelCatalog;
const currentCatalog = modelCatalog.current(DRIVER_KIND);
const processEnv = mergeProviderInstanceEnvironment(environment);
const homeLayout = yield* resolveCodexHomeLayout(config);
const continuationIdentity = codexContinuationIdentity(homeLayout);
@@ -218,13 +220,12 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
// Kick the TTL-gated manifest refresh in the background and classify
// with the in-memory manifest, so a slow or hung fetch never delays the
// provider check. A refresh that lands mid-probe applies on the next one.
const checkProvider = modelManifest.refreshInBackground.pipe(
const checkProvider = modelCatalog.refreshInBackground.pipe(
Effect.andThen(
Effect.zipWith(
checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
modelManifest.current,
(draft, manifest) =>
stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
currentCatalog,
(draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
{ concurrent: true },
),
),
@@ -239,9 +240,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
initialSnapshot: (settings) =>
Effect.zipWith(
makePendingCodexProvider(settings.provider),
modelManifest.current,
(draft, manifest) =>
stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
currentCatalog,
(draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
),
checkProvider,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
+8 -216
View File
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProviderDriverKind, type ServerProviderModel } from "@t3tools/contracts";
import { ProviderDriverKind } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -20,212 +20,6 @@ import * as ModelManifest from "./ModelManifest.ts";
* synthetic models for resolver coverage.
*/
const CODEX = ProviderDriverKind.make("codex");
const model = (overrides: Partial<ServerProviderModel>): ServerProviderModel => ({
slug: "gpt-test",
name: "GPT Test",
isCustom: false,
capabilities: null,
...overrides,
});
describe("classifyModels", () => {
it("classifies qualified Codex families without changing their wire ids", () => {
const manifest: ModelManifest.ModelManifestData = {
version: 1,
currentModels: { codex: ["gpt-test"] },
providers: {
codex: {
profiles: {},
models: [{ slug: "gpt-old", name: "Old", status: "legacy" }],
},
},
};
const models = [
model({ slug: "openai.gpt-test", isLegacy: true }),
model({ slug: "openai.gpt-old" }),
];
assert.deepStrictEqual(
ModelManifest.classifyModels(models, manifest, CODEX).map((entry) => [
entry.slug,
entry.isLegacy ?? false,
]),
[
["openai.gpt-test", false],
["openai.gpt-old", true],
],
);
});
it("flags only known legacy models, clears stale flags, and skips custom models", () => {
const manifest: ModelManifest.ModelManifestData = {
version: 1,
currentModels: { codex: ["current-a", "current-b"] },
providers: {
codex: {
profiles: {},
models: [{ slug: "old-model", name: "Old", status: "legacy" }],
},
},
};
const models = [
model({ slug: "current-a" }),
// Stale flag from a previous classification pass must be cleared.
model({ slug: "current-b", isLegacy: true }),
model({ slug: "old-model" }),
model({ slug: "new-release", isLegacy: true }),
// Custom models are user-defined and never reclassified.
model({ slug: "my-own-model", isCustom: true }),
];
assert.deepStrictEqual(
ModelManifest.classifyModels(models, manifest, CODEX).map((entry) => [
entry.slug,
entry.isLegacy ?? false,
]),
[
["current-a", false],
["current-b", false],
["old-model", true],
["new-release", false],
["my-own-model", false],
],
);
});
it.each(["codex", "antigravity"])(
"keeps newly discovered %s models current when the manifest has no catalog",
(driverKind) => {
const models = [model({ slug: "new-release", isLegacy: true })];
assert.deepStrictEqual(
ModelManifest.classifyModels(
models,
{ version: 1, currentModels: { [driverKind]: ["known-current"] } },
ProviderDriverKind.make(driverKind),
),
[model({ slug: "new-release" })],
);
},
);
});
describe("applyManifestDefault", () => {
it("resolves the manifest default to the qualified live model", () => {
const manifest: ModelManifest.ModelManifestData = {
version: 1,
currentModels: {},
providers: { codex: { models: [], profiles: {}, defaults: { chat: "gpt-test" } } },
};
const models = [
model({ slug: "openai.gpt-old", isDefault: true }),
model({ slug: "openai.gpt-test" }),
];
assert.strictEqual(
ModelManifest.applyManifestDefault(models, manifest, CODEX).find((entry) => entry.isDefault)
?.slug,
"openai.gpt-test",
);
});
it("moves the default flag and its aliases to the manifest's chat default", () => {
const driver = ProviderDriverKind.make("antigravity");
const manifest: ModelManifest.ModelManifestData = {
version: 1,
currentModels: {},
providers: {
antigravity: {
defaults: { chat: "gemini-new" },
profiles: {},
models: [{ slug: "gemini-new", name: "New", status: "current" }],
},
},
};
const models = [
model({ slug: "gemini-old", isDefault: true, aliases: ["antigravity-default"] }),
model({ slug: "gemini-new" }),
];
assert.deepStrictEqual(ModelManifest.applyManifestDefault(models, manifest, driver), [
model({ slug: "gemini-old" }),
model({ slug: "gemini-new", isDefault: true, aliases: ["antigravity-default"] }),
]);
// The account does not offer the manifest default: keep the runtime's choice.
assert.deepStrictEqual(
ModelManifest.applyManifestDefault(models.slice(0, 1), manifest, driver),
models.slice(0, 1),
);
});
});
describe("applyModelManifest", () => {
const manifest: ModelManifest.ModelManifestData = {
version: 1,
currentModels: {},
providers: {
codex: {
profiles: {},
models: [
{
slug: "gpt-next",
name: "GPT Next",
status: "current",
badge: "new",
adapter: { codex: { minVersion: "1.2.0" } },
},
{ slug: "gpt-unversioned", name: "GPT Unversioned", status: "current" },
{
slug: "gpt-retired",
name: "GPT Retired",
status: "legacy",
adapter: { codex: { minVersion: "1.2.0" } },
},
],
},
},
};
const draft = (version: string | null, models: ReadonlyArray<ServerProviderModel> = []) => ({
enabled: true,
installed: true,
version,
status: "ready" as const,
auth: { status: "authenticated" as const },
checkedAt: "2026-01-01T00:00:00.000Z",
models,
slashCommands: [],
skills: [],
});
it("names current Codex models that need a newer CLI and are missing from discovery", () => {
assert.deepStrictEqual(
ModelManifest.applyModelManifest(draft("1.1.9"), manifest, CODEX).updateRequiredModels,
[{ slug: "gpt-next", name: "GPT Next", badge: "new", minVersion: "1.2.0" }],
);
for (const result of [
// The CLI is new enough.
ModelManifest.applyModelManifest(draft("1.2.0"), manifest, CODEX),
// The CLI already lists the model, even under a qualified slug.
ModelManifest.applyModelManifest(
draft("1.1.9", [model({ slug: "openai.gpt-next" })]),
manifest,
CODEX,
),
// An unknown version cannot be compared.
ModelManifest.applyModelManifest(draft(null), manifest, CODEX),
// A qualified manifest slug still matches the discovered family.
ModelManifest.applyModelManifest(
draft("1.1.9", [model({ slug: "gpt-next" })]),
{
...manifest,
providers: {
codex: {
profiles: {},
models: [{ ...manifest.providers!.codex!.models[0]!, slug: "openai.gpt-next" }],
},
},
},
CODEX,
),
]) {
assert.isUndefined(result.updateRequiredModels);
}
});
});
describe("resolveProviderCatalog", () => {
it("resolves generic model presentation through a reusable profile", () => {
const manifest: ModelManifest.ModelManifestData = {
@@ -268,18 +62,16 @@ describe("resolveProviderCatalog", () => {
ProviderDriverKind.make("synthetic"),
);
assert.deepStrictEqual(catalog?.models[0], {
model: {
slug: "model-next",
name: "Model Next",
aliases: ["next"],
badge: "new",
isCustom: false,
isDefault: true,
capabilities: manifest.providers!.synthetic!.profiles.standard!.capabilities!,
},
slug: "model-next",
name: "Model Next",
aliases: ["next"],
badge: "new",
status: "current",
capabilities: manifest.providers!.synthetic!.profiles.standard!.capabilities!,
adapter: undefined,
profileAdapter: { opaque: true },
});
assert.strictEqual(catalog?.defaultChatModel, "model-next");
});
it("rejects invalid catalog references", () => {
+39 -177
View File
@@ -17,17 +17,12 @@ import {
ModelCapabilities,
TrimmedNonEmptyString,
type ProviderDriverKind,
type ServerProviderModel,
type ServerProviderUpdateRequiredModel,
} from "@t3tools/contracts";
import { codexModelFamily } from "@t3tools/shared/model";
import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
@@ -39,7 +34,7 @@ import * as ServerSettings from "../serverSettings.ts";
import { hasValidClaudeManifestAdapters } from "./ClaudeModelManifest.ts";
import bundledManifestJson from "./model-manifest.json" with { type: "json" };
import { ProviderCompatibilityPolicy } from "./providerCompatibility.ts";
import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
const MODEL_MANIFEST_URL =
"https://raw.githubusercontent.com/pingdotgg/t3code/main/apps/server/src/provider/model-manifest.json";
@@ -126,19 +121,6 @@ const ModelManifestSchema = ModelManifestEnvelopeSchema.pipe(
);
export type ModelManifestData = typeof ModelManifestSchema.Type;
export interface ResolvedManifestModel {
readonly model: ServerProviderModel;
readonly adapter: unknown;
readonly profileAdapter: unknown;
}
export interface ResolvedProviderCatalog {
readonly models: ReadonlyArray<ResolvedManifestModel>;
readonly defaults: {
readonly chat: string | undefined;
};
}
const decodeManifest = Schema.decodeUnknownEffect(ModelManifestSchema);
export const BUNDLED_MODEL_MANIFEST: ModelManifestData =
@@ -151,16 +133,19 @@ function manifestUpdatedAtMs(manifest: ModelManifestData): number {
return Number.isNaN(parsed) ? 0 : parsed;
}
/** Resolve provider-neutral model presentation and capability data. */
/**
* A driver's catalog entry as provider packages see it, or `null` when the
* manifest has none or its references are invalid.
*/
export function resolveProviderCatalog(
manifest: ModelManifestData,
driverKind: ProviderDriverKind,
): ResolvedProviderCatalog | null {
): ModelCatalog.ProviderCatalog | null {
const catalog = manifest.providers?.[driverKind];
if (!catalog) return null;
const seen = new Set<string>();
const models: Array<ResolvedManifestModel> = [];
const models: Array<ModelCatalog.ProviderCatalogModel> = [];
for (const entry of catalog.models) {
if (seen.has(entry.slug)) return null;
seen.add(entry.slug);
@@ -169,18 +154,14 @@ export function resolveProviderCatalog(
if (entry.profile && !profile) return null;
models.push({
model: {
slug: entry.slug,
name: entry.name,
...(entry.shortName ? { shortName: entry.shortName } : {}),
...(entry.subProvider ? { subProvider: entry.subProvider } : {}),
...(entry.aliases ? { aliases: entry.aliases } : {}),
...(entry.badge ? { badge: entry.badge } : {}),
isCustom: false,
...(catalog.defaults?.chat === entry.slug ? { isDefault: true } : {}),
...(entry.status === "legacy" ? { isLegacy: true } : {}),
capabilities: profile?.capabilities ?? null,
},
slug: entry.slug,
name: entry.name,
...(entry.shortName ? { shortName: entry.shortName } : {}),
...(entry.subProvider ? { subProvider: entry.subProvider } : {}),
...(entry.aliases ? { aliases: entry.aliases } : {}),
...(entry.badge ? { badge: entry.badge } : {}),
status: entry.status,
capabilities: profile?.capabilities ?? null,
adapter: entry.adapter,
profileAdapter: profile?.adapter,
});
@@ -188,12 +169,7 @@ export function resolveProviderCatalog(
if (catalog.defaults?.chat !== undefined && !seen.has(catalog.defaults.chat)) return null;
return {
models,
defaults: {
chat: catalog.defaults?.chat,
},
};
return { models, defaultChatModel: catalog.defaults?.chat };
}
/** On-disk shape of the last successfully fetched manifest. */
@@ -213,142 +189,6 @@ export const encodeManifestCache = Schema.encodeEffect(
),
);
/** True when the manifest classifies `slug` as legacy for `driverKind`. */
function isLegacyModel(
manifest: ModelManifestData,
driverKind: ProviderDriverKind,
slug: string,
): boolean {
const family = driverKind === "codex" ? codexModelFamily(slug) : slug;
const catalog = manifest.providers?.[driverKind]?.models;
const catalogModel =
catalog?.find((model) => model.slug === slug) ??
catalog?.find((model) => model.slug === family);
return catalogModel?.status === "legacy";
}
/**
* Reclassifies every built-in model on a snapshot draft against the manifest.
* Custom models are user-defined and never reclassified.
*/
export function applyModelManifest(
draft: ServerProviderDraft,
manifest: ModelManifestData,
driverKind: ProviderDriverKind,
): ServerProviderDraft {
const { updateRequiredModels: _previous, ...rest } = draft;
const updateRequiredModels =
driverKind === "codex" ? codexUpdateRequiredModels(manifest, draft) : [];
return {
...rest,
models: applyManifestDefault(
classifyModels(draft.models, manifest, driverKind),
manifest,
driverKind,
),
...(updateRequiredModels.length > 0 ? { updateRequiredModels } : {}),
};
}
const CodexModelAdapter = Schema.Struct({
codex: Schema.optional(Schema.Struct({ minVersion: Schema.optional(TrimmedNonEmptyString) })),
});
const decodeCodexModelAdapter = Schema.decodeUnknownOption(CodexModelAdapter);
/**
* Codex lists only the models its own build knows, so a model released after
* the installed CLI never shows up. A current manifest entry with
* `adapter.codex.minVersion` names that model, letting the picker say an update
* unlocks it instead of leaving users to wonder where it is.
*/
function codexUpdateRequiredModels(
manifest: ModelManifestData,
draft: ServerProviderDraft,
): ReadonlyArray<ServerProviderUpdateRequiredModel> {
const version = draft.version?.replace(/^v/, "");
if (!version || parseSemver(version) === null) return [];
const discovered = new Set(draft.models.map((model) => codexModelFamily(model.slug)));
return (manifest.providers?.codex?.models ?? []).flatMap((entry) => {
if (entry.status !== "current" || discovered.has(codexModelFamily(entry.slug))) return [];
const minVersion = Option.getOrUndefined(decodeCodexModelAdapter(entry.adapter ?? {}))?.codex
?.minVersion;
if (!minVersion || parseSemver(minVersion) === null) return [];
if (compareSemverVersions(version, minVersion) >= 0) return [];
return [
{
slug: entry.slug,
name: entry.name,
...(entry.badge ? { badge: entry.badge } : {}),
minVersion,
},
];
});
}
/** The manifest's chat default for `driverKind`, when it names one. */
export function manifestDefaultModel(
manifest: ModelManifestData,
driverKind: ProviderDriverKind,
): string | undefined {
return manifest.providers?.[driverKind]?.defaults?.chat;
}
/**
* Moves `isDefault` to the manifest's chat default when the catalog carries
* it. Providers that learn their default from the runtime (Antigravity takes
* Google's current model) can be overridden here without a release. Aliases
* that pointed at the old default move with the flag so the shared
* "provider default" alias keeps resolving.
*/
export function applyManifestDefault(
models: ReadonlyArray<ServerProviderModel>,
manifest: ModelManifestData,
driverKind: ProviderDriverKind,
): ReadonlyArray<ServerProviderModel> {
const requestedSlug = manifestDefaultModel(manifest, driverKind);
if (requestedSlug === undefined) return models;
const slug =
models.find((model) => model.slug === requestedSlug)?.slug ??
(driverKind === "codex"
? models.find(
(model) =>
!model.isCustom && codexModelFamily(model.slug) === codexModelFamily(requestedSlug),
)?.slug
: undefined);
if (slug === undefined) return models;
const previous = models.find((model) => model.isDefault && model.slug !== slug);
if (!previous) return models;
const movedAliases = previous.aliases ?? [];
return models.map((model) => {
if (model.slug === previous.slug) {
const { isDefault: _isDefault, aliases: _aliases, ...rest } = model;
return rest;
}
if (model.slug === slug) {
const aliases = [...new Set([...(model.aliases ?? []), ...movedAliases])];
return { ...model, isDefault: true, ...(aliases.length > 0 ? { aliases } : {}) };
}
return model;
});
}
/** Model-level half of `applyModelManifest`, exported for focused tests. */
export function classifyModels(
models: ReadonlyArray<ServerProviderModel>,
manifest: ModelManifestData,
driverKind: ProviderDriverKind,
): ReadonlyArray<ServerProviderModel> {
return models.map((model) => {
if (model.isCustom) return model;
if (isLegacyModel(manifest, driverKind, model.slug)) {
return model.isLegacy ? model : { ...model, isLegacy: true };
}
if (!model.isLegacy) return model;
const { isLegacy: _isLegacy, ...rest } = model;
return rest;
});
}
export class ModelManifest extends Context.Service<
ModelManifest,
{
@@ -374,7 +214,7 @@ const BundledOnlyModelManifest: ModelManifest["Service"] = {
refreshInBackground: Effect.void,
};
export const layerTest = Layer.succeed(ModelManifest, BundledOnlyModelManifest);
const layerBundledOnly = Layer.succeed(ModelManifest, BundledOnlyModelManifest);
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -470,3 +310,25 @@ export const make = Effect.gen(function* () {
});
export const layer = Layer.effect(ModelManifest, make);
/** Bundled data only, with the provider catalog port drivers read; for tests. */
export const layerTest = Layer.suspend(() =>
layerModelCatalog.pipe(Layer.provideMerge(layerBundledOnly)),
);
/** Exposes the manifest to provider packages as their per-driver catalogs. */
export const layerModelCatalog = Layer.effect(
ModelCatalog.ModelCatalog,
Effect.gen(function* () {
const manifest = yield* ModelManifest;
return ModelCatalog.ModelCatalog.of({
current: (driverKind) =>
manifest.current.pipe(
Effect.map((data) => resolveProviderCatalog(data, driverKind) ?? undefined),
),
bundled: (driverKind) =>
resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, driverKind) ?? undefined,
refreshInBackground: manifest.refreshInBackground,
});
}),
);
@@ -0,0 +1,91 @@
import { assert, describe, it } from "@effect/vitest";
import type { ServerProviderModel } from "@t3tools/contracts";
import type * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
import { applyCodexModelCatalog } from "./codexModelCatalog.ts";
/** Synthetic models only; real Codex model data lives in model-manifest.json. */
const model = (overrides: Partial<ServerProviderModel>): ServerProviderModel => ({
slug: "gpt-test",
name: "GPT Test",
isCustom: false,
capabilities: null,
...overrides,
});
const entry = (
overrides: Partial<ModelCatalog.ProviderCatalogModel> & { readonly slug: string },
): ModelCatalog.ProviderCatalogModel => ({
name: overrides.slug,
status: "current",
capabilities: null,
adapter: undefined,
profileAdapter: undefined,
...overrides,
});
const catalog: ModelCatalog.ProviderCatalog = {
defaultChatModel: undefined,
models: [
entry({
slug: "gpt-next",
name: "GPT Next",
badge: "new",
adapter: { codex: { minVersion: "1.2.0" } },
}),
entry({ slug: "gpt-unversioned" }),
entry({ slug: "gpt-retired", status: "legacy", adapter: { codex: { minVersion: "1.2.0" } } }),
],
};
const draft = (version: string | null, models: ReadonlyArray<ServerProviderModel> = []) => ({
enabled: true,
installed: true,
version,
status: "ready" as const,
auth: { status: "authenticated" as const },
checkedAt: "2026-01-01T00:00:00.000Z",
models,
slashCommands: [],
skills: [],
});
describe("applyCodexModelCatalog", () => {
it("names current models that need a newer Codex and are missing from discovery", () => {
assert.deepStrictEqual(applyCodexModelCatalog(draft("1.1.9"), catalog).updateRequiredModels, [
{ slug: "gpt-next", name: "GPT Next", badge: "new", minVersion: "1.2.0" },
]);
for (const result of [
// The CLI is new enough.
applyCodexModelCatalog(draft("1.2.0"), catalog),
// The CLI already lists the model, even under a qualified slug.
applyCodexModelCatalog(draft("1.1.9", [model({ slug: "openai.gpt-next" })]), catalog),
// An unknown version cannot be compared.
applyCodexModelCatalog(draft(null), catalog),
// A qualified catalog slug still matches the discovered family.
applyCodexModelCatalog(draft("1.1.9", [model({ slug: "gpt-next" })]), {
...catalog,
models: [{ ...catalog.models[0]!, slug: "openai.gpt-next" }],
}),
]) {
assert.isUndefined(result.updateRequiredModels);
}
});
it("classifies qualified Codex families without changing their wire ids", () => {
const classified = applyCodexModelCatalog(
draft("1.2.0", [
model({ slug: "openai.gpt-test", isLegacy: true }),
model({ slug: "openai.gpt-retired" }),
]),
catalog,
);
assert.deepStrictEqual(
classified.models.map((entry) => [entry.slug, entry.isLegacy ?? false]),
[
["openai.gpt-test", false],
["openai.gpt-retired", true],
],
);
});
});
@@ -0,0 +1,65 @@
/**
* Codex's view of its manifest catalog. Codex discovers models from its app
* server, so the catalog only reclassifies them, moves the default, and names
* models a newer Codex build would unlock.
*
* @module provider/codexModelCatalog
*/
import type { ServerProviderUpdateRequiredModel } from "@t3tools/contracts";
import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
import { codexModelFamily } from "@t3tools/shared/model";
import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
/** Dated Codex builds match their base model's catalog entry. */
const CODEX_MATCHING: ModelCatalog.CatalogMatching = { family: codexModelFamily };
const CodexModelAdapter = Schema.Struct({
codex: Schema.optional(Schema.Struct({ minVersion: Schema.optional(TrimmedNonEmptyString) })),
});
const decodeCodexModelAdapter = Schema.decodeUnknownOption(CodexModelAdapter);
/**
* Codex lists only the models its own build knows, so a model released after
* the installed CLI never shows up. A current catalog entry with
* `adapter.codex.minVersion` names that model, letting the picker say an update
* unlocks it instead of leaving users to wonder where it is.
*/
function codexUpdateRequiredModels(
catalog: ModelCatalog.ProviderCatalog | undefined,
draft: ServerProviderDraft,
): ReadonlyArray<ServerProviderUpdateRequiredModel> {
const version = draft.version?.replace(/^v/, "");
if (!catalog || !version || parseSemver(version) === null) return [];
const discovered = new Set(draft.models.map((model) => codexModelFamily(model.slug)));
return catalog.models.flatMap((entry) => {
if (entry.status !== "current" || discovered.has(codexModelFamily(entry.slug))) return [];
const minVersion = Option.getOrUndefined(decodeCodexModelAdapter(entry.adapter ?? {}))?.codex
?.minVersion;
if (!minVersion || parseSemver(minVersion) === null) return [];
if (compareSemverVersions(version, minVersion) >= 0) return [];
return [
{
slug: entry.slug,
name: entry.name,
...(entry.badge ? { badge: entry.badge } : {}),
minVersion,
},
];
});
}
/** Reclassifies a Codex snapshot draft's models against its catalog. */
export function applyCodexModelCatalog(
draft: ServerProviderDraft,
catalog: ModelCatalog.ProviderCatalog | undefined,
): ServerProviderDraft {
const updateRequiredModels = codexUpdateRequiredModels(catalog, draft);
return {
...ModelCatalog.applyModelCatalog(draft, catalog, CODEX_MATCHING),
...(updateRequiredModels.length > 0 ? { updateRequiredModels } : {}),
};
}
+8 -4
View File
@@ -604,11 +604,15 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe(
// the rewritten telemetry pipeline can account for logical NDJSON writes.
// Provided once at the runtime level so every consumer sees the same
// logger instances.
// `ModelManifest.layer` is the legacy-model classification data, refreshed
// from the repo's `model-manifest.json` on `main` and applied by the
// Codex/Claude drivers.
// `ModelManifest.layer` is the model manifest, refreshed from the repo's
// `model-manifest.json` on `main`. Drivers read their entry through the
// `ModelCatalog` port it provides.
Layer.provideMerge(
Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer, ResetCreditCoordinator.layer),
Layer.mergeAll(
ProviderEventLoggers.layer,
ModelManifest.layerModelCatalog.pipe(Layer.provideMerge(ModelManifest.layer)),
ResetCreditCoordinator.layer,
),
),
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
// `ProviderRegistry.layer` pulled `OpenCodeRuntimeLive` in for itself, but
+4 -1
View File
@@ -11,7 +11,10 @@ correct model data before the next successful fetch. Bump `updatedAt` whenever t
file changes. Fetch time cannot establish which copy contains the newer edit.
Generic catalog data describes presentation and capabilities. Each provider owns
its adapter schema and dispatch mappings. Claude uses the manifest for its entire
its adapter schema and dispatch mappings. Providers never read the manifest
itself: the server exposes each driver's entry through the
[`ModelCatalog`](../../packages/provider-core/src/server/ModelCatalog.ts) port,
and compatibility policies stay with the server. Claude uses the manifest for its entire
built-in catalog. Adding a model with an existing capability profile is a JSON
edit; a new profile is needed only for a new capability combination. Codex still
gets its model list from its app server.
+4
View File
@@ -75,6 +75,10 @@
"types": "./src/server/mcpToolPresentation.ts",
"import": "./src/server/mcpToolPresentation.ts"
},
"./server/ModelCatalog": {
"types": "./src/server/ModelCatalog.ts",
"import": "./src/server/ModelCatalog.ts"
},
"./server/nativeProtocolLogging": {
"types": "./src/server/nativeProtocolLogging.ts",
"import": "./src/server/nativeProtocolLogging.ts"
@@ -0,0 +1,126 @@
import { assert, describe, it } from "@effect/vitest";
import type { ServerProviderModel } from "@t3tools/contracts";
import * as ModelCatalog from "./ModelCatalog.ts";
/**
* Covers catalog semantics with synthetic models. Real model data lives in the
* server's model-manifest.json and is not asserted here.
*/
const model = (overrides: Partial<ServerProviderModel>): ServerProviderModel => ({
slug: "model-test",
name: "Model Test",
isCustom: false,
capabilities: null,
...overrides,
});
const catalogModel = (
slug: string,
status: ModelCatalog.ProviderCatalogModel["status"],
): ModelCatalog.ProviderCatalogModel => ({
slug,
name: slug,
status,
capabilities: null,
adapter: undefined,
profileAdapter: undefined,
});
/** Strips a vendor prefix, the way a driver maps qualified slugs to catalog families. */
const prefixFamily: ModelCatalog.CatalogMatching = {
family: (slug) => slug.replace(/^vendor\./, ""),
};
describe("classifyCatalogModels", () => {
it("flags only known legacy models, clears stale flags, and skips custom models", () => {
const catalog: ModelCatalog.ProviderCatalog = {
models: [catalogModel("old-model", "legacy")],
defaultChatModel: undefined,
};
const models = [
model({ slug: "current-a" }),
// Stale flag from a previous classification pass must be cleared.
model({ slug: "current-b", isLegacy: true }),
model({ slug: "old-model" }),
// Custom models are user-defined and never reclassified.
model({ slug: "my-own-model", isCustom: true, isLegacy: true }),
];
assert.deepStrictEqual(
ModelCatalog.classifyCatalogModels(models, catalog).map((entry) => [
entry.slug,
entry.isLegacy ?? false,
]),
[
["current-a", false],
["current-b", false],
["old-model", true],
["my-own-model", true],
],
);
});
it("matches qualified slugs through the driver's family without changing their ids", () => {
const catalog: ModelCatalog.ProviderCatalog = {
models: [catalogModel("model-old", "legacy")],
defaultChatModel: undefined,
};
assert.deepStrictEqual(
ModelCatalog.classifyCatalogModels(
[model({ slug: "vendor.model-test", isLegacy: true }), model({ slug: "vendor.model-old" })],
catalog,
prefixFamily,
).map((entry) => [entry.slug, entry.isLegacy ?? false]),
[
["vendor.model-test", false],
["vendor.model-old", true],
],
);
});
it("keeps discovered models current when the driver has no catalog", () => {
assert.deepStrictEqual(
ModelCatalog.classifyCatalogModels([model({ slug: "new", isLegacy: true })], undefined),
[model({ slug: "new" })],
);
});
});
describe("applyCatalogDefault", () => {
it("moves the default flag and its aliases to the catalog's chat default", () => {
const catalog: ModelCatalog.ProviderCatalog = {
models: [catalogModel("model-new", "current")],
defaultChatModel: "model-new",
};
const models = [
model({ slug: "model-old", isDefault: true, aliases: ["provider-default"] }),
model({ slug: "model-new" }),
];
assert.deepStrictEqual(ModelCatalog.applyCatalogDefault(models, catalog), [
model({ slug: "model-old" }),
model({ slug: "model-new", isDefault: true, aliases: ["provider-default"] }),
]);
// The account does not offer the catalog default: keep the runtime's choice.
assert.deepStrictEqual(
ModelCatalog.applyCatalogDefault(models.slice(0, 1), catalog),
models.slice(0, 1),
);
});
it("resolves the catalog default to a qualified discovered model", () => {
const catalog: ModelCatalog.ProviderCatalog = {
models: [],
defaultChatModel: "model-test",
};
const models = [
model({ slug: "vendor.model-old", isDefault: true }),
model({ slug: "vendor.model-test" }),
];
assert.strictEqual(
ModelCatalog.applyCatalogDefault(models, catalog, prefixFamily).find(
(entry) => entry.isDefault,
)?.slug,
"vendor.model-test",
);
});
});
@@ -0,0 +1,171 @@
/**
* ModelCatalog — the model metadata a provider reads from T3's model manifest.
*
* The server owns the manifest itself (bundle, remote refresh, disk cache,
* compatibility policies). A provider only sees its own catalog entry, so a
* provider package never depends on the manifest file or how it is fetched.
* Reads never wait on the network.
*
* @module provider-core/server/ModelCatalog
*/
import type {
ModelCapabilities,
ProviderDriverKind,
ServerProviderModel,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type { ServerProviderDraft } from "./snapshotProbe.ts";
/** One model entry in a provider's manifest catalog. */
export interface ProviderCatalogModel {
readonly slug: string;
readonly name: string;
readonly shortName?: string;
readonly subProvider?: string;
readonly aliases?: ReadonlyArray<string>;
readonly status: "current" | "legacy";
readonly badge?: "new";
readonly capabilities: ModelCapabilities | null;
/** Provider-owned metadata for this model; the provider decodes it. */
readonly adapter: unknown;
/** Provider-owned metadata for the model's capability profile. */
readonly profileAdapter: unknown;
}
/** A provider's catalog entry: its models and the chat default. */
export interface ProviderCatalog {
readonly models: ReadonlyArray<ProviderCatalogModel>;
readonly defaultChatModel: string | undefined;
}
export class ModelCatalog extends Context.Service<
ModelCatalog,
{
/**
* The driver's catalog from the manifest in memory (disk cache or bundle),
* or `undefined` when the manifest has no entry for it. Never fetches.
*/
readonly current: (
driverKind: ProviderDriverKind,
) => Effect.Effect<ProviderCatalog | undefined>;
/** The same catalog from the bundled manifest; for fallbacks when remote data is invalid. */
readonly bundled: (driverKind: ProviderDriverKind) => ProviderCatalog | undefined;
/**
* Starts a TTL-gated remote refresh in the background. Provider checks call
* this; it never fails and never blocks the check.
*/
readonly refreshInBackground: Effect.Effect<void>;
}
>()("@t3tools/provider-core/server/ModelCatalog") {}
/** A catalog model as the snapshot model it presents. */
export const catalogServerModel = (
catalog: ProviderCatalog,
entry: ProviderCatalogModel,
): ServerProviderModel => ({
slug: entry.slug,
name: entry.name,
...(entry.shortName ? { shortName: entry.shortName } : {}),
...(entry.subProvider ? { subProvider: entry.subProvider } : {}),
...(entry.aliases ? { aliases: entry.aliases } : {}),
...(entry.badge ? { badge: entry.badge } : {}),
isCustom: false,
...(catalog.defaultChatModel === entry.slug ? { isDefault: true } : {}),
...(entry.status === "legacy" ? { isLegacy: true } : {}),
capabilities: entry.capabilities,
});
/** How a driver matches its discovered slugs to catalog entries. */
export interface CatalogMatching {
/**
* Maps a slug to the family the catalog names it by, such as a dated Codex
* build to its base model. Defaults to the slug itself.
*/
readonly family?: (slug: string) => string;
}
const familyOf = (matching: CatalogMatching | undefined, slug: string) =>
matching?.family?.(slug) ?? slug;
/**
* Reclassifies built-in models as legacy or current from the catalog. Custom
* models are user-defined and never reclassified.
*/
export function classifyCatalogModels(
models: ReadonlyArray<ServerProviderModel>,
catalog: ProviderCatalog | undefined,
matching?: CatalogMatching,
): ReadonlyArray<ServerProviderModel> {
return models.map((model) => {
if (model.isCustom) return model;
const entry =
catalog?.models.find((candidate) => candidate.slug === model.slug) ??
catalog?.models.find((candidate) => candidate.slug === familyOf(matching, model.slug));
if (entry?.status === "legacy") return model.isLegacy ? model : { ...model, isLegacy: true };
if (!model.isLegacy) return model;
const { isLegacy: _isLegacy, ...rest } = model;
return rest;
});
}
/**
* Moves `isDefault` to the catalog's chat default when the catalog names one
* the models include. Providers that learn their default from the runtime can
* be overridden here without a release. Aliases that pointed at the old
* default move with the flag so the shared "provider default" alias keeps
* resolving.
*/
export function applyCatalogDefault(
models: ReadonlyArray<ServerProviderModel>,
catalog: ProviderCatalog | undefined,
matching?: CatalogMatching,
): ReadonlyArray<ServerProviderModel> {
const requestedSlug = catalog?.defaultChatModel;
if (requestedSlug === undefined) return models;
const slug =
models.find((model) => model.slug === requestedSlug)?.slug ??
(matching?.family === undefined
? undefined
: models.find(
(model) =>
!model.isCustom && familyOf(matching, model.slug) === familyOf(matching, requestedSlug),
)?.slug);
if (slug === undefined) return models;
const previous = models.find((model) => model.isDefault && model.slug !== slug);
if (!previous) return models;
const movedAliases = previous.aliases ?? [];
return models.map((model) => {
if (model.slug === previous.slug) {
const { isDefault: _isDefault, aliases: _aliases, ...rest } = model;
return rest;
}
if (model.slug === slug) {
const aliases = [...new Set([...(model.aliases ?? []), ...movedAliases])];
return { ...model, isDefault: true, ...(aliases.length > 0 ? { aliases } : {}) };
}
return model;
});
}
/**
* Reclassifies a snapshot draft's built-in models and moves its default from
* the catalog. Drivers that announce models a newer CLI unlocks add
* `updateRequiredModels` themselves; this clears a stale list.
*/
export function applyModelCatalog(
draft: ServerProviderDraft,
catalog: ProviderCatalog | undefined,
matching?: CatalogMatching,
): ServerProviderDraft {
const { updateRequiredModels: _previous, ...rest } = draft;
return {
...rest,
models: applyCatalogDefault(
classifyCatalogModels(draft.models, catalog, matching),
catalog,
matching,
),
};
}