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