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