Open History to see the last commit
1import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
2import {
3 AntigravitySettings,
4 ProviderDriverKind,
5 ProviderSetupError,
6 RuntimeMode,
7 settingsSecretLiteral,
8} from "@t3tools/contracts";
9import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
12import {
13 NodeRuntimeUnavailableError,
14 nodeRuntimeUnavailableMessage,
15} from "@t3tools/shared/nodeRuntime";
16import * as Digest from "effect/crypto/Digest";
17import * as SecureRandom from "effect/crypto/SecureRandom";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Exit from "effect/Exit";
21import * as Fiber from "effect/Fiber";
22import * as Option from "effect/Option";
23import * as FileSystem from "effect/FileSystem";
24import * as Path from "effect/Path";
25import * as Schema from "effect/Schema";
26import * as Scope from "effect/Scope";
27import * as Stream from "effect/Stream";
28import * as ChildProcess from "effect/process/ChildProcess";
29import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
30import { HttpClient } from "effect/http";
31import * as AcpErrors from "effect-acp/errors";
32
33import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
34import {
35 isAntigravityTextGenerationAvailable,
36 makeAntigravityTextGeneration,
37} from "../../textGeneration/AntigravityTextGeneration.ts";
38import { makeAntigravityAuth, type AntigravityAuth } from "../AntigravityAuth.ts";
39import * as AntigravityInstallation from "../AntigravityInstallation.ts";
40import { brokenRuntimeError } from "../providerCompatibility.ts";
41import * as AntigravityUsage from "./AntigravityUsage.ts";
42import {
43 antigravityAuthConfigIssue,
44 antigravityAuthLabel,
45 antigravityAuthUsesBrowser,
46 buildAntigravityAcpSpawnInput,
47 isAntigravitySignInRequiredError,
48 prepareAntigravityProfile,
49 resolveAntigravityInstanceDirectories,
50 type AntigravityAuthConfig,
51} from "../antigravityAuthSupport.ts";
52import {
53 antigravityModelOptions,
54 antigravitySessionMode,
55 antigravityThinkingConfig,
56 makeAntigravityAcpRuntime,
57 type AntigravityAcpRuntimeInput,
58} from "../acp/AntigravityAcpSupport.ts";
59import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
60import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
61import {
62 removeAntigravitySessionFiles,
63 retireAntigravityRuntimeTempDirs,
64} from "../acp/AntigravitySessionFiles.ts";
65import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
66import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
67import {
68 makeAntigravityAdapterV2,
69 type AntigravityAdapterV2RuntimeInput,
70} from "../../orchestration-v2/Adapters/AntigravityAdapterV2.ts";
71import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
72import { ProviderDriverError } from "../Errors.ts";
73import { makeAntigravityProvider } from "../AntigravityProvider.ts";
74import { makeAntigravityUsageProbe } from "../antigravityUsageLimits.ts";
75import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
76import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
77import {
78 defaultProviderContinuationIdentity,
79 type ProviderDriver,
80 type ProviderInstance,
81} from "@t3tools/provider-core/server/driver";
82import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
83import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
84import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";
85
86const DRIVER = ProviderDriverKind.make("antigravity");
87const decodeSettings = Schema.decodeSync(AntigravitySettings);
88const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError);
89const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
90const isProviderSetupError = Schema.is(ProviderSetupError);
91const isAcpErrorDetails = Schema.is(Schema.Struct({ details: Schema.String }));
92const RememberedRuntimeModes = Schema.fromJsonString(
93 Schema.Struct({ authMethod: Schema.String, modes: Schema.Array(RuntimeMode) }),
94);
95const decodeRememberedRuntimeModes = Schema.decodeUnknownOption(RememberedRuntimeModes);
96const encodeRememberedRuntimeModes = Schema.encodeSync(RememberedRuntimeModes);
97const REFRESH_FAILED =
98 "Could not refresh Antigravity models. The previous model list is unchanged.";
99const PYTHON_SOCKS_REQUIRED = "python-socks is required to use a SOCKS proxy";
100
101// Keep upstream diagnostics in cause; only recognized, fixed text reaches clients.
102function refreshFailureDetail(cause: unknown) {
103 return isAcpRequestError(cause) &&
104 cause.operation === "receive-response" &&
105 isAcpErrorDetails(cause.data) &&
106 cause.data.details.includes(PYTHON_SOCKS_REQUIRED)
107 ? `${REFRESH_FAILED} Antigravity reported: ${PYTHON_SOCKS_REQUIRED}`
108 : REFRESH_FAILED;
109}
110
111export type AntigravityDriverEnv =
112 | AntigravityInstallation.AntigravityInstallation
113 | ProviderHost.ProviderHost
114 | ChildProcessSpawner.ChildProcessSpawner
115 | Digest.Digest
116 | SecureRandom.SecureRandom
117 | FileSystem.FileSystem
118 | HttpClient.HttpClient
119 | IdAllocator.IdAllocatorV2
120 | McpProviderSessions.McpProviderSessions
121 | ModelCatalog.ModelCatalog
122 | Path.Path
123 | ProviderEventLoggers.ProviderEventLoggers;
124
125export const AntigravityDriver: ProviderDriver<
126 AntigravitySettings,
127 AntigravityDriverEnv,
128 AntigravityUsage.AntigravityUsage
129> = {
130 driverKind: DRIVER,
131 metadata: { displayName: "Antigravity", supportsMultipleInstances: true },
132 configSchema: AntigravitySettings,
133 defaultConfig: () => decodeSettings({}),
134 usage: AntigravityUsage.antigravityUsageReader,
135 create: Effect.fn("AntigravityDriver.create")(function* ({
136 instanceId,
137 displayName,
138 accentColor,
139 environment,
140 enabled,
141 config,
142 }) {
143 const digest = yield* Digest.Digest;
144 const random = yield* SecureRandom.SecureRandom;
145 const fileSystem = yield* FileSystem.FileSystem;
146 const httpClient = yield* HttpClient.HttpClient;
147 const path = yield* Path.Path;
148 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
149 const host = yield* ProviderHost.ProviderHost;
150 const selfInvocation = yield* resolveSelfInvocation();
151 const installation = yield* AntigravityInstallation.AntigravityInstallation;
152 const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
153 const modelCatalog = yield* ModelCatalog.ModelCatalog;
154 const currentCatalog = modelCatalog.current(DRIVER);
155 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
156 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
157 const settings = { ...config, enabled } satisfies AntigravitySettings;
158 const auth: AntigravityAuthConfig = {
159 authMethod: settings.authMethod,
160 // The instance registry has already read a referenced key from its secret provider.
161 apiKey: settingsSecretLiteral(settings.apiKey),
162 gcpProject: settings.gcpProject,
163 gcpLocation: settings.gcpLocation,
164 };
165 const authConfigIssue = antigravityAuthConfigIssue(auth);
166 const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);
167 const userHome = resolveAntigravityUserHome(
168 yield* HostProcess.Platform,
169 processEnvironment,
170 yield* HostProcess.HomeDirectory,
171 );
172 const directories = yield* resolveAntigravityInstanceDirectories(
173 host.paths.stateDir,
174 instanceId,
175 ).pipe(
176 Effect.provideService(Digest.Digest, digest),
177 Effect.provideService(Path.Path, path),
178 Effect.mapError(
179 (cause) =>
180 new ProviderDriverError({
181 driver: DRIVER,
182 instanceId,
183 detail: "Could not resolve the Antigravity profile directory.",
184 cause,
185 }),
186 ),
187 );
188 const profileDirectory = directories.profile;
189 // Only a session reports whether agy offers Auto, so keep the last answer across restarts.
190 const runtimeModesPath = path.join(profileDirectory, "t3-runtime-modes.json");
191 const rememberedRuntimeModes = yield* fileSystem.readFileString(runtimeModesPath).pipe(
192 Effect.map((contents) =>
193 decodeRememberedRuntimeModes(contents).pipe(
194 Option.filter((saved) => saved.authMethod === auth.authMethod),
195 Option.map((saved) => saved.modes),
196 Option.getOrUndefined,
197 ),
198 ),
199 Effect.orElseSucceed(() => undefined),
200 );
201 for (const directory of [
202 directories.runtimeTemp,
203 path.join(profileDirectory, "antigravity-acp", "tmp"),
204 ]) {
205 const removeRetired = yield* retireAntigravityRuntimeTempDirs(directory).pipe(
206 Effect.provideService(FileSystem.FileSystem, fileSystem),
207 Effect.provideService(Path.Path, path),
208 );
209 yield* Effect.forkScoped(removeRetired);
210 }
211 const continuationIdentity = defaultProviderContinuationIdentity({
212 driverKind: DRIVER,
213 instanceId,
214 });
215 const stampIdentity = withInstanceIdentity({
216 instanceId,
217 driverKind: DRIVER,
218 displayName,
219 accentColor,
220 continuationGroupKey: continuationIdentity.continuationKey,
221 });
222 const classifyModels = (draft: ServerProviderDraft) =>
223 currentCatalog.pipe(
224 Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),
225 );
226
227 const prepareSpawn = Effect.fn("AntigravityDriver.prepareSpawn")(function* (
228 cwd: string,
229 baseEnv: NodeJS.ProcessEnv,
230 ): Effect.fn.Return<
231 {
232 readonly executable: AntigravityInstallation.AntigravityExecutable;
233 readonly spawn: AcpSessionRuntime.AcpSpawnInput;
234 },
235 AcpErrors.AcpError | ProviderSetupError,
236 Scope.Scope
237 > {
238 if (authConfigIssue !== null) {
239 return yield* new ProviderSetupError({
240 instanceId,
241 operation: "configure",
242 detail: authConfigIssue,
243 });
244 }
245 const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe(
246 Effect.mapError(
247 (cause) =>
248 new ProviderSetupError({
249 instanceId,
250 operation: "resolve",
251 detail: cause.detail,
252 cause,
253 }),
254 ),
255 );
256 const profile = yield* prepareAntigravityProfile({
257 profileDirectory,
258 baseEnv: processEnvironment,
259 auth,
260 userHome,
261 tempDirectory: directories.runtimeTemp,
262 }).pipe(
263 Effect.provideService(FileSystem.FileSystem, fileSystem),
264 Effect.provideService(Path.Path, path),
265 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
266 Effect.mapError((cause) =>
267 isNodeRuntimeUnavailableError(cause.cause)
268 ? new ProviderSetupError({
269 instanceId,
270 operation: "start",
271 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
272 cause,
273 })
274 : cause,
275 ),
276 );
277 // Use one directory per process; shared cleanup could delete files another session still reads.
278 // Remove after the child dies, best-effort on Windows where handles may outlive the kill;
279 // the next driver start sweeps leftovers.
280 const runtimeTempDirectory = yield* Effect.acquireRelease(
281 fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
282 Effect.mapError(
283 (cause) =>
284 new ProviderSetupError({
285 instanceId,
286 operation: "start",
287 detail: "Could not create an Antigravity runtime temp directory.",
288 cause,
289 }),
290 ),
291 ),
292 (directory) =>
293 fileSystem
294 .remove(directory, { recursive: true, force: true })
295 .pipe(
296 Effect.catch(() =>
297 Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
298 ),
299 ),
300 );
301 return {
302 executable,
303 spawn: buildAntigravityAcpSpawnInput({
304 installation: executable,
305 profile,
306 cwd,
307 baseEnv,
308 auth,
309 runtimeTempDirectory,
310 }),
311 };
312 });
313
314 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
315 input: AntigravityAdapterV2RuntimeInput,
316 ): Effect.fn.Return<
317 AcpSessionRuntime.AcpSessionRuntime["Service"],
318 AcpErrors.AcpError | ProviderSetupError,
319 Scope.Scope
320 > {
321 // `buildAntigravityAcpSpawnInput` sets `extendEnv: false`, so thread variables only reach the
322 // agent's shell through `baseEnv`.
323 const { processEnvironment: threadEnvironment, ...runtimeInput } = input;
324 const { executable, spawn } = yield* prepareSpawn(
325 runtimeInput.cwd,
326 threadEnvironment === undefined
327 ? processEnvironment
328 : { ...processEnvironment, ...threadEnvironment },
329 );
330 const runtime = yield* makeAntigravityAcpRuntime({
331 ...runtimeInput,
332 runtimeVersion: executable.version,
333 authMethod: auth.authMethod,
334 childProcessSpawner: spawner,
335 spawn,
336 }).pipe(Effect.provideService(SecureRandom.SecureRandom, random));
337 // A custom or PATH executable has no version until it answers initialize.
338 const startCompatible = Effect.fn("AntigravityDriver.startCompatible")(function* () {
339 const version = (yield* runtime.initialize()).agentInfo?.version;
340 const advisory = version ? yield* installation.compatibility(version) : undefined;
341 const refused =
342 version &&
343 brokenRuntimeError({
344 instanceId,
345 name: "Antigravity",
346 version,
347 advisory,
348 action:
349 executable.source === "managed"
350 ? "Update it in Antigravity setup"
351 : `Update the Antigravity executable at ${executable.executablePath}`,
352 });
353 if (refused) {
354 return yield* new AcpErrors.AcpTransportError({ detail: refused.detail, cause: refused });
355 }
356 return yield* runtime.start();
357 });
358 return {
359 ...runtime,
360 setMode: (modeId: string) =>
361 runtime.getModeState.pipe(
362 Effect.flatMap((modeState) =>
363 runtime.setMode(antigravitySessionMode(modeId, modeState)),
364 ),
365 ),
366 start: () =>
367 startCompatible().pipe(
368 Effect.tapError((cause): Effect.Effect<void> =>
369 runtimeInput.onAuthorizationUrl === undefined &&
370 isAntigravitySignInRequiredError(cause)
371 ? provider.onAuthRequired
372 : Effect.void,
373 ),
374 ),
375 };
376 });
377
378 const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
379 input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
380 ) {
381 const cwd = yield* fileSystem
382 .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
383 .pipe(
384 Effect.mapError(
385 () =>
386 new ProviderSetupError({
387 instanceId,
388 operation: "start",
389 detail: "Could not create an Antigravity setup workspace.",
390 }),
391 ),
392 );
393 let sessionId: string | undefined;
394 yield* Effect.addFinalizer(() =>
395 removeAntigravitySessionFiles({
396 profileDirectory,
397 sessionId,
398 cwd,
399 }).pipe(
400 Effect.provideService(FileSystem.FileSystem, fileSystem),
401 Effect.provideService(Path.Path, path),
402 ),
403 );
404 const runtime = yield* makeRuntime({
405 cwd,
406 mcpServers: [],
407 ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
408 });
409 return {
410 ...runtime,
411 start: () =>
412 runtime.start().pipe(
413 Effect.tap((started) =>
414 Effect.sync(() => {
415 sessionId = started.sessionId;
416 }),
417 ),
418 ),
419 };
420 });
421
422 // The agy CLI ignores T3's browser helper during ACP `authenticate`, so Google sign-in runs its
423 // remote-friendly `--login`, which stores the sign-in where the ACP process reads it.
424 const codeLogin = Effect.fn("AntigravityDriver.codeLogin")(function* (input: {
425 readonly onAuthorizationUrl: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
426 }) {
427 if (auth.authMethod !== "oauth-personal") return undefined;
428 const cwd = yield* fileSystem
429 .makeTempDirectoryScoped({ prefix: "t3-antigravity-login-" })
430 .pipe(
431 Effect.mapError(
432 () =>
433 new ProviderSetupError({
434 instanceId,
435 operation: "start",
436 detail: "Could not create an Antigravity setup workspace.",
437 }),
438 ),
439 );
440 const { spawn } = yield* prepareSpawn(cwd, processEnvironment);
441 const failed = (detail: string, cause?: unknown) =>
442 new ProviderSetupError({ instanceId, operation: "start", detail, cause });
443 // Without a display it prints the link only, instead of opening a browser on this machine.
444 const { DISPLAY: _display, WAYLAND_DISPLAY: _wayland, ...env } = spawn.env ?? {};
445 const child = yield* spawner
446 .spawn(
447 ChildProcess.make(spawn.command, [...spawn.args, "--login"], {
448 cwd,
449 env,
450 extendEnv: false,
451 shell: false,
452 }),
453 )
454 .pipe(Effect.mapError((cause) => failed("Could not start Antigravity sign-in.", cause)));
455 const code = yield* Deferred.make<string>();
456 yield* Stream.fromEffect(Deferred.await(code)).pipe(
457 Stream.map((response) => `${response}\n`),
458 Stream.encodeText,
459 Stream.run(child.stdin),
460 Effect.ignore,
461 Effect.forkScoped,
462 );
463 const output = yield* child.stdout.pipe(
464 Stream.decodeText(),
465 Stream.splitLines,
466 Stream.map((line) => line.trim()),
467 Stream.runForEach((line) =>
468 line.startsWith("https://accounts.google.com/")
469 ? input.onAuthorizationUrl(line)
470 : Effect.void,
471 ),
472 Effect.forkScoped,
473 );
474 yield* Stream.runDrain(child.stderr).pipe(Effect.ignore, Effect.forkScoped);
475 return {
476 submit: (response: string) => Deferred.succeed(code, response).pipe(Effect.asVoid),
477 completed: Effect.gen(function* () {
478 // Stdout closes when the process exits, or this fails first on an unusable link.
479 yield* Fiber.join(output).pipe(
480 Effect.mapError((cause) =>
481 failed("Antigravity returned an invalid Google sign-in link.", cause),
482 ),
483 );
484 const exitCode = yield* child.exitCode.pipe(
485 Effect.mapError((cause) => failed("Antigravity sign-in stopped unexpectedly.", cause)),
486 );
487 if (Number(exitCode) !== 0) {
488 return yield* failed(
489 "Antigravity could not finish Google sign-in. Start sign-in again.",
490 );
491 }
492 }),
493 };
494 });
495
496 const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* (
497 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
498 runtime: Pick<
499 AcpSessionRuntime.AcpSessionRuntime["Service"],
500 "getEvents" | "drainEvents" | "setModel"
501 >,
502 ) {
503 yield* provider.onSessionStarted(started);
504 yield* authFlow.onSignedInElsewhere;
505 yield* Stream.runForEach(runtime.getEvents(), (event) => {
506 if (event._tag === "EventStreamBarrier") {
507 return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
508 }
509 if (event._tag === "ConfigOptionsUpdated") {
510 return provider.onConfigOptionsUpdated(event.configOptions);
511 }
512 return event._tag === "AvailableCommandsUpdated"
513 ? provider.onAvailableCommands(event.availableCommands)
514 : Effect.void;
515 }).pipe(Effect.forkScoped);
516 // Thinking levels differ per model and are reported only for the selected one.
517 const configOptions = started.sessionSetupResult.configOptions ?? [];
518 const current = configOptions.find((option) => option.id === "model")?.currentValue;
519 if (antigravityThinkingConfig(configOptions) !== undefined && typeof current === "string") {
520 for (const model of [...antigravityModelOptions(configOptions), { value: current }]) {
521 yield* runtime.setModel(model.value).pipe(Effect.ignore);
522 }
523 }
524 yield* runtime.drainEvents;
525 }, Effect.scoped);
526
527 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
528 instanceId,
529 makeRuntime: makeDisposableRuntime,
530 // A new sign-in may be another account; drop any in-flight quota read first.
531 onAuthenticated: (started, runtime) =>
532 Effect.suspend(() => provider.onSignedIn).pipe(
533 Effect.andThen(publishCatalog(started, runtime)),
534 ),
535 onSignedOut: Effect.suspend(() => provider.onSignedOut),
536 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
537 codeLogin,
538 });
539
540 // The probe must not spawn. The agent is a PyInstaller one-file bundle
541 // that unpacks about 1 GB per launch, and the health check runs every
542 // minute.
543 const probe = Effect.gen(function* () {
544 yield* modelCatalog.refreshInBackground;
545 if (authConfigIssue !== null) {
546 return yield* new ProviderSetupError({
547 instanceId,
548 operation: "configure",
549 detail: authConfigIssue,
550 });
551 }
552 const executable = yield* installation.resolve(settings.binaryPath, processEnvironment).pipe(
553 Effect.mapError(
554 (cause) =>
555 new ProviderSetupError({
556 instanceId,
557 operation: "resolve",
558 detail: cause.detail,
559 cause,
560 }),
561 ),
562 );
563 return {
564 protocolVersion: 1,
565 agentCapabilities: {
566 loadSession: true,
567 promptCapabilities: { image: true, audio: true, embeddedContext: true },
568 sessionCapabilities: { list: {}, resume: {} },
569 },
570 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
571 agentInfo: {
572 name: "antigravity-acp",
573 title: "Google Antigravity",
574 version: executable.version ?? "unknown",
575 },
576 };
577 });
578
579 const usage = yield* makeAntigravityUsageProbe({
580 profileDirectory,
581 authMethod: auth.authMethod,
582 }).pipe(
583 Effect.provideService(FileSystem.FileSystem, fileSystem),
584 Effect.provideService(Path.Path, path),
585 Effect.provideService(Digest.Digest, digest),
586 Effect.provideService(HttpClient.HttpClient, httpClient),
587 );
588 const provider = yield* makeAntigravityProvider(settings, {
589 environment: processEnvironment,
590 stampIdentity: classifyModels,
591 probe,
592 probeUsage: usage.probe,
593 clearUsage: usage.clear,
594 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
595 ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}),
596 rememberRuntimeModes: (modes) =>
597 writeFileStringAtomically({
598 filePath: runtimeModesPath,
599 contents: encodeRememberedRuntimeModes({ authMethod: auth.authMethod, modes }),
600 }).pipe(
601 Effect.provideService(FileSystem.FileSystem, fileSystem),
602 Effect.provideService(Path.Path, path),
603 Effect.catch(() => Effect.logWarning("Could not save Antigravity permission modes.")),
604 ),
605 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
606 Effect.provideService(FileSystem.FileSystem, fileSystem),
607 Effect.provideService(Path.Path, path),
608 Effect.orElseSucceed(() => false),
609 ),
610 }).pipe(
611 Effect.mapError(
612 (cause) =>
613 new ProviderDriverError({
614 driver: DRIVER,
615 instanceId,
616 detail: "Could not prepare the Antigravity provider status.",
617 cause,
618 }),
619 ),
620 );
621 const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
622 const orchestrationAdapter = yield* makeAntigravityAdapterV2({
623 instanceId,
624 selfInvocation,
625 makeRuntime,
626 withProcess: authFlow.withProcess,
627 defaultModel,
628 supportsNativeGoals: provider.snapshot.getSnapshot.pipe(
629 Effect.map(
630 (snapshot) => snapshot.slashCommands?.some((command) => command.name === "goal") === true,
631 ),
632 ),
633 profileDirectory,
634 onSessionStarted: (started, cwd) =>
635 provider.onSessionStarted(started, cwd).pipe(Effect.andThen(authFlow.onSignedInElsewhere)),
636 onSessionEvent: (event, cwd) => {
637 if (event._tag === "ConfigOptionsUpdated") {
638 return provider.onConfigOptionsUpdated(event.configOptions);
639 }
640 return event._tag === "AvailableCommandsUpdated"
641 ? provider.onAvailableCommands(event.availableCommands, cwd)
642 : Effect.void;
643 },
644 continuationRequests,
645 nativeLogging: (threadId) =>
646 makeNativeLogger({
647 nativeEventLogger: loggers.native,
648 provider: DRIVER,
649 threadId,
650 }),
651 });
652 const textGeneration = yield* makeAntigravityTextGeneration({
653 profileDirectory,
654 defaultModel,
655 withProcess: authFlow.withProcess,
656 makeRuntime: (cwd) =>
657 makeRuntime({
658 cwd,
659 mcpServers: [],
660 }),
661 });
662
663 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
664 function* () {
665 const processScope = yield* Scope.make();
666 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
667 yield* authFlow
668 .withProcess(
669 Scope.close(processScope, Exit.void),
670 Effect.gen(function* () {
671 const runtime = yield* makeDisposableRuntime({});
672 const started = yield* runtime.start();
673 yield* publishCatalog(started, runtime);
674 }),
675 )
676 .pipe(Effect.provideService(Scope.Scope, processScope));
677 },
678 Effect.scoped,
679 Effect.timeoutOrElse({
680 duration: "90 seconds",
681 orElse: () =>
682 Effect.fail(
683 new ProviderDriverError({
684 driver: DRIVER,
685 instanceId,
686 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
687 }),
688 ),
689 }),
690 Effect.tapError((cause) =>
691 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
692 ),
693 Effect.mapError((cause) =>
694 cause._tag === "ProviderDriverError"
695 ? cause
696 : new ProviderDriverError({
697 driver: DRIVER,
698 instanceId,
699 detail: isAntigravitySignInRequiredError(cause)
700 ? "Sign in to Antigravity in provider settings before refreshing models."
701 : cause._tag === "ProviderSetupError" &&
702 (cause.operation === "configure" || cause.operation === "start")
703 ? cause.detail
704 : cause._tag === "AcpTransportError" &&
705 isProviderSetupError(cause.cause) &&
706 cause.cause.operation === "runtime"
707 ? cause.cause.detail
708 : refreshFailureDetail(cause),
709 cause,
710 }),
711 ),
712 );
713
714 return {
715 instanceId,
716 driverKind: DRIVER,
717 continuationIdentity,
718 displayName,
719 accentColor,
720 enabled,
721 snapshot: provider.snapshot,
722 snapshotForCwd: (cwd) =>
723 !enabled
724 ? provider.snapshot.getSnapshot
725 : discoverAntigravitySkills({ cwd, userHome, profileDirectory }).pipe(
726 Effect.provideService(FileSystem.FileSystem, fileSystem),
727 Effect.provideService(Path.Path, path),
728 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
729 Effect.mapError(
730 (cause) =>
731 new ProviderDriverError({
732 driver: DRIVER,
733 instanceId,
734 detail: "Could not read Antigravity workspace skills.",
735 cause,
736 }),
737 ),
738 ),
739 orchestrationAdapter,
740 textGeneration,
741 auth: authFlow.controller,
742 refreshModels,
743 } satisfies ProviderInstance;
744 }),
745};