Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityDriver.ts

730 lines27.7 KB

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