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

AntigravityDriver.ts

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