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

providerStatusCache.ts

161 lines5.5 KB

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 "muse",
44];
45​
46const driverRank = (driver: string): number => {
47 const index = BUILT_IN_DRIVER_ORDER.indexOf(driver);
48 return index === -1 ? BUILT_IN_DRIVER_ORDER.length : index;
49};
50​
51export const orderProviderSnapshots = (
52 providers: ReadonlyArray<ServerProvider>,
53): ReadonlyArray<ServerProvider> =>
54 [...providers].toSorted(
55 (left, right) =>
56 driverRank(left.driver) - driverRank(right.driver) ||
57 left.driver.localeCompare(right.driver) ||
58 (left.displayName ?? "").localeCompare(right.displayName ?? "") ||
59 left.instanceId.localeCompare(right.instanceId),
60 );
61​
62export const isCachedProviderCorrelated = (input: {
63 readonly cachedProvider: ServerProvider;
64 readonly fallbackProvider: ServerProvider;
65}): boolean =>
66 input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&
67 input.cachedProvider.driver === input.fallbackProvider.driver;
68​
69export const hydrateCachedProvider = (input: {
70 readonly cachedProvider: ServerProvider;
71 readonly fallbackProvider: ServerProvider;
72}): ServerProvider => {
73 if (!isCachedProviderCorrelated(input)) {
74 return input.fallbackProvider;
75 }
76​
77 if (
78 !input.fallbackProvider.enabled ||
79 input.cachedProvider.enabled !== input.fallbackProvider.enabled
80 ) {
81 return input.fallbackProvider;
82 }
83​
84 const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
85 const hydratedProvider: ServerProvider = {
86 ...fallbackWithoutMessage,
87 models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
88 installed: input.cachedProvider.installed,
89 version: input.cachedProvider.version,
90 status: input.cachedProvider.status,
91 auth: input.cachedProvider.auth,
92 checkedAt: input.cachedProvider.checkedAt,
93 slashCommands: input.cachedProvider.slashCommands,
94 skills: input.cachedProvider.skills,
95 };
96​
97 return input.cachedProvider.message
98 ? { ...hydratedProvider, message: input.cachedProvider.message }
99 : hydratedProvider;
100};
101​
102/**
103 * Resolve the on-disk cache path for a provider instance snapshot.
104 *
105 * File naming: `<cacheDir>/<instanceId>.json`. For the default instance of
106 * a built-in kind this equals the legacy `<kind>.json` path (because
107 * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing
108 * cached snapshots remain readable without any rename step.
109 *
110 * Non-default instances (e.g. `codex_personal`) land in their own files and
111 * never collide with other instances.
112 *
113 * Cache contents must still carry matching `instanceId` + `driver` identity
114 * before hydration. The filename alone is not trusted as a routing key.
115 */
116export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")(
117 function* (input: {
118 readonly cacheDir: string;
119 readonly instanceId: ProviderInstanceId;
120 }): Effect.fn.Return<string, never, Path.Path> {
121 const path = yield* Path.Path;
122 return path.join(input.cacheDir, `${input.instanceId}.json`);
123 },
124);
125​
126export const readProviderStatusCache = (filePath: string) =>
127 Effect.gen(function* () {
128 const fs = yield* FileSystem.FileSystem;
129 const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
130 if (!exists) {
131 return undefined;
132 }
133​
134 const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
135 const trimmed = raw.trim();
136 if (trimmed.length === 0) {
137 return undefined;
138 }
139​
140 return yield* decodeProviderStatusCache(trimmed).pipe(
141 Effect.matchCauseEffect({
142 onFailure: (cause) =>
143 Effect.logWarning("failed to parse provider status cache, ignoring", {
144 path: filePath,
145 errorTag: causeErrorTag(cause),
146 }).pipe(Effect.as(undefined)),
147 onSuccess: Effect.succeed,
148 }),
149 );
150 });
151​
152export const writeProviderStatusCache = (input: {
153 readonly filePath: string;
154 readonly provider: ServerProvider;
155}) => {
156 const { updateState: _updateState, ...cacheableProvider } = input.provider;
157 return writeFileStringAtomically({
158 filePath: input.filePath,
159 contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
160 });
161};