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

ModelManifest.ts

290 lines11.0 KB

1import {
2 ModelCapabilities,
3 TrimmedNonEmptyString,
4 type ProviderDriverKind,
5} from "@t3tools/contracts";
6import * as Clock from "effect/Clock";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import { HttpClient, HttpClientResponse } from "effect/http";
16​
17import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
18import { ServerConfig } from "../config.ts";
19import * as ServerSettings from "../serverSettings.ts";
20import { hasValidClaudeManifestAdapters } from "./ClaudeModelManifest.ts";
21import bundledManifestJson from "./model-manifest.json" with { type: "json" };
22import { ProviderCompatibilityPolicy } from "./providerCompatibility.ts";
23import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
24​
25const MODEL_MANIFEST_URL =
26 "https://raw.githubusercontent.com/pingdotgg/t3code/main/apps/server/src/provider/model-manifest.json";
27​
28const MANIFEST_TTL_MS = 60 * 60 * 1000;
29​
30/** Back off failed fetches so offline health checks do not each wait on the network. */
31const MANIFEST_RETRY_MS = 5 * 60 * 1000;
32​
33const FETCH_TIMEOUT_MS = 10_000;
34const MODEL_NEW_BADGE_DURATION_MS = 7 * 24 * 60 * 60 * 1000;
35​
36const ManifestModelStatus = Schema.Literals(["current", "legacy"]);
37​
38const ManifestModelProfile = Schema.Struct({
39 capabilities: Schema.optional(ModelCapabilities),
40 adapter: Schema.optional(Schema.Unknown),
41});
42​
43const ManifestProviderModel = Schema.Struct({
44 slug: TrimmedNonEmptyString,
45 name: TrimmedNonEmptyString,
46 shortName: Schema.optional(TrimmedNonEmptyString),
47 subProvider: Schema.optional(TrimmedNonEmptyString),
48 aliases: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
49 status: ManifestModelStatus,
50 /** ISO date or timestamp of the model's public release, as published by its provider. */
51 releasedAt: Schema.optional(Schema.String),
52 profile: Schema.optional(TrimmedNonEmptyString),
53 adapter: Schema.optional(Schema.Unknown),
54});
55​
56const ManifestProviderCatalog = Schema.Struct({
57 defaults: Schema.optional(
58 Schema.Struct({
59 chat: Schema.optional(TrimmedNonEmptyString),
60 }),
61 ),
62 profiles: Schema.Record(Schema.String, ManifestModelProfile),
63 models: Schema.Array(ManifestProviderModel),
64});
65​
66const ModelManifestEnvelopeSchema = Schema.Struct({
67 version: Schema.Literal(1),
68 /** Older disk caches must not override bundled manifests; absent dates rank below any dated bundle. */
69 updatedAt: Schema.optional(Schema.String),
70 compatibility: Schema.optional(Schema.Array(ProviderCompatibilityPolicy)),
71 currentModels: Schema.Record(Schema.String, Schema.Array(Schema.String)),
72 providers: Schema.optional(Schema.Record(Schema.String, ManifestProviderCatalog)),
73});
74​
75const hasValidProviderCatalogReferences = (
76 manifest: typeof ModelManifestEnvelopeSchema.Type,
77): boolean =>
78 Object.values(manifest.providers ?? {}).every((catalog) => {
79 const slugs = new Set<string>();
80 const modelsAreValid = catalog.models.every((model) => {
81 if (slugs.has(model.slug)) return false;
82 slugs.add(model.slug);
83 return model.profile === undefined || catalog.profiles[model.profile] !== undefined;
84 });
85 return (
86 modelsAreValid && (catalog.defaults?.chat === undefined || slugs.has(catalog.defaults.chat))
87 );
88 });
89​
90const ModelManifestSchema = ModelManifestEnvelopeSchema.pipe(
91 Schema.check(
92 Schema.makeFilter(hasValidProviderCatalogReferences, {
93 expected: "unique model slugs and existing model and profile references",
94 }),
95 Schema.makeFilter(hasValidClaudeManifestAdapters, {
96 expected: "valid Claude adapter metadata",
97 }),
98 ),
99);
100export type ModelManifestData = typeof ModelManifestSchema.Type;
101​
102const decodeManifest = Schema.decodeUnknownEffect(ModelManifestSchema);
103​
104export const BUNDLED_MODEL_MANIFEST: ModelManifestData =
105 Schema.decodeUnknownSync(ModelManifestSchema)(bundledManifestJson);
106​
107function manifestUpdatedAtMs(manifest: ModelManifestData): number {
108 if (manifest.updatedAt === undefined) return 0;
109 const parsed = Date.parse(manifest.updatedAt);
110 return Number.isNaN(parsed) ? 0 : parsed;
112​
113export function resolveProviderCatalog(
114 manifest: ModelManifestData,
115 driverKind: ProviderDriverKind,
116 nowMs = DateTime.toEpochMillis(DateTime.nowUnsafe()),
117): ModelCatalog.ProviderCatalog | null {
118 const catalog = manifest.providers?.[driverKind];
119 if (!catalog) return null;
120​
121 const seen = new Set<string>();
122 const models: Array<ModelCatalog.ProviderCatalogModel> = [];
123 for (const entry of catalog.models) {
124 if (seen.has(entry.slug)) return null;
125 seen.add(entry.slug);
126​
127 const profile = entry.profile ? catalog.profiles[entry.profile] : undefined;
128 if (entry.profile && !profile) return null;
129​
130 const releasedAtMs = entry.releasedAt === undefined ? NaN : Date.parse(entry.releasedAt);
131 const showNewBadge =
132 entry.status === "current" &&
133 nowMs >= releasedAtMs &&
134 nowMs - releasedAtMs < MODEL_NEW_BADGE_DURATION_MS;
135​
136 models.push({
137 slug: entry.slug,
138 name: entry.name,
139 ...(entry.shortName ? { shortName: entry.shortName } : {}),
140 ...(entry.subProvider ? { subProvider: entry.subProvider } : {}),
141 ...(entry.aliases ? { aliases: entry.aliases } : {}),
142 ...(showNewBadge ? { badge: "new" as const } : {}),
143 status: entry.status,
144 capabilities: profile?.capabilities ?? null,
145 adapter: entry.adapter,
146 profileAdapter: profile?.adapter,
147 });
148 }
149​
150 if (catalog.defaults?.chat !== undefined && !seen.has(catalog.defaults.chat)) return null;
151​
152 return { models, defaultChatModel: catalog.defaults?.chat };
154​
155const ManifestCacheFile = Schema.Struct({
156 fetchedAtMs: Schema.Number,
157 manifest: ModelManifestSchema,
158});
159const decodeManifestCache = Schema.decodeUnknownEffect(
160 Schema.fromJsonString(
161 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
162 ),
163);
164export const encodeManifestCache = Schema.encodeEffect(
165 Schema.fromJsonString(
166 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
167 ),
168);
169​
170export class ModelManifest extends Context.Service<
171 ModelManifest,
172 {
173 /** Snapshot classification reads this, so it never waits on the network. */
174 readonly current: Effect.Effect<ModelManifestData>;
175 readonly refresh: Effect.Effect<ModelManifestData>;
176 readonly forceRefresh: Effect.Effect<ModelManifestData>;
177 /** Process-shared fetches must survive the triggering instance's teardown. */
178 readonly refreshInBackground: Effect.Effect<void>;
179 }
180>()("t3/provider/ModelManifest") {}
181​
182const BundledOnlyModelManifest: ModelManifest["Service"] = {
183 current: Effect.succeed(BUNDLED_MODEL_MANIFEST),
184 refresh: Effect.succeed(BUNDLED_MODEL_MANIFEST),
185 forceRefresh: Effect.succeed(BUNDLED_MODEL_MANIFEST),
186 refreshInBackground: Effect.void,
187};
188​
189const layerBundledOnly = Layer.succeed(ModelManifest, BundledOnlyModelManifest);
190​
191export const make = Effect.gen(function* () {
192 const fileSystem = yield* FileSystem.FileSystem;
193 const path = yield* Path.Path;
194 const config = yield* ServerConfig;
195 const settingsService = yield* ServerSettings.ServerSettingsService;
196 const httpClient = yield* HttpClient.HttpClient;
197 const serviceScope = yield* Effect.scope;
198​
199 const cachePath = path.join(config.stateDir, "model-manifest.json");
200 let manifest = BUNDLED_MODEL_MANIFEST;
201 let fetchedAtMs: number | null = null;
202 let lastAttemptMs: number | null = null;
203 const refreshSemaphore = yield* Semaphore.make(1);
204​
205 // Only refresh takes the fetch semaphore; current must not wait on network I/O.
206 const ensureDiskCacheLoaded = yield* Effect.cached(
207 Effect.gen(function* () {
208 const fromDisk = yield* fileSystem.readFileString(cachePath).pipe(
209 Effect.flatMap((raw) => decodeManifestCache(raw)),
210 Effect.catchCause(() => Effect.succeed(null)),
211 );
212 if (fromDisk === null) return;
213 if (manifestUpdatedAtMs(BUNDLED_MODEL_MANIFEST) > manifestUpdatedAtMs(fromDisk.manifest)) {
214 return;
215 }
216 manifest = fromDisk.manifest;
217 fetchedAtMs = fromDisk.fetchedAtMs;
218 }),
219 );
220​
221 const refresh = Effect.fn("ModelManifest.refresh")(function* (force = false) {
222 yield* ensureDiskCacheLoaded;
223 const now = yield* Clock.currentTimeMillis;
224 // Expire future timestamps after clock rollback; disk caches cross restarts, ruling out monotonic time.
225 const isWithin = (sinceMs: number | null, windowMs: number) =>
226 sinceMs !== null && now >= sinceMs && now - sinceMs < windowMs;
227 if (!force && isWithin(fetchedAtMs, MANIFEST_TTL_MS)) return manifest;
228 if (!force && isWithin(lastAttemptMs, MANIFEST_RETRY_MS)) return manifest;
229​
230 const settings = yield* settingsService.getSettings.pipe(
231 Effect.catchCause(() => Effect.succeed(null)),
232 );
233 if (settings !== null && !settings.enableProviderUpdateChecks) return manifest;
234​
235 lastAttemptMs = now;
236 const fetched = yield* httpClient.get(MODEL_MANIFEST_URL).pipe(
237 Effect.flatMap(HttpClientResponse.filterStatusOk),
238 Effect.flatMap((response) => response.json),
239 Effect.flatMap((json) => decodeManifest(json)),
240 Effect.timeout(FETCH_TIMEOUT_MS),
241 Effect.catchCause(() => Effect.succeed(null)),
242 );
243 // Reject stale CDN edits just like stale disk caches to preserve bundled version gates.
244 if (fetched === null || manifestUpdatedAtMs(fetched) < manifestUpdatedAtMs(manifest)) {
245 return manifest;
246 }
247​
248 manifest = fetched;
249 fetchedAtMs = now;
250 yield* encodeManifestCache({ fetchedAtMs: now, manifest: fetched }).pipe(
251 Effect.flatMap((contents) => writeFileStringAtomically({ filePath: cachePath, contents })),
252 Effect.provideService(FileSystem.FileSystem, fileSystem),
253 Effect.provideService(Path.Path, path),
254 Effect.ignoreCause,
255 );
256 return manifest;
257 });
258​
259 const guardedRefresh = refreshSemaphore.withPermits(1)(refresh());
260​
261 return ModelManifest.of({
262 current: ensureDiskCacheLoaded.pipe(Effect.map(() => manifest)),
263 refresh: guardedRefresh,
264 forceRefresh: refreshSemaphore.withPermits(1)(refresh(true)),
265 refreshInBackground: Effect.forkIn(guardedRefresh, serviceScope).pipe(Effect.asVoid),
266 });
267});
268​
269export const layer = Layer.effect(ModelManifest, make);
270​
271export const layerTest = Layer.suspend(() =>
272 layerModelCatalog.pipe(Layer.provideMerge(layerBundledOnly)),
273);
274​
275export const layerModelCatalog = Layer.effect(
276 ModelCatalog.ModelCatalog,
277 Effect.gen(function* () {
278 const manifest = yield* ModelManifest;
279 return ModelCatalog.ModelCatalog.of({
280 current: Effect.fn("ModelCatalog.current")(function* (driverKind: ProviderDriverKind) {
281 const data = yield* manifest.current;
282 const nowMs = yield* Clock.currentTimeMillis;
283 return resolveProviderCatalog(data, driverKind, nowMs) ?? undefined;
284 }),
285 bundled: (driverKind) =>
286 resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, driverKind) ?? undefined,
287 refreshInBackground: manifest.refreshInBackground,
288 });
289 }),
290);