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 * as AcpErrors from "effect-acp/errors";
31
32import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
33import {
34 isAntigravityTextGenerationAvailable,
35 makeAntigravityTextGeneration,
36} from "../../textGeneration/AntigravityTextGeneration.ts";
37import { makeAntigravityAuth, type AntigravityAuth } from "../AntigravityAuth.ts";
38import * as AntigravityInstallation from "../AntigravityInstallation.ts";
39import { brokenRuntimeError } from "../providerCompatibility.ts";
40import * as AntigravityUsage from "./AntigravityUsage.ts";
41import {
42 antigravityAuthConfigIssue,
43 antigravityAuthLabel,
44 antigravityAuthUsesBrowser,
45 buildAntigravityAcpSpawnInput,
46 isAntigravitySignInRequiredError,
47 prepareAntigravityProfile,
48 resolveAntigravityInstanceDirectories,
49 type AntigravityAuthConfig,
50} from "../antigravityAuthSupport.ts";
51import {
52 antigravityModelOptions,
53 antigravityServesT3Code,
54 antigravitySessionMode,
55 antigravityThinkingConfig,
56 makeAntigravityAcpRuntime,
57 OPEN_MODEL_ACCESS_RELEASE,
58 type AntigravityAcpRuntimeInput,
59} from "../acp/AntigravityAcpSupport.ts";
60import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
61import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
62import {
63 removeAntigravitySessionFiles,
64 retireAntigravityRuntimeTempDirs,
65} from "../acp/AntigravitySessionFiles.ts";
66import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
67import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
68import {
69 makeAntigravityAdapterV2,
70 type AntigravityAdapterV2RuntimeInput,
71} from "../../orchestration-v2/Adapters/AntigravityAdapterV2.ts";
72import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
73import { ProviderDriverError } from "../Errors.ts";
74import { makeAntigravityProvider } from "../AntigravityProvider.ts";
75import { makeAntigravityUsageProbe } from "../antigravityUsageLimits.ts";
76import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
77import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
78import {
79 defaultProviderContinuationIdentity,
80 type ProviderDriver,
81 type ProviderInstance,
82} from "@t3tools/provider-core/server/driver";
83import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
84import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
85import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";
86
87const DRIVER = ProviderDriverKind.make("antigravity");
88const decodeSettings = Schema.decodeSync(AntigravitySettings);
89const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError);
90const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
91const isProviderSetupError = Schema.is(ProviderSetupError);
92const isAcpErrorDetails = Schema.is(Schema.Struct({ details: Schema.String }));
93const RememberedRuntimeModes = Schema.fromJsonString(
94 Schema.Struct({ authMethod: Schema.String, modes: Schema.Array(RuntimeMode) }),
95);
96const decodeRememberedRuntimeModes = Schema.decodeUnknownOption(RememberedRuntimeModes);
97const encodeRememberedRuntimeModes = Schema.encodeSync(RememberedRuntimeModes);
98const REFRESH_FAILED =
99 "Could not refresh Antigravity models. The previous model list is unchanged.";
100const PYTHON_SOCKS_REQUIRED = "python-socks is required to use a SOCKS proxy";
101
102// Keep upstream diagnostics in cause; only recognized, fixed text reaches clients.
103function refreshFailureDetail(cause: unknown) {
104 return isAcpRequestError(cause) &&
105 cause.operation === "receive-response" &&
106 isAcpErrorDetails(cause.data) &&
107 cause.data.details.includes(PYTHON_SOCKS_REQUIRED)
108 ? `${REFRESH_FAILED} Antigravity reported: ${PYTHON_SOCKS_REQUIRED}`
109 : REFRESH_FAILED;
110}
111
112export type AntigravityDriverEnv =
113 | AntigravityInstallation.AntigravityInstallation
114 | ProviderHost.ProviderHost
115 | ChildProcessSpawner.ChildProcessSpawner
116 | Digest.Digest
117 | SecureRandom.SecureRandom
118 | FileSystem.FileSystem
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 path = yield* Path.Path;
147 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
148 const host = yield* ProviderHost.ProviderHost;
149 const selfInvocation = yield* resolveSelfInvocation();
150 const installation = yield* AntigravityInstallation.AntigravityInstallation;
151 const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
152 const modelCatalog = yield* ModelCatalog.ModelCatalog;
153 const currentCatalog = modelCatalog.current(DRIVER);
154 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
155 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
156 const settings = { ...config, enabled } satisfies AntigravitySettings;
157 const auth: AntigravityAuthConfig = {
158 authMethod: settings.authMethod,
159 // The instance registry has already read a referenced key from its secret provider.
160 apiKey: settingsSecretLiteral(settings.apiKey),
161 gcpProject: settings.gcpProject,
162 gcpLocation: settings.gcpLocation,
163 };
164 const authConfigIssue = antigravityAuthConfigIssue(auth);
165 const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);
166 const userHome = resolveAntigravityUserHome(
167 yield* HostProcess.Platform,
168 processEnvironment,
169 yield* HostProcess.HomeDirectory,
170 );
171 const directories = yield* resolveAntigravityInstanceDirectories(
172 host.paths.stateDir,
173 instanceId,
174 ).pipe(
175 Effect.provideService(Digest.Digest, digest),
176 Effect.provideService(Path.Path, path),
177 Effect.mapError(
178 (cause) =>
179 new ProviderDriverError({
180 driver: DRIVER,
181 instanceId,
182 detail: "Could not resolve the Antigravity profile directory.",
183 cause,
184 }),
185 ),
186 );
187 const profileDirectory = directories.profile;
188 // Only a session reports whether agy offers Auto, so keep the last answer across restarts.
189 const runtimeModesPath = path.join(profileDirectory, "t3-runtime-modes.json");
190 const rememberedRuntimeModes = yield* fileSystem.readFileString(runtimeModesPath).pipe(
191 Effect.map((contents) =>
192 decodeRememberedRuntimeModes(contents).pipe(
193 Option.filter((saved) => saved.authMethod === auth.authMethod),
194 Option.map((saved) => saved.modes),
195 Option.getOrUndefined,
196 ),
197 ),
198 Effect.orElseSucceed(() => undefined),
199 );
200 for (const directory of [
201 directories.runtimeTemp,
202 path.join(profileDirectory, "antigravity-acp", "tmp"),
203 ]) {
204 const removeRetired = yield* retireAntigravityRuntimeTempDirs(directory).pipe(
205 Effect.provideService(FileSystem.FileSystem, fileSystem),
206 Effect.provideService(Path.Path, path),
207 );
208 yield* Effect.forkScoped(removeRetired);
209 }
210 const continuationIdentity = defaultProviderContinuationIdentity({
211 driverKind: DRIVER,
212 instanceId,
213 });
214 const stampIdentity = withInstanceIdentity({
215 instanceId,
216 driverKind: DRIVER,
217 displayName,
218 accentColor,
219 continuationGroupKey: continuationIdentity.continuationKey,
220 });
221 const classifyModels = (draft: ServerProviderDraft) =>
222 currentCatalog.pipe(
223 Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),
224 );
225
226 const prepareSpawn = Effect.fn("AntigravityDriver.prepareSpawn")(function* (
227 cwd: string,
228 baseEnv: NodeJS.ProcessEnv,
229 ): Effect.fn.Return<
230 {
231 readonly executable: AntigravityInstallation.AntigravityExecutable;
232 readonly spawn: AcpSessionRuntime.AcpSpawnInput;
233 },
234 AcpErrors.AcpError | ProviderSetupError,
235 Scope.Scope
236 > {
237 if (authConfigIssue !== null) {
238 return yield* new ProviderSetupError({
239 instanceId,
240 operation: "configure",
241 detail: authConfigIssue,
242 });
243 }
244 const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe(
245 Effect.mapError(
246 (cause) =>
247 new ProviderSetupError({
248 instanceId,
249 operation: "resolve",
250 detail: cause.detail,
251 cause,
252 }),
253 ),
254 );
255 const profile = yield* prepareAntigravityProfile({
256 profileDirectory,
257 baseEnv: processEnvironment,
258 auth,
259 userHome,
260 tempDirectory: directories.runtimeTemp,
261 }).pipe(
262 Effect.provideService(FileSystem.FileSystem, fileSystem),
263 Effect.provideService(Path.Path, path),
264 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
265 Effect.mapError((cause) =>
266 isNodeRuntimeUnavailableError(cause.cause)
267 ? new ProviderSetupError({
268 instanceId,
269 operation: "start",
270 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
271 cause,
272 })
273 : cause,
274 ),
275 );
276 // Use one directory per process; shared cleanup could delete files another session still reads.
277 // Remove after the child dies, best-effort on Windows where handles may outlive the kill;
278 // the next driver start sweeps leftovers.
279 const runtimeTempDirectory = yield* Effect.acquireRelease(
280 fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
281 Effect.mapError(
282 (cause) =>
283 new ProviderSetupError({
284 instanceId,
285 operation: "start",
286 detail: "Could not create an Antigravity runtime temp directory.",
287 cause,
288 }),
289 ),
290 ),
291 (directory) =>
292 fileSystem
293 .remove(directory, { recursive: true, force: true })
294 .pipe(
295 Effect.catch(() =>
296 Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
297 ),
298 ),
299 );
300 return {
301 executable,
302 spawn: buildAntigravityAcpSpawnInput({
303 installation: executable,
304 profile,
305 cwd,
306 baseEnv,
307 auth,
308 runtimeTempDirectory,
309 }),
310 };
311 });
312
313 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
314 input: AntigravityAdapterV2RuntimeInput,
315 ): Effect.fn.Return<
316 AcpSessionRuntime.AcpSessionRuntime["Service"],
317 AcpErrors.AcpError | ProviderSetupError,
318 Scope.Scope
319 > {
320 // `buildAntigravityAcpSpawnInput` sets `extendEnv: false`, so thread variables only reach the
321 // agent's shell through `baseEnv`.
322 const { processEnvironment: threadEnvironment, ...runtimeInput } = input;
323 const { executable, spawn } = yield* prepareSpawn(
324 runtimeInput.cwd,
325 threadEnvironment === undefined
326 ? processEnvironment
327 : { ...processEnvironment, ...threadEnvironment },
328 );
329 const runtime = yield* makeAntigravityAcpRuntime({
330 ...runtimeInput,
331 authMethod: auth.authMethod,
332 childProcessSpawner: spawner,
333 spawn,
334 }).pipe(Effect.provideService(SecureRandom.SecureRandom, random));
335 // A custom or PATH executable has no version until it answers initialize.
336 const startCompatible = Effect.fn("AntigravityDriver.startCompatible")(function* () {
337 const version = (yield* runtime.initialize()).agentInfo?.version;
338 const advisory = version ? yield* installation.compatibility(version) : undefined;
339 const action =
340 executable.source === "managed"
341 ? "Update it in Antigravity setup"
342 : `Update the Antigravity executable at ${executable.executablePath}`;
343 const refused = !version
344 ? undefined
345 : (brokenRuntimeError({ instanceId, name: "Antigravity", version, advisory, action }) ??
346 (antigravityServesT3Code(version)
347 ? undefined
348 : new ProviderSetupError({
349 instanceId,
350 operation: "runtime",
351 detail: `Antigravity ${version} only serves allowlisted editors, not T3 Code. ${action} to ${OPEN_MODEL_ACCESS_RELEASE.join(".")} or newer, then retry.`,
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, { fromCatalogProbe: true });
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 authMethod: auth.authMethod,
581 baseEnv: processEnvironment,
582 profileDirectory,
583 resolveExecutable: installation.resolve(settings.binaryPath, processEnvironment),
584 }).pipe(
585 Effect.provideService(FileSystem.FileSystem, fileSystem),
586 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
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, session) =>
635 provider
636 .onSessionStarted(started, cwd, session)
637 .pipe(Effect.andThen(authFlow.onSignedInElsewhere)),
638 onSessionEvent: (event, cwd) => {
639 if (event._tag === "ConfigOptionsUpdated") {
640 return provider.onConfigOptionsUpdated(event.configOptions);
641 }
642 return event._tag === "AvailableCommandsUpdated"
643 ? provider.onAvailableCommands(event.availableCommands, cwd)
644 : Effect.void;
645 },
646 continuationRequests,
647 nativeLogging: (threadId) =>
648 makeNativeLogger({
649 nativeEventLogger: loggers.native,
650 provider: DRIVER,
651 threadId,
652 }),
653 });
654 const textGeneration = yield* makeAntigravityTextGeneration({
655 profileDirectory,
656 defaultModel,
657 withProcess: authFlow.withProcess,
658 makeRuntime: (cwd) =>
659 makeRuntime({
660 cwd,
661 mcpServers: [],
662 }),
663 });
664
665 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
666 function* () {
667 const processScope = yield* Scope.make();
668 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
669 yield* authFlow
670 .withProcess(
671 Scope.close(processScope, Exit.void),
672 Effect.gen(function* () {
673 const runtime = yield* makeDisposableRuntime({});
674 const started = yield* runtime.start();
675 yield* publishCatalog(started, runtime);
676 }),
677 )
678 .pipe(Effect.provideService(Scope.Scope, processScope));
679 },
680 Effect.scoped,
681 Effect.timeoutOrElse({
682 duration: "90 seconds",
683 orElse: () =>
684 Effect.fail(
685 new ProviderDriverError({
686 driver: DRIVER,
687 instanceId,
688 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
689 }),
690 ),
691 }),
692 Effect.tapError((cause) =>
693 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
694 ),
695 Effect.mapError((cause) =>
696 cause._tag === "ProviderDriverError"
697 ? cause
698 : new ProviderDriverError({
699 driver: DRIVER,
700 instanceId,
701 detail: isAntigravitySignInRequiredError(cause)
702 ? "Sign in to Antigravity in provider settings before refreshing models."
703 : cause._tag === "ProviderSetupError" &&
704 (cause.operation === "configure" ||
705 cause.operation === "resolve" ||
706 cause.operation === "start")
707 ? cause.detail
708 : cause._tag === "AcpTransportError" &&
709 isProviderSetupError(cause.cause) &&
710 cause.cause.operation === "runtime"
711 ? cause.cause.detail
712 : refreshFailureDetail(cause),
713 cause,
714 }),
715 ),
716 );
717
718 return {
719 instanceId,
720 driverKind: DRIVER,
721 continuationIdentity,
722 displayName,
723 accentColor,
724 enabled,
725 snapshot: provider.snapshot,
726 snapshotForCwd: (cwd) =>
727 !enabled
728 ? provider.snapshot.getSnapshot
729 : discoverAntigravitySkills({ cwd, userHome, profileDirectory }).pipe(
730 Effect.provideService(FileSystem.FileSystem, fileSystem),
731 Effect.provideService(Path.Path, path),
732 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
733 Effect.mapError(
734 (cause) =>
735 new ProviderDriverError({
736 driver: DRIVER,
737 instanceId,
738 detail: "Could not read Antigravity workspace skills.",
739 cause,
740 }),
741 ),
742 ),
743 orchestrationAdapter,
744 textGeneration,
745 auth: authFlow.controller,
746 refreshModels,
747 } satisfies ProviderInstance;
748 }),
749};