Open History to see the last commit
1import {
2 type ProviderInstanceId,
3 type ServerProvider,
4 ServerProvider as ServerProviderSchema,
5} from "@t3tools/contracts";
6import { causeErrorTag } from "@t3tools/shared/observability";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11
12import { writeFileStringAtomically } from "../atomicWrite.ts";
13
14const decodeProviderStatusCache = Schema.decodeUnknownEffect(
15 Schema.fromJsonString(ServerProviderSchema),
16);
17
18const mergeProviderModels = (
19 fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
20 cachedModels: ReadonlyArray<ServerProvider["models"][number]>,
21): ReadonlyArray<ServerProvider["models"][number]> => {
22 const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));
23 // The fallback snapshot is built from current settings and already carries
24 // every custom model, so cached custom rows that are not in it were removed
25 // while the cache was stale and must not come back.
26 return [
27 ...fallbackModels,
28 ...cachedModels.filter((model) => !model.isCustom && !fallbackSlugs.has(model.slug)),
29 ];
30};
31
32/**
33 * Built-in drivers in presentation order. Codex and Claude lead, the opt-in
34 * providers follow, and unknown or fork drivers sort after every built-in.
35 */
36const BUILT_IN_DRIVER_ORDER: ReadonlyArray<string> = [
37 "codex",
38 "claudeAgent",
39 "cursor",
40 "grok",
41 "opencode",
42 "antigravity",
43];
44
45const driverRank = (driver: string): number => {
46 const index = BUILT_IN_DRIVER_ORDER.indexOf(driver);
47 return index === -1 ? BUILT_IN_DRIVER_ORDER.length : index;
48};
49
50export const orderProviderSnapshots = (
51 providers: ReadonlyArray<ServerProvider>,
52): ReadonlyArray<ServerProvider> =>
53 [...providers].toSorted(
54 (left, right) =>
55 driverRank(left.driver) - driverRank(right.driver) ||
56 left.driver.localeCompare(right.driver) ||
57 (left.displayName ?? "").localeCompare(right.displayName ?? "") ||
58 left.instanceId.localeCompare(right.instanceId),
59 );
60
61export const isCachedProviderCorrelated = (input: {
62 readonly cachedProvider: ServerProvider;
63 readonly fallbackProvider: ServerProvider;
64}): boolean =>
65 input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&
66 input.cachedProvider.driver === input.fallbackProvider.driver;
67
68/**
69 * A provider may change the shape of its model inventory without changing its
70 * instance identity. When the live fallback advertises a catalog version,
71 * cached snapshots must carry the same version before their models can be
72 * hydrated. Missing versions are intentionally rejected so snapshots written
73 * before versioning was introduced cannot reintroduce stale model entries.
74 */
75export const isCachedProviderCatalogCompatible = (input: {
76 readonly cachedProvider: ServerProvider;
77 readonly fallbackProvider: ServerProvider;
78}): boolean =>
79 input.fallbackProvider.modelCatalogVersion === undefined ||
80 input.cachedProvider.modelCatalogVersion === input.fallbackProvider.modelCatalogVersion;
81
82export const hydrateCachedProvider = (input: {
83 readonly cachedProvider: ServerProvider;
84 readonly fallbackProvider: ServerProvider;
85}): ServerProvider => {
86 if (!isCachedProviderCorrelated(input)) {
87 return input.fallbackProvider;
88 }
89
90 if (!isCachedProviderCatalogCompatible(input)) {
91 return input.fallbackProvider;
92 }
93
94 if (
95 !input.fallbackProvider.enabled ||
96 input.cachedProvider.enabled !== input.fallbackProvider.enabled
97 ) {
98 return input.fallbackProvider;
99 }
100
101 const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
102 const hydratedProvider: ServerProvider = {
103 ...fallbackWithoutMessage,
104 models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
105 installed: input.cachedProvider.installed,
106 version: input.cachedProvider.version,
107 status: input.cachedProvider.status,
108 auth: input.cachedProvider.auth,
109 checkedAt: input.cachedProvider.checkedAt,
110 slashCommands: input.cachedProvider.slashCommands,
111 skills: input.cachedProvider.skills,
112 };
113
114 return input.cachedProvider.message
115 ? { ...hydratedProvider, message: input.cachedProvider.message }
116 : hydratedProvider;
117};
118
119/**
120 * Resolve the on-disk cache path for a provider instance snapshot.
121 *
122 * File naming: `<cacheDir>/<instanceId>.json`. For the default instance of
123 * a built-in kind this equals the legacy `<kind>.json` path (because
124 * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing
125 * cached snapshots remain readable without any rename step.
126 *
127 * Non-default instances (e.g. `codex_personal`) land in their own files and
128 * never collide with other instances.
129 *
130 * Cache contents must still carry matching `instanceId` + `driver` identity
131 * before hydration. The filename alone is not trusted as a routing key.
132 */
133export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")(
134 function* (input: {
135 readonly cacheDir: string;
136 readonly instanceId: ProviderInstanceId;
137 }): Effect.fn.Return<string, never, Path.Path> {
138 const path = yield* Path.Path;
139 return path.join(input.cacheDir, `${input.instanceId}.json`);
140 },
141);
142
143export const readProviderStatusCache = (filePath: string) =>
144 Effect.gen(function* () {
145 const fs = yield* FileSystem.FileSystem;
146 const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
147 if (!exists) {
148 return undefined;
149 }
150
151 const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
152 const trimmed = raw.trim();
153 if (trimmed.length === 0) {
154 return undefined;
155 }
156
157 return yield* decodeProviderStatusCache(trimmed).pipe(
158 Effect.matchCauseEffect({
159 onFailure: (cause) =>
160 Effect.logWarning("failed to parse provider status cache, ignoring", {
161 path: filePath,
162 errorTag: causeErrorTag(cause),
163 }).pipe(Effect.as(undefined)),
164 onSuccess: Effect.succeed,
165 }),
166 );
167 });
168
169export const writeProviderStatusCache = (input: {
170 readonly filePath: string;
171 readonly provider: ServerProvider;
172}) => {
173 const { updateState: _updateState, ...cacheableProvider } = input.provider;
174 return writeFileStringAtomically({
175 filePath: input.filePath,
176 contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
177 });
178};