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
86export const AntigravityDriver: ProviderDriver<
87 AntigravitySettings,
88 AntigravityDriverEnv,
89 AntigravityUsage.AntigravityUsage
90> = {
91 driverKind: DRIVER,
92 metadata: { displayName: "Antigravity", supportsMultipleInstances: true },
93 configSchema: AntigravitySettings,
94 defaultConfig: () => decodeSettings({}),
95 usage: AntigravityUsage.antigravityUsageReader,
96 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
97 Effect.gen(function* () {
98 const crypto = yield* Crypto.Crypto;
99 const fileSystem = yield* FileSystem.FileSystem;
100 const httpClient = yield* HttpClient.HttpClient;
101 const path = yield* Path.Path;
102 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
103 const host = yield* ProviderHost.ProviderHost;
104 const selfInvocation = yield* resolveSelfInvocation();
105 const installation = yield* AntigravityInstallation.AntigravityInstallation;
106 const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
107 const modelCatalog = yield* ModelCatalog.ModelCatalog;
108 const currentCatalog = modelCatalog.current(DRIVER);
109 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
110 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
111 const settings = { ...config, enabled } satisfies AntigravitySettings;
112 const auth: AntigravityAuthConfig = {
113 authMethod: settings.authMethod,
114 apiKey: settings.apiKey,
115 gcpProject: settings.gcpProject,
116 gcpLocation: settings.gcpLocation,
117 };
118 const authConfigIssue = antigravityAuthConfigIssue(auth);
119 const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);
120 const userHome = resolveAntigravityUserHome(
121 yield* HostProcess.Platform,
122 processEnvironment,
123 yield* HostProcess.HomeDirectory,
124 );
125 const directories = yield* resolveAntigravityInstanceDirectories(
126 host.paths.stateDir,
127 instanceId,
128 ).pipe(
129 Effect.provideService(Crypto.Crypto, crypto),
130 Effect.provideService(Path.Path, path),
131 Effect.mapError(
132 (cause) =>
133 new ProviderDriverError({
134 driver: DRIVER,
135 instanceId,
136 detail: "Could not resolve the Antigravity profile directory.",
137 cause,
138 }),
139 ),
140 );
141 const profileDirectory = directories.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 // 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.
344 const probe = Effect.gen(function* () {
345 yield* modelCatalog.refreshInBackground;
346 if (authConfigIssue !== null) {
347 return yield* new ProviderSetupError({
348 instanceId,
349 operation: "configure",
350 detail: authConfigIssue,
351 });
352 }
353 const executable = yield* installation
354 .resolve(settings.binaryPath, processEnvironment)
355 .pipe(
356 Effect.mapError(
357 (cause) =>
358 new ProviderSetupError({
359 instanceId,
360 operation: "resolve",
361 detail: cause.detail,
362 cause,
363 }),
364 ),
365 );
366 return {
367 protocolVersion: 1,
368 agentCapabilities: {
369 loadSession: true,
370 promptCapabilities: { image: true, audio: true, embeddedContext: true },
371 sessionCapabilities: { list: {}, resume: {} },
372 },
373 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
374 agentInfo: {
375 name: "antigravity-acp",
376 title: "Google Antigravity",
377 version: executable.version ?? "unknown",
378 },
379 };
380 });
381
382 const usage = yield* makeAntigravityUsageProbe({
383 profileDirectory,
384 authMethod: auth.authMethod,
385 }).pipe(
386 Effect.provideService(FileSystem.FileSystem, fileSystem),
387 Effect.provideService(Path.Path, path),
388 Effect.provideService(Crypto.Crypto, crypto),
389 Effect.provideService(HttpClient.HttpClient, httpClient),
390 );
391 const provider = yield* makeAntigravityProvider(settings, {
392 stampIdentity: classifyModels,
393 probe,
394 probeUsage: usage.probe,
395 clearUsage: usage.clear,
396 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
397 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
398 Effect.provideService(FileSystem.FileSystem, fileSystem),
399 Effect.provideService(Path.Path, path),
400 Effect.orElseSucceed(() => false),
401 ),
402 }).pipe(
403 Effect.mapError(
404 (cause) =>
405 new ProviderDriverError({
406 driver: DRIVER,
407 instanceId,
408 detail: "Could not prepare the Antigravity provider status.",
409 cause,
410 }),
411 ),
412 );
413 const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
414 const orchestrationAdapter = yield* makeAntigravityAdapterV2({
415 instanceId,
416 selfInvocation,
417 makeRuntime,
418 withProcess: authFlow.withProcess,
419 defaultModel,
420 onSessionStarted: provider.onSessionStarted,
421 onSessionEvent: (event) => {
422 if (event._tag === "ConfigOptionsUpdated") {
423 return provider.onConfigOptionsUpdated(event.configOptions);
424 }
425 return event._tag === "AvailableCommandsUpdated"
426 ? provider.onAvailableCommands(event.availableCommands)
427 : Effect.void;
428 },
429 continuationRequests,
430 nativeLogging: (threadId) =>
431 makeNativeLogger({
432 nativeEventLogger: loggers.native,
433 provider: DRIVER,
434 threadId,
435 }),
436 });
437 const textGeneration = yield* makeAntigravityTextGeneration({
438 profileDirectory,
439 defaultModel,
440 withProcess: authFlow.withProcess,
441 makeRuntime: (cwd) =>
442 makeRuntime({
443 cwd,
444 clientInfo: { name: "t3-code-text", version: "0.0.0" },
445 mcpServers: [],
446 }),
447 });
448
449 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
450 function* () {
451 const processScope = yield* Scope.make();
452 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
453 yield* authFlow
454 .withProcess(
455 Scope.close(processScope, Exit.void),
456 Effect.gen(function* () {
457 const runtime = yield* makeDisposableRuntime({});
458 const started = yield* runtime.start();
459 yield* publishCatalog(started, runtime);
460 }),
461 )
462 .pipe(Effect.provideService(Scope.Scope, processScope));
463 },
464 Effect.scoped,
465 Effect.timeoutOrElse({
466 duration: "90 seconds",
467 orElse: () =>
468 Effect.fail(
469 new ProviderDriverError({
470 driver: DRIVER,
471 instanceId,
472 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
473 }),
474 ),
475 }),
476 Effect.tapError((cause) =>
477 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
478 ),
479 Effect.mapError((cause) =>
480 cause._tag === "ProviderDriverError"
481 ? cause
482 : new ProviderDriverError({
483 driver: DRIVER,
484 instanceId,
485 detail: isAntigravitySignInRequiredError(cause)
486 ? "Sign in to Antigravity in provider settings before refreshing models."
487 : cause._tag === "ProviderSetupError" &&
488 (cause.operation === "configure" || cause.operation === "start")
489 ? cause.detail
490 : "Could not refresh Antigravity models. The previous model list is unchanged.",
491 cause,
492 }),
493 ),
494 );
495
496 return {
497 instanceId,
498 driverKind: DRIVER,
499 continuationIdentity,
500 displayName,
501 accentColor,
502 enabled,
503 snapshot: provider.snapshot,
504 snapshotForCwd: (cwd) =>
505 !enabled
506 ? provider.snapshot.getSnapshot
507 : discoverAntigravitySkills({ cwd, userHome }).pipe(
508 Effect.provideService(FileSystem.FileSystem, fileSystem),
509 Effect.provideService(Path.Path, path),
510 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
511 Effect.mapError(
512 (cause) =>
513 new ProviderDriverError({
514 driver: DRIVER,
515 instanceId,
516 detail: "Could not read Antigravity workspace skills.",
517 cause,
518 }),
519 ),
520 ),
521 orchestrationAdapter,
522 textGeneration,
523 auth: authFlow.controller,
524 refreshModels,
525 } satisfies ProviderInstance;
526 }),
527};