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