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