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