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

AntigravityDriver.ts

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