The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,526 lines 61 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest or free-space query.
2 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
3 import * as ModelManifest from "./ModelManifest.ts";
4 import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease";
5 import { compareSemverVersions } from "@t3tools/shared/semver";
6 import {
7 ProviderDriverKind,
8 type ProviderInstallState,
9 type ServerProviderCompatibilityAdvisory,
10 } from "@t3tools/contracts";
11 import * as HostProcess from "@t3tools/shared/HostProcess";
12 import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
13 import { resolveCommandPath } from "@t3tools/shared/shell";
14 import * as Clock from "effect/Clock";
15 import * as Cause from "effect/Cause";
16 import * as Context from "effect/Context";
17 import * as SecureRandom from "effect/crypto/SecureRandom";
18 import * as Effect from "effect/Effect";
19 import * as Exit from "effect/Exit";
20 import * as Fiber from "effect/Fiber";
21 import * as FileSystem from "effect/FileSystem";
22 import * as Layer from "effect/Layer";
23 import * as Option from "effect/Option";
24 import * as Path from "effect/Path";
25 import type { PlatformError } from "effect/PlatformError";
26 import * as Predicate from "effect/Predicate";
27 import * as Schema from "effect/Schema";
28 import * as Schedule from "effect/Schedule";
29 import * as Scope from "effect/Scope";
30 import * as Semaphore from "effect/Semaphore";
31 import * as Stream from "effect/Stream";
32 import * as SubscriptionRef from "effect/SubscriptionRef";
33 import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
34 import * as ChildProcess from "effect/process/ChildProcess";
35 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
36 import * as NodeCrypto from "node:crypto";
37 import * as NodeFSP from "node:fs/promises";
38 import * as EffectAcpErrors from "effect-acp/errors";
39 import { lock } from "proper-lockfile";
40
41 import * as ServerConfig from "../config.ts";
42 import * as ServerSettings from "../serverSettings.ts";
43 import {
44 ANTIGRAVITY_CLI_MANIFEST_BASE,
45 antigravityCliTarget,
46 parseAntigravityCliRelease,
47 type AntigravityCliReleaseAsset,
48 } from "./antigravityCliRelease.ts";
49 import { makeAntigravityAcpRuntime } from "./acp/AntigravityAcpSupport.ts";
50 import {
51 buildAntigravityAcpSpawnInput,
52 prepareAntigravityProfile,
53 } from "./antigravityAuthSupport.ts";
54
55 const DRIVER = ProviderDriverKind.make("antigravity");
56 const DOWNLOAD_TIMEOUT = "45 minutes";
57 const VALIDATION_TIMEOUT = "90 seconds";
58 const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
59 const MAX_EXECUTABLE_BYTES = 512 * 1024 * 1024;
60 const UPDATE_CHECK_INTERVAL = 60 * 60 * 1000;
61 const FREE_SPACE_MARGIN = 256 * 1024 * 1024;
62 const RECORD_MAX_BYTES = 8 * 1024;
63 const RELEASE_RECORD = ".install-complete.json";
64 const LARGE_PAGE_KERNEL_MESSAGE =
65 "Google's linux-arm64 Antigravity runtime needs a kernel with 4 KiB memory pages, and this kernel uses larger pages (as on Asahi Linux or Raspberry Pi 5). Use a remote environment or a custom Antigravity executable.";
66
67 const ReleaseId = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u));
68 const ActiveRelease = Schema.Struct({ releaseId: ReleaseId });
69 const InstalledRelease = Schema.Struct({
70 releaseId: ReleaseId,
71 version: Schema.String,
72 executable: Schema.Struct({ name: Schema.String, bytes: Schema.Number }),
73 });
74 type InstalledRelease = typeof InstalledRelease.Type;
75 const encodeActiveRelease = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease));
76 const encodeInstalledRelease = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease));
77 const decodeInstalledRelease = Schema.decodeEffect(Schema.fromJsonString(InstalledRelease));
78
79 export class AntigravityInstallationError extends Schema.TaggedError<AntigravityInstallationError>()(
80 "AntigravityInstallationError",
81 {
82 operation: Schema.String,
83 detail: Schema.String,
84 cause: Schema.optional(Schema.Defect()),
85 },
86 ) {
87 override get message() {
88 return this.detail;
89 }
90 }
91 const isInstallationError = Schema.is(AntigravityInstallationError);
92 const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);
93
94 export interface AntigravityExecutable {
95 readonly executablePath: string;
96 readonly source: "override" | "managed" | "path";
97 readonly version: string | null;
98 readonly managedVersionDirectory: string | null;
99 }
100
101 interface AntigravityInstallationService {
102 readonly managedDirectory: string;
103 readonly resolve: (
104 binaryPath?: string,
105 environment?: NodeJS.ProcessEnv,
106 ) => Effect.Effect<AntigravityExecutable, AntigravityInstallationError>;
107 /** Hold the lease until the spawned process has exited. */
108 readonly acquire: (
109 binaryPath?: string,
110 environment?: NodeJS.ProcessEnv,
111 ) => Effect.Effect<AntigravityExecutable, AntigravityInstallationError, Scope.Scope>;
112 readonly compatibility: (
113 version: string,
114 ) => Effect.Effect<ServerProviderCompatibilityAdvisory | undefined>;
115 readonly start: Effect.Effect<ProviderInstallState, AntigravityInstallationError>;
116 readonly cancel: (
117 operationId: string,
118 ) => Effect.Effect<ProviderInstallState, AntigravityInstallationError>;
119 readonly state: Effect.Effect<ProviderInstallState>;
120 readonly changes: Stream.Stream<ProviderInstallState>;
121 readonly checkForUpdate: Effect.Effect<void>;
122 readonly remove: (
123 protectedBinaryPaths?: ReadonlyArray<string>,
124 ) => Effect.Effect<void, AntigravityInstallationError>;
125 }
126
127 export class AntigravityInstallation extends Context.Service<
128 AntigravityInstallation,
129 AntigravityInstallationService
130 >()("t3/provider/AntigravityInstallation") {
131 static readonly layer = Layer.effect(
132 AntigravityInstallation,
133 Effect.gen(function* () {
134 const config = yield* ServerConfig.ServerConfig;
135 const settings = yield* ServerSettings.ServerSettingsService;
136 return yield* makeAntigravityInstallation({
137 baseDir: config.baseDir,
138 updateChecksEnabled: settings.getSettings.pipe(
139 Effect.map((value) => value.enableProviderUpdateChecks),
140 Effect.orElseSucceed(() => false),
141 ),
142 });
143 }),
144 );
145 }
146
147 export interface AntigravityInstallationOptions {
148 readonly baseDir: string;
149 readonly releaseAsset?: AntigravityCliReleaseAsset | null;
150 readonly updateChecksEnabled?: Effect.Effect<boolean>;
151 readonly validate?: (
152 executable: AntigravityExecutable,
153 expectedVersion: string,
154 ) => Effect.Effect<void, AntigravityInstallationError, Scope.Scope>;
155 }
156
157 const installationError = (operation: string, detail: string, cause?: unknown) =>
158 new AntigravityInstallationError({
159 operation,
160 detail,
161 ...(cause === undefined ? {} : { cause }),
162 });
163
164 const wrapFailure = (operation: string, detail: string) => (cause: unknown) =>
165 isInstallationError(cause) ? cause : installationError(operation, detail, cause);
166
167 function isAntigravityCli(...candidates: ReadonlyArray<string>) {
168 return candidates.some((candidate) =>
169 /^(?:agy|antigravity)(?:\.(?:exe|cmd|bat))?$/iu.test(candidate.split(/[\\/]/u).at(-1) ?? ""),
170 );
171 }
172
173 function isRunning(state: ProviderInstallState) {
174 return (
175 state.phase === "downloading" || state.phase === "extracting" || state.phase === "verifying"
176 );
177 }
178
179 export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.make")(function* (
180 options: AntigravityInstallationOptions,
181 ) {
182 const manifestService = yield* ModelManifest.ModelManifest;
183 const fs = yield* FileSystem.FileSystem;
184 const path = yield* Path.Path;
185 const random = yield* SecureRandom.SecureRandom;
186 const http = yield* HttpClient.HttpClient;
187 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
188 const serviceScope = yield* Effect.scope;
189 const platform = yield* HostProcess.Platform;
190 const arch = yield* HostProcess.Architecture;
191 const environment = yield* HostProcess.Environment;
192 let releaseAsset = options.releaseAsset ?? null;
193 const supported =
194 options.releaseAsset === undefined
195 ? antigravityCliTarget(platform, arch) !== null
196 : options.releaseAsset !== null;
197 const cliExecutableName = platform === "win32" ? "agy.exe" : "antigravity";
198 const managedDirectory = path.join(
199 options.baseDir,
200 "tools",
201 "antigravity-acp",
202 `${platform}-${arch}`,
203 );
204 const versionsDirectory = path.join(managedDirectory, "versions");
205 const activePath = path.join(managedDirectory, "active.json");
206 // Windows briefly keeps handles on fresh runtime files after taskkill or an antivirus scan; retry for up to 10 seconds.
207 const retryWhileWindowsHoldsHandles = <A, R>(effect: Effect.Effect<A, PlatformError, R>) =>
208 effect.pipe(
209 Effect.retry({
210 times: platform === "win32" ? 40 : 0,
211 schedule: Schedule.spaced("250 millis"),
212 while: (error) =>
213 error.reason._tag === "PermissionDenied" ||
214 error.reason._tag === "Busy" ||
215 error.reason._tag === "Unknown",
216 }),
217 );
218 const gate = yield* Semaphore.make(1);
219 const leases = new Map<string, number>();
220 let running: { readonly operationId: string; readonly fiber: Fiber.Fiber<void> } | undefined;
221 const state = yield* SubscriptionRef.make<ProviderInstallState>({
222 driver: DRIVER,
223 operationId: null,
224 phase: "idle",
225 downloadedBytes: 0,
226 totalBytes: null,
227 version: releaseAsset?.version ?? null,
228 installedVersion: null,
229 canRemove: false,
230 message: null,
231 });
232
233 const compatibility = Effect.fn("AntigravityInstallation.compatibility")(function* (
234 version: string,
235 ) {
236 return ModelManifest.providerCompatibility(yield* manifestService.current, DRIVER, version);
237 });
238 const isWithdrawn = Effect.fn("AntigravityInstallation.isWithdrawn")(function* (version: string) {
239 const status = (yield* compatibility(version))?.status;
240 return status === "broken" || status === "unsupported";
241 });
242 const ensureEligible = Effect.fn("AntigravityInstallation.ensureEligible")(function* (
243 version: string,
244 ) {
245 if (yield* isWithdrawn(version))
246 return yield* installationError(
247 "verify",
248 "This Antigravity release was withdrawn. Check for updates and try again.",
249 );
250 });
251
252 const readRecord = Effect.fn("AntigravityInstallation.readRecord")(function* <A>(
253 filePath: string,
254 schema: Schema.Codec<A>,
255 ) {
256 const info = yield* fs.stat(filePath);
257 if (info.type !== "File" || Number(info.size) > RECORD_MAX_BYTES) {
258 return yield* installationError(
259 "resolve",
260 "The managed runtime record is invalid. Reinstall Antigravity.",
261 );
262 }
263 const contents = yield* fs.readFileString(filePath);
264 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(contents);
265 });
266
267 const executableFile = Effect.fn("AntigravityInstallation.executableFile")(function* (
268 filePath: string,
269 bytes?: number,
270 ) {
271 const info = yield* fs.stat(filePath).pipe(Effect.option);
272 return (
273 Option.isSome(info) &&
274 info.value.type === "File" &&
275 (bytes === undefined || Number(info.value.size) === bytes) &&
276 (platform === "win32" || (info.value.mode & 0o111) !== 0)
277 );
278 });
279
280 const isSymlink = Effect.fn("AntigravityInstallation.isSymlink")(function* (filePath: string) {
281 return yield* fs.readLink(filePath).pipe(
282 Effect.as(true),
283 Effect.orElseSucceed(() => false),
284 );
285 });
286
287 const isInsideDirectory = Effect.fn("AntigravityInstallation.isInsideDirectory")(function* (
288 targetPath: string,
289 rootDirectory: string,
290 ) {
291 const realRoot = yield* fs.realPath(rootDirectory).pipe(Effect.option);
292 const realTarget = yield* fs.realPath(targetPath).pipe(Effect.option);
293 if (Option.isNone(realRoot) || Option.isNone(realTarget)) return false;
294 return (
295 realTarget.value === realRoot.value ||
296 realTarget.value.startsWith(`${realRoot.value}${path.sep}`)
297 );
298 });
299
300 const hasSymlinkedManagedRoot = Effect.gen(function* () {
301 return (yield* isSymlink(managedDirectory)) || (yield* isSymlink(versionsDirectory));
302 });
303
304 const ensureRealManagedRoot = Effect.fn("AntigravityInstallation.ensureRealManagedRoot")(
305 function* (operation: "install" | "activate" | "resolve") {
306 if (yield* hasSymlinkedManagedRoot) {
307 return yield* installationError(
308 operation,
309 "The managed Antigravity directory is a symbolic link. Remove it and reinstall.",
310 );
311 }
312 },
313 );
314
315 const isLockContentionError = (cause: unknown) =>
316 isInstallationError(cause) &&
317 Predicate.isObject(cause.cause) &&
318 Predicate.hasProperty(cause.cause, "code") &&
319 cause.cause.code === "ELOCKED";
320
321 // Prevent the native CLI auto-updater from staging and replacing the managed binary in place.
322 const lockReleaseDirectory = Effect.fn("AntigravityInstallation.lockReleaseDirectory")(function* (
323 directory: string,
324 executablePath: string,
325 strict: boolean,
326 ) {
327 if (platform === "win32") return;
328 const recordPath = path.join(directory, RELEASE_RECORD);
329 const apply = Effect.gen(function* () {
330 if (
331 (yield* hasSymlinkedManagedRoot) ||
332 (yield* isSymlink(directory)) ||
333 (yield* isSymlink(executablePath)) ||
334 (yield* isSymlink(recordPath)) ||
335 !(yield* isInsideDirectory(directory, versionsDirectory)) ||
336 !(yield* isInsideDirectory(executablePath, directory)) ||
337 !(yield* isInsideDirectory(recordPath, directory))
338 ) {
339 return yield* installationError(
340 "activate",
341 "The managed Antigravity runtime contains an unexpected symbolic link. Reinstall it.",
342 );
343 }
344 yield* fs.chmod(executablePath, 0o555);
345 yield* fs.chmod(recordPath, 0o400);
346 yield* fs.chmod(directory, 0o500);
347 });
348 if (strict) {
349 yield* apply;
350 } else {
351 yield* apply.pipe(Effect.ignore);
352 }
353 });
354
355 const unlockDirectoryTree = Effect.fn("AntigravityInstallation.unlockDirectoryTree")(function* (
356 directory: string,
357 ): Effect.fn.Return<void> {
358 if (platform === "win32") return;
359 if (
360 (yield* hasSymlinkedManagedRoot) ||
361 (yield* isSymlink(directory)) ||
362 !(yield* isInsideDirectory(directory, managedDirectory))
363 ) {
364 return;
365 }
366 const info = yield* fs.stat(directory).pipe(Effect.option);
367 if (Option.isNone(info) || info.value.type !== "Directory") return;
368 yield* fs.chmod(directory, 0o700).pipe(Effect.ignore);
369 const entries = yield* fs
370 .readDirectory(directory)
371 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
372 for (const entry of entries) {
373 const entryPath = path.join(directory, entry);
374 if (yield* isSymlink(entryPath)) continue;
375 const entryInfo = yield* fs.stat(entryPath).pipe(Effect.option);
376 if (Option.isSome(entryInfo) && entryInfo.value.type === "Directory") {
377 yield* unlockDirectoryTree(entryPath);
378 }
379 }
380 });
381
382 const removeReleaseDirectory = Effect.fn("AntigravityInstallation.removeReleaseDirectory")(
383 function* (directory: string) {
384 yield* unlockDirectoryTree(directory);
385 yield* fs
386 .remove(directory, { recursive: true, force: true })
387 .pipe(retryWhileWindowsHoldsHandles);
388 },
389 );
390
391 // Serialize resolve, publish, activation, pruning, and removal across server instances sharing managedDirectory.
392 // Locking managedDirectory places the lock directory beside it so remove() can delete managedDirectory safely.
393 const withManagedLock = <A, E, R>(
394 operation: "activate" | "remove" | "resolve",
395 effect: Effect.Effect<A, E, R>,
396 ): Effect.Effect<A, E | AntigravityInstallationError, R> =>
397 Effect.scoped(
398 Effect.acquireRelease(
399 Effect.tryPromise({
400 try: () =>
401 lock(managedDirectory, {
402 realpath: false,
403 stale: 30_000,
404 update: 10_000,
405 retries: { retries: 60, minTimeout: 25, maxTimeout: 150 },
406 onCompromised: () => {},
407 }),
408 catch: (cause) =>
409 installationError(
410 operation,
411 Predicate.isObject(cause) &&
412 Predicate.hasProperty(cause, "code") &&
413 cause.code === "ELOCKED"
414 ? "Another Antigravity installation is already in progress. Try again."
415 : "Could not lock the managed Antigravity directory. Try again.",
416 cause,
417 ),
418 }),
419 (release) => Effect.promise(() => release().catch(() => undefined)),
420 ).pipe(Effect.andThen(effect)),
421 );
422
423 const inspectManagedFile = Effect.fn("AntigravityInstallation.inspectManagedFile")(function* (
424 filePath: string,
425 expectedBytes: number,
426 ) {
427 if (yield* isSymlink(filePath)) return "incomplete" as const;
428 const info = yield* fs.stat(filePath).pipe(
429 Effect.catchIf(
430 (error) => error.reason._tag === "NotFound",
431 () => Effect.succeed(null),
432 ),
433 );
434 if (
435 info === null ||
436 info.type !== "File" ||
437 (platform !== "win32" && (info.mode & 0o111) === 0)
438 ) {
439 return "incomplete" as const;
440 }
441 return Number(info.size) === expectedBytes ? ("ok" as const) : ("changed" as const);
442 });
443
444 const inspectRelease = Effect.fn("AntigravityInstallation.inspectRelease")(function* (
445 releaseId: string,
446 ) {
447 const incomplete = () =>
448 ({
449 _tag: "repairable",
450 error: installationError(
451 "resolve",
452 "The managed Antigravity runtime is incomplete. Reinstall it.",
453 ),
454 }) as const;
455 const invalidRecord = (cause?: unknown) =>
456 ({
457 _tag: "repairable",
458 error: installationError(
459 "resolve",
460 "The managed runtime record is invalid. Reinstall Antigravity.",
461 cause,
462 ),
463 }) as const;
464 if (yield* hasSymlinkedManagedRoot) return incomplete();
465 const directory = path.join(versionsDirectory, releaseId);
466 if (yield* isSymlink(directory)) return incomplete();
467 const directoryInfo = yield* fs.stat(directory).pipe(
468 Effect.catchIf(
469 (error) => error.reason._tag === "NotFound",
470 () => Effect.succeed(null),
471 ),
472 );
473 if (directoryInfo === null || directoryInfo.type !== "Directory") return incomplete();
474 const recordPath = path.join(directory, RELEASE_RECORD);
475 if (yield* isSymlink(recordPath)) return incomplete();
476 const recordInfo = yield* fs.stat(recordPath).pipe(
477 Effect.catchIf(
478 (error) => error.reason._tag === "NotFound",
479 () => Effect.succeed(null),
480 ),
481 );
482 if (recordInfo === null) return incomplete();
483 if (recordInfo.type !== "File" || Number(recordInfo.size) > RECORD_MAX_BYTES) {
484 return invalidRecord();
485 }
486 const readResult = yield* fs.readFileString(recordPath).pipe(
487 Effect.map((contents) => ({ _tag: "ok" as const, contents })),
488 Effect.catchIf(
489 (error) => error.reason._tag === "NotFound",
490 () => Effect.succeed({ _tag: "missing" as const }),
491 ),
492 Effect.catchIf(
493 (error) => error.reason._tag === "PermissionDenied",
494 (error) => Effect.succeed({ _tag: "unreadable" as const, error }),
495 ),
496 );
497 if (readResult._tag === "missing") return incomplete();
498 if (readResult._tag === "unreadable") return invalidRecord(readResult.error);
499 const decoded = yield* decodeInstalledRelease(readResult.contents).pipe(Effect.option);
500 if (Option.isNone(decoded)) return invalidRecord();
501 const record = decoded.value;
502 if (record.releaseId === releaseId && record.executable.name !== cliExecutableName) {
503 return {
504 _tag: "repairable" as const,
505 error: installationError(
506 "resolve",
507 `Antigravity ${record.version} predates the Antigravity CLI and no longer works with this T3 Code release. Update it in Antigravity setup.`,
508 ),
509 };
510 }
511 if (
512 record.releaseId !== releaseId ||
513 !Number.isSafeInteger(record.executable.bytes) ||
514 record.executable.bytes <= 0 ||
515 !record.version.trim()
516 ) {
517 return incomplete();
518 }
519 const executablePath = path.join(directory, record.executable.name);
520 const executableStatus = yield* inspectManagedFile(executablePath, record.executable.bytes);
521 if (executableStatus === "incomplete") return incomplete();
522 if (executableStatus === "changed") {
523 return {
524 _tag: "repairable" as const,
525 error: installationError(
526 "resolve",
527 "The managed Antigravity runtime changed on disk. Reinstall it in Antigravity setup.",
528 ),
529 };
530 }
531 return {
532 _tag: "valid" as const,
533 executable: {
534 executablePath,
535 source: "managed" as const,
536 version: record.version,
537 managedVersionDirectory: directory,
538 } satisfies AntigravityExecutable,
539 };
540 });
541
542 const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* (
543 releaseId: string,
544 ) {
545 const inspected = yield* inspectRelease(releaseId);
546 if (inspected._tag === "repairable") return yield* inspected.error;
547 return inspected.executable;
548 });
549
550 const isManagedVersionCandidate = Effect.fn("AntigravityInstallation.isManagedVersionCandidate")(
551 function* (executablePath: string) {
552 const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option);
553 const directory = path.dirname(executablePath);
554 return (
555 Option.isSome(realVersions) &&
556 path.dirname(directory) === realVersions.value &&
557 /^[a-f0-9]{64}$/u.test(path.basename(directory))
558 );
559 },
560 );
561
562 const fromExternal = Effect.fn("AntigravityInstallation.fromExternal")(function* (
563 candidate: string,
564 source: "override" | "path",
565 ) {
566 if (!(yield* executableFile(candidate))) return null;
567 const executablePath = yield* fs.realPath(candidate);
568 const directory = path.dirname(executablePath);
569 if (yield* isManagedVersionCandidate(executablePath)) {
570 const installed = yield* completedRelease(path.basename(directory));
571 return { ...installed, source };
572 }
573 // Keep launcher symlinks intact: version-manager shims dispatch by their invoked name.
574 if (!isAntigravityCli(candidate, executablePath)) return null;
575 return {
576 executablePath: candidate,
577 source,
578 version: null,
579 managedVersionDirectory: null,
580 } satisfies AntigravityExecutable;
581 });
582
583 // Resolve a verified external CLI outside versions/ without taking the managed lock, so a
584 // read-only managed parent or active repair does not block unrelated external executables.
585 const findVerifiedExternal = Effect.fn("AntigravityInstallation.findVerifiedExternal")(function* (
586 candidates: ReadonlyArray<string>,
587 source: "override" | "path",
588 ) {
589 for (const candidate of candidates) {
590 if (!(yield* executableFile(candidate))) continue;
591 const resolved = yield* fs.realPath(candidate).pipe(Effect.option);
592 if (Option.isNone(resolved)) return null;
593 const executablePath = resolved.value;
594 if (yield* isManagedVersionCandidate(executablePath)) return null;
595 if (isAntigravityCli(candidate, executablePath)) {
596 return {
597 executablePath: candidate,
598 source,
599 version: null,
600 managedVersionDirectory: null,
601 } satisfies AntigravityExecutable;
602 }
603 }
604 return null;
605 });
606
607 const commandPath = (command: string, env: NodeJS.ProcessEnv) =>
608 resolveCommandPath(command, { env }).pipe(
609 Effect.map((resolved) => (resolved === null ? null : path.resolve(resolved))),
610 Effect.provideService(HostProcess.Platform, platform),
611 Effect.provideService(FileSystem.FileSystem, fs),
612 Effect.provideService(Path.Path, path),
613 );
614
615 // Resolve per PATH entry so a candidate that is not the CLI falls through to later entries.
616 const commandCandidates = Effect.fn("AntigravityInstallation.commandCandidates")(function* (
617 command: string,
618 processEnvironment = environment,
619 ) {
620 if (command.includes("/") || command.includes("\\")) {
621 const resolved = yield* commandPath(command, processEnvironment);
622 return resolved === null ? [] : [resolved];
623 }
624 const pathValue =
625 platform === "win32"
626 ? Object.entries(processEnvironment).findLast(([key]) => key.toUpperCase() === "PATH")?.[1]
627 : processEnvironment.PATH;
628 const candidates: string[] = [];
629 for (const entry of (pathValue ?? "").split(platform === "win32" ? ";" : ":")) {
630 if (entry.length === 0) continue;
631 const resolved = yield* commandPath(command, { ...processEnvironment, PATH: entry });
632 if (resolved !== null) candidates.push(resolved);
633 }
634 return candidates;
635 });
636
637 const resolveUnlocked = Effect.fn("AntigravityInstallation.resolveUnlocked")(function* (
638 binaryPath?: string,
639 processEnvironment?: NodeJS.ProcessEnv,
640 ) {
641 const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory);
642 if (override) {
643 for (const candidate of yield* commandCandidates(override, processEnvironment)) {
644 const selected = yield* fromExternal(candidate, "override");
645 if (selected) return selected;
646 }
647 return yield* installationError(
648 "resolve",
649 "The custom Antigravity executable is missing or not executable, or it is not the agy CLI.",
650 );
651 }
652 if (yield* fs.exists(activePath)) {
653 yield* ensureRealManagedRoot("resolve");
654 const active = yield* readRecord(activePath, ActiveRelease);
655 const installed = yield* completedRelease(active.releaseId);
656 if (yield* isWithdrawn(installed.version))
657 return yield* installationError(
658 "resolve",
659 `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`,
660 );
661 return installed;
662 }
663 for (const candidate of yield* commandCandidates("agy", processEnvironment)) {
664 const selected = yield* fromExternal(candidate, "path");
665 if (selected) return selected;
666 }
667 return yield* installationError(
668 "resolve",
669 supported
670 ? "Antigravity ACP runtime is not installed. Install it in this environment's provider settings or set a custom ACP executable path. The Antigravity app, IDE, and CLI are separate installations."
671 : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`,
672 );
673 });
674
675 const resolve: AntigravityInstallationService["resolve"] = Effect.fn(
676 "AntigravityInstallation.resolve",
677 )(
678 function* (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) {
679 const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory);
680 if (override) {
681 const external = yield* findVerifiedExternal(
682 yield* commandCandidates(override, processEnvironment),
683 "override",
684 );
685 if (external !== null) return external;
686 }
687 const lookup = resolveUnlocked(binaryPath, processEnvironment);
688 if (!(yield* fs.exists(managedDirectory))) return yield* lookup;
689 return yield* withManagedLock("resolve", lookup).pipe(
690 Effect.catch((cause) =>
691 Effect.gen(function* () {
692 if (!override && !(yield* fs.exists(activePath))) {
693 const external = yield* findVerifiedExternal(
694 yield* commandCandidates("agy", processEnvironment),
695 "path",
696 );
697 if (external !== null) return external;
698 }
699 return yield* cause;
700 }),
701 ),
702 );
703 },
704 Effect.mapError(
705 wrapFailure(
706 "resolve",
707 "Could not read the Antigravity installation. Reinstall it or set a custom executable path.",
708 ),
709 ),
710 );
711
712 const acquire = (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) =>
713 Effect.acquireRelease(
714 gate.withPermit(
715 Effect.gen(function* () {
716 const executable = yield* resolve(binaryPath, processEnvironment);
717 const directory = executable.managedVersionDirectory;
718 if (directory) leases.set(directory, (leases.get(directory) ?? 0) + 1);
719 return executable;
720 }),
721 ),
722 (executable) =>
723 gate.withPermit(
724 Effect.sync(() => {
725 const directory = executable.managedVersionDirectory;
726 if (!directory) return;
727 const remaining = (leases.get(directory) ?? 1) - 1;
728 if (remaining > 0) leases.set(directory, remaining);
729 else leases.delete(directory);
730 }),
731 ),
732 );
733
734 const withValidationTimeout = Effect.timeoutOrElse({
735 duration: VALIDATION_TIMEOUT,
736 orElse: () =>
737 Effect.fail(
738 installationError(
739 "verify",
740 "Antigravity runtime verification timed out after 90 seconds. Check this environment's server logs for startup errors, then retry installation.",
741 ),
742 ),
743 });
744 const validate =
745 options.validate ??
746 Effect.fn("AntigravityInstallation.validate")(
747 function* (executable: AntigravityExecutable, expectedVersion: string) {
748 const validationScope = yield* Effect.scope;
749 const profileDirectory = yield* Effect.acquireRelease(
750 fs.makeTempDirectory({ prefix: "t3-antigravity-validate-" }),
751 (directory) =>
752 fs
753 .remove(directory, { recursive: true, force: true })
754 .pipe(retryWhileWindowsHoldsHandles, Effect.orDie),
755 );
756 const profile = yield* prepareAntigravityProfile({
757 profileDirectory,
758 platform,
759 baseEnv: environment,
760 // A shallow scoped profile cleans up unpacked files within Windows' path limit.
761 tempDirectory: profileDirectory,
762 });
763 const runtime = yield* makeAntigravityAcpRuntime({
764 runtimeVersion: expectedVersion,
765 spawn: buildAntigravityAcpSpawnInput({
766 installation: executable,
767 profile,
768 cwd: profileDirectory,
769 baseEnv: environment,
770 }),
771 cwd: profileDirectory,
772 childProcessSpawner:
773 platform === "win32"
774 ? ChildProcessSpawner.make(
775 Effect.fnUntraced(function* (command) {
776 const child = yield* spawner.spawn(command);
777 // Stop PyInstaller's tree before ACP closes pipes; after launcher exit, taskkill cannot reach children holding DLLs open.
778 yield* Scope.addFinalizer(
779 validationScope,
780 child.kill({ forceKillAfter: "1 second" }).pipe(Effect.orDie),
781 );
782 return child;
783 }),
784 )
785 : spawner,
786 });
787 const initialized = yield* runtime.initialize();
788 if (
789 initialized.agentInfo?.name !== "Antigravity ACP Server" ||
790 initialized.agentInfo?.version !== expectedVersion ||
791 (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) ||
792 initialized.agentCapabilities?.loadSession !== true ||
793 !initialized.agentCapabilities.sessionCapabilities?.resume ||
794 !initialized.agentCapabilities.auth?.logout ||
795 !initialized.authMethods?.some((method) => method.id === "oauth-personal")
796 ) {
797 return yield* installationError(
798 "verify",
799 "The downloaded runtime did not identify as the expected Google Antigravity release.",
800 );
801 }
802 },
803 Effect.provideService(FileSystem.FileSystem, fs),
804 Effect.provideService(Path.Path, path),
805 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
806 Effect.provideService(SecureRandom.SecureRandom, random),
807 Effect.mapError((cause) => {
808 if (isInstallationError(cause)) return cause;
809 const stderr = isAcpProcessExitedError(cause) ? (cause.stderr ?? "") : "";
810 const detail = /\b(?:AF_INET6|enforce_kernel_ipv6_support)\b/.test(stderr)
811 ? "Antigravity requires IPv6 socket support. Enable IPv6 in this environment. On WSL, remove ipv6.disable=1 from .wslconfig and run wsl --shutdown."
812 : /page-size\.cc|Compile-time page size does not match/.test(stderr)
813 ? LARGE_PAGE_KERNEL_MESSAGE
814 : "The downloaded Antigravity runtime could not start in this environment.";
815 return installationError("verify", detail, cause);
816 }),
817 );
818
819 // Each update lands in its own directory. Best effort: a busy gate means a session is
820 // resolving, so the next start or update finishes the cleanup.
821 const pruneInactiveReleasesBody = Effect.gen(function* () {
822 if ((yield* isSymlink(managedDirectory)) || (yield* isSymlink(versionsDirectory))) return;
823 const active = yield* readRecord(activePath, ActiveRelease);
824 for (const entry of yield* fs.readDirectory(versionsDirectory)) {
825 if (entry === active.releaseId || !/^[a-f0-9]{64}$/u.test(entry)) continue;
826 const directory = path.join(versionsDirectory, entry);
827 if (leases.has(directory)) continue;
828 yield* removeReleaseDirectory(directory).pipe(Effect.ignore);
829 }
830 });
831
832 const pruneInactiveReleases = Effect.gen(function* () {
833 if (!(yield* fs.exists(activePath))) return;
834 yield* withManagedLock("activate", pruneInactiveReleasesBody);
835 }).pipe(
836 gate.withPermitsIfAvailable(1),
837 Effect.ignore,
838 Effect.withSpan("AntigravityInstallation.pruneInactiveReleases"),
839 );
840
841 const install = Effect.fn("AntigravityInstallation.install")(
842 function* (asset: AntigravityCliReleaseAsset) {
843 yield* ensureEligible(asset.version);
844 // Release IDs are 64 hex characters, so a release is named by its SHA-512's prefix.
845 const releaseId = asset.sha512.slice(0, 64);
846 yield* resolveNodeExecutable("Antigravity", environment).pipe(
847 Effect.provideService(FileSystem.FileSystem, fs),
848 Effect.provideService(Path.Path, path),
849 Effect.provideService(HostProcess.Platform, platform),
850 Effect.mapError((cause) =>
851 installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause),
852 ),
853 );
854 const report = (phase: ProviderInstallState["phase"], message: string | null) =>
855 SubscriptionRef.update(state, (current) => ({ ...current, phase, message }));
856 yield* ensureRealManagedRoot("install");
857 yield* fs.makeDirectory(versionsDirectory, { recursive: true });
858 yield* ensureRealManagedRoot("install");
859 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
860 const destination = path.join(versionsDirectory, releaseId);
861 const writeAndActivate = Effect.fn("AntigravityInstallation.writeAndActivate")(function* (
862 pointerDirectory: string,
863 ) {
864 yield* ensureRealManagedRoot("activate");
865 yield* ensureEligible(asset.version);
866 const inspected = yield* inspectRelease(releaseId);
867 if (inspected._tag !== "valid" || inspected.executable.version !== asset.version) {
868 return yield* installationError(
869 "activate",
870 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
871 );
872 }
873 yield* lockReleaseDirectory(destination, inspected.executable.executablePath, true);
874 const pointerPath = path.join(pointerDirectory, "contents.tmp");
875 yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), {
876 flag: "wx",
877 mode: 0o600,
878 });
879 yield* fs.rename(pointerPath, activePath);
880 yield* pruneInactiveReleasesBody.pipe(Effect.ignore);
881 yield* SubscriptionRef.update(
882 state,
883 (current) =>
884 ({
885 ...current,
886 phase: "succeeded",
887 installedVersion: asset.version,
888 message: null,
889 }) satisfies ProviderInstallState,
890 );
891 });
892 const activate = Effect.fn("AntigravityInstallation.activate")(
893 function* () {
894 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
895 directory: managedDirectory,
896 prefix: "active.json.",
897 });
898 yield* gate.withPermit(
899 withManagedLock(
900 "activate",
901 writeAndActivate(pointerDirectory).pipe(Effect.uninterruptible),
902 ),
903 );
904 },
905 Effect.scoped,
906 Effect.mapError(
907 wrapFailure(
908 "activate",
909 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
910 ),
911 ),
912 );
913
914 if ((yield* fs.exists(destination)) || (yield* isSymlink(destination))) {
915 const existing = yield* inspectRelease(releaseId);
916 if (existing._tag === "valid") {
917 if (existing.executable.version !== asset.version) {
918 return yield* installationError(
919 "verify",
920 "The existing managed release has the wrong version. Remove it before reinstalling.",
921 );
922 }
923 yield* report("verifying", "Checking the installed runtime.");
924 yield* validate(existing.executable, asset.version).pipe(
925 Effect.scoped,
926 withValidationTimeout,
927 );
928 yield* activate();
929 return;
930 }
931 }
932
933 const available = yield* Effect.tryPromise({
934 try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }),
935 catch: (cause) => installationError("download", "Could not check free disk space.", cause),
936 }).pipe(Effect.option);
937 const required = MAX_DOWNLOAD_BYTES + MAX_EXECUTABLE_BYTES + FREE_SPACE_MARGIN;
938 if (
939 Option.isSome(available) &&
940 available.value.bavail * available.value.bsize < BigInt(required)
941 ) {
942 return yield* installationError(
943 "download",
944 `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`,
945 );
946 }
947 const staging = yield* fs.makeTempDirectoryScoped({
948 directory: versionsDirectory,
949 prefix: ".install-",
950 });
951 yield* Effect.addFinalizer(() => unlockDirectoryTree(staging).pipe(Effect.ignore));
952 const archivePath = path.join(staging, "download");
953 const pairDirectory = path.join(staging, "runtime");
954 yield* fs.makeDirectory(pairDirectory);
955 const hash = NodeCrypto.createHash("sha512");
956 let downloadedBytes = 0;
957 let lastProgressAt = yield* Clock.currentTimeMillis;
958 yield* Effect.gen(function* () {
959 const response = yield* http
960 .execute(HttpClientRequest.get(asset.url))
961 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
962 yield* response.stream.pipe(
963 Stream.tap((chunk) =>
964 Effect.gen(function* () {
965 downloadedBytes += chunk.byteLength;
966 if (downloadedBytes > MAX_DOWNLOAD_BYTES) {
967 return yield* installationError(
968 "download",
969 "The Antigravity download exceeded its allowed size.",
970 );
971 }
972 hash.update(chunk);
973 const now = yield* Clock.currentTimeMillis;
974 if (now - lastProgressAt >= 250) {
975 lastProgressAt = now;
976 yield* SubscriptionRef.update(state, (current) => ({
977 ...current,
978 downloadedBytes,
979 }));
980 }
981 }),
982 ),
983 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
984 );
985 }).pipe(
986 Effect.timeout(DOWNLOAD_TIMEOUT),
987 Effect.mapError((cause) =>
988 HttpClientError.isHttpClientError(cause) || Cause.isTimeoutError(cause)
989 ? installationError(
990 "download",
991 "Could not download Antigravity from Google. Check the network connection and any proxy settings, then try again.",
992 cause,
993 )
994 : cause,
995 ),
996 );
997 if (hash.digest("hex") !== asset.sha512) {
998 return yield* installationError(
999 "download",
1000 "The Antigravity download failed its size or checksum check. Nothing was installed.",
1001 );
1002 }
1003
1004 yield* report("extracting", "Extracting the verified runtime.");
1005 const executablePath = path.join(pairDirectory, asset.executable.name);
1006 if (asset.format === "executable") {
1007 yield* fs.copyFile(archivePath, executablePath);
1008 } else {
1009 const tar = cliArchiveTarCommand(platform, environment);
1010 const list = yield* spawner.string(ChildProcess.make(tar, ["-tzf", archivePath]));
1011 const types = yield* spawner.string(ChildProcess.make(tar, ["-tvzf", archivePath]));
1012 if (
1013 list.trim() !== asset.executable.name ||
1014 types.trim().split(/\r?\n/u).length !== 1 ||
1015 !types.startsWith("-")
1016 ) {
1017 return yield* installationError(
1018 "extract",
1019 "The Antigravity archive must contain one regular executable.",
1020 );
1021 }
1022 yield* Effect.gen(function* () {
1023 const child = yield* spawner.spawn(
1024 ChildProcess.make(tar, ["-xOzf", archivePath, asset.executable.name], {
1025 stdout: "pipe",
1026 stderr: "pipe",
1027 }),
1028 );
1029 let extractedBytes = 0;
1030 yield* child.stdout.pipe(
1031 Stream.tap((chunk) =>
1032 Effect.gen(function* () {
1033 extractedBytes += chunk.byteLength;
1034 if (extractedBytes > MAX_EXECUTABLE_BYTES)
1035 return yield* installationError(
1036 "extract",
1037 "The Antigravity executable exceeded its size limit.",
1038 );
1039 }),
1040 ),
1041 Stream.run(fs.sink(executablePath, { flag: "wx", mode: 0o700 })),
1042 );
1043 if ((yield* child.exitCode) !== 0 || extractedBytes === 0)
1044 return yield* installationError(
1045 "extract",
1046 "Could not extract the Antigravity executable.",
1047 );
1048 }).pipe(Effect.scoped);
1049 }
1050 yield* fs.remove(archivePath);
1051 if (platform !== "win32") yield* fs.chmod(executablePath, 0o755);
1052 yield* report("verifying", "Checking the downloaded runtime.");
1053 yield* validate(
1054 {
1055 executablePath,
1056 source: "managed",
1057 version: asset.version,
1058 managedVersionDirectory: pairDirectory,
1059 },
1060 asset.version,
1061 ).pipe(Effect.scoped, withValidationTimeout);
1062 const record: InstalledRelease = {
1063 releaseId,
1064 version: asset.version,
1065 executable: {
1066 name: asset.executable.name,
1067 bytes: Number((yield* fs.stat(executablePath)).size),
1068 },
1069 };
1070 yield* fs.writeFileString(
1071 path.join(pairDirectory, RELEASE_RECORD),
1072 yield* encodeInstalledRelease(record),
1073 { flag: "wx", mode: 0o600 },
1074 );
1075 // Lock files read-only before publishing; the directory itself is locked after cross-parent rename
1076 // because macOS requires write permission on a moved directory to update its `..` entry.
1077 if (platform !== "win32") {
1078 yield* fs.chmod(executablePath, 0o555);
1079 yield* fs.chmod(path.join(pairDirectory, RELEASE_RECORD), 0o400);
1080 }
1081 const published = yield* Effect.scoped(
1082 Effect.gen(function* () {
1083 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
1084 directory: managedDirectory,
1085 prefix: "active.json.",
1086 });
1087 return yield* gate.withPermit(
1088 withManagedLock(
1089 "activate",
1090 Effect.gen(function* () {
1091 yield* ensureRealManagedRoot("activate");
1092 const destinationExisted =
1093 (yield* fs.exists(destination)) || (yield* isSymlink(destination));
1094 if (!destinationExisted) {
1095 const renameError = yield* fs.rename(pairDirectory, destination).pipe(
1096 retryWhileWindowsHoldsHandles,
1097 Effect.as(null),
1098 Effect.catch((cause) => Effect.succeed(cause)),
1099 );
1100 if (renameError === null) {
1101 const activateError = yield* writeAndActivate(pointerDirectory).pipe(
1102 Effect.as(null),
1103 Effect.catch((cause) => Effect.succeed(cause)),
1104 );
1105 if (activateError !== null) {
1106 yield* removeReleaseDirectory(destination).pipe(Effect.ignore);
1107 return yield* activateError;
1108 }
1109 return { _tag: "published" as const };
1110 }
1111 if (!(yield* fs.exists(destination)) && !(yield* isSymlink(destination))) {
1112 return yield* installationError(
1113 "activate",
1114 "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
1115 renameError,
1116 );
1117 }
1118 }
1119 const inspected = yield* inspectRelease(releaseId);
1120 if (inspected._tag === "valid") {
1121 if (inspected.executable.version !== asset.version) {
1122 return yield* installationError(
1123 "activate",
1124 "Another installation published a different Antigravity release.",
1125 );
1126 }
1127 return { _tag: "existing" as const, executable: inspected.executable };
1128 }
1129 // acquire() cannot lease a broken release, but an already-running session may hold one.
1130 if (leases.has(destination)) {
1131 return yield* installationError(
1132 "activate",
1133 "Stop Antigravity sessions and sign-in flows before reinstalling its managed runtime.",
1134 );
1135 }
1136 // Move the damaged release aside into staging so failure can restore it.
1137 const displaced = path.join(staging, "displaced");
1138 yield* unlockDirectoryTree(destination);
1139 yield* fs.rename(destination, displaced).pipe(
1140 retryWhileWindowsHoldsHandles,
1141 Effect.mapError((cause) =>
1142 installationError(
1143 "activate",
1144 "Could not replace the damaged Antigravity runtime. Check for open processes and try again.",
1145 cause,
1146 ),
1147 ),
1148 );
1149 const publishError = yield* fs.rename(pairDirectory, destination).pipe(
1150 retryWhileWindowsHoldsHandles,
1151 Effect.as(null),
1152 Effect.catch((cause) => Effect.succeed(cause)),
1153 );
1154 if (publishError !== null) {
1155 const restored = yield* fs.rename(displaced, destination).pipe(
1156 retryWhileWindowsHoldsHandles,
1157 Effect.as(true),
1158 Effect.orElseSucceed(() => false),
1159 );
1160 return yield* installationError(
1161 "activate",
1162 restored
1163 ? "Could not replace the damaged Antigravity runtime. The previous files were restored. Try again."
1164 : "Could not replace the damaged Antigravity runtime, and the damaged files could not be restored. Reinstall Antigravity.",
1165 publishError,
1166 );
1167 }
1168 const activateError = yield* writeAndActivate(pointerDirectory).pipe(
1169 Effect.as(null),
1170 Effect.catch((cause) => Effect.succeed(cause)),
1171 );
1172 if (activateError !== null) {
1173 const rolledBack = yield* Effect.gen(function* () {
1174 yield* removeReleaseDirectory(destination);
1175 yield* fs.rename(displaced, destination).pipe(retryWhileWindowsHoldsHandles);
1176 }).pipe(
1177 Effect.as(true),
1178 Effect.orElseSucceed(() => false),
1179 );
1180 return yield* installationError(
1181 "activate",
1182 rolledBack
1183 ? "Could not activate the repaired Antigravity runtime. The previous files were restored. Try again."
1184 : "Could not activate the repaired Antigravity runtime, and the damaged files could not be restored. Reinstall Antigravity.",
1185 activateError,
1186 );
1187 }
1188 return { _tag: "published" as const };
1189 }).pipe(
1190 Effect.mapError((error) =>
1191 isInstallationError(error)
1192 ? error
1193 : installationError(
1194 "activate",
1195 "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
1196 error,
1197 ),
1198 ),
1199 Effect.uninterruptible,
1200 ),
1201 ),
1202 );
1203 }),
1204 );
1205 if (published._tag === "existing") {
1206 yield* validate(published.executable, asset.version).pipe(
1207 Effect.scoped,
1208 withValidationTimeout,
1209 );
1210 yield* activate();
1211 }
1212 },
1213 Effect.scoped,
1214 Effect.mapError(
1215 wrapFailure(
1216 "install",
1217 "Could not install Antigravity. Check free disk space and directory access, then try again.",
1218 ),
1219 ),
1220 );
1221
1222 let lastUpdateCheck: number | undefined;
1223 const refreshRelease = Effect.fn("AntigravityInstallation.refreshRelease")(function* (
1224 explicit = false,
1225 ) {
1226 if (options.releaseAsset !== undefined || !supported) return;
1227 if (!explicit && !(yield* options.updateChecksEnabled ?? Effect.succeed(true))) return;
1228 const now = yield* Clock.currentTimeMillis;
1229 if (!explicit && lastUpdateCheck !== undefined && now - lastUpdateCheck < UPDATE_CHECK_INTERVAL)
1230 return;
1231 lastUpdateCheck = now;
1232 const musl =
1233 platform === "linux" &&
1234 (yield* fs.exists(
1235 arch === "arm64" ? "/lib/libc.musl-aarch64.so.1" : "/lib/libc.musl-x86_64.so.1",
1236 ));
1237 const target = antigravityCliTarget(platform, arch, musl);
1238 const latest = yield* http.get(`${ANTIGRAVITY_CLI_MANIFEST_BASE}/${target}.json`).pipe(
1239 Effect.flatMap(HttpClientResponse.filterStatusOk),
1240 Effect.flatMap((response) => response.json),
1241 Effect.map((json) => parseAntigravityCliRelease(json, platform, arch, musl)),
1242 Effect.timeout("10 seconds"),
1243 Effect.orElseSucceed(() => null),
1244 );
1245 if (latest === null) return;
1246 if (yield* isWithdrawn(latest.version)) {
1247 releaseAsset = null;
1248 return;
1249 }
1250 releaseAsset = latest;
1251 yield* SubscriptionRef.updateEffect(state, (value) =>
1252 isRunning(value)
1253 ? Effect.succeed(value)
1254 : Effect.gen(function* () {
1255 const keepInstalled =
1256 value.installedVersion !== null &&
1257 compareSemverVersions(value.installedVersion, latest.version) > 0 &&
1258 !(yield* isWithdrawn(value.installedVersion));
1259 return {
1260 ...value,
1261 version: keepInstalled ? value.installedVersion : latest.version,
1262 totalBytes: null,
1263 };
1264 }),
1265 );
1266 });
1267
1268 const start = Effect.gen(function* () {
1269 const current = yield* SubscriptionRef.get(state);
1270 if (isRunning(current)) return current;
1271 yield* refreshRelease(true);
1272 return yield* gate.withPermit(
1273 Effect.gen(function* () {
1274 const current = yield* SubscriptionRef.get(state);
1275 if (isRunning(current)) return current;
1276 if (!supported) {
1277 return yield* installationError(
1278 "start",
1279 `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
1280 );
1281 }
1282 const asset =
1283 releaseAsset !== null && !(yield* isWithdrawn(releaseAsset.version))
1284 ? releaseAsset
1285 : null;
1286 const installed = yield* resolve().pipe(Effect.option);
1287 const reuse =
1288 Option.isSome(installed) &&
1289 installed.value.source === "managed" &&
1290 (asset === null || compareSemverVersions(installed.value.version!, asset.version) > 0)
1291 ? installed.value
1292 : undefined;
1293 if (asset === null && reuse === undefined)
1294 return yield* installationError(
1295 "start",
1296 "Could not find a native Antigravity CLI release. Check the network connection and try again.",
1297 );
1298 const operationId = yield* random.uuidV4();
1299 const next: ProviderInstallState = {
1300 driver: DRIVER,
1301 operationId,
1302 phase: reuse === undefined ? "downloading" : "verifying",
1303 downloadedBytes: 0,
1304 totalBytes: null,
1305 version: reuse?.version ?? asset?.version ?? null,
1306 installedVersion: current.installedVersion,
1307 canRemove: current.canRemove,
1308 message:
1309 reuse === undefined
1310 ? "Downloading Google's official Antigravity runtime."
1311 : "Checking the installed runtime.",
1312 };
1313 yield* SubscriptionRef.set(state, next);
1314 const work = (
1315 reuse === undefined
1316 ? install(asset!)
1317 : validate(reuse, reuse.version!).pipe(
1318 Effect.scoped,
1319 withValidationTimeout,
1320 Effect.andThen(ensureEligible(reuse.version!)),
1321 Effect.andThen(
1322 SubscriptionRef.update(state, (value) => ({
1323 ...value,
1324 phase: "succeeded" as const,
1325 installedVersion: reuse.version,
1326 message: null,
1327 })),
1328 ),
1329 )
1330 ).pipe(
1331 Effect.mapError(
1332 wrapFailure("verify", "Could not verify the installed Antigravity runtime."),
1333 ),
1334 Effect.onExit((exit) =>
1335 Exit.isFailure(exit)
1336 ? SubscriptionRef.update(state, (value) => {
1337 if (value.operationId !== operationId || value.phase === "succeeded")
1338 return value;
1339 const error = Cause.findErrorOption(exit.cause);
1340 const cancelled = Cause.hasInterruptsOnly(exit.cause);
1341 return {
1342 ...value,
1343 phase: cancelled ? "cancelled" : "failed",
1344 message: cancelled
1345 ? "Installation cancelled. The previous runtime is unchanged."
1346 : Option.isSome(error)
1347 ? error.value.detail
1348 : "Could not finish the Antigravity installation. Check disk space and directory access.",
1349 } satisfies ProviderInstallState;
1350 })
1351 : Effect.void,
1352 ),
1353 Effect.ignoreCause,
1354 Effect.ensuring(
1355 Effect.sync(() => {
1356 if (running?.operationId === operationId) running = undefined;
1357 }),
1358 ),
1359 );
1360 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
1361 running = { operationId, fiber };
1362 return next;
1363 }).pipe(Effect.uninterruptible),
1364 );
1365 }).pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation.")));
1366
1367 const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) {
1368 return yield* gate.withPermit(
1369 Effect.gen(function* () {
1370 const current = yield* SubscriptionRef.get(state);
1371 if (current.operationId !== operationId) {
1372 return yield* installationError(
1373 "cancel",
1374 "This installation is no longer current. Refresh its status before cancelling.",
1375 );
1376 }
1377 if (running?.operationId === operationId && isRunning(current)) {
1378 yield* Fiber.interrupt(running.fiber);
1379 }
1380 return yield* SubscriptionRef.get(state);
1381 }),
1382 );
1383 });
1384
1385 const remove = Effect.fn("AntigravityInstallation.remove")(
1386 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
1387 yield* gate.withPermit(
1388 Effect.gen(function* () {
1389 if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) {
1390 return yield* installationError(
1391 "remove",
1392 "Stop Antigravity sessions and sign-in flows before removing its managed runtime.",
1393 );
1394 }
1395 if ((yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory))) {
1396 const homeDirectory = yield* HostProcess.HomeDirectory;
1397 yield* withManagedLock(
1398 "remove",
1399 Effect.gen(function* () {
1400 const managedIsSymlink = yield* isSymlink(managedDirectory);
1401 if (!managedIsSymlink) {
1402 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
1403 if (Option.isSome(realManaged)) {
1404 for (const binaryPath of protectedBinaryPaths) {
1405 const trimmed = binaryPath.trim();
1406 if (!trimmed) continue;
1407 const selected = yield* resolveUnlocked(trimmed).pipe(Effect.option);
1408 if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
1409 return yield* installationError(
1410 "remove",
1411 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
1412 );
1413 }
1414 const expanded = expandHomePath(trimmed, homeDirectory);
1415 const resolved = yield* fs.realPath(expanded).pipe(Effect.option);
1416 const candidate = Option.getOrElse(resolved, () => path.resolve(expanded));
1417 if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
1418 return yield* installationError(
1419 "remove",
1420 "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
1421 );
1422 }
1423 }
1424 }
1425 if (!(yield* isSymlink(versionsDirectory))) {
1426 yield* unlockDirectoryTree(versionsDirectory);
1427 }
1428 }
1429 yield* fs
1430 .remove(managedDirectory, { recursive: true, force: true })
1431 .pipe(retryWhileWindowsHoldsHandles);
1432 }),
1433 );
1434 }
1435 yield* SubscriptionRef.update(
1436 state,
1437 (current) =>
1438 ({
1439 ...current,
1440 operationId: null,
1441 phase: "idle",
1442 downloadedBytes: 0,
1443 installedVersion: null,
1444 canRemove: false,
1445 message: null,
1446 }) satisfies ProviderInstallState,
1447 );
1448 }).pipe(Effect.uninterruptible),
1449 );
1450 },
1451 Effect.mapError(
1452 wrapFailure(
1453 "remove",
1454 "Could not remove the managed Antigravity runtime. Check for open processes and try again.",
1455 ),
1456 ),
1457 );
1458
1459 yield* Effect.gen(function* () {
1460 const canRemove = (yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory));
1461 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
1462 if (!(yield* fs.exists(activePath))) return;
1463 yield* gate.withPermit(
1464 withManagedLock(
1465 "activate",
1466 Effect.gen(function* () {
1467 if (!(yield* fs.exists(activePath))) {
1468 const exists =
1469 (yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory));
1470 yield* SubscriptionRef.update(state, (current) => ({
1471 ...current,
1472 canRemove: exists,
1473 }));
1474 return;
1475 }
1476 yield* ensureRealManagedRoot("activate");
1477 const active = yield* readRecord(activePath, ActiveRelease);
1478 const installed = yield* completedRelease(active.releaseId);
1479 if (installed.managedVersionDirectory !== null) {
1480 yield* lockReleaseDirectory(
1481 installed.managedVersionDirectory,
1482 installed.executablePath,
1483 false,
1484 );
1485 }
1486 yield* SubscriptionRef.update(state, (current) => ({
1487 ...current,
1488 installedVersion: installed.version,
1489 }));
1490 }),
1491 ),
1492 );
1493 }).pipe(
1494 Effect.catch((cause) =>
1495 isLockContentionError(cause)
1496 ? Effect.void
1497 : SubscriptionRef.update(
1498 state,
1499 (current) =>
1500 ({
1501 ...current,
1502 phase: "failed",
1503 message: isInstallationError(cause)
1504 ? cause.detail
1505 : "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
1506 }) satisfies ProviderInstallState,
1507 ),
1508 ),
1509 );
1510
1511 // A startup install prunes when it activates; pruning now could delete the release it is verifying.
1512 if (!isRunning(yield* SubscriptionRef.get(state))) yield* pruneInactiveReleases;
1513
1514 return AntigravityInstallation.of({
1515 managedDirectory,
1516 resolve,
1517 acquire,
1518 compatibility,
1519 start,
1520 cancel,
1521 state: SubscriptionRef.get(state),
1522 changes: SubscriptionRef.changes(state),
1523 checkForUpdate: refreshRelease().pipe(Effect.ignore),
1524 remove,
1525 });
1526 });