Open History to see the last commit
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 }
71}
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;
81}
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>;
103}
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 );
116}
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>;
125}
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" };
141}
142
143function isRunning(state: ProviderInstallState) {
144 return (
145 state.phase === "downloading" || state.phase === "extracting" || state.phase === "verifying"
146 );
147}
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 // The profile is scoped, so it cleans up the unpack; a shallow
377 // root keeps it under Windows' path limit.
378 tempDirectory: profileDirectory,
379 });
380 const runtime = yield* makeAntigravityAcpRuntime({
381 spawn: buildAntigravityAcpSpawnInput({
382 installation: executable,
383 profile,
384 cwd: profileDirectory,
385 baseEnv: environment,
386 }),
387 cwd: profileDirectory,
388 childProcessSpawner:
389 platform === "win32"
390 ? ChildProcessSpawner.make(
391 Effect.fnUntraced(function* (command) {
392 const child = yield* spawner.spawn(command);
393 // Stop PyInstaller's tree before ACP closes its pipes. Once
394 // the launcher exits, taskkill cannot reach its children,
395 // which keep the executable and unpacked DLLs locked.
396 yield* Scope.addFinalizer(
397 validationScope,
398 child.kill({ forceKillAfter: "1 second" }).pipe(Effect.orDie),
399 );
400 return child;
401 }),
402 )
403 : spawner,
404 clientInfo: { name: "t3-code", version: "0.0.0" },
405 });
406 const initialized = yield* runtime.initialize();
407 if (
408 initialized.agentInfo?.name !== "antigravity-acp" ||
409 initialized.agentInfo.version !== expectedVersion ||
410 // Antigravity 1.1.1 can report 2 with the legacy ACP response shape.
411 // The ACP client chooses the session wire format from that shape.
412 (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) ||
413 initialized.agentCapabilities?.loadSession !== true ||
414 !initialized.agentCapabilities.sessionCapabilities?.resume ||
415 !initialized.agentCapabilities.auth?.logout ||
416 !initialized.authMethods?.some((method) => method.id === "oauth-personal")
417 ) {
418 return yield* installationError(
419 "verify",
420 "The downloaded runtime did not identify as the expected Google Antigravity release.",
421 );
422 }
423 },
424 Effect.provideService(FileSystem.FileSystem, fs),
425 Effect.provideService(Path.Path, path),
426 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
427 Effect.provideService(Crypto.Crypto, crypto),
428 Effect.mapError((cause) => {
429 if (isInstallationError(cause)) return cause;
430 const detail =
431 isAcpProcessExitedError(cause) &&
432 /\b(?:AF_INET6|enforce_kernel_ipv6_support)\b/.test(cause.stderr ?? "")
433 ? "Antigravity requires IPv6 socket support. Enable IPv6 in this environment. On WSL, remove ipv6.disable=1 from .wslconfig and run wsl --shutdown."
434 : "The downloaded Antigravity runtime could not start in this environment.";
435 return installationError("verify", detail, cause);
436 }),
437 );
438
439 const install = Effect.fn("AntigravityInstallation.install")(
440 function* (asset: AntigravityReleaseAsset) {
441 yield* resolveNodeExecutable("Antigravity", environment).pipe(
442 Effect.provideService(FileSystem.FileSystem, fs),
443 Effect.provideService(Path.Path, path),
444 Effect.provideService(HostProcess.Platform, platform),
445 Effect.mapError((cause) =>
446 installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause),
447 ),
448 );
449 const report = (phase: ProviderInstallState["phase"], message: string | null) =>
450 SubscriptionRef.update(state, (current) => ({ ...current, phase, message }));
451 yield* fs.makeDirectory(versionsDirectory, { recursive: true });
452 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
453 const destination = path.join(versionsDirectory, asset.sha256);
454 const activate = Effect.fn("AntigravityInstallation.activate")(
455 function* () {
456 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
457 directory: managedDirectory,
458 prefix: "active.json.",
459 });
460 const pointerPath = path.join(pointerDirectory, "contents.tmp");
461 yield* fs.writeFileString(
462 pointerPath,
463 yield* encodeActiveRelease({ releaseId: asset.sha256 }),
464 { flag: "wx", mode: 0o600 },
465 );
466 yield* fs.rename(pointerPath, activePath);
467 // The pointer commits the install. Later temp cleanup cannot undo it.
468 yield* SubscriptionRef.update(
469 state,
470 (current) =>
471 ({
472 ...current,
473 phase: "succeeded",
474 installedVersion: asset.version,
475 message: null,
476 }) satisfies ProviderInstallState,
477 );
478 },
479 Effect.scoped,
480 Effect.mapError(
481 wrapFailure(
482 "activate",
483 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
484 ),
485 ),
486 Effect.uninterruptible,
487 );
488
489 if (yield* fs.exists(destination)) {
490 const existing = yield* completedRelease(asset.sha256);
491 if (existing.version !== asset.version) {
492 return yield* installationError(
493 "verify",
494 "The existing managed release has the wrong version. Remove it before reinstalling.",
495 );
496 }
497 yield* report("verifying", "Checking the installed runtime.");
498 yield* validate(existing, asset.version).pipe(
499 Effect.scoped,
500 Effect.timeout(VALIDATION_TIMEOUT),
501 );
502 yield* activate();
503 return;
504 }
505
506 const available = yield* Effect.tryPromise(() =>
507 NodeFSP.statfs(versionsDirectory, { bigint: true }),
508 ).pipe(Effect.option);
509 const required =
510 asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN;
511 if (
512 Option.isSome(available) &&
513 available.value.bavail * available.value.bsize < BigInt(required)
514 ) {
515 return yield* installationError(
516 "download",
517 `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`,
518 );
519 }
520 const staging = yield* fs.makeTempDirectoryScoped({
521 directory: versionsDirectory,
522 prefix: ".install-",
523 });
524 const archivePath = path.join(staging, "download.zip");
525 const pairDirectory = path.join(staging, "runtime");
526 yield* fs.makeDirectory(pairDirectory);
527 const hash = NodeCrypto.createHash("sha256");
528 let downloadedBytes = 0;
529 let lastProgressAt = yield* Clock.currentTimeMillis;
530 yield* Effect.gen(function* () {
531 const response = yield* http
532 .execute(HttpClientRequest.get(asset.url))
533 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
534 // dl.google.com gzips the zip when the client accepts it, so
535 // `content-length` is the encoded size. The decoded stream is still
536 // checked against the pinned byte count and hash below.
537 const contentLength = response.headers["content-length"];
538 const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase();
539 const identityBody = contentEncoding === undefined || contentEncoding === "identity";
540 if (
541 identityBody &&
542 contentLength !== undefined &&
543 Number(contentLength) !== asset.archiveBytes
544 ) {
545 return yield* installationError(
546 "download",
547 "The Antigravity download size did not match the pinned release.",
548 );
549 }
550 yield* response.stream.pipe(
551 Stream.tap((chunk) =>
552 Effect.gen(function* () {
553 downloadedBytes += chunk.byteLength;
554 if (downloadedBytes > asset.archiveBytes) {
555 return yield* installationError(
556 "download",
557 "The Antigravity download exceeded the pinned release size.",
558 );
559 }
560 hash.update(chunk);
561 const now = yield* Clock.currentTimeMillis;
562 if (now - lastProgressAt >= 250 || downloadedBytes === asset.archiveBytes) {
563 lastProgressAt = now;
564 yield* SubscriptionRef.update(state, (current) => ({
565 ...current,
566 downloadedBytes,
567 }));
568 }
569 }),
570 ),
571 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
572 );
573 }).pipe(Effect.timeout(DOWNLOAD_TIMEOUT));
574 if (downloadedBytes !== asset.archiveBytes || hash.digest("hex") !== asset.sha256) {
575 return yield* installationError(
576 "download",
577 "The Antigravity download failed its size or SHA-256 check. Nothing was installed.",
578 );
579 }
580
581 yield* report("extracting", "Extracting the verified runtime.");
582 yield* Effect.gen(function* () {
583 const archive = yield* openZipArchive(archivePath, (detail, cause) =>
584 installationError("extract", detail, cause),
585 );
586 if (archive.entryCount !== 2) {
587 return yield* installationError(
588 "extract",
589 "The archive must contain exactly the Antigravity executable and its harness.",
590 );
591 }
592 const seen = new Set<string>();
593 for (;;) {
594 const entry = yield* archive.next;
595 if (!entry) break;
596 const expected = [asset.executable, asset.harness].find(
597 (file) => file.name === entry.fileName,
598 );
599 const unixType = (entry.externalFileAttributes >>> 16) & 0o170000;
600 if (
601 !expected ||
602 seen.has(entry.fileName) ||
603 entry.fileName.includes("/") ||
604 entry.fileName.includes("\\") ||
605 (unixType !== 0 && unixType !== 0o100000) ||
606 (entry.externalFileAttributes & 0x10) !== 0 ||
607 (entry.generalPurposeBitFlag & 1) !== 0 ||
608 ![0, 8].includes(entry.compressionMethod) ||
609 entry.uncompressedSize !== expected.bytes
610 ) {
611 return yield* installationError(
612 "extract",
613 "The archive contains an unexpected, unsafe, or incorrectly sized member.",
614 );
615 }
616 seen.add(entry.fileName);
617 yield* Effect.gen(function* () {
618 const readable = yield* archive.streamEntry(entry);
619 let extractedBytes = 0;
620 yield* EffectNodeStream.fromReadable<Uint8Array, AntigravityInstallationError>({
621 evaluate: () => readable,
622 onError: wrapFailure("extract", "Could not extract the Antigravity runtime."),
623 }).pipe(
624 Stream.tap((chunk) =>
625 Effect.gen(function* () {
626 extractedBytes += chunk.byteLength;
627 if (extractedBytes > expected.bytes) {
628 return yield* installationError(
629 "extract",
630 "An archive member exceeded its pinned size.",
631 );
632 }
633 }),
634 ),
635 Stream.run(
636 fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }),
637 ),
638 );
639 if (extractedBytes !== expected.bytes) {
640 return yield* installationError("extract", "An archive member was truncated.");
641 }
642 }).pipe(Effect.scoped);
643 }
644 if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) {
645 return yield* installationError(
646 "extract",
647 "The archive is missing the Antigravity executable or its harness.",
648 );
649 }
650 }).pipe(Effect.scoped);
651 yield* fs.remove(archivePath);
652 if (platform !== "win32") {
653 yield* fs.chmod(path.join(pairDirectory, asset.executable.name), 0o755);
654 yield* fs.chmod(path.join(pairDirectory, asset.harness.name), 0o755);
655 }
656 yield* report("verifying", "Checking the downloaded runtime.");
657 yield* validate(
658 {
659 executablePath: path.join(pairDirectory, asset.executable.name),
660 harnessPath: path.join(pairDirectory, asset.harness.name),
661 source: "managed",
662 version: asset.version,
663 managedVersionDirectory: pairDirectory,
664 },
665 asset.version,
666 ).pipe(Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT));
667 const record: InstalledRelease = {
668 releaseId: asset.sha256,
669 version: asset.version,
670 executable: asset.executable,
671 harness: asset.harness,
672 };
673 yield* fs.writeFileString(
674 path.join(pairDirectory, RELEASE_RECORD),
675 yield* encodeInstalledRelease(record),
676 { flag: "wx", mode: 0o600 },
677 );
678 yield* fs.rename(pairDirectory, destination).pipe(
679 Effect.catch((cause) =>
680 completedRelease(asset.sha256).pipe(
681 Effect.flatMap((existing) =>
682 existing.version === asset.version
683 ? validate(existing, asset.version).pipe(
684 Effect.scoped,
685 Effect.timeout(VALIDATION_TIMEOUT),
686 )
687 : Effect.fail(
688 installationError(
689 "activate",
690 "Another installation published a different Antigravity release.",
691 ),
692 ),
693 ),
694 Effect.mapError(() =>
695 installationError(
696 "activate",
697 "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
698 cause,
699 ),
700 ),
701 ),
702 ),
703 );
704 yield* activate();
705 },
706 Effect.scoped,
707 Effect.mapError(
708 wrapFailure(
709 "install",
710 "Could not install Antigravity. Check free disk space and directory access, then try again.",
711 ),
712 ),
713 );
714
715 const start = gate
716 .withPermit(
717 Effect.gen(function* () {
718 const current = yield* SubscriptionRef.get(state);
719 if (isRunning(current)) return current;
720 if (!releaseAsset) {
721 return yield* installationError(
722 "start",
723 `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
724 );
725 }
726 const operationId = yield* crypto.randomUUIDv4();
727 const next: ProviderInstallState = {
728 driver: DRIVER,
729 operationId,
730 phase: "downloading",
731 downloadedBytes: 0,
732 totalBytes: releaseAsset.archiveBytes,
733 version: releaseAsset.version,
734 installedVersion: current.installedVersion,
735 canRemove: current.canRemove,
736 message: "Downloading Google's official Antigravity runtime.",
737 };
738 yield* SubscriptionRef.set(state, next);
739 const work = install(releaseAsset).pipe(
740 Effect.onExit((exit) =>
741 Exit.isFailure(exit)
742 ? SubscriptionRef.update(state, (value) => {
743 if (value.operationId !== operationId || value.phase === "succeeded")
744 return value;
745 const error = Cause.findErrorOption(exit.cause);
746 const cancelled = Cause.hasInterruptsOnly(exit.cause);
747 return {
748 ...value,
749 phase: cancelled ? "cancelled" : "failed",
750 message: cancelled
751 ? "Installation cancelled. The previous runtime is unchanged."
752 : Option.isSome(error)
753 ? error.value.detail
754 : "Could not finish the Antigravity installation. Check disk space and directory access.",
755 } satisfies ProviderInstallState;
756 })
757 : Effect.void,
758 ),
759 Effect.ignoreCause,
760 Effect.ensuring(
761 Effect.sync(() => {
762 if (running?.operationId === operationId) running = undefined;
763 }),
764 ),
765 );
766 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
767 running = { operationId, fiber };
768 return next;
769 }).pipe(Effect.uninterruptible),
770 )
771 .pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation.")));
772
773 const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) {
774 return yield* gate.withPermit(
775 Effect.gen(function* () {
776 const current = yield* SubscriptionRef.get(state);
777 if (current.operationId !== operationId) {
778 return yield* installationError(
779 "cancel",
780 "This installation is no longer current. Refresh its status before cancelling.",
781 );
782 }
783 if (running?.operationId === operationId && isRunning(current)) {
784 yield* Fiber.interrupt(running.fiber);
785 }
786 return yield* SubscriptionRef.get(state);
787 }),
788 );
789 });
790
791 const remove = Effect.fn("AntigravityInstallation.remove")(
792 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
793 yield* gate.withPermit(
794 Effect.gen(function* () {
795 if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) {
796 return yield* installationError(
797 "remove",
798 "Stop Antigravity sessions and sign-in flows before removing its managed runtime.",
799 );
800 }
801 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
802 if (Option.isSome(realManaged)) {
803 for (const binaryPath of protectedBinaryPaths) {
804 if (!binaryPath.trim()) continue;
805 const selected = yield* resolve(binaryPath).pipe(Effect.option);
806 if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
807 return yield* installationError(
808 "remove",
809 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
810 );
811 }
812 const resolved = yield* fs.realPath(binaryPath).pipe(Effect.option);
813 const candidate = Option.getOrElse(resolved, () => path.resolve(binaryPath));
814 if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
815 return yield* installationError(
816 "remove",
817 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
818 );
819 }
820 }
821 }
822 yield* fs.remove(managedDirectory, { recursive: true, force: true });
823 yield* SubscriptionRef.update(
824 state,
825 (current) =>
826 ({
827 ...current,
828 operationId: null,
829 phase: "idle",
830 downloadedBytes: 0,
831 installedVersion: null,
832 canRemove: false,
833 message: null,
834 }) satisfies ProviderInstallState,
835 );
836 }).pipe(Effect.uninterruptible),
837 );
838 },
839 Effect.mapError(
840 wrapFailure(
841 "remove",
842 "Could not remove the managed Antigravity runtime. Check for open processes and try again.",
843 ),
844 ),
845 );
846
847 yield* Effect.gen(function* () {
848 const canRemove = yield* fs.exists(managedDirectory);
849 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
850 if (!(yield* fs.exists(activePath))) return;
851 const active = yield* readRecord(activePath, ActiveRelease);
852 const installed = yield* completedRelease(active.releaseId);
853 yield* SubscriptionRef.update(state, (current) => ({
854 ...current,
855 installedVersion: installed.version,
856 }));
857 }).pipe(
858 Effect.catch(() =>
859 SubscriptionRef.update(
860 state,
861 (current) =>
862 ({
863 ...current,
864 phase: "failed",
865 message: "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
866 }) satisfies ProviderInstallState,
867 ),
868 ),
869 );
870
871 return AntigravityInstallation.of({
872 managedDirectory,
873 resolve,
874 acquire,
875 start,
876 cancel,
877 state: SubscriptionRef.get(state),
878 changes: SubscriptionRef.changes(state),
879 remove,
880 });
881});