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 "@t3tools/shared/atomicWrite";
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
32const BUILT_IN_DRIVER_ORDER: ReadonlyArray<string> = [
33 "codex",
34 "claudeAgent",
35 "cursor",
36 "grok",
37 "opencode",
38 "antigravity",
39];
40
41const driverRank = (driver: string): number => {
42 const index = BUILT_IN_DRIVER_ORDER.indexOf(driver);
43 return index === -1 ? BUILT_IN_DRIVER_ORDER.length : index;
44};
45
46export const orderProviderSnapshots = (
47 providers: ReadonlyArray<ServerProvider>,
48): ReadonlyArray<ServerProvider> =>
49 [...providers].toSorted(
50 (left, right) =>
51 driverRank(left.driver) - driverRank(right.driver) ||
52 left.driver.localeCompare(right.driver) ||
53 (left.displayName ?? "").localeCompare(right.displayName ?? "") ||
54 left.instanceId.localeCompare(right.instanceId),
55 );
56
57export const isCachedProviderCorrelated = (input: {
58 readonly cachedProvider: ServerProvider;
59 readonly fallbackProvider: ServerProvider;
60}): boolean =>
61 input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&
62 input.cachedProvider.driver === input.fallbackProvider.driver;
63
64export const hydrateCachedProvider = (input: {
65 readonly cachedProvider: ServerProvider;
66 readonly fallbackProvider: ServerProvider;
67}): ServerProvider => {
68 if (!isCachedProviderCorrelated(input)) {
69 return input.fallbackProvider;
70 }
71
72 if (
73 !input.fallbackProvider.enabled ||
74 input.cachedProvider.enabled !== input.fallbackProvider.enabled
75 ) {
76 return input.fallbackProvider;
77 }
78
79 const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
80 const hydratedProvider: ServerProvider = {
81 ...fallbackWithoutMessage,
82 models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
83 installed: input.cachedProvider.installed,
84 version: input.cachedProvider.version,
85 status: input.cachedProvider.status,
86 auth: input.cachedProvider.auth,
87 checkedAt: input.cachedProvider.checkedAt,
88 slashCommands: input.cachedProvider.slashCommands,
89 skills: input.cachedProvider.skills,
90 };
91
92 return input.cachedProvider.message
93 ? { ...hydratedProvider, message: input.cachedProvider.message }
94 : hydratedProvider;
95};
96
97/**
98 * Cache contents must still carry matching `instanceId` + `driver` identity
99 * before hydration. The filename alone is not trusted as a routing key.
100 */
101export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")(
102 function* (input: {
103 readonly cacheDir: string;
104 readonly instanceId: ProviderInstanceId;
105 }): Effect.fn.Return<string, never, Path.Path> {
106 const path = yield* Path.Path;
107 return path.join(input.cacheDir, `${input.instanceId}.json`);
108 },
109);
110
111export const readProviderStatusCache = (filePath: string) =>
112 Effect.gen(function* () {
113 const fs = yield* FileSystem.FileSystem;
114 const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
115 if (!exists) {
116 return undefined;
117 }
118
119 const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
120 const trimmed = raw.trim();
121 if (trimmed.length === 0) {
122 return undefined;
123 }
124
125 return yield* decodeProviderStatusCache(trimmed).pipe(
126 Effect.matchCauseEffect({
127 onFailure: (cause) =>
128 Effect.logWarning("failed to parse provider status cache, ignoring", {
129 path: filePath,
130 errorTag: causeErrorTag(cause),
131 }).pipe(Effect.as(undefined)),
132 onSuccess: Effect.succeed,
133 }),
134 );
135 });
136
137export const writeProviderStatusCache = (input: {
138 readonly filePath: string;
139 readonly provider: ServerProvider;
140}) => {
141 const { updateState: _updateState, ...cacheableProvider } = input.provider;
142 return writeFileStringAtomically({
143 filePath: input.filePath,
144 contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
145 });
146};