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

AntigravityDriver.ts

464 lines18.0 KB

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