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