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