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

AntigravityInstallation.ts

903 lines35.6 KB

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