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