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

AntigravityInstallation.ts

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