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

AntigravityInstallation.ts

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