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

ModelManifest.ts

342 lines12.7 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 * 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 currentModels: Schema.Record(Schema.String, Schema.Array(Schema.String)),
86 providers: Schema.optional(Schema.Record(Schema.String, ManifestProviderCatalog)),
87});
88​
89const hasValidProviderCatalogReferences = (
90 manifest: typeof ModelManifestEnvelopeSchema.Type,
91): boolean =>
92 Object.values(manifest.providers ?? {}).every((catalog) => {
93 const slugs = new Set<string>();
94 const modelsAreValid = catalog.models.every((model) => {
95 if (slugs.has(model.slug)) return false;
96 slugs.add(model.slug);
97 return model.profile === undefined || catalog.profiles[model.profile] !== undefined;
98 });
99 return (
100 modelsAreValid && (catalog.defaults?.chat === undefined || slugs.has(catalog.defaults.chat))
101 );
102 });
103​
104const ModelManifestSchema = ModelManifestEnvelopeSchema.pipe(
105 Schema.check(
106 Schema.makeFilter(hasValidProviderCatalogReferences, {
107 expected: "unique model slugs and existing model and profile references",
108 }),
109 Schema.makeFilter(hasValidClaudeManifestAdapters, {
110 expected: "valid Claude adapter metadata",
111 }),
112 ),
113);
114export type ModelManifestData = typeof ModelManifestSchema.Type;
115​
116export interface ResolvedManifestModel {
117 readonly model: ServerProviderModel;
118 readonly adapter: unknown;
119 readonly profileAdapter: unknown;
121​
122export interface ResolvedProviderCatalog {
123 readonly models: ReadonlyArray<ResolvedManifestModel>;
124 readonly defaults: {
125 readonly chat: string | undefined;
126 };
128​
129const decodeManifest = Schema.decodeUnknownEffect(ModelManifestSchema);
130​
131export const BUNDLED_MODEL_MANIFEST: ModelManifestData =
132 Schema.decodeUnknownSync(ModelManifestSchema)(bundledManifestJson);
133​
134/** Resolve provider-neutral model presentation and capability data. */
135export function resolveProviderCatalog(
136 manifest: ModelManifestData,
137 driverKind: ProviderDriverKind,
138): ResolvedProviderCatalog | null {
139 const catalog = manifest.providers?.[driverKind];
140 if (!catalog) return null;
141​
142 const seen = new Set<string>();
143 const models: Array<ResolvedManifestModel> = [];
144 for (const entry of catalog.models) {
145 if (seen.has(entry.slug)) return null;
146 seen.add(entry.slug);
147​
148 const profile = entry.profile ? catalog.profiles[entry.profile] : undefined;
149 if (entry.profile && !profile) return null;
150​
151 models.push({
152 model: {
153 slug: entry.slug,
154 name: entry.name,
155 ...(entry.shortName ? { shortName: entry.shortName } : {}),
156 ...(entry.subProvider ? { subProvider: entry.subProvider } : {}),
157 ...(entry.aliases ? { aliases: entry.aliases } : {}),
158 ...(entry.badge ? { badge: entry.badge } : {}),
159 isCustom: false,
160 ...(catalog.defaults?.chat === entry.slug ? { isDefault: true } : {}),
161 ...(entry.status === "legacy" ? { isLegacy: true } : {}),
162 capabilities: profile?.capabilities ?? null,
163 },
164 adapter: entry.adapter,
165 profileAdapter: profile?.adapter,
166 });
167 }
168​
169 if (catalog.defaults?.chat !== undefined && !seen.has(catalog.defaults.chat)) return null;
170​
171 return {
172 models,
173 defaults: {
174 chat: catalog.defaults?.chat,
175 },
176 };
178​
179/** On-disk shape of the last successfully fetched manifest. */
180const ManifestCacheFile = Schema.Struct({
181 fetchedAtMs: Schema.Number,
182 manifest: ModelManifestSchema,
183});
184const decodeManifestCache = Schema.decodeUnknownEffect(
185 Schema.fromJsonString(
186 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
187 ),
188);
189const encodeManifestCache = Schema.encodeEffect(
190 Schema.fromJsonString(
191 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
192 ),
193);
194​
195/** True when the manifest classifies `slug` as legacy for `driverKind`. */
196export function isLegacyModel(
197 manifest: ModelManifestData,
198 driverKind: ProviderDriverKind,
199 slug: string,
200): boolean {
201 const catalogModel = manifest.providers?.[driverKind]?.models.find(
202 (model) => model.slug === slug,
203 );
204 if (catalogModel) return catalogModel.status === "legacy";
205 const currentModels = manifest.currentModels[driverKind];
206 if (!currentModels) return false;
207 return !currentModels.includes(slug);
209​
210/**
211 * Reclassifies every built-in model on a snapshot draft against the manifest.
212 * Custom models are user-defined and never reclassified.
213 */
214export function applyModelManifest(
215 draft: ServerProviderDraft,
216 manifest: ModelManifestData,
217 driverKind: ProviderDriverKind,
218): ServerProviderDraft {
219 return { ...draft, models: classifyModels(draft.models, manifest, driverKind) };
221​
222/** Model-level half of `applyModelManifest`, exported for focused tests. */
223export function classifyModels(
224 models: ReadonlyArray<ServerProviderModel>,
225 manifest: ModelManifestData,
226 driverKind: ProviderDriverKind,
227): ReadonlyArray<ServerProviderModel> {
228 return models.map((model) => {
229 if (model.isCustom) return model;
230 if (isLegacyModel(manifest, driverKind, model.slug)) {
231 return model.isLegacy ? model : { ...model, isLegacy: true };
232 }
233 if (!model.isLegacy) return model;
234 const { isLegacy: _isLegacy, ...rest } = model;
235 return rest;
236 });
238​
239export class ModelManifest extends Context.Service<
240 ModelManifest,
241 {
242 /** Manifest already in memory (disk cache or bundle); never fetches.
243 * Snapshot classification reads this, so it never waits on the network. */
244 readonly current: Effect.Effect<ModelManifestData>;
245 /** Manifest after a TTL-gated remote refresh; never fails. */
246 readonly refresh: Effect.Effect<ModelManifestData>;
247 /** Forks `refresh` into the service's own scope. Drivers call this from
248 * provider checks: the fetch is process-shared state, so it must survive
249 * the teardown of whichever instance happened to trigger it. */
250 readonly refreshInBackground: Effect.Effect<void>;
251 }
252>()("t3/provider/ModelManifest") {}
253​
254/** Constant service for tests and callers that only need the bundled data. */
255export const BundledOnlyModelManifest: ModelManifest["Service"] = {
256 current: Effect.succeed(BUNDLED_MODEL_MANIFEST),
257 refresh: Effect.succeed(BUNDLED_MODEL_MANIFEST),
258 refreshInBackground: Effect.void,
259};
260​
261export const layerTest = Layer.succeed(ModelManifest, BundledOnlyModelManifest);
262​
263export const make = Effect.gen(function* () {
264 const fileSystem = yield* FileSystem.FileSystem;
265 const path = yield* Path.Path;
266 const config = yield* ServerConfig;
267 const settingsService = yield* ServerSettings.ServerSettingsService;
268 const httpClient = yield* HttpClient.HttpClient;
269 const serviceScope = yield* Effect.scope;
270​
271 const cachePath = path.join(config.stateDir, "model-manifest.json");
272 let manifest = BUNDLED_MODEL_MANIFEST;
273 let fetchedAtMs: number | null = null;
274 let lastAttemptMs: number | null = null;
275 const refreshSemaphore = yield* Semaphore.make(1);
276​
277 // `Effect.cached` makes concurrent first readers await the same disk load
278 // rather than racing a "loaded" flag. Only `refreshed` takes the fetch
279 // semaphore; `current` must never wait behind an in-flight network refresh.
280 const ensureDiskCacheLoaded = yield* Effect.cached(
281 Effect.gen(function* () {
282 const fromDisk = yield* fileSystem.readFileString(cachePath).pipe(
283 Effect.flatMap((raw) => decodeManifestCache(raw)),
284 Effect.catchCause(() => Effect.succeed(null)),
285 );
286 if (fromDisk === null) return;
287 // The disk copy is the last-seen remote manifest, so it outranks the
288 // bundle even when stale: it is refreshed on the next successful fetch.
289 manifest = fromDisk.manifest;
290 fetchedAtMs = fromDisk.fetchedAtMs;
291 }),
292 );
293​
294 const refresh = Effect.fn("ModelManifest.refresh")(function* () {
295 yield* ensureDiskCacheLoaded;
296 const now = yield* Clock.currentTimeMillis;
297 // A timestamp in the future means the wall clock moved backwards (the
298 // disk cache crosses restarts, so monotonic time cannot cover it). Treat
299 // it as expired: the refetch rewrites both timestamps and self-heals.
300 const isWithin = (sinceMs: number | null, windowMs: number) =>
301 sinceMs !== null && now >= sinceMs && now - sinceMs < windowMs;
302 if (isWithin(fetchedAtMs, MANIFEST_TTL_MS)) return manifest;
303 if (isWithin(lastAttemptMs, MANIFEST_RETRY_MS)) return manifest;
304​
305 // The same switch that gates provider CLI update checks. It stops network
306 // fetches only: a manifest already cached on disk from an earlier fetch
307 // stays in effect, since the setting is about phoning home, not about
308 // discarding data the server already holds.
309 const settings = yield* settingsService.getSettings.pipe(
310 Effect.catchCause(() => Effect.succeed(null)),
311 );
312 if (settings !== null && !settings.enableProviderUpdateChecks) return manifest;
313​
314 lastAttemptMs = now;
315 const fetched = yield* httpClient.get(MODEL_MANIFEST_URL).pipe(
316 Effect.flatMap(HttpClientResponse.filterStatusOk),
317 Effect.flatMap((response) => response.json),
318 Effect.flatMap((json) => decodeManifest(json)),
319 Effect.timeout(FETCH_TIMEOUT_MS),
320 Effect.catchCause(() => Effect.succeed(null)),
321 );
322 if (fetched === null) return manifest;
323​
324 manifest = fetched;
325 fetchedAtMs = now;
326 yield* encodeManifestCache({ fetchedAtMs: now, manifest: fetched }).pipe(
327 Effect.flatMap((serialized) => fileSystem.writeFileString(cachePath, serialized)),
328 Effect.catchCause(() => Effect.void),
329 );
330 return manifest;
331 });
332​
333 const guardedRefresh = refreshSemaphore.withPermits(1)(refresh());
334​
335 return ModelManifest.of({
336 current: ensureDiskCacheLoaded.pipe(Effect.map(() => manifest)),
337 refresh: guardedRefresh,
338 refreshInBackground: Effect.forkIn(guardedRefresh, serviceScope).pipe(Effect.asVoid),
339 });
340});
341​
342export const layer = Layer.effect(ModelManifest, make);