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 { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
5import {
6 NodeRuntimeUnavailableError,
7 nodeRuntimeUnavailableMessage,
8} from "@t3tools/shared/nodeRuntime";
9import * as Crypto from "effect/Crypto";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
19import type { AcpError } from "effect-acp/errors";
20
21import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
22import * as ServerConfig from "../../config.ts";
23import * as ServerSettings from "../../serverSettings.ts";
24import {
25 isAntigravityTextGenerationAvailable,
26 makeAntigravityTextGeneration,
27} from "../../textGeneration/AntigravityTextGeneration.ts";
28import { makeAntigravityAuth, type AntigravityAuth } from "../AntigravityAuth.ts";
29import * as AntigravityInstallation from "../AntigravityInstallation.ts";
30import {
31 antigravityAuthConfigIssue,
32 antigravityAuthLabel,
33 antigravityAuthUsesBrowser,
34 buildAntigravityAcpSpawnInput,
35 isAntigravitySignInRequiredError,
36 prepareAntigravityProfile,
37 resolveAntigravityInstanceDirectories,
38 type AntigravityAuthConfig,
39} from "../antigravityAuthSupport.ts";
40import {
41 makeAntigravityAcpRuntime,
42 type AntigravityAcpRuntimeInput,
43} from "../acp/AntigravityAcpSupport.ts";
44import type { AcpSessionRuntime, AcpSessionRuntimeStartResult } from "../acp/AcpSessionRuntime.ts";
45import type { ServerProviderDraft } from "../providerSnapshot.ts";
46import {
47 removeAntigravityRuntimeTempDirs,
48 removeAntigravitySessionFiles,
49} from "../acp/AntigravitySessionFiles.ts";
50import * as IdAllocator from "../../orchestration-v2/IdAllocator.ts";
51import * as ProviderContinuationRequests from "../../orchestration-v2/ProviderContinuationRequests.ts";
52import { makeAntigravityAdapterV2 } from "../../orchestration-v2/Adapters/AntigravityAdapterV2.ts";
53import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
54import { ProviderDriverError } from "../Errors.ts";
55import { makeAntigravityProvider } from "../Layers/AntigravityProvider.ts";
56import * as ProviderEventLoggers from "../Layers/ProviderEventLoggers.ts";
57import * as ModelManifest from "../ModelManifest.ts";
58import {
59 defaultProviderContinuationIdentity,
60 type ProviderDriver,
61 type ProviderInstance,
62} from "../ProviderDriver.ts";
63import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
64import { withInstanceIdentity } from "./instanceIdentity.ts";
65import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";
66
67const DRIVER = ProviderDriverKind.make("antigravity");
68const decodeSettings = Schema.decodeSync(AntigravitySettings);
69const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError);
70
71export type AntigravityDriverEnv =
72 | AntigravityInstallation.AntigravityInstallation
73 | BackgroundPolicy.BackgroundPolicy
74 | ChildProcessSpawner.ChildProcessSpawner
75 | Crypto.Crypto
76 | FileSystem.FileSystem
77 | IdAllocator.IdAllocatorV2
78 | ModelManifest.ModelManifest
79 | Path.Path
80 | ProviderEventLoggers.ProviderEventLoggers
81 | ServerConfig.ServerConfig
82 | ServerSettings.ServerSettingsService;
83
84/** Each instance owns its Google profile. Executable releases are shared by the environment. */
85export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityDriverEnv> = {
86 driverKind: DRIVER,
87 metadata: { displayName: "Antigravity", supportsMultipleInstances: true },
88 configSchema: AntigravitySettings,
89 defaultConfig: () => decodeSettings({}),
90 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
91 Effect.gen(function* () {
92 const crypto = yield* Crypto.Crypto;
93 const fileSystem = yield* FileSystem.FileSystem;
94 const path = yield* Path.Path;
95 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
96 const serverConfig = yield* ServerConfig.ServerConfig;
97 const selfInvocation = yield* resolveSelfInvocation();
98 const installation = yield* AntigravityInstallation.AntigravityInstallation;
99 const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
100 const modelManifest = yield* ModelManifest.ModelManifest;
101 const idAllocator = yield* IdAllocator.IdAllocatorV2;
102 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
103 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
104 const settings = { ...config, enabled } satisfies AntigravitySettings;
105 const auth: AntigravityAuthConfig = {
106 authMethod: settings.authMethod,
107 apiKey: settings.apiKey,
108 gcpProject: settings.gcpProject,
109 gcpLocation: settings.gcpLocation,
110 };
111 const authConfigIssue = antigravityAuthConfigIssue(auth);
112 const processEnvironment = mergeProviderInstanceEnvironment(environment);
113 const userHome = resolveAntigravityUserHome(yield* HostProcessPlatform, processEnvironment);
114 const directories = yield* resolveAntigravityInstanceDirectories(
115 serverConfig.stateDir,
116 instanceId,
117 ).pipe(
118 Effect.provideService(Crypto.Crypto, crypto),
119 Effect.provideService(Path.Path, path),
120 Effect.mapError(
121 (cause) =>
122 new ProviderDriverError({
123 driver: DRIVER,
124 instanceId,
125 detail: "Could not resolve the Antigravity profile directory.",
126 cause,
127 }),
128 ),
129 );
130 const profileDirectory = directories.profile;
131 // No process of this instance exists yet, so every runtime temp
132 // directory it owns is an orphan from a killed server. Older builds
133 // unpacked inside the profile.
134 for (const directory of [
135 directories.runtimeTemp,
136 path.join(profileDirectory, "antigravity-acp", "tmp"),
137 ]) {
138 yield* removeAntigravityRuntimeTempDirs(directory).pipe(
139 Effect.provideService(FileSystem.FileSystem, fileSystem),
140 );
141 }
142 const continuationIdentity = defaultProviderContinuationIdentity({
143 driverKind: DRIVER,
144 instanceId,
145 });
146 const stampIdentity = withInstanceIdentity({
147 instanceId,
148 driverKind: DRIVER,
149 displayName,
150 accentColor,
151 continuationGroupKey: continuationIdentity.continuationKey,
152 });
153 // Google returns every model the account can use, including older
154 // Gemini generations. The manifest names the current ones so the picker
155 // folds the rest under its legacy section, as it does for Codex.
156 const classifyModels = (draft: ServerProviderDraft) =>
157 modelManifest.current.pipe(
158 Effect.map((manifest) =>
159 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER)),
160 ),
161 );
162
163 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
164 input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
165 ): Effect.fn.Return<
166 AcpSessionRuntime["Service"],
167 AcpError | ProviderSetupError,
168 Scope.Scope
169 > {
170 if (authConfigIssue !== null) {
171 return yield* new ProviderSetupError({
172 instanceId,
173 operation: "configure",
174 detail: authConfigIssue,
175 });
176 }
177 const executable = yield* installation
178 .acquire(settings.binaryPath, processEnvironment)
179 .pipe(
180 Effect.mapError(
181 (cause) =>
182 new ProviderSetupError({
183 instanceId,
184 operation: "resolve",
185 detail: cause.detail,
186 cause,
187 }),
188 ),
189 );
190 const profile = yield* prepareAntigravityProfile({
191 profileDirectory,
192 baseEnv: processEnvironment,
193 auth,
194 userHome,
195 tempDirectory: directories.runtimeTemp,
196 }).pipe(
197 Effect.provideService(FileSystem.FileSystem, fileSystem),
198 Effect.provideService(Path.Path, path),
199 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
200 Effect.mapError((cause) =>
201 isNodeRuntimeUnavailableError(cause.cause)
202 ? new ProviderSetupError({
203 instanceId,
204 operation: "start",
205 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
206 cause,
207 })
208 : cause,
209 ),
210 );
211 // Each process unpacks into its own directory that dies with the
212 // runtime scope, after the child is killed. A shared directory would
213 // let one session's teardown delete files a sibling still reads.
214 // Removal is best effort: a handle can outlive the kill on Windows,
215 // and the sweep on the next driver start reclaims what is left.
216 const runtimeTempDirectory = yield* Effect.acquireRelease(
217 fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
218 Effect.mapError(
219 (cause) =>
220 new ProviderSetupError({
221 instanceId,
222 operation: "start",
223 detail: "Could not create an Antigravity runtime temp directory.",
224 cause,
225 }),
226 ),
227 ),
228 (directory) =>
229 fileSystem
230 .remove(directory, { recursive: true, force: true })
231 .pipe(
232 Effect.catch(() =>
233 Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
234 ),
235 ),
236 );
237 const runtime = yield* makeAntigravityAcpRuntime({
238 ...input,
239 authMethod: auth.authMethod,
240 childProcessSpawner: spawner,
241 spawn: buildAntigravityAcpSpawnInput({
242 installation: executable,
243 profile,
244 cwd: input.cwd,
245 baseEnv: withAgentDeviceEnvironment(processEnvironment, input),
246 auth,
247 runtimeTempDirectory,
248 }),
249 }).pipe(Effect.provideService(Crypto.Crypto, crypto));
250 return {
251 ...runtime,
252 start: () =>
253 runtime
254 .start()
255 .pipe(
256 Effect.tapError((cause): Effect.Effect<void> =>
257 input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)
258 ? provider.onAuthRequired
259 : Effect.void,
260 ),
261 ),
262 };
263 });
264
265 const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
266 input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
267 ) {
268 const cwd = yield* fileSystem
269 .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
270 .pipe(
271 Effect.mapError(
272 () =>
273 new ProviderSetupError({
274 instanceId,
275 operation: "start",
276 detail: "Could not create an Antigravity setup workspace.",
277 }),
278 ),
279 );
280 let sessionId: string | undefined;
281 yield* Effect.addFinalizer(() =>
282 removeAntigravitySessionFiles({
283 profileDirectory,
284 sessionId,
285 cwd,
286 }).pipe(
287 Effect.provideService(FileSystem.FileSystem, fileSystem),
288 Effect.provideService(Path.Path, path),
289 ),
290 );
291 const runtime = yield* makeRuntime({
292 cwd,
293 clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" },
294 mcpServers: [],
295 ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
296 });
297 return {
298 ...runtime,
299 start: () =>
300 runtime.start().pipe(
301 Effect.tap((started) =>
302 Effect.sync(() => {
303 sessionId = started.sessionId;
304 }),
305 ),
306 ),
307 };
308 });
309
310 const publishCatalog = (
311 started: AcpSessionRuntimeStartResult,
312 runtime: Pick<AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,
313 ): Effect.Effect<void> =>
314 Effect.gen(function* () {
315 yield* provider.onSessionStarted(started);
316 yield* Stream.runForEach(runtime.getEvents(), (event) => {
317 if (event._tag === "EventStreamBarrier") {
318 return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
319 }
320 if (event._tag === "ConfigOptionsUpdated") {
321 return provider.onConfigOptionsUpdated(event.configOptions);
322 }
323 return event._tag === "AvailableCommandsUpdated"
324 ? provider.onAvailableCommands(event.availableCommands)
325 : Effect.void;
326 }).pipe(Effect.forkScoped);
327 yield* runtime.drainEvents;
328 }).pipe(Effect.scoped);
329
330 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
331 instanceId,
332 makeRuntime: makeDisposableRuntime,
333 onAuthenticated: publishCatalog,
334 onSignedOut: Effect.suspend(() => provider.onSignedOut),
335 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
336 });
337
338 // Kick the TTL-gated manifest refresh alongside the health check, as
339 // Codex and Claude do. Without it an environment that only runs
340 // Antigravity would keep classifying against a stale disk cache.
341 // The probe must not spawn. The agent is a PyInstaller one-file bundle
342 // that unpacks about 1 GB per launch, and the health check runs every
343 // minute. Resolving the install on disk is enough to report installed
344 // and version. The response below is synthetic: only agentInfo.version
345 // is read from it. Sessions and manual refreshes still spawn.
346 const probe = Effect.gen(function* () {
347 yield* modelManifest.refreshInBackground;
348 if (authConfigIssue !== null) {
349 return yield* new ProviderSetupError({
350 instanceId,
351 operation: "configure",
352 detail: authConfigIssue,
353 });
354 }
355 const executable = yield* installation
356 .resolve(settings.binaryPath, processEnvironment)
357 .pipe(
358 Effect.mapError(
359 (cause) =>
360 new ProviderSetupError({
361 instanceId,
362 operation: "resolve",
363 detail: cause.detail,
364 cause,
365 }),
366 ),
367 );
368 return {
369 protocolVersion: 1,
370 agentCapabilities: {
371 loadSession: true,
372 promptCapabilities: { image: true, audio: true, embeddedContext: true },
373 sessionCapabilities: { list: {}, resume: {} },
374 },
375 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
376 agentInfo: {
377 name: "antigravity-acp",
378 title: "Google Antigravity",
379 version: executable.version ?? "unknown",
380 },
381 };
382 });
383
384 const provider = yield* makeAntigravityProvider(settings, {
385 stampIdentity: classifyModels,
386 probe,
387 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
388 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
389 Effect.provideService(FileSystem.FileSystem, fileSystem),
390 Effect.provideService(Path.Path, path),
391 Effect.orElseSucceed(() => false),
392 ),
393 }).pipe(
394 Effect.mapError(
395 (cause) =>
396 new ProviderDriverError({
397 driver: DRIVER,
398 instanceId,
399 detail: "Could not prepare the Antigravity provider status.",
400 cause,
401 }),
402 ),
403 );
404 const defaultModel = modelManifest.current.pipe(
405 Effect.map((manifest) => ModelManifest.manifestDefaultModel(manifest, DRIVER)),
406 );
407 const orchestrationAdapter = makeAntigravityAdapterV2({
408 instanceId,
409 crypto,
410 fileSystem,
411 path,
412 idAllocator,
413 serverConfig,
414 selfInvocation,
415 makeRuntime,
416 withProcess: authFlow.withProcess,
417 defaultModel,
418 onSessionStarted: provider.onSessionStarted,
419 onSessionEvent: (event) => {
420 if (event._tag === "ConfigOptionsUpdated") {
421 return provider.onConfigOptionsUpdated(event.configOptions);
422 }
423 return event._tag === "AvailableCommandsUpdated"
424 ? provider.onAvailableCommands(event.availableCommands)
425 : Effect.void;
426 },
427 continuationRequests,
428 nativeLogging: (threadId) =>
429 makeNativeLogger({
430 nativeEventLogger: loggers.native,
431 provider: DRIVER,
432 threadId,
433 }),
434 });
435 const textGeneration = yield* makeAntigravityTextGeneration({
436 profileDirectory,
437 defaultModel,
438 withProcess: authFlow.withProcess,
439 makeRuntime: (cwd) =>
440 makeRuntime({
441 cwd,
442 clientInfo: { name: "t3-code-text", version: "0.0.0" },
443 mcpServers: [],
444 }),
445 });
446
447 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
448 function* () {
449 const processScope = yield* Scope.make();
450 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
451 yield* authFlow
452 .withProcess(
453 Scope.close(processScope, Exit.void),
454 Effect.gen(function* () {
455 const runtime = yield* makeDisposableRuntime({});
456 const started = yield* runtime.start();
457 yield* publishCatalog(started, runtime);
458 }),
459 )
460 .pipe(Effect.provideService(Scope.Scope, processScope));
461 },
462 Effect.scoped,
463 Effect.timeoutOrElse({
464 duration: "90 seconds",
465 orElse: () =>
466 Effect.fail(
467 new ProviderDriverError({
468 driver: DRIVER,
469 instanceId,
470 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
471 }),
472 ),
473 }),
474 Effect.tapError((cause) =>
475 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
476 ),
477 Effect.mapError((cause) =>
478 cause._tag === "ProviderDriverError"
479 ? cause
480 : new ProviderDriverError({
481 driver: DRIVER,
482 instanceId,
483 detail: isAntigravitySignInRequiredError(cause)
484 ? "Sign in to Antigravity in provider settings before refreshing models."
485 : cause._tag === "ProviderSetupError" &&
486 (cause.operation === "configure" || cause.operation === "start")
487 ? cause.detail
488 : "Could not refresh Antigravity models. The previous model list is unchanged.",
489 cause,
490 }),
491 ),
492 );
493
494 return {
495 instanceId,
496 driverKind: DRIVER,
497 continuationIdentity,
498 displayName,
499 accentColor,
500 enabled,
501 snapshot: provider.snapshot,
502 snapshotForCwd: (cwd) =>
503 !enabled
504 ? provider.snapshot.getSnapshot
505 : discoverAntigravitySkills({ cwd, userHome }).pipe(
506 Effect.provideService(FileSystem.FileSystem, fileSystem),
507 Effect.provideService(Path.Path, path),
508 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
509 Effect.mapError(
510 (cause) =>
511 new ProviderDriverError({
512 driver: DRIVER,
513 instanceId,
514 detail: "Could not read Antigravity workspace skills.",
515 cause,
516 }),
517 ),
518 ),
519 orchestrationAdapter,
520 textGeneration,
521 auth: authFlow.controller,
522 refreshModels,
523 } satisfies ProviderInstance;
524 }),
525};