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

AntigravityInstallation.ts

1,247 lines51.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest or free-space query.
2import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
3import * as ModelManifest from "./ModelManifest.ts";
4import { resolveProviderCompatibility } from "./providerCompatibility.ts";
5import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease";
6import { compareSemverVersions } from "@t3tools/shared/semver";
7import * as EffectNodeStream from "@effect/platform-node/NodeStream";
8import { ProviderDriverKind, type ProviderInstallState } from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
11import { resolveCommandPath } from "@t3tools/shared/shell";
12import * as Clock from "effect/Clock";
13import * as Cause from "effect/Cause";
14import * as Context from "effect/Context";
15import * as SecureRandom from "effect/crypto/SecureRandom";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Fiber from "effect/Fiber";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Path from "effect/Path";
23import type { PlatformError } from "effect/PlatformError";
24import * as Schema from "effect/Schema";
25import * as Schedule from "effect/Schedule";
26import * as Scope from "effect/Scope";
27import * as Semaphore from "effect/Semaphore";
28import * as Stream from "effect/Stream";
29import * as SubscriptionRef from "effect/SubscriptionRef";
30import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
31import * as ChildProcess from "effect/process/ChildProcess";
32import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
33import * as NodeCrypto from "node:crypto";
34import * as NodeFSP from "node:fs/promises";
35import * as EffectAcpErrors from "effect-acp/errors";
36​
37import * as ServerConfig from "../config.ts";
38import * as ServerSettings from "../serverSettings.ts";
39import {
40 ANTIGRAVITY_CLI_MANIFEST_BASE,
41 antigravityCliTarget,
42 parseAntigravityCliRelease,
43 type AntigravityCliReleaseAsset,
44} from "./antigravityCliRelease.ts";
45import { openZipArchive } from "../zipArchive.ts";
46import { makeAntigravityAcpRuntime } from "./acp/AntigravityAcpSupport.ts";
47import {
48 buildAntigravityAcpSpawnInput,
49 prepareAntigravityProfile,
50} from "./antigravityAuthSupport.ts";
51import { type AntigravityReleaseAsset } from "./antigravityRelease.ts";
52​
53const DRIVER = ProviderDriverKind.make("antigravity");
54const DOWNLOAD_TIMEOUT = "45 minutes";
55const VALIDATION_TIMEOUT = "90 seconds";
56const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
57const MAX_EXECUTABLE_BYTES = 512 * 1024 * 1024;
58const UPDATE_CHECK_INTERVAL = 60 * 60 * 1000;
59const FREE_SPACE_MARGIN = 256 * 1024 * 1024;
60const RECORD_MAX_BYTES = 8 * 1024;
61const RELEASE_RECORD = ".install-complete.json";
62const LAUNCHER_SETUP =
63 /^[\s@]*(?:|::[^&|<>]*|rem(?:\s[^&|<>]*|$)|set\s+"[^"=&|<>]+=[^"&|<>]*"\s*|(?:echo|set|setlocal|endlocal)(?:\s[^&|<>()]*)?)$/iu;
64const LAUNCHER_COMMAND =
65 /^[\s@]*(?:"([^"]*agy_acp_server\.exe)"|([^\s"&|<>()@]*agy_acp_server\.exe))(?:\s[^&|<>()]*)?$/iu;
66const LARGE_PAGE_KERNEL_MESSAGE =
67 "Google's linux-arm64 Antigravity runtime needs a kernel with 4 KiB memory pages, and this kernel uses larger pages (as on Asahi Linux or Raspberry Pi 5). Use a remote environment or a custom Antigravity executable.";
68​
69// The launcher runs in the project directory, so a target like `\x\agy_acp_server.exe`
70// whose drive comes from the working directory may not be the file resolved here.
71export const launcherTargetPath = (path: Path.Path, launcher: string, written: string) => {
72 const target = written.replace(/%~dp0/giu, () => `${path.dirname(launcher)}${path.sep}`);
73 if (/[%!]/u.test(target)) return null;
74 const resolved = path.resolve(target);
75 return path.parse(path.normalize(target)).root === path.parse(resolved).root ? resolved : null;
76};
77​
78const ReleaseId = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u));
79const ActiveRelease = Schema.Struct({ releaseId: ReleaseId });
80const InstalledRelease = Schema.Struct({
81 releaseId: ReleaseId,
82 version: Schema.String,
83 executable: Schema.Struct({ name: Schema.String, bytes: Schema.Number }),
84 harness: Schema.NullOr(Schema.Struct({ name: Schema.String, bytes: Schema.Number })),
85});
86type InstalledRelease = typeof InstalledRelease.Type;
87const encodeActiveRelease = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease));
88const encodeInstalledRelease = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease));
89​
90export class AntigravityInstallationError extends Schema.TaggedError<AntigravityInstallationError>()(
91 "AntigravityInstallationError",
92 {
93 operation: Schema.String,
94 detail: Schema.String,
95 cause: Schema.optional(Schema.Defect()),
96 },
97) {
98 override get message() {
99 return this.detail;
100 }
102const isInstallationError = Schema.is(AntigravityInstallationError);
103const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);
104​
105export interface AntigravityExecutable {
106 readonly executablePath: string;
107 /** Null for the `agy` CLI, which embeds the harness and runs as `agy acp`. */
108 readonly harnessPath: string | null;
109 readonly source: "override" | "managed" | "path";
110 readonly version: string | null;
111 readonly managedVersionDirectory: string | null;
113​
114interface AntigravityInstallationService {
115 readonly managedDirectory: string;
116 readonly resolve: (
117 binaryPath?: string,
118 environment?: NodeJS.ProcessEnv,
119 ) => Effect.Effect<AntigravityExecutable, AntigravityInstallationError>;
120 /** Hold the lease until the spawned process has exited. */
121 readonly acquire: (
122 binaryPath?: string,
123 environment?: NodeJS.ProcessEnv,
124 ) => Effect.Effect<AntigravityExecutable, AntigravityInstallationError, Scope.Scope>;
125 readonly start: Effect.Effect<ProviderInstallState, AntigravityInstallationError>;
126 readonly cancel: (
127 operationId: string,
128 ) => Effect.Effect<ProviderInstallState, AntigravityInstallationError>;
129 readonly state: Effect.Effect<ProviderInstallState>;
130 readonly changes: Stream.Stream<ProviderInstallState>;
131 readonly checkForUpdate: Effect.Effect<void>;
132 readonly remove: (
133 protectedBinaryPaths?: ReadonlyArray<string>,
134 ) => Effect.Effect<void, AntigravityInstallationError>;
136​
137export class AntigravityInstallation extends Context.Service<
138 AntigravityInstallation,
139 AntigravityInstallationService
140>()("t3/provider/AntigravityInstallation") {
141 static readonly layer = Layer.effect(
142 AntigravityInstallation,
143 Effect.gen(function* () {
144 const config = yield* ServerConfig.ServerConfig;
145 const settings = yield* ServerSettings.ServerSettingsService;
146 return yield* makeAntigravityInstallation({
147 baseDir: config.baseDir,
148 updateChecksEnabled: settings.getSettings.pipe(
149 Effect.map((value) => value.enableProviderUpdateChecks),
150 Effect.orElseSucceed(() => false),
151 ),
152 });
153 }),
154 );
156​
157export interface AntigravityInstallationOptions {
158 readonly baseDir: string;
159 readonly releaseAsset?: AntigravityReleaseAsset | AntigravityCliReleaseAsset | null;
160 readonly updateChecksEnabled?: Effect.Effect<boolean>;
161 readonly validate?: (
162 executable: AntigravityExecutable,
163 expectedVersion: string,
164 ) => Effect.Effect<void, AntigravityInstallationError, Scope.Scope>;
166​
167const installationError = (operation: string, detail: string, cause?: unknown) =>
168 new AntigravityInstallationError({
169 operation,
170 detail,
171 ...(cause === undefined ? {} : { cause }),
172 });
173​
174const wrapFailure = (operation: string, detail: string) => (cause: unknown) =>
175 isInstallationError(cause) ? cause : installationError(operation, detail, cause);
176​
177function executableNames(platform: NodeJS.Platform) {
178 return platform === "win32"
179 ? { executable: "agy_acp_server.exe", harness: "localharness_external.exe" }
180 : { executable: "agy_acp_server.par", harness: "localharness_external" };
182​
183/** Antigravity CLI 1.5.0+ serves ACP itself (`agy acp`), so it has no `localharness_external` sibling. */
184function isAntigravityCli(...candidates: ReadonlyArray<string>) {
185 return candidates.some((candidate) =>
186 /^(?:agy|antigravity)(?:\.(?:exe|cmd|bat))?$/iu.test(candidate.split(/[\\/]/u).at(-1) ?? ""),
187 );
189​
190function isRunning(state: ProviderInstallState) {
191 return (
192 state.phase === "downloading" || state.phase === "extracting" || state.phase === "verifying"
193 );
195​
196export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.make")(function* (
197 options: AntigravityInstallationOptions,
198) {
199 const manifestService = yield* ModelManifest.ModelManifest;
200 const fs = yield* FileSystem.FileSystem;
201 const path = yield* Path.Path;
202 const random = yield* SecureRandom.SecureRandom;
203 const http = yield* HttpClient.HttpClient;
204 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
205 const serviceScope = yield* Effect.scope;
206 const platform = yield* HostProcess.Platform;
207 const arch = yield* HostProcess.Architecture;
208 const environment = yield* HostProcess.Environment;
209 let releaseAsset = options.releaseAsset ?? null;
210 const supported =
211 options.releaseAsset === undefined
212 ? antigravityCliTarget(platform, arch) !== null
213 : options.releaseAsset !== null;
214 const names = executableNames(platform);
215 const managedDirectory = path.join(
216 options.baseDir,
217 "tools",
218 "antigravity-acp",
219 `${platform}-${arch}`,
220 );
221 const versionsDirectory = path.join(managedDirectory, "versions");
222 const activePath = path.join(managedDirectory, "active.json");
223 // Windows briefly keeps handles on fresh runtime files after taskkill or an antivirus scan; retry for up to 10 seconds.
224 const retryWhileWindowsHoldsHandles = <A, R>(effect: Effect.Effect<A, PlatformError, R>) =>
225 effect.pipe(
226 Effect.retry({
227 times: platform === "win32" ? 40 : 0,
228 schedule: Schedule.spaced("250 millis"),
229 while: (error) =>
230 error.reason._tag === "PermissionDenied" ||
231 error.reason._tag === "Busy" ||
232 error.reason._tag === "Unknown",
233 }),
234 );
235 const gate = yield* Semaphore.make(1);
236 const leases = new Map<string, number>();
237 let running: { readonly operationId: string; readonly fiber: Fiber.Fiber<void> } | undefined;
238 const state = yield* SubscriptionRef.make<ProviderInstallState>({
239 driver: DRIVER,
240 operationId: null,
241 phase: "idle",
242 downloadedBytes: 0,
243 totalBytes:
244 releaseAsset !== null && "archiveBytes" in releaseAsset ? releaseAsset.archiveBytes : null,
245 version: releaseAsset?.version ?? null,
246 installedVersion: null,
247 canRemove: false,
248 message: null,
249 });
250​
251 const isWithdrawn = Effect.fn("AntigravityInstallation.isWithdrawn")(function* (version: string) {
252 const manifest = yield* manifestService.current;
253 const status = (
254 resolveProviderCompatibility(manifest.compatibility, DRIVER, version) ??
255 resolveProviderCompatibility(
256 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
257 DRIVER,
258 version,
259 )
260 )?.status;
261 return status === "broken" || status === "unsupported";
262 });
263 const ensureEligible = Effect.fn("AntigravityInstallation.ensureEligible")(function* (
264 version: string,
265 ) {
266 if (yield* isWithdrawn(version))
267 return yield* installationError(
268 "verify",
269 "This Antigravity release was withdrawn. Check for updates and try again.",
270 );
271 });
272​
273 const readRecord = Effect.fn("AntigravityInstallation.readRecord")(function* <A>(
274 filePath: string,
275 schema: Schema.Codec<A>,
276 ) {
277 const info = yield* fs.stat(filePath);
278 if (info.type !== "File" || Number(info.size) > RECORD_MAX_BYTES) {
279 return yield* installationError(
280 "resolve",
281 "The managed runtime record is invalid. Reinstall Antigravity.",
282 );
283 }
284 const contents = yield* fs.readFileString(filePath);
285 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(contents);
286 });
287​
288 const executableFile = Effect.fn("AntigravityInstallation.executableFile")(function* (
289 filePath: string,
290 bytes?: number,
291 ) {
292 const info = yield* fs.stat(filePath).pipe(Effect.option);
293 return (
294 Option.isSome(info) &&
295 info.value.type === "File" &&
296 (bytes === undefined || Number(info.value.size) === bytes) &&
297 (platform === "win32" || (info.value.mode & 0o111) !== 0)
298 );
299 });
300​
301 const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* (
302 releaseId: string,
303 ) {
304 const directory = path.join(versionsDirectory, releaseId);
305 const record = yield* readRecord(path.join(directory, RELEASE_RECORD), InstalledRelease);
306 if (
307 record.releaseId !== releaseId ||
308 (record.harness === null
309 ? record.executable.name !== (platform === "win32" ? "agy.exe" : "antigravity")
310 : record.executable.name !== names.executable || record.harness.name !== names.harness) ||
311 !Number.isSafeInteger(record.executable.bytes) ||
312 record.executable.bytes <= 0 ||
313 (record.harness !== null &&
314 (!Number.isSafeInteger(record.harness.bytes) || record.harness.bytes <= 0)) ||
315 !record.version.trim() ||
316 !(yield* executableFile(
317 path.join(directory, record.executable.name),
318 record.executable.bytes,
319 )) ||
320 (record.harness !== null &&
321 !(yield* executableFile(path.join(directory, record.harness.name), record.harness.bytes)))
322 ) {
323 return yield* installationError(
324 "resolve",
325 "The managed Antigravity runtime is incomplete. Reinstall it.",
326 );
327 }
328 return {
329 executablePath: path.join(directory, record.executable.name),
330 harnessPath: record.harness === null ? null : path.join(directory, record.harness.name),
331 source: "managed",
332 version: record.version,
333 managedVersionDirectory: directory,
334 } satisfies AntigravityExecutable;
335 });
336​
337 // Infer helper pairing only from a plain launcher with one literal executable path.
338 const launcherTarget = Effect.fn("AntigravityInstallation.launcherTarget")(function* (
339 launcher: string,
340 ) {
341 if (platform !== "win32" || !/\.(?:bat|cmd)$/iu.test(launcher)) return null;
342 const contents = yield* fs.readFileString(launcher);
343 const targets = new Set<string>();
344 for (const line of contents.split(/\r?\n/u)) {
345 if (line.includes("^")) return null;
346 if (/^[\s@]*exit(?:\s+\/b)?(?:\s+-?\d+)?\s*$/iu.test(line)) break;
347 if (LAUNCHER_SETUP.test(line)) continue;
348 const match = LAUNCHER_COMMAND.exec(line);
349 if (!match) return null;
350 const target = launcherTargetPath(path, launcher, match[1] ?? match[2] ?? "");
351 if (target === null) return null;
352 targets.add(target);
353 }
354 const [target] = targets;
355 if (targets.size !== 1 || !target || !(yield* executableFile(target))) return null;
356 return yield* fs.realPath(target);
357 });
358​
359 const fromExternal = Effect.fn("AntigravityInstallation.fromExternal")(function* (
360 candidate: string,
361 source: "override" | "path",
362 ) {
363 if (!(yield* executableFile(candidate))) return null;
364 const executablePath = yield* fs.realPath(candidate);
365 const launched = yield* launcherTarget(executablePath);
366 const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option);
367 const directory = path.dirname(launched ?? executablePath);
368 if (
369 Option.isSome(realVersions) &&
370 path.dirname(directory) === realVersions.value &&
371 /^[a-f0-9]{64}$/u.test(path.basename(directory))
372 ) {
373 const installed = yield* completedRelease(path.basename(directory));
374 return launched === null
375 ? { ...installed, source }
376 : { ...installed, executablePath, source };
377 }
378 // Keep launcher symlinks intact: version-manager shims dispatch by their invoked name.
379 if (launched === null && isAntigravityCli(candidate, executablePath)) {
380 return {
381 executablePath: candidate,
382 harnessPath: null,
383 source,
384 version: null,
385 managedVersionDirectory: null,
386 } satisfies AntigravityExecutable;
387 }
388 const harnessPath = path.join(directory, names.harness);
389 if (!(yield* executableFile(harnessPath))) return null;
390 return {
391 executablePath,
392 harnessPath,
393 source,
394 version: null,
395 managedVersionDirectory: null,
396 } satisfies AntigravityExecutable;
397 });
398​
399 const commandPath = (command: string, env: NodeJS.ProcessEnv) =>
400 resolveCommandPath(command, { env }).pipe(
401 Effect.map((resolved) => (resolved === null ? null : path.resolve(resolved))),
402 Effect.provideService(HostProcess.Platform, platform),
403 Effect.provideService(FileSystem.FileSystem, fs),
404 Effect.provideService(Path.Path, path),
405 );
406​
407 // Resolve per PATH entry so an executable without its harness falls through to later entries.
408 const commandCandidates = Effect.fn("AntigravityInstallation.commandCandidates")(function* (
409 command: string,
410 processEnvironment = environment,
411 ) {
412 if (command.includes("/") || command.includes("\\")) {
413 const resolved = yield* commandPath(command, processEnvironment);
414 return resolved === null ? [] : [resolved];
415 }
416 const pathValue =
417 platform === "win32"
418 ? Object.entries(processEnvironment).findLast(([key]) => key.toUpperCase() === "PATH")?.[1]
419 : processEnvironment.PATH;
420 const candidates: string[] = [];
421 for (const entry of (pathValue ?? "").split(platform === "win32" ? ";" : ":")) {
422 if (entry.length === 0) continue;
423 const resolved = yield* commandPath(command, { ...processEnvironment, PATH: entry });
424 if (resolved !== null) candidates.push(resolved);
425 }
426 return candidates;
427 });
428​
429 const resolve: AntigravityInstallationService["resolve"] = Effect.fn(
430 "AntigravityInstallation.resolve",
431 )(
432 function* (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) {
433 const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory);
434 if (override) {
435 for (const candidate of yield* commandCandidates(override, processEnvironment)) {
436 const selected = yield* fromExternal(candidate, "override");
437 if (selected) return selected;
438 }
439 return yield* installationError(
440 "resolve",
441 "The custom Antigravity executable is missing or not executable, or it needs a localharness_external sibling. The agy CLI does not.",
442 );
443 }
444 if (yield* fs.exists(activePath)) {
445 const active = yield* readRecord(activePath, ActiveRelease);
446 const installed = yield* completedRelease(active.releaseId);
447 if (yield* isWithdrawn(installed.version))
448 return yield* installationError(
449 "resolve",
450 `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`,
451 );
452 return installed;
453 }
454 for (const command of [names.executable, "agy"]) {
455 for (const candidate of yield* commandCandidates(command, processEnvironment)) {
456 const selected = yield* fromExternal(candidate, "path");
457 if (selected) return selected;
458 }
459 }
460 return yield* installationError(
461 "resolve",
462 supported
463 ? "Antigravity ACP runtime is not installed. Install it in this environment's provider settings or set a custom ACP executable path. The Antigravity app, IDE, and CLI are separate installations."
464 : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`,
465 );
466 },
467 Effect.mapError(
468 wrapFailure(
469 "resolve",
470 "Could not read the Antigravity installation. Reinstall it or set a custom executable path.",
471 ),
472 ),
473 );
474​
475 const acquire = (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) =>
476 Effect.acquireRelease(
477 gate.withPermit(
478 Effect.gen(function* () {
479 const executable = yield* resolve(binaryPath, processEnvironment);
480 const directory = executable.managedVersionDirectory;
481 if (directory) leases.set(directory, (leases.get(directory) ?? 0) + 1);
482 return executable;
483 }),
484 ),
485 (executable) =>
486 gate.withPermit(
487 Effect.sync(() => {
488 const directory = executable.managedVersionDirectory;
489 if (!directory) return;
490 const remaining = (leases.get(directory) ?? 1) - 1;
491 if (remaining > 0) leases.set(directory, remaining);
492 else leases.delete(directory);
493 }),
494 ),
495 );
496​
497 const withValidationTimeout = Effect.timeoutOrElse({
498 duration: VALIDATION_TIMEOUT,
499 orElse: () =>
500 Effect.fail(
501 installationError(
502 "verify",
503 "Antigravity runtime verification timed out after 90 seconds. Check this environment's server logs for startup errors, then retry installation.",
504 ),
505 ),
506 });
507 const validate =
508 options.validate ??
509 Effect.fn("AntigravityInstallation.validate")(
510 function* (executable: AntigravityExecutable, expectedVersion: string) {
511 const validationScope = yield* Effect.scope;
512 const profileDirectory = yield* Effect.acquireRelease(
513 fs.makeTempDirectory({ prefix: "t3-antigravity-validate-" }),
514 (directory) =>
515 fs
516 .remove(directory, { recursive: true, force: true })
517 .pipe(retryWhileWindowsHoldsHandles, Effect.orDie),
518 );
519 const profile = yield* prepareAntigravityProfile({
520 profileDirectory,
521 platform,
522 baseEnv: environment,
523 // A shallow scoped profile cleans up unpacked files within Windows' path limit.
524 tempDirectory: profileDirectory,
525 });
526 const runtime = yield* makeAntigravityAcpRuntime({
527 runtimeVersion: expectedVersion,
528 spawn: buildAntigravityAcpSpawnInput({
529 installation: executable,
530 profile,
531 cwd: profileDirectory,
532 baseEnv: environment,
533 }),
534 cwd: profileDirectory,
535 childProcessSpawner:
536 platform === "win32"
537 ? ChildProcessSpawner.make(
538 Effect.fnUntraced(function* (command) {
539 const child = yield* spawner.spawn(command);
540 // Stop PyInstaller's tree before ACP closes pipes; after launcher exit, taskkill cannot reach children holding DLLs open.
541 yield* Scope.addFinalizer(
542 validationScope,
543 child.kill({ forceKillAfter: "1 second" }).pipe(Effect.orDie),
544 );
545 return child;
546 }),
547 )
548 : spawner,
549 });
550 const initialized = yield* runtime.initialize();
551 if (
552 (executable.harnessPath === null
553 ? initialized.agentInfo?.name !== "Antigravity ACP Server"
554 : initialized.agentInfo?.name !== "antigravity-acp") ||
555 initialized.agentInfo?.version !== expectedVersion ||
556 // Antigravity 1.1.1 may report protocol 2 with legacy ACP; choose wire format from the response shape.
557 (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) ||
558 initialized.agentCapabilities?.loadSession !== true ||
559 !initialized.agentCapabilities.sessionCapabilities?.resume ||
560 !initialized.agentCapabilities.auth?.logout ||
561 !initialized.authMethods?.some((method) => method.id === "oauth-personal")
562 ) {
563 return yield* installationError(
564 "verify",
565 "The downloaded runtime did not identify as the expected Google Antigravity release.",
566 );
567 }
568 },
569 Effect.provideService(FileSystem.FileSystem, fs),
570 Effect.provideService(Path.Path, path),
571 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
572 Effect.provideService(SecureRandom.SecureRandom, random),
573 Effect.mapError((cause) => {
574 if (isInstallationError(cause)) return cause;
575 const stderr = isAcpProcessExitedError(cause) ? (cause.stderr ?? "") : "";
576 const detail = /\b(?:AF_INET6|enforce_kernel_ipv6_support)\b/.test(stderr)
577 ? "Antigravity requires IPv6 socket support. Enable IPv6 in this environment. On WSL, remove ipv6.disable=1 from .wslconfig and run wsl --shutdown."
578 : /page-size\.cc|Compile-time page size does not match/.test(stderr)
579 ? LARGE_PAGE_KERNEL_MESSAGE
580 : "The downloaded Antigravity runtime could not start in this environment.";
581 return installationError("verify", detail, cause);
582 }),
583 );
584​
585 // Each update lands in its own directory. Best effort: a busy gate means a session is
586 // resolving, so the next start or update finishes the cleanup.
587 const pruneInactiveReleases = Effect.gen(function* () {
588 const active = yield* readRecord(activePath, ActiveRelease);
589 for (const entry of yield* fs.readDirectory(versionsDirectory)) {
590 if (entry === active.releaseId || !/^[a-f0-9]{64}$/u.test(entry)) continue;
591 const directory = path.join(versionsDirectory, entry);
592 if (leases.has(directory)) continue;
593 yield* fs.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore);
594 }
595 }).pipe(
596 gate.withPermitsIfAvailable(1),
597 Effect.ignore,
598 Effect.withSpan("AntigravityInstallation.pruneInactiveReleases"),
599 );
600​
601 const install = Effect.fn("AntigravityInstallation.install")(
602 function* (asset: AntigravityReleaseAsset | AntigravityCliReleaseAsset) {
603 yield* ensureEligible(asset.version);
604 const cli = "sha512" in asset;
605 // Existing installation records use 64-character IDs, including native SHA-512 prefixes.
606 const releaseId = cli ? asset.sha512.slice(0, 64) : asset.sha256;
607 const archiveBytes = cli ? null : asset.archiveBytes;
608 yield* resolveNodeExecutable("Antigravity", environment).pipe(
609 Effect.provideService(FileSystem.FileSystem, fs),
610 Effect.provideService(Path.Path, path),
611 Effect.provideService(HostProcess.Platform, platform),
612 Effect.mapError((cause) =>
613 installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause),
614 ),
615 );
616 if (!cli && platform === "linux" && arch === "arm64") {
617 const pageSize = yield* spawner
618 .string(ChildProcess.make("getconf", ["PAGESIZE"], { stdin: "ignore", stderr: "ignore" }))
619 .pipe(
620 Effect.map((output) => Number(output.trim())),
621 Effect.timeout("5 seconds"),
622 Effect.orElseSucceed(() => Number.NaN),
623 );
624 if (pageSize > 4096) {
625 return yield* installationError("download", LARGE_PAGE_KERNEL_MESSAGE);
626 }
627 }
628 const report = (phase: ProviderInstallState["phase"], message: string | null) =>
629 SubscriptionRef.update(state, (current) => ({ ...current, phase, message }));
630 yield* fs.makeDirectory(versionsDirectory, { recursive: true });
631 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
632 const destination = path.join(versionsDirectory, releaseId);
633 const activate = Effect.fn("AntigravityInstallation.activate")(
634 function* () {
635 yield* ensureEligible(asset.version);
636 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
637 directory: managedDirectory,
638 prefix: "active.json.",
639 });
640 const pointerPath = path.join(pointerDirectory, "contents.tmp");
641 yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), {
642 flag: "wx",
643 mode: 0o600,
644 });
645 yield* fs.rename(pointerPath, activePath);
646 yield* pruneInactiveReleases;
647 yield* SubscriptionRef.update(
648 state,
649 (current) =>
650 ({
651 ...current,
652 phase: "succeeded",
653 installedVersion: asset.version,
654 message: null,
655 }) satisfies ProviderInstallState,
656 );
657 },
658 Effect.scoped,
659 Effect.mapError(
660 wrapFailure(
661 "activate",
662 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
663 ),
664 ),
665 Effect.uninterruptible,
666 );
667​
668 if (yield* fs.exists(destination)) {
669 const existing = yield* completedRelease(releaseId);
670 if (existing.version !== asset.version) {
671 return yield* installationError(
672 "verify",
673 "The existing managed release has the wrong version. Remove it before reinstalling.",
674 );
675 }
676 yield* report("verifying", "Checking the installed runtime.");
677 yield* validate(existing, asset.version).pipe(Effect.scoped, withValidationTimeout);
678 yield* activate();
679 return;
680 }
681​
682 const available = yield* Effect.tryPromise({
683 try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }),
684 catch: (cause) => installationError("download", "Could not check free disk space.", cause),
685 }).pipe(Effect.option);
686 const required = cli
687 ? MAX_DOWNLOAD_BYTES + MAX_EXECUTABLE_BYTES + FREE_SPACE_MARGIN
688 : asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN;
689 if (
690 Option.isSome(available) &&
691 available.value.bavail * available.value.bsize < BigInt(required)
692 ) {
693 return yield* installationError(
694 "download",
695 `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`,
696 );
697 }
698 const staging = yield* fs.makeTempDirectoryScoped({
699 directory: versionsDirectory,
700 prefix: ".install-",
701 });
702 const archivePath = path.join(staging, "download.zip");
703 const pairDirectory = path.join(staging, "runtime");
704 yield* fs.makeDirectory(pairDirectory);
705 const hash = NodeCrypto.createHash(cli ? "sha512" : "sha256");
706 let downloadedBytes = 0;
707 let lastProgressAt = yield* Clock.currentTimeMillis;
708 yield* Effect.gen(function* () {
709 const response = yield* http
710 .execute(HttpClientRequest.get(asset.url))
711 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
712 // dl.google.com may gzip the zip: content-length is encoded, while byte/hash checks use decoded data.
713 const contentLength = response.headers["content-length"];
714 const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase();
715 const identityBody = contentEncoding === undefined || contentEncoding === "identity";
716 if (
717 identityBody &&
718 contentLength !== undefined &&
719 archiveBytes !== null &&
720 Number(contentLength) !== archiveBytes
721 ) {
722 return yield* installationError(
723 "download",
724 "The Antigravity download size did not match the pinned release.",
725 );
726 }
727 yield* response.stream.pipe(
728 Stream.tap((chunk) =>
729 Effect.gen(function* () {
730 downloadedBytes += chunk.byteLength;
731 if (downloadedBytes > (archiveBytes ?? MAX_DOWNLOAD_BYTES)) {
732 return yield* installationError(
733 "download",
734 "The Antigravity download exceeded its allowed size.",
735 );
736 }
737 hash.update(chunk);
738 const now = yield* Clock.currentTimeMillis;
739 if (now - lastProgressAt >= 250 || downloadedBytes === archiveBytes) {
740 lastProgressAt = now;
741 yield* SubscriptionRef.update(state, (current) => ({
742 ...current,
743 downloadedBytes,
744 }));
745 }
746 }),
747 ),
748 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
749 );
750 }).pipe(
751 Effect.timeout(DOWNLOAD_TIMEOUT),
752 Effect.mapError((cause) =>
753 HttpClientError.isHttpClientError(cause) || Cause.isTimeoutError(cause)
754 ? installationError(
755 "download",
756 "Could not download Antigravity from Google. Check the network connection and any proxy settings, then try again.",
757 cause,
758 )
759 : cause,
760 ),
761 );
762 if (
763 (archiveBytes !== null && downloadedBytes !== archiveBytes) ||
764 hash.digest("hex") !== (cli ? asset.sha512 : asset.sha256)
765 ) {
766 return yield* installationError(
767 "download",
768 "The Antigravity download failed its size or checksum check. Nothing was installed.",
769 );
770 }
771​
772 yield* report("extracting", "Extracting the verified runtime.");
773 if (cli) {
774 const executablePath = path.join(pairDirectory, asset.executable.name);
775 if (asset.format === "executable") {
776 yield* fs.copyFile(archivePath, executablePath);
777 } else {
778 const tar = cliArchiveTarCommand(platform, environment);
779 const list = yield* spawner.string(ChildProcess.make(tar, ["-tzf", archivePath]));
780 const types = yield* spawner.string(ChildProcess.make(tar, ["-tvzf", archivePath]));
781 if (
782 list.trim() !== asset.executable.name ||
783 types.trim().split(/\r?\n/u).length !== 1 ||
784 !types.startsWith("-")
785 ) {
786 return yield* installationError(
787 "extract",
788 "The Antigravity archive must contain one regular executable.",
789 );
790 }
791 yield* Effect.gen(function* () {
792 const child = yield* spawner.spawn(
793 ChildProcess.make(tar, ["-xOzf", archivePath, asset.executable.name], {
794 stdout: "pipe",
795 stderr: "pipe",
796 }),
797 );
798 let extractedBytes = 0;
799 yield* child.stdout.pipe(
800 Stream.tap((chunk) =>
801 Effect.gen(function* () {
802 extractedBytes += chunk.byteLength;
803 if (extractedBytes > MAX_EXECUTABLE_BYTES)
804 return yield* installationError(
805 "extract",
806 "The Antigravity executable exceeded its size limit.",
807 );
808 }),
809 ),
810 Stream.run(fs.sink(executablePath, { flag: "wx", mode: 0o700 })),
811 );
812 if ((yield* child.exitCode) !== 0 || extractedBytes === 0)
813 return yield* installationError(
814 "extract",
815 "Could not extract the Antigravity executable.",
816 );
817 }).pipe(Effect.scoped);
818 }
819 } else
820 yield* Effect.gen(function* () {
821 const archive = yield* openZipArchive(archivePath, (detail, cause) =>
822 installationError("extract", detail, cause),
823 );
824 if (archive.entryCount !== 2) {
825 return yield* installationError(
826 "extract",
827 "The archive must contain exactly the Antigravity executable and its harness.",
828 );
829 }
830 const seen = new Set<string>();
831 for (;;) {
832 const entry = yield* archive.next;
833 if (!entry) break;
834 const expected = [asset.executable, asset.harness].find(
835 (file) => file.name === entry.fileName,
836 );
837 const unixType = (entry.externalFileAttributes >>> 16) & 0o170000;
838 if (
839 !expected ||
840 seen.has(entry.fileName) ||
841 entry.fileName.includes("/") ||
842 entry.fileName.includes("\\") ||
843 (unixType !== 0 && unixType !== 0o100000) ||
844 (entry.externalFileAttributes & 0x10) !== 0 ||
845 (entry.generalPurposeBitFlag & 1) !== 0 ||
846 ![0, 8].includes(entry.compressionMethod) ||
847 entry.uncompressedSize !== expected.bytes
848 ) {
849 return yield* installationError(
850 "extract",
851 "The archive contains an unexpected, unsafe, or incorrectly sized member.",
852 );
853 }
854 seen.add(entry.fileName);
855 yield* Effect.gen(function* () {
856 const readable = yield* archive.streamEntry(entry);
857 let extractedBytes = 0;
858 yield* EffectNodeStream.fromReadable<Uint8Array, AntigravityInstallationError>({
859 evaluate: () => readable,
860 onError: wrapFailure("extract", "Could not extract the Antigravity runtime."),
861 }).pipe(
862 Stream.tap((chunk) =>
863 Effect.gen(function* () {
864 extractedBytes += chunk.byteLength;
865 if (extractedBytes > expected.bytes) {
866 return yield* installationError(
867 "extract",
868 "An archive member exceeded its pinned size.",
869 );
870 }
871 }),
872 ),
873 Stream.run(
874 fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }),
875 ),
876 );
877 if (extractedBytes !== expected.bytes) {
878 return yield* installationError("extract", "An archive member was truncated.");
879 }
880 }).pipe(Effect.scoped);
881 }
882 if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) {
883 return yield* installationError(
884 "extract",
885 "The archive is missing the Antigravity executable or its harness.",
886 );
887 }
888 }).pipe(Effect.scoped);
889 yield* fs.remove(archivePath);
890 const executablePath = path.join(pairDirectory, asset.executable.name);
891 const harnessPath = cli ? null : path.join(pairDirectory, asset.harness.name);
892 if (platform !== "win32") {
893 yield* fs.chmod(executablePath, 0o755);
894 if (harnessPath !== null) yield* fs.chmod(harnessPath, 0o755);
895 }
896 if (!cli && platform === "darwin" && arch === "x64") {
897 // Google signs the Intel build with the hardened runtime but no JIT entitlement, so
898 // libffi's writable+executable trampolines spin forever. Re-sign ad hoc after the hash check.
899 const exitCode = yield* spawner
900 .spawn(
901 ChildProcess.make(
902 "/usr/bin/codesign",
903 [
904 "--force",
905 "--sign",
906 "-",
907 executablePath,
908 ...(harnessPath === null ? [] : [harnessPath]),
909 ],
910 { stdout: "ignore", stderr: "ignore" },
911 ),
912 )
913 .pipe(
914 Effect.flatMap((child) => child.exitCode),
915 Effect.scoped,
916 );
917 if (exitCode !== 0) {
918 return yield* installationError(
919 "extract",
920 "Could not prepare the Antigravity runtime for this Mac. Check that codesign is available.",
921 );
922 }
923 }
924 yield* report("verifying", "Checking the downloaded runtime.");
925 yield* validate(
926 {
927 executablePath,
928 harnessPath,
929 source: "managed",
930 version: asset.version,
931 managedVersionDirectory: pairDirectory,
932 },
933 asset.version,
934 ).pipe(Effect.scoped, withValidationTimeout);
935 const record: InstalledRelease = {
936 releaseId,
937 version: asset.version,
938 executable: {
939 name: asset.executable.name,
940 bytes: Number((yield* fs.stat(executablePath)).size),
941 },
942 harness:
943 cli || harnessPath === null
944 ? null
945 : { name: asset.harness.name, bytes: Number((yield* fs.stat(harnessPath)).size) },
946 };
947 yield* fs.writeFileString(
948 path.join(pairDirectory, RELEASE_RECORD),
949 yield* encodeInstalledRelease(record),
950 { flag: "wx", mode: 0o600 },
951 );
952 yield* fs.rename(pairDirectory, destination).pipe(
953 retryWhileWindowsHoldsHandles,
954 Effect.catch((cause) =>
955 completedRelease(releaseId).pipe(
956 Effect.flatMap((existing) =>
957 existing.version === asset.version
958 ? validate(existing, asset.version).pipe(Effect.scoped, withValidationTimeout)
959 : Effect.fail(
960 installationError(
961 "activate",
962 "Another installation published a different Antigravity release.",
963 ),
964 ),
965 ),
966 Effect.mapError((error) =>
967 isInstallationError(error) && error.operation === "verify"
968 ? error
969 : installationError(
970 "activate",
971 "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
972 cause,
973 ),
974 ),
975 ),
976 ),
977 );
978 yield* activate();
979 },
980 Effect.scoped,
981 Effect.mapError(
982 wrapFailure(
983 "install",
984 "Could not install Antigravity. Check free disk space and directory access, then try again.",
985 ),
986 ),
987 );
988​
989 let lastUpdateCheck: number | undefined;
990 const refreshRelease = Effect.fn("AntigravityInstallation.refreshRelease")(function* (
991 explicit = false,
992 ) {
993 if (options.releaseAsset !== undefined || !supported) return;
994 if (!explicit && !(yield* options.updateChecksEnabled ?? Effect.succeed(true))) return;
995 const now = yield* Clock.currentTimeMillis;
996 if (!explicit && lastUpdateCheck !== undefined && now - lastUpdateCheck < UPDATE_CHECK_INTERVAL)
997 return;
998 lastUpdateCheck = now;
999 const musl =
1000 platform === "linux" &&
1001 (yield* fs.exists(
1002 arch === "arm64" ? "/lib/libc.musl-aarch64.so.1" : "/lib/libc.musl-x86_64.so.1",
1003 ));
1004 const target = antigravityCliTarget(platform, arch, musl);
1005 const latest = yield* http.get(`${ANTIGRAVITY_CLI_MANIFEST_BASE}/${target}.json`).pipe(
1006 Effect.flatMap(HttpClientResponse.filterStatusOk),
1007 Effect.flatMap((response) => response.json),
1008 Effect.map((json) => parseAntigravityCliRelease(json, platform, arch, musl)),
1009 Effect.timeout("10 seconds"),
1010 Effect.orElseSucceed(() => null),
1011 );
1012 if (latest === null) return;
1013 if (yield* isWithdrawn(latest.version)) {
1014 releaseAsset = null;
1015 return;
1017 releaseAsset = latest;
1018 yield* SubscriptionRef.updateEffect(state, (value) =>
1019 isRunning(value)
1020 ? Effect.succeed(value)
1021 : Effect.gen(function* () {
1022 const keepInstalled =
1023 value.installedVersion !== null &&
1024 compareSemverVersions(value.installedVersion, latest.version) > 0 &&
1025 !(yield* isWithdrawn(value.installedVersion));
1026 return {
1027 ...value,
1028 version: keepInstalled ? value.installedVersion : latest.version,
1029 totalBytes: null,
1030 };
1031 }),
1032 );
1033 });
1034​
1035 const start = Effect.gen(function* () {
1036 const current = yield* SubscriptionRef.get(state);
1037 if (isRunning(current)) return current;
1038 yield* refreshRelease(true);
1039 return yield* gate.withPermit(
1040 Effect.gen(function* () {
1041 const current = yield* SubscriptionRef.get(state);
1042 if (isRunning(current)) return current;
1043 if (!supported) {
1044 return yield* installationError(
1045 "start",
1046 `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
1047 );
1049 const asset =
1050 releaseAsset !== null && !(yield* isWithdrawn(releaseAsset.version))
1051 ? releaseAsset
1052 : null;
1053 const installed = yield* resolve().pipe(Effect.option);
1054 const reuse =
1055 Option.isSome(installed) &&
1056 installed.value.source === "managed" &&
1057 installed.value.harnessPath === null &&
1058 (asset === null || compareSemverVersions(installed.value.version!, asset.version) > 0)
1059 ? installed.value
1060 : undefined;
1061 if (asset === null && reuse === undefined)
1062 return yield* installationError(
1063 "start",
1064 "Could not find a native Antigravity CLI release. Check the network connection and try again.",
1065 );
1066 const operationId = yield* random.uuidV4();
1067 const next: ProviderInstallState = {
1068 driver: DRIVER,
1069 operationId,
1070 phase: reuse === undefined ? "downloading" : "verifying",
1071 downloadedBytes: 0,
1072 totalBytes: asset !== null && "archiveBytes" in asset ? asset.archiveBytes : null,
1073 version: reuse?.version ?? asset?.version ?? null,
1074 installedVersion: current.installedVersion,
1075 canRemove: current.canRemove,
1076 message:
1077 reuse === undefined
1078 ? "Downloading Google's official Antigravity runtime."
1079 : "Checking the installed runtime.",
1080 };
1081 yield* SubscriptionRef.set(state, next);
1082 const work = (
1083 reuse === undefined
1084 ? install(asset!)
1085 : validate(reuse, reuse.version!).pipe(
1086 Effect.scoped,
1087 withValidationTimeout,
1088 Effect.andThen(ensureEligible(reuse.version!)),
1089 Effect.andThen(
1090 SubscriptionRef.update(state, (value) => ({
1091 ...value,
1092 phase: "succeeded" as const,
1093 installedVersion: reuse.version,
1094 message: null,
1095 })),
1096 ),
1098 ).pipe(
1099 Effect.mapError(
1100 wrapFailure("verify", "Could not verify the installed Antigravity runtime."),
1101 ),
1102 Effect.onExit((exit) =>
1103 Exit.isFailure(exit)
1104 ? SubscriptionRef.update(state, (value) => {
1105 if (value.operationId !== operationId || value.phase === "succeeded")
1106 return value;
1107 const error = Cause.findErrorOption(exit.cause);
1108 const cancelled = Cause.hasInterruptsOnly(exit.cause);
1109 return {
1110 ...value,
1111 phase: cancelled ? "cancelled" : "failed",
1112 message: cancelled
1113 ? "Installation cancelled. The previous runtime is unchanged."
1114 : Option.isSome(error)
1115 ? error.value.detail
1116 : "Could not finish the Antigravity installation. Check disk space and directory access.",
1117 } satisfies ProviderInstallState;
1118 })
1119 : Effect.void,
1120 ),
1121 Effect.ignoreCause,
1122 Effect.ensuring(
1123 Effect.sync(() => {
1124 if (running?.operationId === operationId) running = undefined;
1125 }),
1126 ),
1127 );
1128 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
1129 running = { operationId, fiber };
1130 return next;
1131 }).pipe(Effect.uninterruptible),
1132 );
1133 }).pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation.")));
1134​
1135 const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) {
1136 return yield* gate.withPermit(
1137 Effect.gen(function* () {
1138 const current = yield* SubscriptionRef.get(state);
1139 if (current.operationId !== operationId) {
1140 return yield* installationError(
1141 "cancel",
1142 "This installation is no longer current. Refresh its status before cancelling.",
1143 );
1145 if (running?.operationId === operationId && isRunning(current)) {
1146 yield* Fiber.interrupt(running.fiber);
1148 return yield* SubscriptionRef.get(state);
1149 }),
1150 );
1151 });
1152​
1153 const remove = Effect.fn("AntigravityInstallation.remove")(
1154 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
1155 yield* gate.withPermit(
1156 Effect.gen(function* () {
1157 if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) {
1158 return yield* installationError(
1159 "remove",
1160 "Stop Antigravity sessions and sign-in flows before removing its managed runtime.",
1161 );
1163 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
1164 if (Option.isSome(realManaged)) {
1165 for (const binaryPath of protectedBinaryPaths) {
1166 if (!binaryPath.trim()) continue;
1167 const selected = yield* resolve(binaryPath).pipe(Effect.option);
1168 if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
1169 return yield* installationError(
1170 "remove",
1171 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
1172 );
1174 const resolved = yield* fs.realPath(binaryPath).pipe(Effect.option);
1175 const candidate = Option.getOrElse(resolved, () => path.resolve(binaryPath));
1176 if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
1177 return yield* installationError(
1178 "remove",
1179 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
1180 );
1184 yield* fs.remove(managedDirectory, { recursive: true, force: true });
1185 yield* SubscriptionRef.update(
1186 state,
1187 (current) =>
1188 ({
1189 ...current,
1190 operationId: null,
1191 phase: "idle",
1192 downloadedBytes: 0,
1193 installedVersion: null,
1194 canRemove: false,
1195 message: null,
1196 }) satisfies ProviderInstallState,
1197 );
1198 }).pipe(Effect.uninterruptible),
1199 );
1200 },
1201 Effect.mapError(
1202 wrapFailure(
1203 "remove",
1204 "Could not remove the managed Antigravity runtime. Check for open processes and try again.",
1205 ),
1206 ),
1207 );
1208​
1209 yield* Effect.gen(function* () {
1210 const canRemove = yield* fs.exists(managedDirectory);
1211 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
1212 if (!(yield* fs.exists(activePath))) return;
1213 const active = yield* readRecord(activePath, ActiveRelease);
1214 const installed = yield* completedRelease(active.releaseId);
1215 yield* SubscriptionRef.update(state, (current) => ({
1216 ...current,
1217 installedVersion: installed.version,
1218 }));
1219 }).pipe(
1220 Effect.catch(() =>
1221 SubscriptionRef.update(
1222 state,
1223 (current) =>
1224 ({
1225 ...current,
1226 phase: "failed",
1227 message: "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
1228 }) satisfies ProviderInstallState,
1229 ),
1230 ),
1231 );
1232​
1233 // A startup install prunes when it activates; pruning now could delete the release it is verifying.
1234 if (!isRunning(yield* SubscriptionRef.get(state))) yield* pruneInactiveReleases;
1235​
1236 return AntigravityInstallation.of({
1237 managedDirectory,
1238 resolve,
1239 acquire,
1240 start,
1241 cancel,
1242 state: SubscriptionRef.get(state),
1243 changes: SubscriptionRef.changes(state),
1244 checkForUpdate: refreshRelease().pipe(Effect.ignore),
1245 remove,
1246 });
1247});