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