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