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