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

AntigravityInstallation.ts

964 lines36.5 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 * as 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.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.decodeEffect(Schema.fromJsonString(schema))(contents);
319 });
320​
321 const executableFile = Effect.fn("AntigravityInstallation.executableFile")(function* (
322 filePath: string,
323 bytes?: number,
324 ) {
325 const info = yield* fs.stat(filePath).pipe(Effect.option);
326 return (
327 Option.isSome(info) &&
328 info.value.type === "File" &&
329 (bytes === undefined || Number(info.value.size) === bytes) &&
330 (platform === "win32" || (info.value.mode & 0o111) !== 0)
331 );
332 });
333​
334 const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* (
335 releaseId: string,
336 ) {
337 const directory = path.join(versionsDirectory, releaseId);
338 const record = yield* readRecord(path.join(directory, RELEASE_RECORD), InstalledRelease);
339 if (
340 record.releaseId !== releaseId ||
341 record.executable.name !== names.executable ||
342 record.harness.name !== names.harness ||
343 !Number.isSafeInteger(record.executable.bytes) ||
344 record.executable.bytes <= 0 ||
345 !Number.isSafeInteger(record.harness.bytes) ||
346 record.harness.bytes <= 0 ||
347 !record.version.trim() ||
348 !(yield* executableFile(path.join(directory, names.executable), record.executable.bytes)) ||
349 !(yield* executableFile(path.join(directory, names.harness), record.harness.bytes))
350 ) {
351 return yield* installationError(
352 "resolve",
353 "The managed Antigravity runtime is incomplete. Reinstall it.",
354 );
355 }
356 return {
357 executablePath: path.join(directory, names.executable),
358 harnessPath: path.join(directory, names.harness),
359 source: "managed",
360 version: record.version,
361 managedVersionDirectory: directory,
362 } satisfies AntigravityExecutable;
363 });
364​
365 const fromExternal = Effect.fn("AntigravityInstallation.fromExternal")(function* (
366 candidate: string,
367 source: "override" | "path",
368 ) {
369 if (!(yield* executableFile(candidate))) return null;
370 const executablePath = yield* fs.realPath(candidate);
371 const directory = path.dirname(executablePath);
372 const harnessPath = path.join(directory, names.harness);
373 if (!(yield* executableFile(harnessPath))) return null;
374 const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option);
375 if (
376 Option.isSome(realVersions) &&
377 path.dirname(directory) === realVersions.value &&
378 /^[a-f0-9]{64}$/u.test(path.basename(directory))
379 ) {
380 const installed = yield* completedRelease(path.basename(directory));
381 return { ...installed, executablePath, harnessPath, source } satisfies AntigravityExecutable;
382 }
383 return {
384 executablePath,
385 harnessPath,
386 source,
387 version: null,
388 managedVersionDirectory: null,
389 } satisfies AntigravityExecutable;
390 });
391​
392 const pathCandidates = (binary: string, processEnvironment = environment) => {
393 const pathValue =
394 platform === "win32"
395 ? Object.entries(processEnvironment).findLast(([key]) => key.toUpperCase() === "PATH")?.[1]
396 : processEnvironment.PATH;
397 return (pathValue ?? "")
398 .split(platform === "win32" ? ";" : ":")
399 .map((directory) => directory.trim().replace(/^"|"$/gu, ""))
400 .filter((directory) => directory.length > 0)
401 .map((directory) => path.resolve(directory, binary));
402 };
403​
404 const resolve: AntigravityInstallationService["resolve"] = Effect.fn(
405 "AntigravityInstallation.resolve",
406 )(
407 function* (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) {
408 const override = binaryPath?.trim();
409 if (override) {
410 const candidates =
411 path.isAbsolute(override) || override.includes("/") || override.includes("\\")
412 ? [path.resolve(override)]
413 : pathCandidates(override, processEnvironment);
414 for (const candidate of candidates) {
415 const selected = yield* fromExternal(candidate, "override");
416 if (selected) return selected;
417 }
418 return yield* installationError(
419 "resolve",
420 "The custom Antigravity executable or its localharness_external sibling is missing or not executable.",
421 );
422 }
423 if (yield* fs.exists(activePath)) {
424 const active = yield* readRecord(activePath, ActiveRelease);
425 return yield* completedRelease(active.releaseId);
426 }
427 for (const candidate of pathCandidates(names.executable, processEnvironment)) {
428 const selected = yield* fromExternal(candidate, "path");
429 if (selected) return selected;
430 }
431 return yield* installationError(
432 "resolve",
433 releaseAsset
434 ? "Antigravity is not installed. Install it in this environment or set a custom executable path."
435 : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`,
436 );
437 },
438 Effect.mapError(
439 wrapFailure(
440 "resolve",
441 "Could not read the Antigravity installation. Reinstall it or set a custom executable path.",
442 ),
443 ),
444 );
445​
446 const acquire = (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) =>
447 Effect.acquireRelease(
448 gate.withPermit(
449 Effect.gen(function* () {
450 const executable = yield* resolve(binaryPath, processEnvironment);
451 const directory = executable.managedVersionDirectory;
452 if (directory) leases.set(directory, (leases.get(directory) ?? 0) + 1);
453 return executable;
454 }),
455 ),
456 (executable) =>
457 gate.withPermit(
458 Effect.sync(() => {
459 const directory = executable.managedVersionDirectory;
460 if (!directory) return;
461 const remaining = (leases.get(directory) ?? 1) - 1;
462 if (remaining > 0) leases.set(directory, remaining);
463 else leases.delete(directory);
464 }),
465 ),
466 );
467​
468 const validate =
469 options.validate ??
470 Effect.fn("AntigravityInstallation.validate")(
471 function* (executable: AntigravityExecutable, expectedVersion: string) {
472 const profileDirectory = yield* fs.makeTempDirectoryScoped({
473 prefix: "t3-antigravity-validate-",
474 });
475 const profile = yield* prepareAntigravityProfile({
476 profileDirectory,
477 platform,
478 baseEnv: environment,
479 // The profile is scoped, so it cleans up the unpack; a shallow
480 // root keeps it under Windows' path limit.
481 tempDirectory: profileDirectory,
482 });
483 const runtime = yield* makeAntigravityAcpRuntime({
484 spawn: buildAntigravityAcpSpawnInput({
485 installation: executable,
486 profile,
487 cwd: profileDirectory,
488 baseEnv: environment,
489 }),
490 cwd: profileDirectory,
491 childProcessSpawner: spawner,
492 clientInfo: { name: "t3-code", version: "0.0.0" },
493 });
494 const initialized = yield* runtime.initialize();
495 if (
496 initialized.agentInfo?.name !== "antigravity-acp" ||
497 initialized.agentInfo.version !== expectedVersion ||
498 // Antigravity 1.1.1 can report 2 with the legacy ACP response shape.
499 // The ACP client chooses the session wire format from that shape.
500 (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) ||
501 initialized.agentCapabilities?.loadSession !== true ||
502 !initialized.agentCapabilities.sessionCapabilities?.resume ||
503 !initialized.agentCapabilities.auth?.logout ||
504 !initialized.authMethods?.some((method) => method.id === "oauth-personal")
505 ) {
506 return yield* installationError(
507 "verify",
508 "The downloaded runtime did not identify as the expected Google Antigravity release.",
509 );
510 }
511 },
512 Effect.provideService(FileSystem.FileSystem, fs),
513 Effect.provideService(Path.Path, path),
514 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
515 Effect.provideService(Crypto.Crypto, crypto),
516 Effect.mapError(
517 wrapFailure(
518 "verify",
519 "The downloaded Antigravity runtime could not start in this environment.",
520 ),
521 ),
522 );
523​
524 const install = Effect.fn("AntigravityInstallation.install")(
525 function* (asset: AntigravityReleaseAsset) {
526 yield* resolveNodeExecutable("Antigravity", environment).pipe(
527 Effect.provideService(FileSystem.FileSystem, fs),
528 Effect.provideService(Path.Path, path),
529 Effect.provideService(HostProcessPlatform, platform),
530 Effect.mapError((cause) =>
531 installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause),
532 ),
533 );
534 const report = (phase: ProviderInstallState["phase"], message: string | null) =>
535 SubscriptionRef.update(state, (current) => ({ ...current, phase, message }));
536 yield* fs.makeDirectory(versionsDirectory, { recursive: true });
537 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
538 const destination = path.join(versionsDirectory, asset.sha256);
539 const activate = Effect.fn("AntigravityInstallation.activate")(
540 function* () {
541 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
542 directory: managedDirectory,
543 prefix: "active.json.",
544 });
545 const pointerPath = path.join(pointerDirectory, "contents.tmp");
546 yield* fs.writeFileString(
547 pointerPath,
548 yield* encodeActiveRelease({ releaseId: asset.sha256 }),
549 { flag: "wx", mode: 0o600 },
550 );
551 yield* fs.rename(pointerPath, activePath);
552 // The pointer commits the install. Later temp cleanup cannot undo it.
553 yield* SubscriptionRef.update(
554 state,
555 (current) =>
556 ({
557 ...current,
558 phase: "succeeded",
559 installedVersion: asset.version,
560 message: null,
561 }) satisfies ProviderInstallState,
562 );
563 },
564 Effect.scoped,
565 Effect.mapError(
566 wrapFailure(
567 "activate",
568 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
569 ),
570 ),
571 Effect.uninterruptible,
572 );
573​
574 if (yield* fs.exists(destination)) {
575 const existing = yield* completedRelease(asset.sha256);
576 if (existing.version !== asset.version) {
577 return yield* installationError(
578 "verify",
579 "The existing managed release has the wrong version. Remove it before reinstalling.",
580 );
581 }
582 yield* report("verifying", "Checking the installed runtime.");
583 yield* validate(existing, asset.version).pipe(
584 Effect.scoped,
585 Effect.timeout(VALIDATION_TIMEOUT),
586 );
587 yield* activate();
588 return;
589 }
590​
591 const available = yield* Effect.tryPromise(() =>
592 NodeFSP.statfs(versionsDirectory, { bigint: true }),
593 ).pipe(Effect.option);
594 const required =
595 asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN;
596 if (
597 Option.isSome(available) &&
598 available.value.bavail * available.value.bsize < BigInt(required)
599 ) {
600 return yield* installationError(
601 "download",
602 `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`,
603 );
604 }
605 const staging = yield* fs.makeTempDirectoryScoped({
606 directory: versionsDirectory,
607 prefix: ".install-",
608 });
609 const archivePath = path.join(staging, "download.zip");
610 const pairDirectory = path.join(staging, "runtime");
611 yield* fs.makeDirectory(pairDirectory);
612 const hash = NodeCrypto.createHash("sha256");
613 let downloadedBytes = 0;
614 let lastProgressAt = yield* Clock.currentTimeMillis;
615 yield* Effect.gen(function* () {
616 const response = yield* http
617 .execute(HttpClientRequest.get(asset.url))
618 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
619 // dl.google.com gzips the zip when the client accepts it, so
620 // `content-length` is the encoded size. The decoded stream is still
621 // checked against the pinned byte count and hash below.
622 const contentLength = response.headers["content-length"];
623 const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase();
624 const identityBody = contentEncoding === undefined || contentEncoding === "identity";
625 if (
626 identityBody &&
627 contentLength !== undefined &&
628 Number(contentLength) !== asset.archiveBytes
629 ) {
630 return yield* installationError(
631 "download",
632 "The Antigravity download size did not match the pinned release.",
633 );
634 }
635 yield* response.stream.pipe(
636 Stream.tap((chunk) =>
637 Effect.gen(function* () {
638 downloadedBytes += chunk.byteLength;
639 if (downloadedBytes > asset.archiveBytes) {
640 return yield* installationError(
641 "download",
642 "The Antigravity download exceeded the pinned release size.",
643 );
644 }
645 hash.update(chunk);
646 const now = yield* Clock.currentTimeMillis;
647 if (now - lastProgressAt >= 250 || downloadedBytes === asset.archiveBytes) {
648 lastProgressAt = now;
649 yield* SubscriptionRef.update(state, (current) => ({
650 ...current,
651 downloadedBytes,
652 }));
653 }
654 }),
655 ),
656 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
657 );
658 }).pipe(Effect.timeout(DOWNLOAD_TIMEOUT));
659 if (downloadedBytes !== asset.archiveBytes || hash.digest("hex") !== asset.sha256) {
660 return yield* installationError(
661 "download",
662 "The Antigravity download failed its size or SHA-256 check. Nothing was installed.",
663 );
664 }
665​
666 yield* report("extracting", "Extracting the verified runtime.");
667 yield* Effect.gen(function* () {
668 const archive = yield* openArchive(archivePath);
669 if (archive.entryCount !== 2) {
670 return yield* installationError(
671 "extract",
672 "The archive must contain exactly the Antigravity executable and its harness.",
673 );
674 }
675 const seen = new Set<string>();
676 for (;;) {
677 const entry = yield* archive.next;
678 if (!entry) break;
679 const expected = [asset.executable, asset.harness].find(
680 (file) => file.name === entry.fileName,
681 );
682 const unixType = (entry.externalFileAttributes >>> 16) & 0o170000;
683 if (
684 !expected ||
685 seen.has(entry.fileName) ||
686 entry.fileName.includes("/") ||
687 entry.fileName.includes("\\") ||
688 (unixType !== 0 && unixType !== 0o100000) ||
689 (entry.externalFileAttributes & 0x10) !== 0 ||
690 (entry.generalPurposeBitFlag & 1) !== 0 ||
691 ![0, 8].includes(entry.compressionMethod) ||
692 entry.uncompressedSize !== expected.bytes
693 ) {
694 return yield* installationError(
695 "extract",
696 "The archive contains an unexpected, unsafe, or incorrectly sized member.",
697 );
698 }
699 seen.add(entry.fileName);
700 yield* Effect.gen(function* () {
701 const readable = yield* archive.streamEntry(entry);
702 let extractedBytes = 0;
703 yield* EffectNodeStream.fromReadable<Uint8Array, AntigravityInstallationError>({
704 evaluate: () => readable,
705 onError: wrapFailure("extract", "Could not extract the Antigravity runtime."),
706 }).pipe(
707 Stream.tap((chunk) =>
708 Effect.gen(function* () {
709 extractedBytes += chunk.byteLength;
710 if (extractedBytes > expected.bytes) {
711 return yield* installationError(
712 "extract",
713 "An archive member exceeded its pinned size.",
714 );
715 }
716 }),
717 ),
718 Stream.run(
719 fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }),
720 ),
721 );
722 if (extractedBytes !== expected.bytes) {
723 return yield* installationError("extract", "An archive member was truncated.");
724 }
725 }).pipe(Effect.scoped);
726 }
727 if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) {
728 return yield* installationError(
729 "extract",
730 "The archive is missing the Antigravity executable or its harness.",
731 );
732 }
733 }).pipe(Effect.scoped);
734 yield* fs.remove(archivePath);
735 if (platform !== "win32") {
736 yield* fs.chmod(path.join(pairDirectory, asset.executable.name), 0o755);
737 yield* fs.chmod(path.join(pairDirectory, asset.harness.name), 0o755);
738 }
739 yield* report("verifying", "Checking the downloaded runtime.");
740 yield* validate(
741 {
742 executablePath: path.join(pairDirectory, asset.executable.name),
743 harnessPath: path.join(pairDirectory, asset.harness.name),
744 source: "managed",
745 version: asset.version,
746 managedVersionDirectory: pairDirectory,
747 },
748 asset.version,
749 ).pipe(Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT));
750 const record: InstalledRelease = {
751 releaseId: asset.sha256,
752 version: asset.version,
753 executable: asset.executable,
754 harness: asset.harness,
755 };
756 yield* fs.writeFileString(
757 path.join(pairDirectory, RELEASE_RECORD),
758 yield* encodeInstalledRelease(record),
759 { flag: "wx", mode: 0o600 },
760 );
761 yield* fs.rename(pairDirectory, destination).pipe(
762 Effect.catch((cause) =>
763 completedRelease(asset.sha256).pipe(
764 Effect.flatMap((existing) =>
765 existing.version === asset.version
766 ? validate(existing, asset.version).pipe(
767 Effect.scoped,
768 Effect.timeout(VALIDATION_TIMEOUT),
769 )
770 : Effect.fail(
771 installationError(
772 "activate",
773 "Another installation published a different Antigravity release.",
774 ),
775 ),
776 ),
777 Effect.mapError(() =>
778 installationError(
779 "activate",
780 "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
781 cause,
782 ),
783 ),
784 ),
785 ),
786 );
787 yield* activate();
788 },
789 Effect.scoped,
790 Effect.mapError(
791 wrapFailure(
792 "install",
793 "Could not install Antigravity. Check free disk space and directory access, then try again.",
794 ),
795 ),
796 );
797​
798 const start = gate
799 .withPermit(
800 Effect.gen(function* () {
801 const current = yield* SubscriptionRef.get(state);
802 if (isRunning(current)) return current;
803 if (!releaseAsset) {
804 return yield* installationError(
805 "start",
806 `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
807 );
808 }
809 const operationId = yield* crypto.randomUUIDv4;
810 const next: ProviderInstallState = {
811 driver: DRIVER,
812 operationId,
813 phase: "downloading",
814 downloadedBytes: 0,
815 totalBytes: releaseAsset.archiveBytes,
816 version: releaseAsset.version,
817 installedVersion: current.installedVersion,
818 canRemove: current.canRemove,
819 message: "Downloading Google's official Antigravity runtime.",
820 };
821 yield* SubscriptionRef.set(state, next);
822 const work = install(releaseAsset).pipe(
823 Effect.onExit((exit) =>
824 Exit.isFailure(exit)
825 ? SubscriptionRef.update(state, (value) => {
826 if (value.operationId !== operationId || value.phase === "succeeded")
827 return value;
828 const error = Cause.findErrorOption(exit.cause);
829 const cancelled = Cause.hasInterruptsOnly(exit.cause);
830 return {
831 ...value,
832 phase: cancelled ? "cancelled" : "failed",
833 message: cancelled
834 ? "Installation cancelled. The previous runtime is unchanged."
835 : Option.isSome(error)
836 ? error.value.detail
837 : "Could not finish the Antigravity installation. Check disk space and directory access.",
838 } satisfies ProviderInstallState;
839 })
840 : Effect.void,
841 ),
842 Effect.ignoreCause,
843 Effect.ensuring(
844 Effect.sync(() => {
845 if (running?.operationId === operationId) running = undefined;
846 }),
847 ),
848 );
849 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
850 running = { operationId, fiber };
851 return next;
852 }).pipe(Effect.uninterruptible),
853 )
854 .pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation.")));
855​
856 const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) {
857 return yield* gate.withPermit(
858 Effect.gen(function* () {
859 const current = yield* SubscriptionRef.get(state);
860 if (current.operationId !== operationId) {
861 return yield* installationError(
862 "cancel",
863 "This installation is no longer current. Refresh its status before cancelling.",
864 );
865 }
866 if (running?.operationId === operationId && isRunning(current)) {
867 yield* Fiber.interrupt(running.fiber);
868 }
869 return yield* SubscriptionRef.get(state);
870 }),
871 );
872 });
873​
874 const remove = Effect.fn("AntigravityInstallation.remove")(
875 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
876 yield* gate.withPermit(
877 Effect.gen(function* () {
878 if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) {
879 return yield* installationError(
880 "remove",
881 "Stop Antigravity sessions and sign-in flows before removing its managed runtime.",
882 );
883 }
884 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
885 if (Option.isSome(realManaged)) {
886 for (const binaryPath of protectedBinaryPaths) {
887 if (!binaryPath.trim()) continue;
888 const selected = yield* resolve(binaryPath).pipe(Effect.option);
889 if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
890 return yield* installationError(
891 "remove",
892 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
893 );
894 }
895 const resolved = yield* fs.realPath(binaryPath).pipe(Effect.option);
896 const candidate = Option.getOrElse(resolved, () => path.resolve(binaryPath));
897 if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
898 return yield* installationError(
899 "remove",
900 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
901 );
902 }
903 }
904 }
905 yield* fs.remove(managedDirectory, { recursive: true, force: true });
906 yield* SubscriptionRef.update(
907 state,
908 (current) =>
909 ({
910 ...current,
911 operationId: null,
912 phase: "idle",
913 downloadedBytes: 0,
914 installedVersion: null,
915 canRemove: false,
916 message: null,
917 }) satisfies ProviderInstallState,
918 );
919 }).pipe(Effect.uninterruptible),
920 );
921 },
922 Effect.mapError(
923 wrapFailure(
924 "remove",
925 "Could not remove the managed Antigravity runtime. Check for open processes and try again.",
926 ),
927 ),
928 );
929​
930 yield* Effect.gen(function* () {
931 const canRemove = yield* fs.exists(managedDirectory);
932 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
933 if (!(yield* fs.exists(activePath))) return;
934 const active = yield* readRecord(activePath, ActiveRelease);
935 const installed = yield* completedRelease(active.releaseId);
936 yield* SubscriptionRef.update(state, (current) => ({
937 ...current,
938 installedVersion: installed.version,
939 }));
940 }).pipe(
941 Effect.catch(() =>
942 SubscriptionRef.update(
943 state,
944 (current) =>
945 ({
946 ...current,
947 phase: "failed",
948 message: "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
949 }) satisfies ProviderInstallState,
950 ),
951 ),
952 );
953​
954 return AntigravityInstallation.of({
955 managedDirectory,
956 resolve,
957 acquire,
958 start,
959 cancel,
960 state: SubscriptionRef.get(state),
961 changes: SubscriptionRef.changes(state),
962 remove,
963 });
964});