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