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

providerStatusCache.ts

117 lines4.0 KB

1import * as nodePath from "node:path";
2import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts";
3import { Cause, Effect, FileSystem, Path, Schema } from "effect";
4​
5export const PROVIDER_CACHE_IDS = [
6 "codex",
7 "claudeAgent",
8 "opencode",
9 "cursor",
10] as const satisfies ReadonlyArray<ServerProvider["provider"]>;
11​
12const decodeProviderStatusCache = Schema.decodeUnknownEffect(
13 Schema.fromJsonString(ServerProviderSchema),
14);
15​
16const providerOrderRank = (provider: ServerProvider["provider"]): number => {
17 const rank = PROVIDER_CACHE_IDS.indexOf(provider);
18 return rank === -1 ? Number.MAX_SAFE_INTEGER : rank;
19};
20​
21const mergeProviderModels = (
22 fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
23 cachedModels: ReadonlyArray<ServerProvider["models"][number]>,
24): ReadonlyArray<ServerProvider["models"][number]> => {
25 const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));
26 return [...fallbackModels, ...cachedModels.filter((model) => !fallbackSlugs.has(model.slug))];
27};
28​
29export const orderProviderSnapshots = (
30 providers: ReadonlyArray<ServerProvider>,
31): ReadonlyArray<ServerProvider> =>
32 [...providers].toSorted(
33 (left, right) => providerOrderRank(left.provider) - providerOrderRank(right.provider),
34 );
35​
36export const hydrateCachedProvider = (input: {
37 readonly cachedProvider: ServerProvider;
38 readonly fallbackProvider: ServerProvider;
39}): ServerProvider => {
40 if (
41 !input.fallbackProvider.enabled ||
42 input.cachedProvider.enabled !== input.fallbackProvider.enabled
43 ) {
44 return input.fallbackProvider;
45 }
46​
47 const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
48 const hydratedProvider: ServerProvider = {
49 ...fallbackWithoutMessage,
50 models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
51 installed: input.cachedProvider.installed,
52 version: input.cachedProvider.version,
53 status: input.cachedProvider.status,
54 auth: input.cachedProvider.auth,
55 checkedAt: input.cachedProvider.checkedAt,
56 slashCommands: input.cachedProvider.slashCommands,
57 skills: input.cachedProvider.skills,
58 };
59​
60 return input.cachedProvider.message
61 ? { ...hydratedProvider, message: input.cachedProvider.message }
62 : hydratedProvider;
63};
64​
65export const resolveProviderStatusCachePath = (input: {
66 readonly cacheDir: string;
67 readonly provider: ServerProvider["provider"];
68}) => nodePath.join(input.cacheDir, `${input.provider}.json`);
69​
70export const readProviderStatusCache = (filePath: string) =>
71 Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
74 if (!exists) {
75 return undefined;
76 }
77​
78 const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
79 const trimmed = raw.trim();
80 if (trimmed.length === 0) {
81 return undefined;
82 }
83​
84 return yield* decodeProviderStatusCache(trimmed).pipe(
85 Effect.matchCauseEffect({
86 onFailure: (cause) =>
87 Effect.logWarning("failed to parse provider status cache, ignoring", {
88 path: filePath,
89 issues: Cause.pretty(cause),
90 }).pipe(Effect.as(undefined)),
91 onSuccess: Effect.succeed,
92 }),
93 );
94 });
95​
96export const writeProviderStatusCache = (input: {
97 readonly filePath: string;
98 readonly provider: ServerProvider;
99}) => {
100 const tempPath = `${input.filePath}.${process.pid}.${Date.now()}.tmp`;
101 return Effect.gen(function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const encoded = `${JSON.stringify(input.provider, null, 2)}\n`;
105​
106 yield* fs.makeDirectory(path.dirname(input.filePath), { recursive: true });
107 yield* fs.writeFileString(tempPath, encoded);
108 yield* fs.rename(tempPath, input.filePath);
109 }).pipe(
110 Effect.ensuring(
111 Effect.gen(function* () {
112 const fs = yield* FileSystem.FileSystem;
113 yield* fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }));
114 }),
115 ),
116 );
117};