Open History to see the last commit
1import {
2 type ProviderDriverKind,
3 type ProviderInstanceId,
4 type ServerProvider,
5 ServerProvider as ServerProviderSchema,
6} from "@t3tools/contracts";
7import { Cause, Effect, FileSystem, Path, Schema } from "effect";
8
9import { writeFileStringAtomically } from "../atomicWrite.ts";
10
11const decodeProviderStatusCache = Schema.decodeUnknownEffect(
12 Schema.fromJsonString(ServerProviderSchema),
13);
14
15const mergeProviderModels = (
16 fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
17 cachedModels: ReadonlyArray<ServerProvider["models"][number]>,
18): ReadonlyArray<ServerProvider["models"][number]> => {
19 const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));
20 return [...fallbackModels, ...cachedModels.filter((model) => !fallbackSlugs.has(model.slug))];
21};
22
23export const orderProviderSnapshots = (
24 providers: ReadonlyArray<ServerProvider>,
25): ReadonlyArray<ServerProvider> =>
26 [...providers].toSorted(
27 (left, right) =>
28 (left.displayName ?? "").localeCompare(right.displayName ?? "") ||
29 left.driver.localeCompare(right.driver) ||
30 left.instanceId.localeCompare(right.instanceId),
31 );
32
33export const isCachedProviderCorrelated = (input: {
34 readonly cachedProvider: ServerProvider;
35 readonly fallbackProvider: ServerProvider;
36}): boolean =>
37 input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&
38 input.cachedProvider.driver === input.fallbackProvider.driver;
39
40export const hydrateCachedProvider = (input: {
41 readonly cachedProvider: ServerProvider;
42 readonly fallbackProvider: ServerProvider;
43}): ServerProvider => {
44 if (!isCachedProviderCorrelated(input)) {
45 return input.fallbackProvider;
46 }
47
48 if (
49 !input.fallbackProvider.enabled ||
50 input.cachedProvider.enabled !== input.fallbackProvider.enabled
51 ) {
52 return input.fallbackProvider;
53 }
54
55 const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
56 const hydratedProvider: ServerProvider = {
57 ...fallbackWithoutMessage,
58 models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
59 installed: input.cachedProvider.installed,
60 version: input.cachedProvider.version,
61 status: input.cachedProvider.status,
62 auth: input.cachedProvider.auth,
63 checkedAt: input.cachedProvider.checkedAt,
64 slashCommands: input.cachedProvider.slashCommands,
65 skills: input.cachedProvider.skills,
66 };
67
68 return input.cachedProvider.message
69 ? { ...hydratedProvider, message: input.cachedProvider.message }
70 : hydratedProvider;
71};
72
73/**
74 * Resolve the on-disk cache path for a provider instance snapshot.
75 *
76 * File naming: `<cacheDir>/<instanceId>.json`. For the default instance of
77 * a built-in kind this equals the legacy `<kind>.json` path (because
78 * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing
79 * cached snapshots remain readable without any rename step.
80 *
81 * Non-default instances (e.g. `codex_personal`) land in their own files and
82 * never collide with other instances.
83 *
84 * Cache contents must still carry matching `instanceId` + `driver` identity
85 * before hydration. The filename alone is not trusted as a routing key.
86 */
87export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")(
88 function* (input: {
89 readonly cacheDir: string;
90 readonly instanceId: ProviderInstanceId;
91 }): Effect.fn.Return<string, never, Path.Path> {
92 const path = yield* Path.Path;
93 return path.join(input.cacheDir, `${input.instanceId}.json`);
94 },
95);
96
97/**
98 * Legacy kind-keyed path resolver retained for callers that still think in
99 * terms of `ProviderDriverKind`. Prefer `resolveProviderStatusCachePath` with an
100 * `instanceId`; new code should route through the instance registry.
101 *
102 * @deprecated use `resolveProviderStatusCachePath` with an instance id.
103 */
104export const resolveLegacyProviderStatusCachePath = Effect.fn(
105 "resolveLegacyProviderStatusCachePath",
106)(function* (input: {
107 readonly cacheDir: string;
108 readonly provider: ProviderDriverKind;
109}): Effect.fn.Return<string, never, Path.Path> {
110 const path = yield* Path.Path;
111 return path.join(input.cacheDir, `${input.provider}.json`);
112});
113
114export const readProviderStatusCache = (filePath: string) =>
115 Effect.gen(function* () {
116 const fs = yield* FileSystem.FileSystem;
117 const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
118 if (!exists) {
119 return undefined;
120 }
121
122 const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
123 const trimmed = raw.trim();
124 if (trimmed.length === 0) {
125 return undefined;
126 }
127
128 return yield* decodeProviderStatusCache(trimmed).pipe(
129 Effect.matchCauseEffect({
130 onFailure: (cause) =>
131 Effect.logWarning("failed to parse provider status cache, ignoring", {
132 path: filePath,
133 issues: Cause.pretty(cause),
134 }).pipe(Effect.as(undefined)),
135 onSuccess: Effect.succeed,
136 }),
137 );
138 });
139
140export const writeProviderStatusCache = (input: {
141 readonly filePath: string;
142 readonly provider: ServerProvider;
143}) =>
144 writeFileStringAtomically({
145 filePath: input.filePath,
146 contents: `${JSON.stringify(input.provider, null, 2)}\n`,
147 });