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

AntigravityDriver.ts

525 lines19.1 KB

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