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

AntigravityDriver.ts

511 lines20.1 KB

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