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

AntigravityDriver.ts

402 lines15.5 KB

1import { AntigravitySettings, ProviderDriverKind, ProviderSetupError } from "@t3tools/contracts";
2import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
3import * as Crypto from "effect/Crypto";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11import * as Stream from "effect/Stream";
12import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
13import type { AcpError } from "effect-acp/errors";
14​
15import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
16import { ServerConfig } from "../../config.ts";
17import { ServerSettingsService } from "../../serverSettings.ts";
18import {
19 isAntigravityTextGenerationAvailable,
20 makeAntigravityTextGeneration,
21} from "../../textGeneration/AntigravityTextGeneration.ts";
22import { makeAntigravityAuth, type AntigravityAuth } from "../AntigravityAuth.ts";
23import { AntigravityInstallation } from "../AntigravityInstallation.ts";
24import {
25 antigravityAuthConfigIssue,
26 antigravityAuthLabel,
27 antigravityAuthUsesBrowser,
28 buildAntigravityAcpSpawnInput,
29 isAntigravitySignInRequiredError,
30 prepareAntigravityProfile,
31 resolveAntigravityProfileDirectory,
32 type AntigravityAuthConfig,
33} from "../antigravityAuthSupport.ts";
34import {
35 makeAntigravityAcpRuntime,
36 type AntigravityAcpRuntimeInput,
37} from "../acp/AntigravityAcpSupport.ts";
38import type { AcpSessionRuntime, AcpSessionRuntimeStartResult } from "../acp/AcpSessionRuntime.ts";
39import type { ServerProviderDraft } from "../providerSnapshot.ts";
40import { removeAntigravitySessionFiles } from "../acp/AntigravitySessionFiles.ts";
41import { ProviderDriverError } from "../Errors.ts";
42import { makeAntigravityAdapter } from "../Layers/AntigravityAdapter.ts";
43import { makeAntigravityProvider } from "../Layers/AntigravityProvider.ts";
44import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
45import * as ModelManifest from "../ModelManifest.ts";
46import {
47 defaultProviderContinuationIdentity,
48 type ProviderDriver,
49 type ProviderInstance,
50} from "../ProviderDriver.ts";
51import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
52import { withInstanceIdentity } from "./instanceIdentity.ts";
53import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";
54​
55const DRIVER = ProviderDriverKind.make("antigravity");
56const decodeSettings = Schema.decodeSync(AntigravitySettings);
57​
58export type AntigravityDriverEnv =
59 | AntigravityInstallation
60 | BackgroundPolicy.BackgroundPolicy
61 | ChildProcessSpawner.ChildProcessSpawner
62 | Crypto.Crypto
63 | FileSystem.FileSystem
64 | ModelManifest.ModelManifest
65 | Path.Path
66 | ProviderEventLoggers
67 | ServerConfig
68 | ServerSettingsService;
69​
70/** Each instance owns its Google profile. Executable releases are shared by the environment. */
71export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityDriverEnv> = {
72 driverKind: DRIVER,
73 metadata: { displayName: "Antigravity", supportsMultipleInstances: true },
74 configSchema: AntigravitySettings,
75 defaultConfig: () => decodeSettings({}),
76 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
77 Effect.gen(function* () {
78 const crypto = yield* Crypto.Crypto;
79 const fileSystem = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
82 const serverConfig = yield* ServerConfig;
83 const installation = yield* AntigravityInstallation;
84 const loggers = yield* ProviderEventLoggers;
85 const modelManifest = yield* ModelManifest.ModelManifest;
86 const settings = { ...config, enabled } satisfies AntigravitySettings;
87 const auth: AntigravityAuthConfig = {
88 authMethod: settings.authMethod,
89 apiKey: settings.apiKey,
90 gcpProject: settings.gcpProject,
91 gcpLocation: settings.gcpLocation,
92 };
93 const authConfigIssue = antigravityAuthConfigIssue(auth);
94 const processEnvironment = mergeProviderInstanceEnvironment(environment);
95 const userHome = resolveAntigravityUserHome(yield* HostProcessPlatform, processEnvironment);
96 const profileDirectory = resolveAntigravityProfileDirectory(
97 serverConfig.stateDir,
98 instanceId,
99 );
100 const continuationIdentity = defaultProviderContinuationIdentity({
101 driverKind: DRIVER,
102 instanceId,
103 });
104 const stampIdentity = withInstanceIdentity({
105 instanceId,
106 driverKind: DRIVER,
107 displayName,
108 accentColor,
109 continuationGroupKey: continuationIdentity.continuationKey,
110 });
111 // Google returns every model the account can use, including older
112 // Gemini generations. The manifest names the current ones so the picker
113 // folds the rest under its legacy section, as it does for Codex.
114 const classifyModels = (draft: ServerProviderDraft) =>
115 modelManifest.current.pipe(
116 Effect.map((manifest) =>
117 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER)),
118 ),
119 );
120​
121 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
122 input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
123 ): Effect.fn.Return<
124 AcpSessionRuntime["Service"],
125 AcpError | ProviderSetupError,
126 Scope.Scope
127 > {
128 if (authConfigIssue !== null) {
129 return yield* new ProviderSetupError({
130 instanceId,
131 operation: "configure",
132 detail: authConfigIssue,
133 });
134 }
135 const executable = yield* installation
136 .acquire(settings.binaryPath, processEnvironment)
137 .pipe(
138 Effect.mapError(
139 (cause) =>
140 new ProviderSetupError({
141 instanceId,
142 operation: "resolve",
143 detail: cause.detail,
144 }),
145 ),
146 );
147 const profile = yield* prepareAntigravityProfile({
148 profileDirectory,
149 baseEnv: processEnvironment,
150 auth,
151 userHome,
152 }).pipe(
153 Effect.provideService(FileSystem.FileSystem, fileSystem),
154 Effect.provideService(Path.Path, path),
155 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
156 );
157 const runtime = yield* makeAntigravityAcpRuntime({
158 ...input,
159 authMethod: auth.authMethod,
160 childProcessSpawner: spawner,
161 spawn: buildAntigravityAcpSpawnInput({
162 installation: executable,
163 profile,
164 cwd: input.cwd,
165 baseEnv: processEnvironment,
166 auth,
167 }),
168 }).pipe(Effect.provideService(Crypto.Crypto, crypto));
169 return {
170 ...runtime,
171 start: () =>
172 runtime
173 .start()
174 .pipe(
175 Effect.tapError((cause): Effect.Effect<void> =>
176 input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)
177 ? provider.onAuthRequired
178 : Effect.void,
179 ),
180 ),
181 };
182 });
183​
184 const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
185 input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
186 ) {
187 const cwd = yield* fileSystem
188 .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
189 .pipe(
190 Effect.mapError(
191 () =>
192 new ProviderSetupError({
193 instanceId,
194 operation: "start",
195 detail: "Could not create an Antigravity setup workspace.",
196 }),
197 ),
198 );
199 let sessionId: string | undefined;
200 yield* Effect.addFinalizer(() =>
201 removeAntigravitySessionFiles({
202 profileDirectory,
203 sessionId,
204 cwd,
205 }).pipe(
206 Effect.provideService(FileSystem.FileSystem, fileSystem),
207 Effect.provideService(Path.Path, path),
208 ),
209 );
210 const runtime = yield* makeRuntime({
211 cwd,
212 clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" },
213 mcpServers: [],
214 ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
215 });
216 return {
217 ...runtime,
218 start: () =>
219 runtime.start().pipe(
220 Effect.tap((started) =>
221 Effect.sync(() => {
222 sessionId = started.sessionId;
223 }),
224 ),
225 ),
226 };
227 });
228​
229 const publishCatalog = (
230 started: AcpSessionRuntimeStartResult,
231 runtime: Pick<AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,
232 ): Effect.Effect<void> =>
233 Effect.gen(function* () {
234 yield* provider.onSessionStarted(started);
235 yield* Stream.runForEach(runtime.getEvents(), (event) => {
236 if (event._tag === "EventStreamBarrier") {
237 return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
238 }
239 if (event._tag === "ConfigOptionsUpdated") {
240 return provider.onConfigOptionsUpdated(event.configOptions);
241 }
242 return event._tag === "AvailableCommandsUpdated"
243 ? provider.onAvailableCommands(event.availableCommands)
244 : Effect.void;
245 }).pipe(Effect.forkScoped);
246 yield* runtime.drainEvents;
247 }).pipe(Effect.scoped);
248​
249 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
250 instanceId,
251 makeRuntime: makeDisposableRuntime,
252 onAuthenticated: publishCatalog,
253 onSignedOut: Effect.suspend(() => provider.onSignedOut),
254 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
255 });
256​
257 // Kick the TTL-gated manifest refresh alongside the health check, as
258 // Codex and Claude do. Without it an environment that only runs
259 // Antigravity would keep classifying against a stale disk cache.
260 const probe = Effect.gen(function* () {
261 yield* modelManifest.refreshInBackground;
262 const processScope = yield* Scope.make();
263 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
264 return yield* authFlow
265 .withProcess(
266 Scope.close(processScope, Exit.void),
267 Effect.gen(function* () {
268 const runtime = yield* makeRuntime({
269 cwd: serverConfig.stateDir,
270 clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
271 mcpServers: [],
272 });
273 return yield* runtime.initialize();
274 }),
275 )
276 .pipe(Effect.provideService(Scope.Scope, processScope));
277 }).pipe(Effect.scoped);
278​
279 const provider = yield* makeAntigravityProvider(settings, {
280 stampIdentity: classifyModels,
281 probe,
282 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
283 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
284 Effect.provideService(FileSystem.FileSystem, fileSystem),
285 Effect.provideService(Path.Path, path),
286 Effect.orElseSucceed(() => false),
287 ),
288 }).pipe(
289 Effect.mapError(
290 (cause) =>
291 new ProviderDriverError({
292 driver: DRIVER,
293 instanceId,
294 detail: "Could not prepare the Antigravity provider status.",
295 cause,
296 }),
297 ),
298 );
299 const defaultModel = modelManifest.current.pipe(
300 Effect.map((manifest) => ModelManifest.manifestDefaultModel(manifest, DRIVER)),
301 );
302 const adapter = yield* makeAntigravityAdapter(settings, {
303 instanceId,
304 makeRuntime,
305 withProcess: authFlow.withProcess,
306 defaultModel,
307 onSessionStarted: provider.onSessionStarted,
308 onConfigOptionsUpdated: provider.onConfigOptionsUpdated,
309 onAvailableCommands: provider.onAvailableCommands,
310 onAuthRequired: provider.onAuthRequired,
311 ...(loggers.native ? { nativeEventLogger: loggers.native } : {}),
312 });
313 const textGeneration = yield* makeAntigravityTextGeneration({
314 profileDirectory,
315 defaultModel,
316 withProcess: authFlow.withProcess,
317 makeRuntime: (cwd) =>
318 makeRuntime({
319 cwd,
320 clientInfo: { name: "t3-code-text", version: "0.0.0" },
321 mcpServers: [],
322 }),
323 });
324​
325 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
326 function* () {
327 const processScope = yield* Scope.make();
328 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
329 yield* authFlow
330 .withProcess(
331 Scope.close(processScope, Exit.void),
332 Effect.gen(function* () {
333 const runtime = yield* makeDisposableRuntime({});
334 const started = yield* runtime.start();
335 yield* publishCatalog(started, runtime);
336 }),
337 )
338 .pipe(Effect.provideService(Scope.Scope, processScope));
339 },
340 Effect.scoped,
341 Effect.timeoutOrElse({
342 duration: "90 seconds",
343 orElse: () =>
344 Effect.fail(
345 new ProviderDriverError({
346 driver: DRIVER,
347 instanceId,
348 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
349 }),
350 ),
351 }),
352 Effect.tapError((cause) =>
353 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
354 ),
355 Effect.mapError((cause) =>
356 cause._tag === "ProviderDriverError"
357 ? cause
358 : new ProviderDriverError({
359 driver: DRIVER,
360 instanceId,
361 detail: isAntigravitySignInRequiredError(cause)
362 ? "Sign in to Antigravity in provider settings before refreshing models."
363 : cause._tag === "ProviderSetupError" && cause.operation === "configure"
364 ? cause.detail
365 : "Could not refresh Antigravity models. The previous model list is unchanged.",
366 cause,
367 }),
368 ),
369 );
370​
371 return {
372 instanceId,
373 driverKind: DRIVER,
374 continuationIdentity,
375 displayName,
376 accentColor,
377 enabled,
378 snapshot: provider.snapshot,
379 snapshotForCwd: (cwd) =>
380 !enabled
381 ? provider.snapshot.getSnapshot
382 : discoverAntigravitySkills({ cwd, userHome }).pipe(
383 Effect.provideService(FileSystem.FileSystem, fileSystem),
384 Effect.provideService(Path.Path, path),
385 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
386 Effect.mapError(
387 (cause) =>
388 new ProviderDriverError({
389 driver: DRIVER,
390 instanceId,
391 detail: "Could not read Antigravity workspace skills.",
392 cause,
393 }),
394 ),
395 ),
396 adapter,
397 textGeneration,
398 auth: authFlow.controller,
399 refreshModels,
400 } satisfies ProviderInstance;
401 }),
402};