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

AntigravityDriver.ts

399 lines15.3 KB

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