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

AntigravityInstallation.ts

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