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

AntigravityInstallation.ts

950 lines35.6 KB

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