Open History to see the last commit
1import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
2import {
3 AntigravitySettings,
4 ProviderDriverKind,
5 type ProviderInstallState,
6 ProviderSetupError,
7 RuntimeMode,
8 type ServerProvider,
9 settingsSecretLiteral,
10} from "@t3tools/contracts";
11import {
12 createProviderVersionAdvisory,
13 makeManualOnlyProviderMaintenanceCapabilities,
14 type ProviderMaintenanceCapabilities,
15} from "@t3tools/provider-core/server/maintenanceResolver";
16import type { ProviderMaintenanceManagedAction } from "@t3tools/provider-core/server/maintenance";
17import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
20import {
21 NodeRuntimeUnavailableError,
22 nodeRuntimeUnavailableMessage,
23} from "@t3tools/shared/nodeRuntime";
24import * as Digest from "effect/crypto/Digest";
25import * as SecureRandom from "effect/crypto/SecureRandom";
26import * as Deferred from "effect/Deferred";
27import * as Effect from "effect/Effect";
28import * as Equal from "effect/Equal";
29import * as Exit from "effect/Exit";
30import * as Fiber from "effect/Fiber";
31import * as Option from "effect/Option";
32import * as FileSystem from "effect/FileSystem";
33import * as Path from "effect/Path";
34import * as Schema from "effect/Schema";
35import * as Scope from "effect/Scope";
36import * as Stream from "effect/Stream";
37import * as ChildProcess from "effect/process/ChildProcess";
38import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
39import * as AcpErrors from "effect-acp/errors";
40
41import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
42import {
43 isAntigravityTextGenerationAvailable,
44 makeAntigravityTextGeneration,
45} from "../../textGeneration/AntigravityTextGeneration.ts";
46import { makeAntigravityAuth, type AntigravityAuth } from "../AntigravityAuth.ts";
47import * as AntigravityInstallation from "../AntigravityInstallation.ts";
48import { brokenRuntimeError } from "../providerCompatibility.ts";
49import * as AntigravityUsage from "./AntigravityUsage.ts";
50import {
51 antigravityAuthConfigIssue,
52 antigravityAuthLabel,
53 antigravityAuthUsesBrowser,
54 buildAntigravityAcpSpawnInput,
55 isAntigravitySignInRequiredError,
56 prepareAntigravityProfile,
57 resolveAntigravityInstanceDirectories,
58 type AntigravityAuthConfig,
59} from "../antigravityAuthSupport.ts";
60import {
61 antigravityModelOptions,
62 antigravityServesT3Code,
63 antigravitySessionMode,
64 antigravityThinkingConfig,
65 makeAntigravityAcpRuntime,
66 OPEN_MODEL_ACCESS_RELEASE,
67 type AntigravityAcpRuntimeInput,
68} from "../acp/AntigravityAcpSupport.ts";
69import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
70import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
71import {
72 removeAntigravitySessionFiles,
73 retireAntigravityRuntimeTempDirs,
74} from "../acp/AntigravitySessionFiles.ts";
75import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
76import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
77import {
78 makeAntigravityAdapterV2,
79 type AntigravityAdapterV2RuntimeInput,
80} from "../../orchestration-v2/Adapters/AntigravityAdapterV2.ts";
81import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
82import { ProviderDriverError } from "../Errors.ts";
83import {
84 AntigravityProbeIncompatibility,
85 makeAntigravityProvider,
86} from "../AntigravityProvider.ts";
87import { makeAntigravityUsageProbe } from "../antigravityUsageLimits.ts";
88import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
89import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
90import {
91 defaultProviderContinuationIdentity,
92 type ProviderDriver,
93 type ProviderInstance,
94} from "@t3tools/provider-core/server/driver";
95import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
96import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
97import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
98import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";
99
100const DRIVER = ProviderDriverKind.make("antigravity");
101const decodeSettings = Schema.decodeSync(AntigravitySettings);
102const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError);
103const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
104const isProviderSetupError = Schema.is(ProviderSetupError);
105const isAcpErrorDetails = Schema.is(Schema.Struct({ details: Schema.String }));
106const RememberedRuntimeModes = Schema.fromJsonString(
107 Schema.Struct({ authMethod: Schema.String, modes: Schema.Array(RuntimeMode) }),
108);
109const decodeRememberedRuntimeModes = Schema.decodeUnknownOption(RememberedRuntimeModes);
110const encodeRememberedRuntimeModes = Schema.encodeSync(RememberedRuntimeModes);
111const REFRESH_FAILED =
112 "Could not refresh Antigravity models. The previous model list is unchanged.";
113const PYTHON_SOCKS_REQUIRED = "python-socks is required to use a SOCKS proxy";
114
115const INSTALLING_PHASES: ReadonlySet<ProviderInstallState["phase"]> = new Set([
116 "downloading",
117 "extracting",
118 "verifying",
119]);
120
121/**
122 * The managed runtime can only move to the release the installation offers, so any other
123 * version is behind it, the same rule as the setup section's update button.
124 */
125function antigravityMaintenanceCapabilities(
126 state: ProviderInstallState | undefined,
127 run: ProviderMaintenanceManagedAction["run"],
128): ProviderMaintenanceCapabilities {
129 const manual = makeManualOnlyProviderMaintenanceCapabilities({
130 provider: DRIVER,
131 packageName: null,
132 });
133 if (state?.installedVersion == null) return manual;
134 return {
135 ...manual,
136 latestVersion: state.version,
137 compareVersions: (current, latest) => (current === latest ? 0 : -1),
138 managedUpdate: { lockKey: `${DRIVER}-managed`, run },
139 };
140}
141
142// The install state names the active runtime; the snapshot's version waits for the next probe.
143function withVersionAdvisory(
144 snapshot: ServerProvider,
145 state: ProviderInstallState | undefined,
146 run: ProviderMaintenanceManagedAction["run"],
147): ServerProvider {
148 if (state?.installedVersion == null || state.version === null) return snapshot;
149 return {
150 ...snapshot,
151 versionAdvisory: createProviderVersionAdvisory({
152 driver: DRIVER,
153 currentVersion: state.installedVersion,
154 latestVersion: state.version,
155 checkedAt: snapshot.checkedAt,
156 maintenanceCapabilities: antigravityMaintenanceCapabilities(state, run),
157 }),
158 };
159}
160
161// Keep upstream diagnostics in cause; only recognized, fixed text reaches clients.
162function refreshFailureDetail(cause: unknown) {
163 return isAcpRequestError(cause) &&
164 cause.operation === "receive-response" &&
165 isAcpErrorDetails(cause.data) &&
166 cause.data.details.includes(PYTHON_SOCKS_REQUIRED)
167 ? `${REFRESH_FAILED} Antigravity reported: ${PYTHON_SOCKS_REQUIRED}`
168 : REFRESH_FAILED;
169}
170
171export type AntigravityDriverEnv =
172 | AntigravityInstallation.AntigravityInstallation
173 | ProviderHost.ProviderHost
174 | ChildProcessSpawner.ChildProcessSpawner
175 | Digest.Digest
176 | SecureRandom.SecureRandom
177 | FileSystem.FileSystem
178 | IdAllocator.IdAllocatorV2
179 | McpProviderSessions.McpProviderSessions
180 | ModelCatalog.ModelCatalog
181 | Path.Path
182 | ProviderEventLoggers.ProviderEventLoggers;
183
184export const AntigravityDriver: ProviderDriver<
185 AntigravitySettings,
186 AntigravityDriverEnv,
187 AntigravityUsage.AntigravityUsage
188> = {
189 driverKind: DRIVER,
190 metadata: { displayName: "Antigravity", supportsMultipleInstances: true },
191 configSchema: AntigravitySettings,
192 defaultConfig: () => decodeSettings({}),
193 usage: AntigravityUsage.antigravityUsageReader,
194 create: Effect.fn("AntigravityDriver.create")(function* ({
195 instanceId,
196 displayName,
197 accentColor,
198 environment,
199 enabled,
200 config,
201 }) {
202 const digest = yield* Digest.Digest;
203 const random = yield* SecureRandom.SecureRandom;
204 const fileSystem = yield* FileSystem.FileSystem;
205 const path = yield* Path.Path;
206 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
207 const host = yield* ProviderHost.ProviderHost;
208 const selfInvocation = yield* resolveSelfInvocation();
209 const driverScope = yield* Effect.scope;
210 const installation = yield* AntigravityInstallation.AntigravityInstallation;
211 const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
212 const modelCatalog = yield* ModelCatalog.ModelCatalog;
213 const currentCatalog = modelCatalog.current(DRIVER);
214 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
215 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
216 const settings = { ...config, enabled } satisfies AntigravitySettings;
217 const auth: AntigravityAuthConfig = {
218 authMethod: settings.authMethod,
219 // The instance registry has already read a referenced key from its secret provider.
220 apiKey: settingsSecretLiteral(settings.apiKey),
221 gcpProject: settings.gcpProject,
222 gcpLocation: settings.gcpLocation,
223 };
224 const authConfigIssue = antigravityAuthConfigIssue(auth);
225 const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);
226 const userHome = resolveAntigravityUserHome(
227 yield* HostProcess.Platform,
228 processEnvironment,
229 yield* HostProcess.HomeDirectory,
230 );
231 const directories = yield* resolveAntigravityInstanceDirectories(
232 host.paths.stateDir,
233 instanceId,
234 ).pipe(
235 Effect.provideService(Digest.Digest, digest),
236 Effect.provideService(Path.Path, path),
237 Effect.mapError(
238 (cause) =>
239 new ProviderDriverError({
240 driver: DRIVER,
241 instanceId,
242 detail: "Could not resolve the Antigravity profile directory.",
243 cause,
244 }),
245 ),
246 );
247 const profileDirectory = directories.profile;
248 // Only a session reports whether agy offers Auto, so keep the last answer across restarts.
249 const runtimeModesPath = path.join(profileDirectory, "t3-runtime-modes.json");
250 const rememberedRuntimeModes = yield* fileSystem.readFileString(runtimeModesPath).pipe(
251 Effect.map((contents) =>
252 decodeRememberedRuntimeModes(contents).pipe(
253 Option.filter((saved) => saved.authMethod === auth.authMethod),
254 Option.map((saved) => saved.modes),
255 Option.getOrUndefined,
256 ),
257 ),
258 Effect.orElseSucceed(() => undefined),
259 );
260 // The health check does not run a PATH agy, so start from the version and commands last saved.
261 const cachedStatus = yield* resolveProviderStatusCachePath({
262 cacheDir: host.paths.providerStatusCacheDir,
263 instanceId,
264 }).pipe(
265 Effect.flatMap(readProviderStatusCache),
266 Effect.provideService(FileSystem.FileSystem, fileSystem),
267 Effect.provideService(Path.Path, path),
268 );
269 const rememberedMetadata =
270 cachedStatus?.instanceId === instanceId &&
271 cachedStatus.driver === DRIVER &&
272 cachedStatus.auth.type === auth.authMethod
273 ? { version: cachedStatus.version, slashCommands: cachedStatus.slashCommands }
274 : undefined;
275 for (const directory of [
276 directories.runtimeTemp,
277 path.join(profileDirectory, "antigravity-acp", "tmp"),
278 ]) {
279 const removeRetired = yield* retireAntigravityRuntimeTempDirs(directory).pipe(
280 Effect.provideService(FileSystem.FileSystem, fileSystem),
281 Effect.provideService(Path.Path, path),
282 );
283 yield* Effect.forkScoped(removeRetired);
284 }
285 const continuationIdentity = defaultProviderContinuationIdentity({
286 driverKind: DRIVER,
287 instanceId,
288 });
289 const stampIdentity = withInstanceIdentity({
290 instanceId,
291 driverKind: DRIVER,
292 displayName,
293 accentColor,
294 continuationGroupKey: continuationIdentity.continuationKey,
295 });
296 // A custom executable path takes precedence over the managed runtime.
297 const managedRuntimeState = installation.state.pipe(
298 Effect.map((state) => (settings.binaryPath.trim() === "" ? state : undefined)),
299 );
300 const updateChecksEnabled = host.settings.get.pipe(
301 Effect.map((current) => current.enableProviderUpdateChecks),
302 Effect.orElseSucceed(() => true),
303 );
304 const updateManagedRuntime: ProviderMaintenanceManagedAction["run"] = Effect.fn(
305 "AntigravityDriver.updateManagedRuntime",
306 )(function* (onProgress) {
307 const started = yield* installation.start;
308 // Download progress repeats one state many times, so each phase reports once.
309 const finished = yield* installation.changes.pipe(
310 Stream.takeUntil(
311 (state) =>
312 state.operationId !== started.operationId || !INSTALLING_PHASES.has(state.phase),
313 ),
314 Stream.changesWith(
315 (previous, next) => previous.phase === next.phase && previous.message === next.message,
316 ),
317 Stream.tap((state) =>
318 state.message !== null && INSTALLING_PHASES.has(state.phase)
319 ? onProgress(state.message)
320 : Effect.void,
321 ),
322 Stream.runLast,
323 Effect.map(Option.getOrElse(() => started)),
324 );
325 if (finished.phase !== "succeeded") {
326 return yield* new AntigravityInstallation.AntigravityInstallationError({
327 operation: "update",
328 detail: finished.message ?? "Could not update the Antigravity runtime.",
329 });
330 }
331 });
332 const resolveMaintenance = managedRuntimeState.pipe(
333 Effect.map((state) => antigravityMaintenanceCapabilities(state, updateManagedRuntime)),
334 );
335 const classifyModels = (draft: ServerProviderDraft) =>
336 Effect.all([currentCatalog, managedRuntimeState, updateChecksEnabled]).pipe(
337 Effect.map(([catalog, state, checksEnabled]) =>
338 withVersionAdvisory(
339 stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog)),
340 checksEnabled ? state : undefined,
341 updateManagedRuntime,
342 ),
343 ),
344 );
345
346 const prepareSpawn = Effect.fn("AntigravityDriver.prepareSpawn")(function* (
347 cwd: string,
348 baseEnv: NodeJS.ProcessEnv,
349 ): Effect.fn.Return<
350 {
351 readonly executable: AntigravityInstallation.AntigravityExecutable;
352 readonly spawn: AcpSessionRuntime.AcpSpawnInput;
353 },
354 AcpErrors.AcpError | ProviderSetupError,
355 Scope.Scope
356 > {
357 if (authConfigIssue !== null) {
358 return yield* new ProviderSetupError({
359 instanceId,
360 operation: "configure",
361 detail: authConfigIssue,
362 });
363 }
364 // Thread variables affect the child environment, while health and startup select the same provider executable.
365 const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe(
366 Effect.mapError(
367 (cause) =>
368 new ProviderSetupError({
369 instanceId,
370 operation: "resolve",
371 detail: cause.detail,
372 cause,
373 }),
374 ),
375 );
376 const profile = yield* prepareAntigravityProfile({
377 profileDirectory,
378 baseEnv: processEnvironment,
379 auth,
380 userHome,
381 }).pipe(
382 Effect.provideService(FileSystem.FileSystem, fileSystem),
383 Effect.provideService(Path.Path, path),
384 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
385 Effect.mapError((cause) =>
386 isNodeRuntimeUnavailableError(cause.cause)
387 ? new ProviderSetupError({
388 instanceId,
389 operation: "start",
390 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
391 cause,
392 })
393 : cause,
394 ),
395 );
396 return {
397 executable,
398 spawn: buildAntigravityAcpSpawnInput({
399 installation: executable,
400 profile,
401 cwd,
402 baseEnv,
403 auth,
404 }),
405 };
406 });
407
408 const runtimeIncompatibility = Effect.fn("AntigravityDriver.runtimeIncompatibility")(function* (
409 executable: AntigravityInstallation.AntigravityExecutable,
410 version: string | null | undefined,
411 ) {
412 if (!version) return;
413 const advisory = yield* installation.compatibility(version);
414 const action =
415 executable.source === "managed"
416 ? "Update it in Antigravity setup"
417 : `Update the Antigravity executable at ${executable.executablePath}`;
418 const refused = brokenRuntimeError({
419 instanceId,
420 name: "Antigravity",
421 version,
422 advisory,
423 action,
424 });
425 if (refused) return refused;
426 if (!antigravityServesT3Code(version)) {
427 return new ProviderSetupError({
428 instanceId,
429 operation: "runtime",
430 detail: `Antigravity ${version} only serves allowlisted editors, not T3 Code. ${action} to ${OPEN_MODEL_ACCESS_RELEASE.join(".")} or newer, then retry.`,
431 });
432 }
433 });
434
435 const externalExecutableIdentity = Effect.fn("AntigravityDriver.externalExecutableIdentity")(
436 function* (executablePath: string) {
437 const target = yield* fileSystem.realPath(executablePath);
438 const info = yield* fileSystem.stat(target);
439 return {
440 executablePath,
441 target,
442 device: info.dev,
443 inode: info.ino.valueOrUndefined,
444 size: info.size,
445 modifiedAt: info.mtime.valueOrUndefined?.getTime(),
446 };
447 },
448 Effect.orElseSucceed(() => undefined),
449 );
450 let nextExternalAttempt = 0;
451 let completedExternalAttempt = 0;
452 type ExternalExecutableIdentity = NonNullable<
453 Effect.Success<ReturnType<typeof externalExecutableIdentity>>
454 >;
455 let rejectedExternalRuntime:
456 | { readonly identity: ExternalExecutableIdentity; readonly version: string }
457 | undefined;
458
459 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
460 input: AntigravityAdapterV2RuntimeInput,
461 ): Effect.fn.Return<
462 AcpSessionRuntime.AcpSessionRuntime["Service"],
463 AcpErrors.AcpError | ProviderSetupError,
464 Scope.Scope
465 > {
466 // `buildAntigravityAcpSpawnInput` sets `extendEnv: false`, so thread variables only reach the
467 // agent's shell through `baseEnv`.
468 const { processEnvironment: threadEnvironment, ...runtimeInput } = input;
469 const { executable, spawn } = yield* prepareSpawn(
470 runtimeInput.cwd,
471 threadEnvironment === undefined
472 ? processEnvironment
473 : { ...processEnvironment, ...threadEnvironment },
474 );
475 const runtime = yield* makeAntigravityAcpRuntime({
476 ...runtimeInput,
477 authMethod: auth.authMethod,
478 childProcessSpawner: spawner,
479 spawn,
480 }).pipe(Effect.provideService(SecureRandom.SecureRandom, random));
481 const startCompatible = Effect.fn("AntigravityDriver.startCompatible")(function* () {
482 // A launcher can select a different runtime based on the thread's environment.
483 const observeVersion = executable.version === null && threadEnvironment === undefined;
484 const attempt = observeVersion ? ++nextExternalAttempt : 0;
485 const identity = observeVersion
486 ? yield* externalExecutableIdentity(executable.executablePath)
487 : undefined;
488 const version = (yield* runtime.initialize()).agentInfo?.version;
489 const refused = yield* runtimeIncompatibility(executable, version);
490 // An unversioned or late handshake cannot supersede a known version.
491 if (version && identity && attempt > completedExternalAttempt) {
492 completedExternalAttempt = attempt;
493 rejectedExternalRuntime = refused ? { identity, version } : undefined;
494 }
495 if (refused) {
496 return yield* new AcpErrors.AcpTransportError({ detail: refused.detail, cause: refused });
497 }
498 return yield* runtime.start();
499 });
500 return {
501 ...runtime,
502 setMode: (modeId: string) =>
503 runtime.getModeState.pipe(
504 Effect.flatMap((modeState) =>
505 runtime.setMode(antigravitySessionMode(modeId, modeState)),
506 ),
507 ),
508 start: () =>
509 startCompatible().pipe(
510 Effect.tapError((cause): Effect.Effect<void> =>
511 runtimeInput.onAuthorizationUrl === undefined &&
512 isAntigravitySignInRequiredError(cause)
513 ? provider.onAuthRequired
514 : Effect.void,
515 ),
516 ),
517 };
518 });
519
520 const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
521 input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
522 ) {
523 const cwd = yield* fileSystem
524 .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
525 .pipe(
526 Effect.mapError(
527 () =>
528 new ProviderSetupError({
529 instanceId,
530 operation: "start",
531 detail: "Could not create an Antigravity setup workspace.",
532 }),
533 ),
534 );
535 let sessionId: string | undefined;
536 yield* Effect.addFinalizer(() =>
537 removeAntigravitySessionFiles({
538 profileDirectory,
539 sessionId,
540 cwd,
541 }).pipe(
542 Effect.provideService(FileSystem.FileSystem, fileSystem),
543 Effect.provideService(Path.Path, path),
544 ),
545 );
546 const runtime = yield* makeRuntime({
547 cwd,
548 mcpServers: [],
549 ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
550 });
551 return {
552 ...runtime,
553 start: () =>
554 runtime.start().pipe(
555 Effect.tap((started) =>
556 Effect.sync(() => {
557 sessionId = started.sessionId;
558 }),
559 ),
560 ),
561 };
562 });
563
564 // The agy CLI ignores T3's browser helper during ACP `authenticate`, so Google sign-in runs its
565 // remote-friendly `--login`, which stores the sign-in where the ACP process reads it.
566 const codeLogin = Effect.fn("AntigravityDriver.codeLogin")(function* (input: {
567 readonly onAuthorizationUrl: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
568 }) {
569 if (auth.authMethod !== "oauth-personal") return undefined;
570 const cwd = yield* fileSystem
571 .makeTempDirectoryScoped({ prefix: "t3-antigravity-login-" })
572 .pipe(
573 Effect.mapError(
574 () =>
575 new ProviderSetupError({
576 instanceId,
577 operation: "start",
578 detail: "Could not create an Antigravity setup workspace.",
579 }),
580 ),
581 );
582 const { spawn } = yield* prepareSpawn(cwd, processEnvironment);
583 const failed = (detail: string, cause?: unknown) =>
584 new ProviderSetupError({ instanceId, operation: "start", detail, cause });
585 // Without a display it prints the link only, instead of opening a browser on this machine.
586 const { DISPLAY: _display, WAYLAND_DISPLAY: _wayland, ...env } = spawn.env ?? {};
587 const child = yield* spawner
588 .spawn(
589 ChildProcess.make(spawn.command, [...spawn.args, "--login"], {
590 cwd,
591 env,
592 extendEnv: false,
593 shell: false,
594 }),
595 )
596 .pipe(Effect.mapError((cause) => failed("Could not start Antigravity sign-in.", cause)));
597 const code = yield* Deferred.make<string>();
598 yield* Stream.fromEffect(Deferred.await(code)).pipe(
599 Stream.map((response) => `${response}\n`),
600 Stream.encodeText,
601 Stream.run(child.stdin),
602 Effect.ignore,
603 Effect.forkScoped,
604 );
605 const output = yield* child.stdout.pipe(
606 Stream.decodeText(),
607 Stream.splitLines,
608 Stream.map((line) => line.trim()),
609 Stream.runForEach((line) =>
610 line.startsWith("https://accounts.google.com/")
611 ? input.onAuthorizationUrl(line)
612 : Effect.void,
613 ),
614 Effect.forkScoped,
615 );
616 yield* Stream.runDrain(child.stderr).pipe(Effect.ignore, Effect.forkScoped);
617 return {
618 submit: (response: string) => Deferred.succeed(code, response).pipe(Effect.asVoid),
619 completed: Effect.gen(function* () {
620 // Stdout closes when the process exits, or this fails first on an unusable link.
621 yield* Fiber.join(output).pipe(
622 Effect.mapError((cause) =>
623 failed("Antigravity returned an invalid Google sign-in link.", cause),
624 ),
625 );
626 const exitCode = yield* child.exitCode.pipe(
627 Effect.mapError((cause) => failed("Antigravity sign-in stopped unexpectedly.", cause)),
628 );
629 if (Number(exitCode) !== 0) {
630 return yield* failed(
631 "Antigravity could not finish Google sign-in. Start sign-in again.",
632 );
633 }
634 }),
635 };
636 });
637
638 const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* (
639 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
640 runtime: Pick<
641 AcpSessionRuntime.AcpSessionRuntime["Service"],
642 "getEvents" | "drainEvents" | "setModel"
643 >,
644 ) {
645 yield* provider.onSessionStarted(started);
646 yield* authFlow.onSignedInElsewhere;
647 yield* Stream.runForEach(runtime.getEvents(), (event) => {
648 if (event._tag === "EventStreamBarrier") {
649 return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
650 }
651 if (event._tag === "ConfigOptionsUpdated") {
652 return provider.onConfigOptionsUpdated(event.configOptions, { fromCatalogProbe: true });
653 }
654 return event._tag === "AvailableCommandsUpdated"
655 ? provider.onAvailableCommands(event.availableCommands)
656 : Effect.void;
657 }).pipe(Effect.forkScoped);
658 // Thinking levels differ per model and are reported only for the selected one.
659 const configOptions = started.sessionSetupResult.configOptions ?? [];
660 const current = configOptions.find((option) => option.id === "model")?.currentValue;
661 if (antigravityThinkingConfig(configOptions) !== undefined && typeof current === "string") {
662 for (const model of [...antigravityModelOptions(configOptions), { value: current }]) {
663 yield* runtime.setModel(model.value).pipe(Effect.ignore);
664 }
665 }
666 yield* runtime.drainEvents;
667 }, Effect.scoped);
668
669 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
670 instanceId,
671 makeRuntime: makeDisposableRuntime,
672 // A new sign-in may be another account; drop any in-flight quota read first.
673 onAuthenticated: (started, runtime) =>
674 Effect.suspend(() => provider.onSignedIn).pipe(
675 Effect.andThen(publishCatalog(started, runtime)),
676 ),
677 onSignedOut: Effect.suspend(() => provider.onSignedOut),
678 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
679 codeLogin,
680 });
681
682 // The probe must not spawn. The agent is a PyInstaller one-file bundle
683 // that unpacks about 1 GB per launch, and the health check runs every
684 // minute.
685 const probe = Effect.gen(function* () {
686 yield* modelCatalog.refreshInBackground;
687 if (authConfigIssue !== null) {
688 return yield* new ProviderSetupError({
689 instanceId,
690 operation: "configure",
691 detail: authConfigIssue,
692 });
693 }
694 // Rate-limited and gated on the update-checks setting inside the installation. Runs before
695 // resolution, so a runtime this release refuses is still offered its update.
696 if ((yield* managedRuntimeState)?.installedVersion != null) {
697 yield* Effect.forkIn(installation.checkForUpdate, driverScope);
698 }
699 const executable = yield* installation.resolve(settings.binaryPath, processEnvironment).pipe(
700 Effect.mapError(
701 (cause) =>
702 new ProviderSetupError({
703 instanceId,
704 operation: "resolve",
705 detail: cause.detail,
706 cause,
707 }),
708 ),
709 );
710 const previousRejection = rejectedExternalRuntime;
711 const identity =
712 executable.version === null && previousRejection
713 ? yield* externalExecutableIdentity(executable.executablePath)
714 : undefined;
715 const rememberedVersion =
716 rejectedExternalRuntime && Equal.equals(rejectedExternalRuntime.identity, identity)
717 ? rejectedExternalRuntime.version
718 : undefined;
719 const invalidatedVersion =
720 previousRejection &&
721 previousRejection === rejectedExternalRuntime &&
722 identity &&
723 rememberedVersion === undefined
724 ? previousRejection.version
725 : undefined;
726 if (invalidatedVersion !== undefined || executable.version !== null) {
727 rejectedExternalRuntime = undefined;
728 }
729 const version = executable.version ?? rememberedVersion;
730 if (version) {
731 const refused = yield* runtimeIncompatibility(executable, version);
732 if (refused) {
733 return yield* new AntigravityProbeIncompatibility({ version, detail: refused.detail });
734 }
735 }
736 return {
737 protocolVersion: 1,
738 ...(invalidatedVersion === undefined ? {} : { invalidatedVersion }),
739 agentCapabilities: {
740 loadSession: true,
741 promptCapabilities: { image: true, audio: true, embeddedContext: true },
742 sessionCapabilities: { list: {}, resume: {} },
743 },
744 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
745 agentInfo: {
746 name: "antigravity-acp",
747 title: "Google Antigravity",
748 version: version ?? "unknown",
749 },
750 };
751 });
752
753 const usage = yield* makeAntigravityUsageProbe({
754 profileDirectory,
755 authMethod: auth.authMethod,
756 environment: processEnvironment,
757 executable: installation.acquire(settings.binaryPath, processEnvironment),
758 }).pipe(
759 Effect.provideService(FileSystem.FileSystem, fileSystem),
760 Effect.provideService(Path.Path, path),
761 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
762 );
763 const provider = yield* makeAntigravityProvider(settings, {
764 environment: processEnvironment,
765 stampIdentity: classifyModels,
766 resolveMaintenance,
767 snapshotInputChanges: Stream.merge(
768 installation.changes.pipe(
769 Stream.changesWith(
770 (previous, next) =>
771 previous.version === next.version &&
772 previous.installedVersion === next.installedVersion,
773 ),
774 ),
775 host.settings.changes.pipe(
776 Stream.map((current) => current.enableProviderUpdateChecks),
777 Stream.changes,
778 Stream.tap((checksEnabled) =>
779 checksEnabled
780 ? managedRuntimeState.pipe(
781 Effect.flatMap((state) =>
782 state?.installedVersion != null
783 ? Effect.forkIn(installation.checkForUpdate, driverScope)
784 : Effect.void,
785 ),
786 )
787 : Effect.void,
788 ),
789 ),
790 ),
791 probe,
792 probeUsage: usage.probe,
793 clearUsage: usage.clear,
794 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
795 ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}),
796 rememberRuntimeModes: (modes) =>
797 writeFileStringAtomically({
798 filePath: runtimeModesPath,
799 contents: encodeRememberedRuntimeModes({ authMethod: auth.authMethod, modes }),
800 }).pipe(
801 Effect.provideService(FileSystem.FileSystem, fileSystem),
802 Effect.provideService(Path.Path, path),
803 Effect.catch(() => Effect.logWarning("Could not save Antigravity permission modes.")),
804 ),
805 ...(rememberedMetadata ? { rememberedMetadata } : {}),
806 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
807 Effect.provideService(FileSystem.FileSystem, fileSystem),
808 Effect.provideService(Path.Path, path),
809 Effect.orElseSucceed(() => false),
810 ),
811 }).pipe(
812 Effect.mapError(
813 (cause) =>
814 new ProviderDriverError({
815 driver: DRIVER,
816 instanceId,
817 detail: "Could not prepare the Antigravity provider status.",
818 cause,
819 }),
820 ),
821 );
822 const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
823 const orchestrationAdapter = yield* makeAntigravityAdapterV2({
824 instanceId,
825 selfInvocation,
826 makeRuntime,
827 withProcess: authFlow.withProcess,
828 defaultModel,
829 supportsNativeGoals: provider.snapshot.getSnapshot.pipe(
830 Effect.map(
831 (snapshot) => snapshot.slashCommands?.some((command) => command.name === "goal") === true,
832 ),
833 ),
834 profileDirectory,
835 onSessionStarted: (started, cwd, session) =>
836 provider
837 .onSessionStarted(started, cwd, session)
838 .pipe(Effect.andThen(authFlow.onSignedInElsewhere)),
839 onSessionEvent: (event, cwd) => {
840 if (event._tag === "ConfigOptionsUpdated") {
841 return provider.onConfigOptionsUpdated(event.configOptions);
842 }
843 return event._tag === "AvailableCommandsUpdated"
844 ? provider.onAvailableCommands(event.availableCommands, cwd)
845 : Effect.void;
846 },
847 continuationRequests,
848 nativeLogging: (threadId) =>
849 makeNativeLogger({
850 nativeEventLogger: loggers.native,
851 provider: DRIVER,
852 threadId,
853 }),
854 });
855 const textGeneration = yield* makeAntigravityTextGeneration({
856 profileDirectory,
857 defaultModel,
858 withProcess: authFlow.withProcess,
859 makeRuntime: (cwd) =>
860 makeRuntime({
861 cwd,
862 mcpServers: [],
863 }),
864 });
865
866 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
867 function* () {
868 const processScope = yield* Scope.make();
869 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
870 yield* authFlow
871 .withProcess(
872 Scope.close(processScope, Exit.void),
873 Effect.gen(function* () {
874 const runtime = yield* makeDisposableRuntime({});
875 const started = yield* runtime.start();
876 yield* publishCatalog(started, runtime);
877 }),
878 )
879 .pipe(Effect.provideService(Scope.Scope, processScope));
880 },
881 Effect.scoped,
882 Effect.timeoutOrElse({
883 duration: "90 seconds",
884 orElse: () =>
885 Effect.fail(
886 new ProviderDriverError({
887 driver: DRIVER,
888 instanceId,
889 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
890 }),
891 ),
892 }),
893 Effect.tapError((cause) =>
894 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
895 ),
896 Effect.mapError((cause) =>
897 cause._tag === "ProviderDriverError"
898 ? cause
899 : new ProviderDriverError({
900 driver: DRIVER,
901 instanceId,
902 detail: isAntigravitySignInRequiredError(cause)
903 ? "Sign in to Antigravity in provider settings before refreshing models."
904 : cause._tag === "ProviderSetupError" &&
905 (cause.operation === "configure" ||
906 cause.operation === "resolve" ||
907 cause.operation === "start")
908 ? cause.detail
909 : cause._tag === "AcpTransportError" &&
910 isProviderSetupError(cause.cause) &&
911 cause.cause.operation === "runtime"
912 ? cause.cause.detail
913 : refreshFailureDetail(cause),
914 cause,
915 }),
916 ),
917 );
918
919 return {
920 instanceId,
921 driverKind: DRIVER,
922 continuationIdentity,
923 displayName,
924 accentColor,
925 enabled,
926 snapshot: provider.snapshot,
927 snapshotForCwd: (cwd) =>
928 !enabled
929 ? provider.snapshot.getSnapshot
930 : discoverAntigravitySkills({ cwd, userHome, profileDirectory }).pipe(
931 Effect.provideService(FileSystem.FileSystem, fileSystem),
932 Effect.provideService(Path.Path, path),
933 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
934 Effect.mapError(
935 (cause) =>
936 new ProviderDriverError({
937 driver: DRIVER,
938 instanceId,
939 detail: "Could not read Antigravity workspace skills.",
940 cause,
941 }),
942 ),
943 ),
944 orchestrationAdapter,
945 textGeneration,
946 auth: authFlow.controller,
947 invalidateCaches: installation.invalidateUpdateCheck,
948 refreshModels,
949 } satisfies ProviderInstance;
950 }),
951};