Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest or free-space query.
2import * as EffectNodeStream from "@effect/platform-node/NodeStream";
3import { ProviderDriverKind, type ProviderInstallState } from "@t3tools/contracts";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
6import * as Clock from "effect/Clock";
7import * as Cause from "effect/Cause";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Fiber from "effect/Fiber";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as Schema from "effect/Schema";
18import * as Schedule from "effect/Schedule";
19import * as Scope from "effect/Scope";
20import * as Semaphore from "effect/Semaphore";
21import * as Stream from "effect/Stream";
22import * as SubscriptionRef from "effect/SubscriptionRef";
23import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
24import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
25import * as NodeCrypto from "node:crypto";
26import * as NodeFSP from "node:fs/promises";
27import * as EffectAcpErrors from "effect-acp/errors";
28
29import * as ServerConfig from "../config.ts";
30import { openZipArchive } from "../zipArchive.ts";
31import { makeAntigravityAcpRuntime } from "./acp/AntigravityAcpSupport.ts";
32import {
33 buildAntigravityAcpSpawnInput,
34 prepareAntigravityProfile,
35} from "./antigravityAuthSupport.ts";
36import {
37 resolveAntigravityReleaseAsset,
38 type AntigravityReleaseAsset,
39} from "./antigravityRelease.ts";
40
41const DRIVER = ProviderDriverKind.make("antigravity");
42const DOWNLOAD_TIMEOUT = "45 minutes";
43const VALIDATION_TIMEOUT = "90 seconds";
44const FREE_SPACE_MARGIN = 256 * 1024 * 1024;
45const RECORD_MAX_BYTES = 8 * 1024;
46const RELEASE_RECORD = ".install-complete.json";
47
48const ReleaseId = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u));
49const ActiveRelease = Schema.Struct({ releaseId: ReleaseId });
50const InstalledRelease = Schema.Struct({
51 releaseId: ReleaseId,
52 version: Schema.String,
53 executable: Schema.Struct({ name: Schema.String, bytes: Schema.Number }),
54 harness: Schema.Struct({ name: Schema.String, bytes: Schema.Number }),
55});
56type InstalledRelease = typeof InstalledRelease.Type;
57const encodeActiveRelease = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease));
58const encodeInstalledRelease = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease));
59
60export class AntigravityInstallationError extends Schema.TaggedError<AntigravityInstallationError>()(
61 "AntigravityInstallationError",
62 {
63 operation: Schema.String,
64 detail: Schema.String,
65 cause: Schema.optional(Schema.Defect()),
66 },
67) {
68 override get message() {
69 return this.detail;
70 }
71}
72const isInstallationError = Schema.is(AntigravityInstallationError);
73const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);
74
75export interface AntigravityExecutable {
76 readonly executablePath: string;
77 readonly harnessPath: string;
78 readonly source: "override" | "managed" | "path";
79 readonly version: string | null;
80 readonly managedVersionDirectory: string | null;
81}
82
83interface AntigravityInstallationService {
84 readonly managedDirectory: string;
85 readonly resolve: (
86 binaryPath?: string,
87 environment?: NodeJS.ProcessEnv,
88 ) => Effect.Effect<AntigravityExecutable, AntigravityInstallationError>;
89 /** Hold the lease until the spawned process has exited. */
90 readonly acquire: (
91 binaryPath?: string,
92 environment?: NodeJS.ProcessEnv,
93 ) => Effect.Effect<AntigravityExecutable, AntigravityInstallationError, Scope.Scope>;
94 readonly start: Effect.Effect<ProviderInstallState, AntigravityInstallationError>;
95 readonly cancel: (
96 operationId: string,
97 ) => Effect.Effect<ProviderInstallState, AntigravityInstallationError>;
98 readonly state: Effect.Effect<ProviderInstallState>;
99 readonly changes: Stream.Stream<ProviderInstallState>;
100 readonly remove: (
101 protectedBinaryPaths?: ReadonlyArray<string>,
102 ) => Effect.Effect<void, AntigravityInstallationError>;
103}
104
105export class AntigravityInstallation extends Context.Service<
106 AntigravityInstallation,
107 AntigravityInstallationService
108>()("t3/provider/AntigravityInstallation") {
109 static readonly layer = Layer.effect(
110 AntigravityInstallation,
111 Effect.gen(function* () {
112 const config = yield* ServerConfig.ServerConfig;
113 return yield* makeAntigravityInstallation({ baseDir: config.baseDir });
114 }),
115 );
116}
117
118export interface AntigravityInstallationOptions {
119 readonly baseDir: string;
120 readonly releaseAsset?: AntigravityReleaseAsset | null;
121 readonly validate?: (
122 executable: AntigravityExecutable,
123 expectedVersion: string,
124 ) => Effect.Effect<void, AntigravityInstallationError, Scope.Scope>;
125}
126
127const installationError = (operation: string, detail: string, cause?: unknown) =>
128 new AntigravityInstallationError({
129 operation,
130 detail,
131 ...(cause === undefined ? {} : { cause }),
132 });
133
134const wrapFailure = (operation: string, detail: string) => (cause: unknown) =>
135 isInstallationError(cause) ? cause : installationError(operation, detail, cause);
136
137function executableNames(platform: NodeJS.Platform) {
138 return platform === "win32"
139 ? { executable: "agy_acp_server.exe", harness: "localharness_external.exe" }
140 : { executable: "agy_acp_server.par", harness: "localharness_external" };
141}
142
143function isRunning(state: ProviderInstallState) {
144 return (
145 state.phase === "downloading" || state.phase === "extracting" || state.phase === "verifying"
146 );
147}
148
149export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.make")(function* (
150 options: AntigravityInstallationOptions,
151) {
152 const fs = yield* FileSystem.FileSystem;
153 const path = yield* Path.Path;
154 const crypto = yield* Crypto.Crypto;
155 const http = yield* HttpClient.HttpClient;
156 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
157 const serviceScope = yield* Effect.scope;
158 const platform = yield* HostProcess.Platform;
159 const arch = yield* HostProcess.Architecture;
160 const environment = yield* HostProcess.Environment;
161 const releaseAsset =
162 options.releaseAsset === undefined
163 ? resolveAntigravityReleaseAsset(platform, arch)
164 : options.releaseAsset;
165 const names = executableNames(platform);
166 const managedDirectory = path.join(
167 options.baseDir,
168 "tools",
169 "antigravity-acp",
170 `${platform}-${arch}`,
171 );
172 const versionsDirectory = path.join(managedDirectory, "versions");
173 const activePath = path.join(managedDirectory, "active.json");
174 const gate = yield* Semaphore.make(1);
175 const leases = new Map<string, number>();
176 let running: { readonly operationId: string; readonly fiber: Fiber.Fiber<void> } | undefined;
177 const state = yield* SubscriptionRef.make<ProviderInstallState>({
178 driver: DRIVER,
179 operationId: null,
180 phase: "idle",
181 downloadedBytes: 0,
182 totalBytes: releaseAsset?.archiveBytes ?? null,
183 version: releaseAsset?.version ?? null,
184 installedVersion: null,
185 canRemove: false,
186 message: null,
187 });
188
189 const readRecord = Effect.fn("AntigravityInstallation.readRecord")(function* <A>(
190 filePath: string,
191 schema: Schema.Codec<A>,
192 ) {
193 const info = yield* fs.stat(filePath);
194 if (info.type !== "File" || Number(info.size) > RECORD_MAX_BYTES) {
195 return yield* installationError(
196 "resolve",
197 "The managed runtime record is invalid. Reinstall Antigravity.",
198 );
199 }
200 const contents = yield* fs.readFileString(filePath);
201 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(contents);
202 });
203
204 const executableFile = Effect.fn("AntigravityInstallation.executableFile")(function* (
205 filePath: string,
206 bytes?: number,
207 ) {
208 const info = yield* fs.stat(filePath).pipe(Effect.option);
209 return (
210 Option.isSome(info) &&
211 info.value.type === "File" &&
212 (bytes === undefined || Number(info.value.size) === bytes) &&
213 (platform === "win32" || (info.value.mode & 0o111) !== 0)
214 );
215 });
216
217 const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* (
218 releaseId: string,
219 ) {
220 const directory = path.join(versionsDirectory, releaseId);
221 const record = yield* readRecord(path.join(directory, RELEASE_RECORD), InstalledRelease);
222 if (
223 record.releaseId !== releaseId ||
224 record.executable.name !== names.executable ||
225 record.harness.name !== names.harness ||
226 !Number.isSafeInteger(record.executable.bytes) ||
227 record.executable.bytes <= 0 ||
228 !Number.isSafeInteger(record.harness.bytes) ||
229 record.harness.bytes <= 0 ||
230 !record.version.trim() ||
231 !(yield* executableFile(path.join(directory, names.executable), record.executable.bytes)) ||
232 !(yield* executableFile(path.join(directory, names.harness), record.harness.bytes))
233 ) {
234 return yield* installationError(
235 "resolve",
236 "The managed Antigravity runtime is incomplete. Reinstall it.",
237 );
238 }
239 return {
240 executablePath: path.join(directory, names.executable),
241 harnessPath: path.join(directory, names.harness),
242 source: "managed",
243 version: record.version,
244 managedVersionDirectory: directory,
245 } satisfies AntigravityExecutable;
246 });
247
248 const fromExternal = Effect.fn("AntigravityInstallation.fromExternal")(function* (
249 candidate: string,
250 source: "override" | "path",
251 ) {
252 if (!(yield* executableFile(candidate))) return null;
253 const executablePath = yield* fs.realPath(candidate);
254 const directory = path.dirname(executablePath);
255 const harnessPath = path.join(directory, names.harness);
256 if (!(yield* executableFile(harnessPath))) return null;
257 const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option);
258 if (
259 Option.isSome(realVersions) &&
260 path.dirname(directory) === realVersions.value &&
261 /^[a-f0-9]{64}$/u.test(path.basename(directory))
262 ) {
263 const installed = yield* completedRelease(path.basename(directory));
264 return { ...installed, executablePath, harnessPath, source } satisfies AntigravityExecutable;
265 }
266 return {
267 executablePath,
268 harnessPath,
269 source,
270 version: null,
271 managedVersionDirectory: null,
272 } satisfies AntigravityExecutable;
273 });
274
275 const pathCandidates = (binary: string, processEnvironment = environment) => {
276 const pathValue =
277 platform === "win32"
278 ? Object.entries(processEnvironment).findLast(([key]) => key.toUpperCase() === "PATH")?.[1]
279 : processEnvironment.PATH;
280 return (pathValue ?? "")
281 .split(platform === "win32" ? ";" : ":")
282 .map((directory) => directory.trim().replace(/^"|"$/gu, ""))
283 .filter((directory) => directory.length > 0)
284 .map((directory) => path.resolve(directory, binary));
285 };
286
287 const resolve: AntigravityInstallationService["resolve"] = Effect.fn(
288 "AntigravityInstallation.resolve",
289 )(
290 function* (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) {
291 const override = binaryPath?.trim();
292 if (override) {
293 const candidates =
294 path.isAbsolute(override) || override.includes("/") || override.includes("\\")
295 ? [path.resolve(override)]
296 : pathCandidates(override, processEnvironment);
297 for (const candidate of candidates) {
298 const selected = yield* fromExternal(candidate, "override");
299 if (selected) return selected;
300 }
301 return yield* installationError(
302 "resolve",
303 "The custom Antigravity executable or its localharness_external sibling is missing or not executable.",
304 );
305 }
306 if (yield* fs.exists(activePath)) {
307 const active = yield* readRecord(activePath, ActiveRelease);
308 return yield* completedRelease(active.releaseId);
309 }
310 for (const candidate of pathCandidates(names.executable, processEnvironment)) {
311 const selected = yield* fromExternal(candidate, "path");
312 if (selected) return selected;
313 }
314 return yield* installationError(
315 "resolve",
316 releaseAsset
317 ? "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."
318 : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`,
319 );
320 },
321 Effect.mapError(
322 wrapFailure(
323 "resolve",
324 "Could not read the Antigravity installation. Reinstall it or set a custom executable path.",
325 ),
326 ),
327 );
328
329 const acquire = (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) =>
330 Effect.acquireRelease(
331 gate.withPermit(
332 Effect.gen(function* () {
333 const executable = yield* resolve(binaryPath, processEnvironment);
334 const directory = executable.managedVersionDirectory;
335 if (directory) leases.set(directory, (leases.get(directory) ?? 0) + 1);
336 return executable;
337 }),
338 ),
339 (executable) =>
340 gate.withPermit(
341 Effect.sync(() => {
342 const directory = executable.managedVersionDirectory;
343 if (!directory) return;
344 const remaining = (leases.get(directory) ?? 1) - 1;
345 if (remaining > 0) leases.set(directory, remaining);
346 else leases.delete(directory);
347 }),
348 ),
349 );
350
351 const validate =
352 options.validate ??
353 Effect.fn("AntigravityInstallation.validate")(
354 function* (executable: AntigravityExecutable, expectedVersion: string) {
355 const validationScope = yield* Effect.scope;
356 const profileDirectory = yield* Effect.acquireRelease(
357 fs.makeTempDirectory({ prefix: "t3-antigravity-validate-" }),
358 (directory) =>
359 fs.remove(directory, { recursive: true, force: true }).pipe(
360 // Windows may retain DLL handles briefly after taskkill returns.
361 Effect.retry({
362 times: platform === "win32" ? 10 : 0,
363 schedule: Schedule.spaced("100 millis"),
364 while: (error) =>
365 error.reason._tag === "PermissionDenied" ||
366 error.reason._tag === "Busy" ||
367 error.reason._tag === "Unknown",
368 }),
369 Effect.orDie,
370 ),
371 );
372 const profile = yield* prepareAntigravityProfile({
373 profileDirectory,
374 platform,
375 baseEnv: environment,
376 // A shallow scoped profile cleans up unpacked files within Windows' path limit.
377 tempDirectory: profileDirectory,
378 });
379 const runtime = yield* makeAntigravityAcpRuntime({
380 spawn: buildAntigravityAcpSpawnInput({
381 installation: executable,
382 profile,
383 cwd: profileDirectory,
384 baseEnv: environment,
385 }),
386 cwd: profileDirectory,
387 childProcessSpawner:
388 platform === "win32"
389 ? ChildProcessSpawner.make(
390 Effect.fnUntraced(function* (command) {
391 const child = yield* spawner.spawn(command);
392 // Stop PyInstaller's tree before ACP closes pipes; after launcher exit, taskkill cannot reach children holding DLLs open.
393 yield* Scope.addFinalizer(
394 validationScope,
395 child.kill({ forceKillAfter: "1 second" }).pipe(Effect.orDie),
396 );
397 return child;
398 }),
399 )
400 : spawner,
401 });
402 const initialized = yield* runtime.initialize();
403 if (
404 initialized.agentInfo?.name !== "antigravity-acp" ||
405 initialized.agentInfo.version !== expectedVersion ||
406 // Antigravity 1.1.1 may report protocol 2 with legacy ACP; choose wire format from the response shape.
407 (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) ||
408 initialized.agentCapabilities?.loadSession !== true ||
409 !initialized.agentCapabilities.sessionCapabilities?.resume ||
410 !initialized.agentCapabilities.auth?.logout ||
411 !initialized.authMethods?.some((method) => method.id === "oauth-personal")
412 ) {
413 return yield* installationError(
414 "verify",
415 "The downloaded runtime did not identify as the expected Google Antigravity release.",
416 );
417 }
418 },
419 Effect.provideService(FileSystem.FileSystem, fs),
420 Effect.provideService(Path.Path, path),
421 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
422 Effect.provideService(Crypto.Crypto, crypto),
423 Effect.mapError((cause) => {
424 if (isInstallationError(cause)) return cause;
425 const detail =
426 isAcpProcessExitedError(cause) &&
427 /\b(?:AF_INET6|enforce_kernel_ipv6_support)\b/.test(cause.stderr ?? "")
428 ? "Antigravity requires IPv6 socket support. Enable IPv6 in this environment. On WSL, remove ipv6.disable=1 from .wslconfig and run wsl --shutdown."
429 : "The downloaded Antigravity runtime could not start in this environment.";
430 return installationError("verify", detail, cause);
431 }),
432 );
433
434 const install = Effect.fn("AntigravityInstallation.install")(
435 function* (asset: AntigravityReleaseAsset) {
436 yield* resolveNodeExecutable("Antigravity", environment).pipe(
437 Effect.provideService(FileSystem.FileSystem, fs),
438 Effect.provideService(Path.Path, path),
439 Effect.provideService(HostProcess.Platform, platform),
440 Effect.mapError((cause) =>
441 installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause),
442 ),
443 );
444 const report = (phase: ProviderInstallState["phase"], message: string | null) =>
445 SubscriptionRef.update(state, (current) => ({ ...current, phase, message }));
446 yield* fs.makeDirectory(versionsDirectory, { recursive: true });
447 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
448 const destination = path.join(versionsDirectory, asset.sha256);
449 const activate = Effect.fn("AntigravityInstallation.activate")(
450 function* () {
451 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
452 directory: managedDirectory,
453 prefix: "active.json.",
454 });
455 const pointerPath = path.join(pointerDirectory, "contents.tmp");
456 yield* fs.writeFileString(
457 pointerPath,
458 yield* encodeActiveRelease({ releaseId: asset.sha256 }),
459 { flag: "wx", mode: 0o600 },
460 );
461 yield* fs.rename(pointerPath, activePath);
462 yield* SubscriptionRef.update(
463 state,
464 (current) =>
465 ({
466 ...current,
467 phase: "succeeded",
468 installedVersion: asset.version,
469 message: null,
470 }) satisfies ProviderInstallState,
471 );
472 },
473 Effect.scoped,
474 Effect.mapError(
475 wrapFailure(
476 "activate",
477 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
478 ),
479 ),
480 Effect.uninterruptible,
481 );
482
483 if (yield* fs.exists(destination)) {
484 const existing = yield* completedRelease(asset.sha256);
485 if (existing.version !== asset.version) {
486 return yield* installationError(
487 "verify",
488 "The existing managed release has the wrong version. Remove it before reinstalling.",
489 );
490 }
491 yield* report("verifying", "Checking the installed runtime.");
492 yield* validate(existing, asset.version).pipe(
493 Effect.scoped,
494 Effect.timeout(VALIDATION_TIMEOUT),
495 );
496 yield* activate();
497 return;
498 }
499
500 const available = yield* Effect.tryPromise(() =>
501 NodeFSP.statfs(versionsDirectory, { bigint: true }),
502 ).pipe(Effect.option);
503 const required =
504 asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN;
505 if (
506 Option.isSome(available) &&
507 available.value.bavail * available.value.bsize < BigInt(required)
508 ) {
509 return yield* installationError(
510 "download",
511 `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`,
512 );
513 }
514 const staging = yield* fs.makeTempDirectoryScoped({
515 directory: versionsDirectory,
516 prefix: ".install-",
517 });
518 const archivePath = path.join(staging, "download.zip");
519 const pairDirectory = path.join(staging, "runtime");
520 yield* fs.makeDirectory(pairDirectory);
521 const hash = NodeCrypto.createHash("sha256");
522 let downloadedBytes = 0;
523 let lastProgressAt = yield* Clock.currentTimeMillis;
524 yield* Effect.gen(function* () {
525 const response = yield* http
526 .execute(HttpClientRequest.get(asset.url))
527 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
528 // dl.google.com may gzip the zip: content-length is encoded, while byte/hash checks use decoded data.
529 const contentLength = response.headers["content-length"];
530 const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase();
531 const identityBody = contentEncoding === undefined || contentEncoding === "identity";
532 if (
533 identityBody &&
534 contentLength !== undefined &&
535 Number(contentLength) !== asset.archiveBytes
536 ) {
537 return yield* installationError(
538 "download",
539 "The Antigravity download size did not match the pinned release.",
540 );
541 }
542 yield* response.stream.pipe(
543 Stream.tap((chunk) =>
544 Effect.gen(function* () {
545 downloadedBytes += chunk.byteLength;
546 if (downloadedBytes > asset.archiveBytes) {
547 return yield* installationError(
548 "download",
549 "The Antigravity download exceeded the pinned release size.",
550 );
551 }
552 hash.update(chunk);
553 const now = yield* Clock.currentTimeMillis;
554 if (now - lastProgressAt >= 250 || downloadedBytes === asset.archiveBytes) {
555 lastProgressAt = now;
556 yield* SubscriptionRef.update(state, (current) => ({
557 ...current,
558 downloadedBytes,
559 }));
560 }
561 }),
562 ),
563 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
564 );
565 }).pipe(Effect.timeout(DOWNLOAD_TIMEOUT));
566 if (downloadedBytes !== asset.archiveBytes || hash.digest("hex") !== asset.sha256) {
567 return yield* installationError(
568 "download",
569 "The Antigravity download failed its size or SHA-256 check. Nothing was installed.",
570 );
571 }
572
573 yield* report("extracting", "Extracting the verified runtime.");
574 yield* Effect.gen(function* () {
575 const archive = yield* openZipArchive(archivePath, (detail, cause) =>
576 installationError("extract", detail, cause),
577 );
578 if (archive.entryCount !== 2) {
579 return yield* installationError(
580 "extract",
581 "The archive must contain exactly the Antigravity executable and its harness.",
582 );
583 }
584 const seen = new Set<string>();
585 for (;;) {
586 const entry = yield* archive.next;
587 if (!entry) break;
588 const expected = [asset.executable, asset.harness].find(
589 (file) => file.name === entry.fileName,
590 );
591 const unixType = (entry.externalFileAttributes >>> 16) & 0o170000;
592 if (
593 !expected ||
594 seen.has(entry.fileName) ||
595 entry.fileName.includes("/") ||
596 entry.fileName.includes("\\") ||
597 (unixType !== 0 && unixType !== 0o100000) ||
598 (entry.externalFileAttributes & 0x10) !== 0 ||
599 (entry.generalPurposeBitFlag & 1) !== 0 ||
600 ![0, 8].includes(entry.compressionMethod) ||
601 entry.uncompressedSize !== expected.bytes
602 ) {
603 return yield* installationError(
604 "extract",
605 "The archive contains an unexpected, unsafe, or incorrectly sized member.",
606 );
607 }
608 seen.add(entry.fileName);
609 yield* Effect.gen(function* () {
610 const readable = yield* archive.streamEntry(entry);
611 let extractedBytes = 0;
612 yield* EffectNodeStream.fromReadable<Uint8Array, AntigravityInstallationError>({
613 evaluate: () => readable,
614 onError: wrapFailure("extract", "Could not extract the Antigravity runtime."),
615 }).pipe(
616 Stream.tap((chunk) =>
617 Effect.gen(function* () {
618 extractedBytes += chunk.byteLength;
619 if (extractedBytes > expected.bytes) {
620 return yield* installationError(
621 "extract",
622 "An archive member exceeded its pinned size.",
623 );
624 }
625 }),
626 ),
627 Stream.run(
628 fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }),
629 ),
630 );
631 if (extractedBytes !== expected.bytes) {
632 return yield* installationError("extract", "An archive member was truncated.");
633 }
634 }).pipe(Effect.scoped);
635 }
636 if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) {
637 return yield* installationError(
638 "extract",
639 "The archive is missing the Antigravity executable or its harness.",
640 );
641 }
642 }).pipe(Effect.scoped);
643 yield* fs.remove(archivePath);
644 if (platform !== "win32") {
645 yield* fs.chmod(path.join(pairDirectory, asset.executable.name), 0o755);
646 yield* fs.chmod(path.join(pairDirectory, asset.harness.name), 0o755);
647 }
648 yield* report("verifying", "Checking the downloaded runtime.");
649 yield* validate(
650 {
651 executablePath: path.join(pairDirectory, asset.executable.name),
652 harnessPath: path.join(pairDirectory, asset.harness.name),
653 source: "managed",
654 version: asset.version,
655 managedVersionDirectory: pairDirectory,
656 },
657 asset.version,
658 ).pipe(Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT));
659 const record: InstalledRelease = {
660 releaseId: asset.sha256,
661 version: asset.version,
662 executable: asset.executable,
663 harness: asset.harness,
664 };
665 yield* fs.writeFileString(
666 path.join(pairDirectory, RELEASE_RECORD),
667 yield* encodeInstalledRelease(record),
668 { flag: "wx", mode: 0o600 },
669 );
670 yield* fs.rename(pairDirectory, destination).pipe(
671 Effect.catch((cause) =>
672 completedRelease(asset.sha256).pipe(
673 Effect.flatMap((existing) =>
674 existing.version === asset.version
675 ? validate(existing, asset.version).pipe(
676 Effect.scoped,
677 Effect.timeout(VALIDATION_TIMEOUT),
678 )
679 : Effect.fail(
680 installationError(
681 "activate",
682 "Another installation published a different Antigravity release.",
683 ),
684 ),
685 ),
686 Effect.mapError(() =>
687 installationError(
688 "activate",
689 "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
690 cause,
691 ),
692 ),
693 ),
694 ),
695 );
696 yield* activate();
697 },
698 Effect.scoped,
699 Effect.mapError(
700 wrapFailure(
701 "install",
702 "Could not install Antigravity. Check free disk space and directory access, then try again.",
703 ),
704 ),
705 );
706
707 const start = gate
708 .withPermit(
709 Effect.gen(function* () {
710 const current = yield* SubscriptionRef.get(state);
711 if (isRunning(current)) return current;
712 if (!releaseAsset) {
713 return yield* installationError(
714 "start",
715 `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
716 );
717 }
718 const operationId = yield* crypto.randomUUIDv4();
719 const next: ProviderInstallState = {
720 driver: DRIVER,
721 operationId,
722 phase: "downloading",
723 downloadedBytes: 0,
724 totalBytes: releaseAsset.archiveBytes,
725 version: releaseAsset.version,
726 installedVersion: current.installedVersion,
727 canRemove: current.canRemove,
728 message: "Downloading Google's official Antigravity runtime.",
729 };
730 yield* SubscriptionRef.set(state, next);
731 const work = install(releaseAsset).pipe(
732 Effect.onExit((exit) =>
733 Exit.isFailure(exit)
734 ? SubscriptionRef.update(state, (value) => {
735 if (value.operationId !== operationId || value.phase === "succeeded")
736 return value;
737 const error = Cause.findErrorOption(exit.cause);
738 const cancelled = Cause.hasInterruptsOnly(exit.cause);
739 return {
740 ...value,
741 phase: cancelled ? "cancelled" : "failed",
742 message: cancelled
743 ? "Installation cancelled. The previous runtime is unchanged."
744 : Option.isSome(error)
745 ? error.value.detail
746 : "Could not finish the Antigravity installation. Check disk space and directory access.",
747 } satisfies ProviderInstallState;
748 })
749 : Effect.void,
750 ),
751 Effect.ignoreCause,
752 Effect.ensuring(
753 Effect.sync(() => {
754 if (running?.operationId === operationId) running = undefined;
755 }),
756 ),
757 );
758 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
759 running = { operationId, fiber };
760 return next;
761 }).pipe(Effect.uninterruptible),
762 )
763 .pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation.")));
764
765 const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) {
766 return yield* gate.withPermit(
767 Effect.gen(function* () {
768 const current = yield* SubscriptionRef.get(state);
769 if (current.operationId !== operationId) {
770 return yield* installationError(
771 "cancel",
772 "This installation is no longer current. Refresh its status before cancelling.",
773 );
774 }
775 if (running?.operationId === operationId && isRunning(current)) {
776 yield* Fiber.interrupt(running.fiber);
777 }
778 return yield* SubscriptionRef.get(state);
779 }),
780 );
781 });
782
783 const remove = Effect.fn("AntigravityInstallation.remove")(
784 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
785 yield* gate.withPermit(
786 Effect.gen(function* () {
787 if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) {
788 return yield* installationError(
789 "remove",
790 "Stop Antigravity sessions and sign-in flows before removing its managed runtime.",
791 );
792 }
793 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
794 if (Option.isSome(realManaged)) {
795 for (const binaryPath of protectedBinaryPaths) {
796 if (!binaryPath.trim()) continue;
797 const selected = yield* resolve(binaryPath).pipe(Effect.option);
798 if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
799 return yield* installationError(
800 "remove",
801 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
802 );
803 }
804 const resolved = yield* fs.realPath(binaryPath).pipe(Effect.option);
805 const candidate = Option.getOrElse(resolved, () => path.resolve(binaryPath));
806 if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
807 return yield* installationError(
808 "remove",
809 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
810 );
811 }
812 }
813 }
814 yield* fs.remove(managedDirectory, { recursive: true, force: true });
815 yield* SubscriptionRef.update(
816 state,
817 (current) =>
818 ({
819 ...current,
820 operationId: null,
821 phase: "idle",
822 downloadedBytes: 0,
823 installedVersion: null,
824 canRemove: false,
825 message: null,
826 }) satisfies ProviderInstallState,
827 );
828 }).pipe(Effect.uninterruptible),
829 );
830 },
831 Effect.mapError(
832 wrapFailure(
833 "remove",
834 "Could not remove the managed Antigravity runtime. Check for open processes and try again.",
835 ),
836 ),
837 );
838
839 yield* Effect.gen(function* () {
840 const canRemove = yield* fs.exists(managedDirectory);
841 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
842 if (!(yield* fs.exists(activePath))) return;
843 const active = yield* readRecord(activePath, ActiveRelease);
844 const installed = yield* completedRelease(active.releaseId);
845 yield* SubscriptionRef.update(state, (current) => ({
846 ...current,
847 installedVersion: installed.version,
848 }));
849 }).pipe(
850 Effect.catch(() =>
851 SubscriptionRef.update(
852 state,
853 (current) =>
854 ({
855 ...current,
856 phase: "failed",
857 message: "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
858 }) satisfies ProviderInstallState,
859 ),
860 ),
861 );
862
863 return AntigravityInstallation.of({
864 managedDirectory,
865 resolve,
866 acquire,
867 start,
868 cancel,
869 state: SubscriptionRef.get(state),
870 changes: SubscriptionRef.changes(state),
871 remove,
872 });
873});