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

AntigravityDriver.ts

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