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

ModelManifest.ts

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