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