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