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

ModelManifest.ts

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