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

ModelManifest.ts

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