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.decodeUnknownEffect(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 });
480 const runtime = yield* makeAntigravityAcpRuntime({
481 spawn: buildAntigravityAcpSpawnInput({
482 installation: executable,
483 profile,
484 cwd: profileDirectory,
485 baseEnv: environment,
486 }),
487 cwd: profileDirectory,
488 childProcessSpawner: spawner,
489 clientInfo: { name: "t3-code", version: "0.0.0" },
490 });
491 const initialized = yield* runtime.initialize();
492 if (
493 initialized.agentInfo?.name !== "antigravity-acp" ||
494 initialized.agentInfo.version !== expectedVersion ||
495 // Antigravity 1.1.1 can report 2 with the legacy ACP response shape.
496 // The ACP client chooses the session wire format from that shape.
497 (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) ||
498 initialized.agentCapabilities?.loadSession !== true ||
499 !initialized.agentCapabilities.sessionCapabilities?.resume ||
500 !initialized.agentCapabilities.auth?.logout ||
501 !initialized.authMethods?.some((method) => method.id === "oauth-personal")
502 ) {
503 return yield* installationError(
504 "verify",
505 "The downloaded runtime did not identify as the expected Google Antigravity release.",
506 );
507 }
508 },
509 Effect.provideService(FileSystem.FileSystem, fs),
510 Effect.provideService(Path.Path, path),
511 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
512 Effect.provideService(Crypto.Crypto, crypto),
513 Effect.mapError(
514 wrapFailure(
515 "verify",
516 "The downloaded Antigravity runtime could not start in this environment.",
517 ),
518 ),
519 );
520
521 const install = Effect.fn("AntigravityInstallation.install")(
522 function* (asset: AntigravityReleaseAsset) {
523 yield* resolveNodeExecutable("Antigravity", environment).pipe(
524 Effect.provideService(FileSystem.FileSystem, fs),
525 Effect.provideService(Path.Path, path),
526 Effect.provideService(HostProcessPlatform, platform),
527 Effect.mapError((cause) =>
528 installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause),
529 ),
530 );
531 const report = (phase: ProviderInstallState["phase"], message: string | null) =>
532 SubscriptionRef.update(state, (current) => ({ ...current, phase, message }));
533 yield* fs.makeDirectory(versionsDirectory, { recursive: true });
534 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
535 const destination = path.join(versionsDirectory, asset.sha256);
536 const activate = Effect.fn("AntigravityInstallation.activate")(
537 function* () {
538 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
539 directory: managedDirectory,
540 prefix: "active.json.",
541 });
542 const pointerPath = path.join(pointerDirectory, "contents.tmp");
543 yield* fs.writeFileString(
544 pointerPath,
545 yield* encodeActiveRelease({ releaseId: asset.sha256 }),
546 { flag: "wx", mode: 0o600 },
547 );
548 yield* fs.rename(pointerPath, activePath);
549 // The pointer commits the install. Later temp cleanup cannot undo it.
550 yield* SubscriptionRef.update(
551 state,
552 (current) =>
553 ({
554 ...current,
555 phase: "succeeded",
556 installedVersion: asset.version,
557 message: null,
558 }) satisfies ProviderInstallState,
559 );
560 },
561 Effect.scoped,
562 Effect.mapError(
563 wrapFailure(
564 "activate",
565 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
566 ),
567 ),
568 Effect.uninterruptible,
569 );
570
571 if (yield* fs.exists(destination)) {
572 const existing = yield* completedRelease(asset.sha256);
573 if (existing.version !== asset.version) {
574 return yield* installationError(
575 "verify",
576 "The existing managed release has the wrong version. Remove it before reinstalling.",
577 );
578 }
579 yield* report("verifying", "Checking the installed runtime.");
580 yield* validate(existing, asset.version).pipe(
581 Effect.scoped,
582 Effect.timeout(VALIDATION_TIMEOUT),
583 );
584 yield* activate();
585 return;
586 }
587
588 const available = yield* Effect.tryPromise(() =>
589 NodeFSP.statfs(versionsDirectory, { bigint: true }),
590 ).pipe(Effect.option);
591 const required =
592 asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN;
593 if (
594 Option.isSome(available) &&
595 available.value.bavail * available.value.bsize < BigInt(required)
596 ) {
597 return yield* installationError(
598 "download",
599 `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`,
600 );
601 }
602 const staging = yield* fs.makeTempDirectoryScoped({
603 directory: versionsDirectory,
604 prefix: ".install-",
605 });
606 const archivePath = path.join(staging, "download.zip");
607 const pairDirectory = path.join(staging, "runtime");
608 yield* fs.makeDirectory(pairDirectory);
609 const hash = NodeCrypto.createHash("sha256");
610 let downloadedBytes = 0;
611 let lastProgressAt = yield* Clock.currentTimeMillis;
612 yield* Effect.gen(function* () {
613 const response = yield* http
614 .execute(HttpClientRequest.get(asset.url))
615 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
616 // dl.google.com gzips the zip when the client accepts it, so
617 // `content-length` is the encoded size. The decoded stream is still
618 // checked against the pinned byte count and hash below.
619 const contentLength = response.headers["content-length"];
620 const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase();
621 const identityBody = contentEncoding === undefined || contentEncoding === "identity";
622 if (
623 identityBody &&
624 contentLength !== undefined &&
625 Number(contentLength) !== asset.archiveBytes
626 ) {
627 return yield* installationError(
628 "download",
629 "The Antigravity download size did not match the pinned release.",
630 );
631 }
632 yield* response.stream.pipe(
633 Stream.tap((chunk) =>
634 Effect.gen(function* () {
635 downloadedBytes += chunk.byteLength;
636 if (downloadedBytes > asset.archiveBytes) {
637 return yield* installationError(
638 "download",
639 "The Antigravity download exceeded the pinned release size.",
640 );
641 }
642 hash.update(chunk);
643 const now = yield* Clock.currentTimeMillis;
644 if (now - lastProgressAt >= 250 || downloadedBytes === asset.archiveBytes) {
645 lastProgressAt = now;
646 yield* SubscriptionRef.update(state, (current) => ({
647 ...current,
648 downloadedBytes,
649 }));
650 }
651 }),
652 ),
653 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
654 );
655 }).pipe(Effect.timeout(DOWNLOAD_TIMEOUT));
656 if (downloadedBytes !== asset.archiveBytes || hash.digest("hex") !== asset.sha256) {
657 return yield* installationError(
658 "download",
659 "The Antigravity download failed its size or SHA-256 check. Nothing was installed.",
660 );
661 }
662
663 yield* report("extracting", "Extracting the verified runtime.");
664 yield* Effect.gen(function* () {
665 const archive = yield* openArchive(archivePath);
666 if (archive.entryCount !== 2) {
667 return yield* installationError(
668 "extract",
669 "The archive must contain exactly the Antigravity executable and its harness.",
670 );
671 }
672 const seen = new Set<string>();
673 for (;;) {
674 const entry = yield* archive.next;
675 if (!entry) break;
676 const expected = [asset.executable, asset.harness].find(
677 (file) => file.name === entry.fileName,
678 );
679 const unixType = (entry.externalFileAttributes >>> 16) & 0o170000;
680 if (
681 !expected ||
682 seen.has(entry.fileName) ||
683 entry.fileName.includes("/") ||
684 entry.fileName.includes("\\") ||
685 (unixType !== 0 && unixType !== 0o100000) ||
686 (entry.externalFileAttributes & 0x10) !== 0 ||
687 (entry.generalPurposeBitFlag & 1) !== 0 ||
688 ![0, 8].includes(entry.compressionMethod) ||
689 entry.uncompressedSize !== expected.bytes
690 ) {
691 return yield* installationError(
692 "extract",
693 "The archive contains an unexpected, unsafe, or incorrectly sized member.",
694 );
695 }
696 seen.add(entry.fileName);
697 yield* Effect.gen(function* () {
698 const readable = yield* archive.streamEntry(entry);
699 let extractedBytes = 0;
700 yield* EffectNodeStream.fromReadable<Uint8Array, AntigravityInstallationError>({
701 evaluate: () => readable,
702 onError: wrapFailure("extract", "Could not extract the Antigravity runtime."),
703 }).pipe(
704 Stream.tap((chunk) =>
705 Effect.gen(function* () {
706 extractedBytes += chunk.byteLength;
707 if (extractedBytes > expected.bytes) {
708 return yield* installationError(
709 "extract",
710 "An archive member exceeded its pinned size.",
711 );
712 }
713 }),
714 ),
715 Stream.run(
716 fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }),
717 ),
718 );
719 if (extractedBytes !== expected.bytes) {
720 return yield* installationError("extract", "An archive member was truncated.");
721 }
722 }).pipe(Effect.scoped);
723 }
724 if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) {
725 return yield* installationError(
726 "extract",
727 "The archive is missing the Antigravity executable or its harness.",
728 );
729 }
730 }).pipe(Effect.scoped);
731 yield* fs.remove(archivePath);
732 if (platform !== "win32") {
733 yield* fs.chmod(path.join(pairDirectory, asset.executable.name), 0o755);
734 yield* fs.chmod(path.join(pairDirectory, asset.harness.name), 0o755);
735 }
736 yield* report("verifying", "Checking the downloaded runtime.");
737 yield* validate(
738 {
739 executablePath: path.join(pairDirectory, asset.executable.name),
740 harnessPath: path.join(pairDirectory, asset.harness.name),
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: asset.executable,
751 harness: asset.harness,
752 };
753 yield* fs.writeFileString(
754 path.join(pairDirectory, RELEASE_RECORD),
755 yield* encodeInstalledRelease(record),
756 { flag: "wx", mode: 0o600 },
757 );
758 yield* fs.rename(pairDirectory, destination).pipe(
759 Effect.catch((cause) =>
760 completedRelease(asset.sha256).pipe(
761 Effect.flatMap((existing) =>
762 existing.version === asset.version
763 ? validate(existing, asset.version).pipe(
764 Effect.scoped,
765 Effect.timeout(VALIDATION_TIMEOUT),
766 )
767 : Effect.fail(
768 installationError(
769 "activate",
770 "Another installation published a different Antigravity release.",
771 ),
772 ),
773 ),
774 Effect.mapError(() =>
775 installationError(
776 "activate",
777 "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
778 cause,
779 ),
780 ),
781 ),
782 ),
783 );
784 yield* activate();
785 },
786 Effect.scoped,
787 Effect.mapError(
788 wrapFailure(
789 "install",
790 "Could not install Antigravity. Check free disk space and directory access, then try again.",
791 ),
792 ),
793 );
794
795 const start = gate
796 .withPermit(
797 Effect.gen(function* () {
798 const current = yield* SubscriptionRef.get(state);
799 if (isRunning(current)) return current;
800 if (!releaseAsset) {
801 return yield* installationError(
802 "start",
803 `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
804 );
805 }
806 const operationId = yield* crypto.randomUUIDv4;
807 const next: ProviderInstallState = {
808 driver: DRIVER,
809 operationId,
810 phase: "downloading",
811 downloadedBytes: 0,
812 totalBytes: releaseAsset.archiveBytes,
813 version: releaseAsset.version,
814 installedVersion: current.installedVersion,
815 canRemove: current.canRemove,
816 message: "Downloading Google's official Antigravity runtime.",
817 };
818 yield* SubscriptionRef.set(state, next);
819 const work = install(releaseAsset).pipe(
820 Effect.onExit((exit) =>
821 Exit.isFailure(exit)
822 ? SubscriptionRef.update(state, (value) => {
823 if (value.operationId !== operationId || value.phase === "succeeded")
824 return value;
825 const error = Cause.findErrorOption(exit.cause);
826 const cancelled = Cause.hasInterruptsOnly(exit.cause);
827 return {
828 ...value,
829 phase: cancelled ? "cancelled" : "failed",
830 message: cancelled
831 ? "Installation cancelled. The previous runtime is unchanged."
832 : Option.isSome(error)
833 ? error.value.detail
834 : "Could not finish the Antigravity installation. Check disk space and directory access.",
835 } satisfies ProviderInstallState;
836 })
837 : Effect.void,
838 ),
839 Effect.ignoreCause,
840 Effect.ensuring(
841 Effect.sync(() => {
842 if (running?.operationId === operationId) running = undefined;
843 }),
844 ),
845 );
846 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
847 running = { operationId, fiber };
848 return next;
849 }).pipe(Effect.uninterruptible),
850 )
851 .pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation.")));
852
853 const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) {
854 return yield* gate.withPermit(
855 Effect.gen(function* () {
856 const current = yield* SubscriptionRef.get(state);
857 if (current.operationId !== operationId) {
858 return yield* installationError(
859 "cancel",
860 "This installation is no longer current. Refresh its status before cancelling.",
861 );
862 }
863 if (running?.operationId === operationId && isRunning(current)) {
864 yield* Fiber.interrupt(running.fiber);
865 }
866 return yield* SubscriptionRef.get(state);
867 }),
868 );
869 });
870
871 const remove = Effect.fn("AntigravityInstallation.remove")(
872 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
873 yield* gate.withPermit(
874 Effect.gen(function* () {
875 if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) {
876 return yield* installationError(
877 "remove",
878 "Stop Antigravity sessions and sign-in flows before removing its managed runtime.",
879 );
880 }
881 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
882 if (Option.isSome(realManaged)) {
883 for (const binaryPath of protectedBinaryPaths) {
884 if (!binaryPath.trim()) continue;
885 const selected = yield* resolve(binaryPath).pipe(Effect.option);
886 if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
887 return yield* installationError(
888 "remove",
889 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
890 );
891 }
892 const resolved = yield* fs.realPath(binaryPath).pipe(Effect.option);
893 const candidate = Option.getOrElse(resolved, () => path.resolve(binaryPath));
894 if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
895 return yield* installationError(
896 "remove",
897 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
898 );
899 }
900 }
901 }
902 yield* fs.remove(managedDirectory, { recursive: true, force: true });
903 yield* SubscriptionRef.update(
904 state,
905 (current) =>
906 ({
907 ...current,
908 operationId: null,
909 phase: "idle",
910 downloadedBytes: 0,
911 installedVersion: null,
912 canRemove: false,
913 message: null,
914 }) satisfies ProviderInstallState,
915 );
916 }).pipe(Effect.uninterruptible),
917 );
918 },
919 Effect.mapError(
920 wrapFailure(
921 "remove",
922 "Could not remove the managed Antigravity runtime. Check for open processes and try again.",
923 ),
924 ),
925 );
926
927 yield* Effect.gen(function* () {
928 const canRemove = yield* fs.exists(managedDirectory);
929 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
930 if (!(yield* fs.exists(activePath))) return;
931 const active = yield* readRecord(activePath, ActiveRelease);
932 const installed = yield* completedRelease(active.releaseId);
933 yield* SubscriptionRef.update(state, (current) => ({
934 ...current,
935 installedVersion: installed.version,
936 }));
937 }).pipe(
938 Effect.catch(() =>
939 SubscriptionRef.update(
940 state,
941 (current) =>
942 ({
943 ...current,
944 phase: "failed",
945 message: "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
946 }) satisfies ProviderInstallState,
947 ),
948 ),
949 );
950
951 return AntigravityInstallation.of({
952 managedDirectory,
953 resolve,
954 acquire,
955 start,
956 cancel,
957 state: SubscriptionRef.get(state),
958 changes: SubscriptionRef.changes(state),
959 remove,
960 });
961});