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

providerInstallation.ts

234 lines9.3 KB

1import {
2 AntigravitySettings,
3 CodexSettings,
4 ProviderDriverKind,
5 type ProviderInstallCancelInput,
6 type ProviderInstallState,
7 type ProviderInstanceId,
8 ProviderSetupError,
9 type ProviderSetupInput,
10} from "@t3tools/contracts";
11import { resolveCommandPath } from "@t3tools/shared/shell";
12import * as Context from "effect/Context";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as FileSystem from "effect/FileSystem";
16import * as Path from "effect/Path";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20​
21import * as CodexInstallation from "./CodexInstallation.ts";
22import * as ServerSettings from "../serverSettings.ts";
23import * as AntigravityInstallation from "./AntigravityInstallation.ts";
24import { deriveProviderInstanceConfigMap } from "./ProviderInstanceRegistryHydration.ts";
25import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
26import * as ProviderRegistry from "./ProviderRegistry.ts";
27import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
28​
29const ANTIGRAVITY = ProviderDriverKind.make("antigravity");
30const hasBinaryPath = Schema.is(Schema.Struct({ binaryPath: Schema.String }));
31const decodeCodexSettings = Schema.decodeUnknownEffect(CodexSettings);
32const decodeAntigravitySettings = Schema.decodeUnknownEffect(AntigravitySettings);
33​
34export class ProviderInstallation extends Context.Service<
35 ProviderInstallation,
36 {
37 readonly start: (
38 input: ProviderSetupInput,
39 ) => Effect.Effect<ProviderInstallState, ProviderSetupError>;
40 readonly cancel: (
41 input: ProviderInstallCancelInput,
42 ) => Effect.Effect<ProviderInstallState, ProviderSetupError>;
43 readonly subscribe: (
44 input: ProviderSetupInput,
45 ) => Stream.Stream<ProviderInstallState, ProviderSetupError>;
46 readonly remove: (
47 input: ProviderSetupInput,
48 ) => Effect.Effect<ProviderInstallState, ProviderSetupError>;
49 }
50>()("t3/provider/providerInstallation") {}
51​
52const make = Effect.fn("makeProviderInstallation")(function* () {
53 const antigravityInstallation = yield* AntigravityInstallation.AntigravityInstallation;
54 const codexInstallation = yield* CodexInstallation.CodexInstallation;
55 const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
56 const providers = yield* ProviderRegistry.ProviderRegistry;
57 const settings = yield* ServerSettings.ServerSettingsService;
58 const fileSystem = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 const scope = yield* Effect.scope;
61​
62 const readEntries = Effect.fn("ProviderInstallation.readEntries")(function* (
63 instanceId: ProviderInstanceId,
64 operation: string,
65 ) {
66 const current = yield* settings.getSettings.pipe(
67 Effect.mapError(
68 () =>
69 new ProviderSetupError({
70 instanceId,
71 operation,
72 detail: "Could not read provider installation settings.",
73 }),
74 ),
75 );
76 return deriveProviderInstanceConfigMap(current);
77 });
78​
79 const requireInstance = Effect.fn("ProviderInstallation.requireInstance")(function* (
80 instanceId: ProviderInstanceId,
81 operation: string,
82 managedOnly = false,
83 ) {
84 const instance = yield* instances.getInstance(instanceId);
85 const isCodex = instance?.driverKind === ProviderDriverKind.make("codex");
86 if (instance?.driverKind !== ANTIGRAVITY && !isCodex) {
87 return yield* new ProviderSetupError({
88 instanceId,
89 operation,
90 detail: "Managed installation is not available for this provider instance.",
91 });
92 }
93 const installation = isCodex ? codexInstallation : antigravityInstallation;
94 const entries = yield* readEntries(instanceId, operation);
95 const invalidConfig = () =>
96 new ProviderSetupError({
97 instanceId,
98 operation,
99 detail: "The provider instance configuration is invalid.",
100 });
101 const config = isCodex
102 ? yield* decodeCodexSettings(entries[instanceId]?.config ?? {}).pipe(
103 Effect.mapError(invalidConfig),
104 )
105 : yield* decodeAntigravitySettings(entries[instanceId]?.config ?? {}).pipe(
106 Effect.mapError(invalidConfig),
107 );
108 if (isCodex && (!("setupMode" in config) || config.setupMode !== "managed")) {
109 return yield* new ProviderSetupError({
110 instanceId,
111 operation,
112 detail: "Choose managed setup to install Codex in T3 Code.",
113 });
114 }
115 if (managedOnly && config.binaryPath && (!isCodex || config.binaryPath !== "codex")) {
116 return yield* new ProviderSetupError({
117 instanceId,
118 operation,
119 detail:
120 "This instance uses a custom executable. Clear its binary path to manage installation in T3 Code.",
121 });
122 }
123 return { installation, driver: instance.driverKind };
124 });
125​
126 const failure =
127 (instanceId: ProviderInstanceId) =>
128 (
129 error:
130 | AntigravityInstallation.AntigravityInstallationError
131 | CodexInstallation.CodexInstallationError,
132 ) =>
133 new ProviderSetupError({ instanceId, operation: error.operation, detail: error.detail });
134​
135 // Every instance without a custom executable runs the one managed runtime, so an install
136 // replaces the runtime behind all of their model lists, not only the instance that asked.
137 const checkManagedRuntimeInstances = Effect.fn(
138 "ProviderInstallation.checkManagedRuntimeInstances",
139 )(function* () {
140 const entries = deriveProviderInstanceConfigMap(yield* settings.getSettings);
141 for (const instance of yield* instances.listInstances) {
142 if (instance.driverKind !== ANTIGRAVITY || !instance.enabled || !instance.refreshModels) {
143 continue;
144 }
145 const config = yield* decodeAntigravitySettings(
146 entries[instance.instanceId]?.config ?? {},
147 ).pipe(Effect.option);
148 if (Option.isNone(config) || config.value.binaryPath) continue;
149 yield* instance.refreshModels().pipe(Effect.ignore({ log: true }));
150 yield* providers.refreshInstance(instance.instanceId);
151 }
152 });
153​
154 // Watched for the server's lifetime: the provider update flow starts installs too, and one
155 // can finish while every client is disconnected. An operation is checked once.
156 yield* antigravityInstallation.changes.pipe(
157 Stream.filter((state) => state.operationId !== null && state.phase === "succeeded"),
158 Stream.changesWith((previous, next) => previous.operationId === next.operationId),
159 Stream.runForEach(() => checkManagedRuntimeInstances().pipe(Effect.ignore({ log: true }))),
160 Effect.forkIn(scope),
161 );
162​
163 const start = Effect.fn("ProviderInstallation.start")(function* (input: ProviderSetupInput) {
164 const { installation } = yield* requireInstance(input.instanceId, "install", true);
165 return yield* installation.start.pipe(Effect.mapError(failure(input.instanceId)));
166 });
167​
168 const cancel = Effect.fn("ProviderInstallation.cancel")(function* (
169 input: ProviderInstallCancelInput,
170 ) {
171 const { installation } = yield* requireInstance(input.instanceId, "cancel-install");
172 return yield* installation
173 .cancel(input.operationId)
174 .pipe(Effect.mapError(failure(input.instanceId)));
175 });
176​
177 // Watching an installation is when its owner can act on an update, so the
178 // lookup runs then, in the background, unless update checks are off.
179 const subscribe = (input: ProviderSetupInput) =>
180 Stream.unwrap(
181 requireInstance(input.instanceId, "observe-install").pipe(
182 Effect.tap(({ installation }) =>
183 settings.getSettings.pipe(
184 Effect.flatMap((current) =>
185 current.enableProviderUpdateChecks
186 ? Effect.forkDetach(installation.checkForUpdate)
187 : Effect.void,
188 ),
189 Effect.ignore,
190 ),
191 ),
192 Effect.map(({ installation }) => installation.changes),
193 ),
194 );
195​
196 const remove = Effect.fn("ProviderInstallation.remove")(function* (input: ProviderSetupInput) {
197 const { installation, driver } = yield* requireInstance(
198 input.instanceId,
199 "remove-install",
200 true,
201 );
202 const entries = yield* readEntries(input.instanceId, "remove-install");
203 const protectedPaths = yield* Effect.forEach(
204 Object.values(entries),
205 Effect.fnUntraced(function* (entry) {
206 if (!hasBinaryPath(entry.config) || !entry.config.binaryPath.trim()) {
207 return [];
208 }
209 const binaryPath = entry.config.binaryPath.trim();
210 const resolved = yield* resolveCommandPath(binaryPath, {
211 env: yield* mergeProviderInstanceEnvironment(entry.environment),
212 }).pipe(
213 Effect.provideService(FileSystem.FileSystem, fileSystem),
214 Effect.provideService(Path.Path, path),
215 );
216 return resolved === null ? [binaryPath] : [binaryPath, resolved];
217 }),
218 );
219 yield* installation
220 .remove(protectedPaths.flat())
221 .pipe(Effect.mapError(failure(input.instanceId)));
222 const allInstances = yield* instances.listInstances;
223 yield* Effect.forEach(
224 allInstances.filter((instance) => instance.driverKind === driver),
225 (instance) => providers.refreshInstance(instance.instanceId),
226 { discard: true },
227 );
228 return yield* installation.state;
229 });
230​
231 return { start, cancel, subscribe, remove };
232});
233​
234export const layer = Layer.effect(ProviderInstallation, make());