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

AntigravityDriver.ts

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