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

AntigravityInstallation.ts

876 lines34.1 KB

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