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

AntigravityDriver.ts

512 lines19.9 KB

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