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

AntigravityDriver.ts

499 lines19.2 KB

1import { withAgentDeviceEnvironment } from "../../mcp/McpProviderSession.ts";
2import { AntigravitySettings, ProviderDriverKind, ProviderSetupError } from "@t3tools/contracts";
3import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import {
5 NodeRuntimeUnavailableError,
6 nodeRuntimeUnavailableMessage,
7} from "@t3tools/shared/nodeRuntime";
8import * as Crypto from "effect/Crypto";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import * as Schema from "effect/Schema";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
18import type { AcpError } from "effect-acp/errors";
19​
20import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
21import { ServerConfig } from "../../config.ts";
22import { ServerSettingsService } from "../../serverSettings.ts";
23import {
24 isAntigravityTextGenerationAvailable,
25 makeAntigravityTextGeneration,
26} from "../../textGeneration/AntigravityTextGeneration.ts";
27import { makeAntigravityAuth, type AntigravityAuth } from "../AntigravityAuth.ts";
28import { AntigravityInstallation } from "../AntigravityInstallation.ts";
29import {
30 antigravityAuthConfigIssue,
31 antigravityAuthLabel,
32 antigravityAuthUsesBrowser,
33 buildAntigravityAcpSpawnInput,
34 isAntigravitySignInRequiredError,
35 prepareAntigravityProfile,
36 resolveAntigravityInstanceDirectories,
37 type AntigravityAuthConfig,
38} from "../antigravityAuthSupport.ts";
39import {
40 makeAntigravityAcpRuntime,
41 type AntigravityAcpRuntimeInput,
42} from "../acp/AntigravityAcpSupport.ts";
43import type { AcpSessionRuntime, AcpSessionRuntimeStartResult } from "../acp/AcpSessionRuntime.ts";
44import type { ServerProviderDraft } from "../providerSnapshot.ts";
45import {
46 removeAntigravityRuntimeTempDirs,
47 removeAntigravitySessionFiles,
48} from "../acp/AntigravitySessionFiles.ts";
49import { ProviderDriverError } from "../Errors.ts";
50import { makeAntigravityAdapter } from "../Layers/AntigravityAdapter.ts";
51import { makeAntigravityProvider } from "../Layers/AntigravityProvider.ts";
52import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
53import * as ModelManifest from "../ModelManifest.ts";
54import {
55 defaultProviderContinuationIdentity,
56 type ProviderDriver,
57 type ProviderInstance,
58} from "../ProviderDriver.ts";
59import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
60import { withInstanceIdentity } from "./instanceIdentity.ts";
61import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";
62​
63const DRIVER = ProviderDriverKind.make("antigravity");
64const decodeSettings = Schema.decodeSync(AntigravitySettings);
65const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError);
66​
67export type AntigravityDriverEnv =
68 | AntigravityInstallation
69 | BackgroundPolicy.BackgroundPolicy
70 | ChildProcessSpawner.ChildProcessSpawner
71 | Crypto.Crypto
72 | FileSystem.FileSystem
73 | ModelManifest.ModelManifest
74 | Path.Path
75 | ProviderEventLoggers
76 | ServerConfig
77 | ServerSettingsService;
78​
79/** Each instance owns its Google profile. Executable releases are shared by the environment. */
80export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityDriverEnv> = {
81 driverKind: DRIVER,
82 metadata: { displayName: "Antigravity", supportsMultipleInstances: true },
83 configSchema: AntigravitySettings,
84 defaultConfig: () => decodeSettings({}),
85 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
86 Effect.gen(function* () {
87 const crypto = yield* Crypto.Crypto;
88 const fileSystem = yield* FileSystem.FileSystem;
89 const path = yield* Path.Path;
90 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
91 const serverConfig = yield* ServerConfig;
92 const installation = yield* AntigravityInstallation;
93 const loggers = yield* ProviderEventLoggers;
94 const modelManifest = yield* ModelManifest.ModelManifest;
95 const settings = { ...config, enabled } satisfies AntigravitySettings;
96 const auth: AntigravityAuthConfig = {
97 authMethod: settings.authMethod,
98 apiKey: settings.apiKey,
99 gcpProject: settings.gcpProject,
100 gcpLocation: settings.gcpLocation,
101 };
102 const authConfigIssue = antigravityAuthConfigIssue(auth);
103 const processEnvironment = mergeProviderInstanceEnvironment(environment);
104 const userHome = resolveAntigravityUserHome(yield* HostProcessPlatform, processEnvironment);
105 const directories = yield* resolveAntigravityInstanceDirectories(
106 serverConfig.stateDir,
107 instanceId,
108 ).pipe(
109 Effect.provideService(Crypto.Crypto, crypto),
110 Effect.provideService(Path.Path, path),
111 Effect.mapError(
112 (cause) =>
113 new ProviderDriverError({
114 driver: DRIVER,
115 instanceId,
116 detail: "Could not resolve the Antigravity profile directory.",
117 cause,
118 }),
119 ),
120 );
121 const profileDirectory = directories.profile;
122 // No process of this instance exists yet, so every runtime temp
123 // directory it owns is an orphan from a killed server. Older builds
124 // unpacked inside the profile.
125 for (const directory of [
126 directories.runtimeTemp,
127 path.join(profileDirectory, "antigravity-acp", "tmp"),
128 ]) {
129 yield* removeAntigravityRuntimeTempDirs(directory).pipe(
130 Effect.provideService(FileSystem.FileSystem, fileSystem),
131 );
132 }
133 const continuationIdentity = defaultProviderContinuationIdentity({
134 driverKind: DRIVER,
135 instanceId,
136 });
137 const stampIdentity = withInstanceIdentity({
138 instanceId,
139 driverKind: DRIVER,
140 displayName,
141 accentColor,
142 continuationGroupKey: continuationIdentity.continuationKey,
143 });
144 // Google returns every model the account can use, including older
145 // Gemini generations. The manifest names the current ones so the picker
146 // folds the rest under its legacy section, as it does for Codex.
147 const classifyModels = (draft: ServerProviderDraft) =>
148 modelManifest.current.pipe(
149 Effect.map((manifest) =>
150 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER)),
151 ),
152 );
153​
154 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
155 input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
156 ): Effect.fn.Return<
157 AcpSessionRuntime["Service"],
158 AcpError | ProviderSetupError,
159 Scope.Scope
160 > {
161 if (authConfigIssue !== null) {
162 return yield* new ProviderSetupError({
163 instanceId,
164 operation: "configure",
165 detail: authConfigIssue,
166 });
167 }
168 const executable = yield* installation
169 .acquire(settings.binaryPath, processEnvironment)
170 .pipe(
171 Effect.mapError(
172 (cause) =>
173 new ProviderSetupError({
174 instanceId,
175 operation: "resolve",
176 detail: cause.detail,
177 cause,
178 }),
179 ),
180 );
181 const profile = yield* prepareAntigravityProfile({
182 profileDirectory,
183 baseEnv: processEnvironment,
184 auth,
185 userHome,
186 tempDirectory: directories.runtimeTemp,
187 }).pipe(
188 Effect.provideService(FileSystem.FileSystem, fileSystem),
189 Effect.provideService(Path.Path, path),
190 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
191 Effect.mapError((cause) =>
192 isNodeRuntimeUnavailableError(cause.cause)
193 ? new ProviderSetupError({
194 instanceId,
195 operation: "start",
196 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
197 cause,
198 })
199 : cause,
200 ),
201 );
202 // Each process unpacks into its own directory that dies with the
203 // runtime scope, after the child is killed. A shared directory would
204 // let one session's teardown delete files a sibling still reads.
205 // Removal is best effort: a handle can outlive the kill on Windows,
206 // and the sweep on the next driver start reclaims what is left.
207 const runtimeTempDirectory = yield* Effect.acquireRelease(
208 fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
209 Effect.mapError(
210 (cause) =>
211 new ProviderSetupError({
212 instanceId,
213 operation: "start",
214 detail: "Could not create an Antigravity runtime temp directory.",
215 cause,
216 }),
217 ),
218 ),
219 (directory) =>
220 fileSystem
221 .remove(directory, { recursive: true, force: true })
222 .pipe(
223 Effect.catch(() =>
224 Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
225 ),
226 ),
227 );
228 const runtime = yield* makeAntigravityAcpRuntime({
229 ...input,
230 authMethod: auth.authMethod,
231 childProcessSpawner: spawner,
232 spawn: buildAntigravityAcpSpawnInput({
233 installation: executable,
234 profile,
235 cwd: input.cwd,
236 baseEnv: withAgentDeviceEnvironment(processEnvironment, input),
237 auth,
238 runtimeTempDirectory,
239 }),
240 }).pipe(Effect.provideService(Crypto.Crypto, crypto));
241 return {
242 ...runtime,
243 start: () =>
244 runtime
245 .start()
246 .pipe(
247 Effect.tapError((cause): Effect.Effect<void> =>
248 input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)
249 ? provider.onAuthRequired
250 : Effect.void,
251 ),
252 ),
253 };
254 });
255​
256 const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
257 input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
258 ) {
259 const cwd = yield* fileSystem
260 .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
261 .pipe(
262 Effect.mapError(
263 () =>
264 new ProviderSetupError({
265 instanceId,
266 operation: "start",
267 detail: "Could not create an Antigravity setup workspace.",
268 }),
269 ),
270 );
271 let sessionId: string | undefined;
272 yield* Effect.addFinalizer(() =>
273 removeAntigravitySessionFiles({
274 profileDirectory,
275 sessionId,
276 cwd,
277 }).pipe(
278 Effect.provideService(FileSystem.FileSystem, fileSystem),
279 Effect.provideService(Path.Path, path),
280 ),
281 );
282 const runtime = yield* makeRuntime({
283 cwd,
284 clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" },
285 mcpServers: [],
286 ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
287 });
288 return {
289 ...runtime,
290 start: () =>
291 runtime.start().pipe(
292 Effect.tap((started) =>
293 Effect.sync(() => {
294 sessionId = started.sessionId;
295 }),
296 ),
297 ),
298 };
299 });
300​
301 const publishCatalog = (
302 started: AcpSessionRuntimeStartResult,
303 runtime: Pick<AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,
304 ): Effect.Effect<void> =>
305 Effect.gen(function* () {
306 yield* provider.onSessionStarted(started);
307 yield* Stream.runForEach(runtime.getEvents(), (event) => {
308 if (event._tag === "EventStreamBarrier") {
309 return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
310 }
311 if (event._tag === "ConfigOptionsUpdated") {
312 return provider.onConfigOptionsUpdated(event.configOptions);
313 }
314 return event._tag === "AvailableCommandsUpdated"
315 ? provider.onAvailableCommands(event.availableCommands)
316 : Effect.void;
317 }).pipe(Effect.forkScoped);
318 yield* runtime.drainEvents;
319 }).pipe(Effect.scoped);
320​
321 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
322 instanceId,
323 makeRuntime: makeDisposableRuntime,
324 onAuthenticated: publishCatalog,
325 onSignedOut: Effect.suspend(() => provider.onSignedOut),
326 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
327 });
328​
329 // Kick the TTL-gated manifest refresh alongside the health check, as
330 // Codex and Claude do. Without it an environment that only runs
331 // Antigravity would keep classifying against a stale disk cache.
332 // The probe must not spawn. The agent is a PyInstaller one-file bundle
333 // that unpacks about 1 GB per launch, and the health check runs every
334 // minute. Resolving the install on disk is enough to report installed
335 // and version. The response below is synthetic: only agentInfo.version
336 // is read from it. Sessions and manual refreshes still spawn.
337 const probe = Effect.gen(function* () {
338 yield* modelManifest.refreshInBackground;
339 if (authConfigIssue !== null) {
340 return yield* new ProviderSetupError({
341 instanceId,
342 operation: "configure",
343 detail: authConfigIssue,
344 });
345 }
346 const executable = yield* installation
347 .resolve(settings.binaryPath, processEnvironment)
348 .pipe(
349 Effect.mapError(
350 (cause) =>
351 new ProviderSetupError({
352 instanceId,
353 operation: "resolve",
354 detail: cause.detail,
355 cause,
356 }),
357 ),
358 );
359 return {
360 protocolVersion: 1,
361 agentCapabilities: {
362 loadSession: true,
363 promptCapabilities: { image: true, audio: true, embeddedContext: true },
364 sessionCapabilities: { list: {}, resume: {} },
365 },
366 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
367 agentInfo: {
368 name: "antigravity-acp",
369 title: "Google Antigravity",
370 version: executable.version ?? "unknown",
371 },
372 };
373 });
374​
375 const provider = yield* makeAntigravityProvider(settings, {
376 stampIdentity: classifyModels,
377 probe,
378 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
379 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
380 Effect.provideService(FileSystem.FileSystem, fileSystem),
381 Effect.provideService(Path.Path, path),
382 Effect.orElseSucceed(() => false),
383 ),
384 }).pipe(
385 Effect.mapError(
386 (cause) =>
387 new ProviderDriverError({
388 driver: DRIVER,
389 instanceId,
390 detail: "Could not prepare the Antigravity provider status.",
391 cause,
392 }),
393 ),
394 );
395 const defaultModel = modelManifest.current.pipe(
396 Effect.map((manifest) => ModelManifest.manifestDefaultModel(manifest, DRIVER)),
397 );
398 const adapter = yield* makeAntigravityAdapter(settings, {
399 instanceId,
400 makeRuntime,
401 withProcess: authFlow.withProcess,
402 defaultModel,
403 onSessionStarted: provider.onSessionStarted,
404 onConfigOptionsUpdated: provider.onConfigOptionsUpdated,
405 onAvailableCommands: provider.onAvailableCommands,
406 onAuthRequired: provider.onAuthRequired,
407 ...(loggers.native ? { nativeEventLogger: loggers.native } : {}),
408 });
409 const textGeneration = yield* makeAntigravityTextGeneration({
410 profileDirectory,
411 defaultModel,
412 withProcess: authFlow.withProcess,
413 makeRuntime: (cwd) =>
414 makeRuntime({
415 cwd,
416 clientInfo: { name: "t3-code-text", version: "0.0.0" },
417 mcpServers: [],
418 }),
419 });
420​
421 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
422 function* () {
423 const processScope = yield* Scope.make();
424 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
425 yield* authFlow
426 .withProcess(
427 Scope.close(processScope, Exit.void),
428 Effect.gen(function* () {
429 const runtime = yield* makeDisposableRuntime({});
430 const started = yield* runtime.start();
431 yield* publishCatalog(started, runtime);
432 }),
433 )
434 .pipe(Effect.provideService(Scope.Scope, processScope));
435 },
436 Effect.scoped,
437 Effect.timeoutOrElse({
438 duration: "90 seconds",
439 orElse: () =>
440 Effect.fail(
441 new ProviderDriverError({
442 driver: DRIVER,
443 instanceId,
444 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
445 }),
446 ),
447 }),
448 Effect.tapError((cause) =>
449 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
450 ),
451 Effect.mapError((cause) =>
452 cause._tag === "ProviderDriverError"
453 ? cause
454 : new ProviderDriverError({
455 driver: DRIVER,
456 instanceId,
457 detail: isAntigravitySignInRequiredError(cause)
458 ? "Sign in to Antigravity in provider settings before refreshing models."
459 : cause._tag === "ProviderSetupError" &&
460 (cause.operation === "configure" || cause.operation === "start")
461 ? cause.detail
462 : "Could not refresh Antigravity models. The previous model list is unchanged.",
463 cause,
464 }),
465 ),
466 );
467​
468 return {
469 instanceId,
470 driverKind: DRIVER,
471 continuationIdentity,
472 displayName,
473 accentColor,
474 enabled,
475 snapshot: provider.snapshot,
476 snapshotForCwd: (cwd) =>
477 !enabled
478 ? provider.snapshot.getSnapshot
479 : discoverAntigravitySkills({ cwd, userHome }).pipe(
480 Effect.provideService(FileSystem.FileSystem, fileSystem),
481 Effect.provideService(Path.Path, path),
482 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
483 Effect.mapError(
484 (cause) =>
485 new ProviderDriverError({
486 driver: DRIVER,
487 instanceId,
488 detail: "Could not read Antigravity workspace skills.",
489 cause,
490 }),
491 ),
492 ),
493 adapter,
494 textGeneration,
495 auth: authFlow.controller,
496 refreshModels,
497 } satisfies ProviderInstance;
498 }),
499};