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