Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ModelManifest.ts

472 lines18.3 KB

1/**
2 * ModelManifest — remote provider-model metadata with a bundled offline
3 * fallback.
4 *
5 * Provider catalogs and legacy classification live in `model-manifest.json`.
6 * The bundled copy ships with every release; at runtime the service refreshes
7 * it from the same file on `main`. Preference order is remote, then the last
8 * successful on-disk copy, then the bundle. A failed fetch never fails a
9 * provider check.
10 *
11 * Providers with authoritative discovery can use only the classification
12 * overlay. Providers with static catalogs can resolve presentation and
13 * capabilities from `providers`, then decode their own allowlisted adapter
14 * payload separately.
15 */
16import {
17 ModelCapabilities,
18 TrimmedNonEmptyString,
19 type ProviderDriverKind,
20 type ServerProviderModel,
21 type ServerProviderUpdateRequiredModel,
22} from "@t3tools/contracts";
23import { codexModelFamily } from "@t3tools/shared/model";
24import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
25import * as Clock from "effect/Clock";
26import * as Context from "effect/Context";
27import * as Effect from "effect/Effect";
28import * as FileSystem from "effect/FileSystem";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Path from "effect/Path";
32import * as Schema from "effect/Schema";
33import * as Semaphore from "effect/Semaphore";
34import { HttpClient, HttpClientResponse } from "effect/http";
35​
36import { writeFileStringAtomically } from "../atomicWrite.ts";
37import { ServerConfig } from "../config.ts";
38import * as ServerSettings from "../serverSettings.ts";
39import { hasValidClaudeManifestAdapters } from "./ClaudeModelManifest.ts";
40import bundledManifestJson from "./model-manifest.json" with { type: "json" };
41import { ProviderCompatibilityPolicy } from "./providerCompatibility.ts";
42import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
43​
44const MODEL_MANIFEST_URL =
45 "https://raw.githubusercontent.com/pingdotgg/t3code/main/apps/server/src/provider/model-manifest.json";
46​
47/** How long a fetched manifest stays fresh before the next probe re-fetches. */
48const MANIFEST_TTL_MS = 60 * 60 * 1000;
49​
50/** Minimum gap between fetch attempts after a failure, so an offline server
51 * does not pay a network timeout on every provider check. */
52const MANIFEST_RETRY_MS = 5 * 60 * 1000;
53​
54const FETCH_TIMEOUT_MS = 10_000;
55​
56const ManifestModelStatus = Schema.Literals(["current", "legacy"]);
57​
58const ManifestModelProfile = Schema.Struct({
59 capabilities: Schema.optional(ModelCapabilities),
60 adapter: Schema.optional(Schema.Unknown),
61});
62​
63const ManifestProviderModel = Schema.Struct({
64 slug: TrimmedNonEmptyString,
65 name: TrimmedNonEmptyString,
66 shortName: Schema.optional(TrimmedNonEmptyString),
67 subProvider: Schema.optional(TrimmedNonEmptyString),
68 aliases: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
69 status: ManifestModelStatus,
70 badge: Schema.optional(Schema.Literal("new")),
71 profile: Schema.optional(TrimmedNonEmptyString),
72 adapter: Schema.optional(Schema.Unknown),
73});
74​
75const ManifestProviderCatalog = Schema.Struct({
76 defaults: Schema.optional(
77 Schema.Struct({
78 chat: Schema.optional(TrimmedNonEmptyString),
79 }),
80 ),
81 profiles: Schema.Record(Schema.String, ManifestModelProfile),
82 models: Schema.Array(ManifestProviderModel),
83});
84​
85/**
86 * `version` gates breaking schema changes. Provider catalogs are additive so
87 * clients that only understand `currentModels` keep accepting this v1 file.
88 */
89const ModelManifestEnvelopeSchema = Schema.Struct({
90 version: Schema.Literal(1),
91 /**
92 * ISO date of the last edit. A release bundles its manifest, and a disk
93 * cache of an older edit must not outrank it. Optional so older remote
94 * files still decode; they count as older than any dated bundle.
95 */
96 updatedAt: Schema.optional(Schema.String),
97 compatibility: Schema.optional(Schema.Array(ProviderCompatibilityPolicy)),
98 currentModels: Schema.Record(Schema.String, Schema.Array(Schema.String)),
99 providers: Schema.optional(Schema.Record(Schema.String, ManifestProviderCatalog)),
100});
101​
102const hasValidProviderCatalogReferences = (
103 manifest: typeof ModelManifestEnvelopeSchema.Type,
104): boolean =>
105 Object.values(manifest.providers ?? {}).every((catalog) => {
106 const slugs = new Set<string>();
107 const modelsAreValid = catalog.models.every((model) => {
108 if (slugs.has(model.slug)) return false;
109 slugs.add(model.slug);
110 return model.profile === undefined || catalog.profiles[model.profile] !== undefined;
111 });
112 return (
113 modelsAreValid && (catalog.defaults?.chat === undefined || slugs.has(catalog.defaults.chat))
114 );
115 });
116​
117const ModelManifestSchema = ModelManifestEnvelopeSchema.pipe(
118 Schema.check(
119 Schema.makeFilter(hasValidProviderCatalogReferences, {
120 expected: "unique model slugs and existing model and profile references",
121 }),
122 Schema.makeFilter(hasValidClaudeManifestAdapters, {
123 expected: "valid Claude adapter metadata",
124 }),
125 ),
126);
127export type ModelManifestData = typeof ModelManifestSchema.Type;
128​
129export interface ResolvedManifestModel {
130 readonly model: ServerProviderModel;
131 readonly adapter: unknown;
132 readonly profileAdapter: unknown;
134​
135export interface ResolvedProviderCatalog {
136 readonly models: ReadonlyArray<ResolvedManifestModel>;
137 readonly defaults: {
138 readonly chat: string | undefined;
139 };
141​
142const decodeManifest = Schema.decodeUnknownEffect(ModelManifestSchema);
143​
144export const BUNDLED_MODEL_MANIFEST: ModelManifestData =
145 Schema.decodeUnknownSync(ModelManifestSchema)(bundledManifestJson);
146​
147/** Epoch millis of the manifest's `updatedAt`, or 0 when absent or unparsable. */
148function manifestUpdatedAtMs(manifest: ModelManifestData): number {
149 if (manifest.updatedAt === undefined) return 0;
150 const parsed = Date.parse(manifest.updatedAt);
151 return Number.isNaN(parsed) ? 0 : parsed;
153​
154/** Resolve provider-neutral model presentation and capability data. */
155export function resolveProviderCatalog(
156 manifest: ModelManifestData,
157 driverKind: ProviderDriverKind,
158): ResolvedProviderCatalog | null {
159 const catalog = manifest.providers?.[driverKind];
160 if (!catalog) return null;
161​
162 const seen = new Set<string>();
163 const models: Array<ResolvedManifestModel> = [];
164 for (const entry of catalog.models) {
165 if (seen.has(entry.slug)) return null;
166 seen.add(entry.slug);
167​
168 const profile = entry.profile ? catalog.profiles[entry.profile] : undefined;
169 if (entry.profile && !profile) return null;
170​
171 models.push({
172 model: {
173 slug: entry.slug,
174 name: entry.name,
175 ...(entry.shortName ? { shortName: entry.shortName } : {}),
176 ...(entry.subProvider ? { subProvider: entry.subProvider } : {}),
177 ...(entry.aliases ? { aliases: entry.aliases } : {}),
178 ...(entry.badge ? { badge: entry.badge } : {}),
179 isCustom: false,
180 ...(catalog.defaults?.chat === entry.slug ? { isDefault: true } : {}),
181 ...(entry.status === "legacy" ? { isLegacy: true } : {}),
182 capabilities: profile?.capabilities ?? null,
183 },
184 adapter: entry.adapter,
185 profileAdapter: profile?.adapter,
186 });
187 }
188​
189 if (catalog.defaults?.chat !== undefined && !seen.has(catalog.defaults.chat)) return null;
190​
191 return {
192 models,
193 defaults: {
194 chat: catalog.defaults?.chat,
195 },
196 };
198​
199/** On-disk shape of the last successfully fetched manifest. */
200const ManifestCacheFile = Schema.Struct({
201 fetchedAtMs: Schema.Number,
202 manifest: ModelManifestSchema,
203});
204const decodeManifestCache = Schema.decodeUnknownEffect(
205 Schema.fromJsonString(
206 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
207 ),
208);
209/** Exported for tests that seed the disk cache. */
210export const encodeManifestCache = Schema.encodeEffect(
211 Schema.fromJsonString(
212 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
213 ),
214);
215​
216/** True when the manifest classifies `slug` as legacy for `driverKind`. */
217function isLegacyModel(
218 manifest: ModelManifestData,
219 driverKind: ProviderDriverKind,
220 slug: string,
221): boolean {
222 const family = driverKind === "codex" ? codexModelFamily(slug) : slug;
223 const catalog = manifest.providers?.[driverKind]?.models;
224 const catalogModel =
225 catalog?.find((model) => model.slug === slug) ??
226 catalog?.find((model) => model.slug === family);
227 return catalogModel?.status === "legacy";
229​
230/**
231 * Reclassifies every built-in model on a snapshot draft against the manifest.
232 * Custom models are user-defined and never reclassified.
233 */
234export function applyModelManifest(
235 draft: ServerProviderDraft,
236 manifest: ModelManifestData,
237 driverKind: ProviderDriverKind,
238): ServerProviderDraft {
239 const { updateRequiredModels: _previous, ...rest } = draft;
240 const updateRequiredModels =
241 driverKind === "codex" ? codexUpdateRequiredModels(manifest, draft) : [];
242 return {
243 ...rest,
244 models: applyManifestDefault(
245 classifyModels(draft.models, manifest, driverKind),
246 manifest,
247 driverKind,
248 ),
249 ...(updateRequiredModels.length > 0 ? { updateRequiredModels } : {}),
250 };
252​
253const CodexModelAdapter = Schema.Struct({
254 codex: Schema.optional(Schema.Struct({ minVersion: Schema.optional(TrimmedNonEmptyString) })),
255});
256const decodeCodexModelAdapter = Schema.decodeUnknownOption(CodexModelAdapter);
257​
258/**
259 * Codex lists only the models its own build knows, so a model released after
260 * the installed CLI never shows up. A current manifest entry with
261 * `adapter.codex.minVersion` names that model, letting the picker say an update
262 * unlocks it instead of leaving users to wonder where it is.
263 */
264function codexUpdateRequiredModels(
265 manifest: ModelManifestData,
266 draft: ServerProviderDraft,
267): ReadonlyArray<ServerProviderUpdateRequiredModel> {
268 const version = draft.version?.replace(/^v/, "");
269 if (!version || parseSemver(version) === null) return [];
270 const discovered = new Set(draft.models.map((model) => codexModelFamily(model.slug)));
271 return (manifest.providers?.codex?.models ?? []).flatMap((entry) => {
272 if (entry.status !== "current" || discovered.has(codexModelFamily(entry.slug))) return [];
273 const minVersion = Option.getOrUndefined(decodeCodexModelAdapter(entry.adapter ?? {}))?.codex
274 ?.minVersion;
275 if (!minVersion || parseSemver(minVersion) === null) return [];
276 if (compareSemverVersions(version, minVersion) >= 0) return [];
277 return [
278 {
279 slug: entry.slug,
280 name: entry.name,
281 ...(entry.badge ? { badge: entry.badge } : {}),
282 minVersion,
283 },
284 ];
285 });
287​
288/** The manifest's chat default for `driverKind`, when it names one. */
289export function manifestDefaultModel(
290 manifest: ModelManifestData,
291 driverKind: ProviderDriverKind,
292): string | undefined {
293 return manifest.providers?.[driverKind]?.defaults?.chat;
295​
296/**
297 * Moves `isDefault` to the manifest's chat default when the catalog carries
298 * it. Providers that learn their default from the runtime (Antigravity takes
299 * Google's current model) can be overridden here without a release. Aliases
300 * that pointed at the old default move with the flag so the shared
301 * "provider default" alias keeps resolving.
302 */
303export function applyManifestDefault(
304 models: ReadonlyArray<ServerProviderModel>,
305 manifest: ModelManifestData,
306 driverKind: ProviderDriverKind,
307): ReadonlyArray<ServerProviderModel> {
308 const requestedSlug = manifestDefaultModel(manifest, driverKind);
309 if (requestedSlug === undefined) return models;
310 const slug =
311 models.find((model) => model.slug === requestedSlug)?.slug ??
312 (driverKind === "codex"
313 ? models.find(
314 (model) =>
315 !model.isCustom && codexModelFamily(model.slug) === codexModelFamily(requestedSlug),
316 )?.slug
317 : undefined);
318 if (slug === undefined) return models;
319 const previous = models.find((model) => model.isDefault && model.slug !== slug);
320 if (!previous) return models;
321 const movedAliases = previous.aliases ?? [];
322 return models.map((model) => {
323 if (model.slug === previous.slug) {
324 const { isDefault: _isDefault, aliases: _aliases, ...rest } = model;
325 return rest;
326 }
327 if (model.slug === slug) {
328 const aliases = [...new Set([...(model.aliases ?? []), ...movedAliases])];
329 return { ...model, isDefault: true, ...(aliases.length > 0 ? { aliases } : {}) };
330 }
331 return model;
332 });
334​
335/** Model-level half of `applyModelManifest`, exported for focused tests. */
336export function classifyModels(
337 models: ReadonlyArray<ServerProviderModel>,
338 manifest: ModelManifestData,
339 driverKind: ProviderDriverKind,
340): ReadonlyArray<ServerProviderModel> {
341 return models.map((model) => {
342 if (model.isCustom) return model;
343 if (isLegacyModel(manifest, driverKind, model.slug)) {
344 return model.isLegacy ? model : { ...model, isLegacy: true };
345 }
346 if (!model.isLegacy) return model;
347 const { isLegacy: _isLegacy, ...rest } = model;
348 return rest;
349 });
351​
352export class ModelManifest extends Context.Service<
353 ModelManifest,
354 {
355 /** Manifest already in memory (disk cache or bundle); never fetches.
356 * Snapshot classification reads this, so it never waits on the network. */
357 readonly current: Effect.Effect<ModelManifestData>;
358 /** Manifest after a TTL-gated remote refresh; never fails. */
359 readonly refresh: Effect.Effect<ModelManifestData>;
360 /** Explicit refresh bypasses freshness and retry timers, retaining last-good data. */
361 readonly forceRefresh: Effect.Effect<ModelManifestData>;
362 /** Forks `refresh` into the service's own scope. Drivers call this from
363 * provider checks: the fetch is process-shared state, so it must survive
364 * the teardown of whichever instance happened to trigger it. */
365 readonly refreshInBackground: Effect.Effect<void>;
366 }
367>()("t3/provider/ModelManifest") {}
368​
369/** Constant service backing the bundled-data test layer. */
370const BundledOnlyModelManifest: ModelManifest["Service"] = {
371 current: Effect.succeed(BUNDLED_MODEL_MANIFEST),
372 refresh: Effect.succeed(BUNDLED_MODEL_MANIFEST),
373 forceRefresh: Effect.succeed(BUNDLED_MODEL_MANIFEST),
374 refreshInBackground: Effect.void,
375};
376​
377export const layerTest = Layer.succeed(ModelManifest, BundledOnlyModelManifest);
378​
379export const make = Effect.gen(function* () {
380 const fileSystem = yield* FileSystem.FileSystem;
381 const path = yield* Path.Path;
382 const config = yield* ServerConfig;
383 const settingsService = yield* ServerSettings.ServerSettingsService;
384 const httpClient = yield* HttpClient.HttpClient;
385 const serviceScope = yield* Effect.scope;
386​
387 const cachePath = path.join(config.stateDir, "model-manifest.json");
388 let manifest = BUNDLED_MODEL_MANIFEST;
389 let fetchedAtMs: number | null = null;
390 let lastAttemptMs: number | null = null;
391 const refreshSemaphore = yield* Semaphore.make(1);
392​
393 // `Effect.cached` makes concurrent first readers await the same disk load
394 // rather than racing a "loaded" flag. Only `refreshed` takes the fetch
395 // semaphore; `current` must never wait behind an in-flight network refresh.
396 const ensureDiskCacheLoaded = yield* Effect.cached(
397 Effect.gen(function* () {
398 const fromDisk = yield* fileSystem.readFileString(cachePath).pipe(
399 Effect.flatMap((raw) => decodeManifestCache(raw)),
400 Effect.catchCause(() => Effect.succeed(null)),
401 );
402 if (fromDisk === null) return;
403 // The disk copy is the last-seen remote manifest, so it outranks the
404 // bundle even when stale, unless the bundle's own edit date is newer
405 // than the cached manifest's. Then the release carries data the cache
406 // has not seen and the cache is dropped so the next refresh replaces
407 // it. Comparing edit dates, not fetch time, keeps this independent of
408 // when the cache was written relative to the release.
409 if (manifestUpdatedAtMs(BUNDLED_MODEL_MANIFEST) > manifestUpdatedAtMs(fromDisk.manifest)) {
410 return;
411 }
412 manifest = fromDisk.manifest;
413 fetchedAtMs = fromDisk.fetchedAtMs;
414 }),
415 );
416​
417 const refresh = Effect.fn("ModelManifest.refresh")(function* (force = false) {
418 yield* ensureDiskCacheLoaded;
419 const now = yield* Clock.currentTimeMillis;
420 // A timestamp in the future means the wall clock moved backwards (the
421 // disk cache crosses restarts, so monotonic time cannot cover it). Treat
422 // it as expired: the refetch rewrites both timestamps and self-heals.
423 const isWithin = (sinceMs: number | null, windowMs: number) =>
424 sinceMs !== null && now >= sinceMs && now - sinceMs < windowMs;
425 if (!force && isWithin(fetchedAtMs, MANIFEST_TTL_MS)) return manifest;
426 if (!force && isWithin(lastAttemptMs, MANIFEST_RETRY_MS)) return manifest;
427​
428 // The same switch that gates provider CLI update checks. It stops network
429 // fetches only: a manifest already cached on disk from an earlier fetch
430 // stays in effect, since the setting is about phoning home, not about
431 // discarding data the server already holds.
432 const settings = yield* settingsService.getSettings.pipe(
433 Effect.catchCause(() => Effect.succeed(null)),
434 );
435 if (settings !== null && !settings.enableProviderUpdateChecks) return manifest;
436​
437 lastAttemptMs = now;
438 const fetched = yield* httpClient.get(MODEL_MANIFEST_URL).pipe(
439 Effect.flatMap(HttpClientResponse.filterStatusOk),
440 Effect.flatMap((response) => response.json),
441 Effect.flatMap((json) => decodeManifest(json)),
442 Effect.timeout(FETCH_TIMEOUT_MS),
443 Effect.catchCause(() => Effect.succeed(null)),
444 );
445 // A CDN can still serve an earlier edit after a release. Apply the same
446 // freshness rule as the disk cache so it cannot undo bundled version gates.
447 if (fetched === null || manifestUpdatedAtMs(fetched) < manifestUpdatedAtMs(manifest)) {
448 return manifest;
449 }
450​
451 manifest = fetched;
452 fetchedAtMs = now;
453 yield* encodeManifestCache({ fetchedAtMs: now, manifest: fetched }).pipe(
454 Effect.flatMap((contents) => writeFileStringAtomically({ filePath: cachePath, contents })),
455 Effect.provideService(FileSystem.FileSystem, fileSystem),
456 Effect.provideService(Path.Path, path),
457 Effect.ignoreCause,
458 );
459 return manifest;
460 });
461​
462 const guardedRefresh = refreshSemaphore.withPermits(1)(refresh());
463​
464 return ModelManifest.of({
465 current: ensureDiskCacheLoaded.pipe(Effect.map(() => manifest)),
466 refresh: guardedRefresh,
467 forceRefresh: refreshSemaphore.withPermits(1)(refresh(true)),
468 refreshInBackground: Effect.forkIn(guardedRefresh, serviceScope).pipe(Effect.asVoid),
469 });
470});
471​
472export const layer = Layer.effect(ModelManifest, make);