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

ModelManifest.ts

221 lines9.0 KB

1/**
2 * ModelManifest — decides which provider models are current and which belong
3 * in the model picker's legacy section.
4 *
5 * The classification data (current slugs per driver kind) lives in
6 * `model-manifest.json` next to this file. The bundled copy ships with every
7 * release. At runtime the service refreshes it from the same file on `main`
8 * via raw.githubusercontent.com, so a new model can leave the legacy section
9 * with a commit to `main` instead of a release. Preference order is remote,
10 * then the on-disk copy of the last successful fetch, then the bundle. A
11 * failed fetch never fails a provider check.
12 *
13 * Drivers apply the manifest to snapshot drafts with `applyModelManifest`
14 * before publishing, so every path that produces models (pending, probe,
15 * error fallbacks) is classified the same way.
16 */
17import type { ProviderDriverKind, ServerProviderModel } from "@t3tools/contracts";
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Path from "effect/Path";
24import * as Schema from "effect/Schema";
25import * as Semaphore from "effect/Semaphore";
26import { HttpClient, HttpClientResponse } from "effect/unstable/http";
27​
28import { ServerConfig } from "../config.ts";
29import * as ServerSettings from "../serverSettings.ts";
30import bundledManifestJson from "./model-manifest.json" with { type: "json" };
31import type { ServerProviderDraft } from "./providerSnapshot.ts";
32​
33const MODEL_MANIFEST_URL =
34 "https://raw.githubusercontent.com/pingdotgg/t3code/main/apps/server/src/provider/model-manifest.json";
35​
36/** How long a fetched manifest stays fresh before the next probe re-fetches. */
37const MANIFEST_TTL_MS = 60 * 60 * 1000;
38​
39/** Minimum gap between fetch attempts after a failure, so an offline server
40 * does not pay a network timeout on every provider check. */
41const MANIFEST_RETRY_MS = 5 * 60 * 1000;
42​
43const FETCH_TIMEOUT_MS = 10_000;
44​
45/**
46 * `version` gates breaking schema changes: a build only accepts remote
47 * manifests whose version it understands, and keeps its bundled copy
48 * otherwise. `currentModels` is keyed by driver kind; kinds absent from the
49 * map have no legacy concept and their models are left unflagged.
50 */
51const ModelManifestSchema = Schema.Struct({
52 version: Schema.Literal(1),
53 currentModels: Schema.Record(Schema.String, Schema.Array(Schema.String)),
54});
55export type ModelManifestData = typeof ModelManifestSchema.Type;
56​
57const decodeManifest = Schema.decodeUnknownEffect(ModelManifestSchema);
58​
59export const BUNDLED_MODEL_MANIFEST: ModelManifestData =
60 Schema.decodeUnknownSync(ModelManifestSchema)(bundledManifestJson);
61​
62/** On-disk shape of the last successfully fetched manifest. */
63const ManifestCacheFile = Schema.Struct({
64 fetchedAtMs: Schema.Number,
65 manifest: ModelManifestSchema,
66});
67const decodeManifestCache = Schema.decodeUnknownEffect(
68 Schema.fromJsonString(
69 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
70 ),
71);
72const encodeManifestCache = Schema.encodeEffect(
73 Schema.fromJsonString(
74 ManifestCacheFile as unknown as Schema.Codec<typeof ManifestCacheFile.Type>,
75 ),
76);
77​
78/** True when the manifest classifies `slug` as legacy for `driverKind`. */
79export function isLegacyModel(
80 manifest: ModelManifestData,
81 driverKind: ProviderDriverKind,
82 slug: string,
83): boolean {
84 const currentModels = manifest.currentModels[driverKind];
85 if (!currentModels) return false;
86 return !currentModels.includes(slug);
88​
89/**
90 * Reclassifies every built-in model on a snapshot draft against the manifest.
91 * Custom models are user-defined and never reclassified.
92 */
93export function applyModelManifest(
94 draft: ServerProviderDraft,
95 manifest: ModelManifestData,
96 driverKind: ProviderDriverKind,
97): ServerProviderDraft {
98 return { ...draft, models: classifyModels(draft.models, manifest, driverKind) };
100​
101/** Model-level half of `applyModelManifest`, exported for focused tests. */
102export function classifyModels(
103 models: ReadonlyArray<ServerProviderModel>,
104 manifest: ModelManifestData,
105 driverKind: ProviderDriverKind,
106): ReadonlyArray<ServerProviderModel> {
107 return models.map((model) => {
108 if (model.isCustom) return model;
109 if (isLegacyModel(manifest, driverKind, model.slug)) {
110 return model.isLegacy ? model : { ...model, isLegacy: true };
111 }
112 if (!model.isLegacy) return model;
113 const { isLegacy: _isLegacy, ...rest } = model;
114 return rest;
115 });
117​
118export class ModelManifest extends Context.Service<
119 ModelManifest,
120 {
121 /** Manifest already in memory (disk cache or bundle); never fetches.
122 * Snapshot classification reads this, so it never waits on the network. */
123 readonly current: Effect.Effect<ModelManifestData>;
124 /** Manifest after a TTL-gated remote refresh; never fails. */
125 readonly refresh: Effect.Effect<ModelManifestData>;
126 /** Forks `refresh` into the service's own scope. Drivers call this from
127 * provider checks: the fetch is process-shared state, so it must survive
128 * the teardown of whichever instance happened to trigger it. */
129 readonly refreshInBackground: Effect.Effect<void>;
130 }
131>()("t3/provider/ModelManifest") {}
132​
133/** Constant service for tests and callers that only need the bundled data. */
134export const BundledOnlyModelManifest: ModelManifest["Service"] = {
135 current: Effect.succeed(BUNDLED_MODEL_MANIFEST),
136 refresh: Effect.succeed(BUNDLED_MODEL_MANIFEST),
137 refreshInBackground: Effect.void,
138};
139​
140export const layerTest = Layer.succeed(ModelManifest, BundledOnlyModelManifest);
141​
142export const make = Effect.gen(function* () {
143 const fileSystem = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const config = yield* ServerConfig;
146 const settingsService = yield* ServerSettings.ServerSettingsService;
147 const httpClient = yield* HttpClient.HttpClient;
148 const serviceScope = yield* Effect.scope;
149​
150 const cachePath = path.join(config.stateDir, "model-manifest.json");
151 let manifest = BUNDLED_MODEL_MANIFEST;
152 let fetchedAtMs: number | null = null;
153 let lastAttemptMs: number | null = null;
154 const refreshSemaphore = yield* Semaphore.make(1);
155​
156 // `Effect.cached` makes concurrent first readers await the same disk load
157 // rather than racing a "loaded" flag. Only `refreshed` takes the fetch
158 // semaphore; `current` must never wait behind an in-flight network refresh.
159 const ensureDiskCacheLoaded = yield* Effect.cached(
160 Effect.gen(function* () {
161 const fromDisk = yield* fileSystem.readFileString(cachePath).pipe(
162 Effect.flatMap((raw) => decodeManifestCache(raw)),
163 Effect.catchCause(() => Effect.succeed(null)),
164 );
165 if (fromDisk === null) return;
166 // The disk copy is the last-seen remote manifest, so it outranks the
167 // bundle even when stale: it is refreshed on the next successful fetch.
168 manifest = fromDisk.manifest;
169 fetchedAtMs = fromDisk.fetchedAtMs;
170 }),
171 );
172​
173 const refresh = Effect.fn("ModelManifest.refresh")(function* () {
174 yield* ensureDiskCacheLoaded;
175 const now = yield* Clock.currentTimeMillis;
176 // A timestamp in the future means the wall clock moved backwards (the
177 // disk cache crosses restarts, so monotonic time cannot cover it). Treat
178 // it as expired: the refetch rewrites both timestamps and self-heals.
179 const isWithin = (sinceMs: number | null, windowMs: number) =>
180 sinceMs !== null && now >= sinceMs && now - sinceMs < windowMs;
181 if (isWithin(fetchedAtMs, MANIFEST_TTL_MS)) return manifest;
182 if (isWithin(lastAttemptMs, MANIFEST_RETRY_MS)) return manifest;
183​
184 // The same switch that gates provider CLI update checks. It stops network
185 // fetches only: a manifest already cached on disk from an earlier fetch
186 // stays in effect, since the setting is about phoning home, not about
187 // discarding data the server already holds.
188 const settings = yield* settingsService.getSettings.pipe(
189 Effect.catchCause(() => Effect.succeed(null)),
190 );
191 if (settings !== null && !settings.enableProviderUpdateChecks) return manifest;
192​
193 lastAttemptMs = now;
194 const fetched = yield* httpClient.get(MODEL_MANIFEST_URL).pipe(
195 Effect.flatMap(HttpClientResponse.filterStatusOk),
196 Effect.flatMap((response) => response.json),
197 Effect.flatMap((json) => decodeManifest(json)),
198 Effect.timeout(FETCH_TIMEOUT_MS),
199 Effect.catchCause(() => Effect.succeed(null)),
200 );
201 if (fetched === null) return manifest;
202​
203 manifest = fetched;
204 fetchedAtMs = now;
205 yield* encodeManifestCache({ fetchedAtMs: now, manifest: fetched }).pipe(
206 Effect.flatMap((serialized) => fileSystem.writeFileString(cachePath, serialized)),
207 Effect.catchCause(() => Effect.void),
208 );
209 return manifest;
210 });
211​
212 const guardedRefresh = refreshSemaphore.withPermits(1)(refresh());
213​
214 return ModelManifest.of({
215 current: ensureDiskCacheLoaded.pipe(Effect.map(() => manifest)),
216 refresh: guardedRefresh,
217 refreshInBackground: Effect.forkIn(guardedRefresh, serviceScope).pipe(Effect.asVoid),
218 });
219});
220​
221export const layer = Layer.effect(ModelManifest, make);