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

AntigravityDriver.ts

544 lines20.0 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 removeAntigravitySessionFiles,
50 retireAntigravityRuntimeTempDirs,
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 const removeRetired = yield* retireAntigravityRuntimeTempDirs(directory).pipe(
154 Effect.provideService(FileSystem.FileSystem, fileSystem),
155 Effect.provideService(Path.Path, path),
156 );
157 yield* Effect.forkScoped(removeRetired);
158 }
159 const continuationIdentity = defaultProviderContinuationIdentity({
160 driverKind: DRIVER,
161 instanceId,
162 });
163 const stampIdentity = withInstanceIdentity({
164 instanceId,
165 driverKind: DRIVER,
166 displayName,
167 accentColor,
168 continuationGroupKey: continuationIdentity.continuationKey,
169 });
170 const classifyModels = (draft: ServerProviderDraft) =>
171 currentCatalog.pipe(
172 Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),
173 );
174​
175 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
176 input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
177 ): Effect.fn.Return<
178 AcpSessionRuntime.AcpSessionRuntime["Service"],
179 AcpError | ProviderSetupError,
180 Scope.Scope
181 > {
182 if (authConfigIssue !== null) {
183 return yield* new ProviderSetupError({
184 instanceId,
185 operation: "configure",
186 detail: authConfigIssue,
187 });
188 }
189 const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe(
190 Effect.mapError(
191 (cause) =>
192 new ProviderSetupError({
193 instanceId,
194 operation: "resolve",
195 detail: cause.detail,
196 cause,
197 }),
198 ),
199 );
200 const profile = yield* prepareAntigravityProfile({
201 profileDirectory,
202 baseEnv: processEnvironment,
203 auth,
204 userHome,
205 tempDirectory: directories.runtimeTemp,
206 }).pipe(
207 Effect.provideService(FileSystem.FileSystem, fileSystem),
208 Effect.provideService(Path.Path, path),
209 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
210 Effect.mapError((cause) =>
211 isNodeRuntimeUnavailableError(cause.cause)
212 ? new ProviderSetupError({
213 instanceId,
214 operation: "start",
215 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
216 cause,
217 })
218 : cause,
219 ),
220 );
221 // Use one directory per process; shared cleanup could delete files another session still reads.
222 // Remove after the child dies, best-effort on Windows where handles may outlive the kill;
223 // the next driver start sweeps leftovers.
224 const runtimeTempDirectory = yield* Effect.acquireRelease(
225 fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
226 Effect.mapError(
227 (cause) =>
228 new ProviderSetupError({
229 instanceId,
230 operation: "start",
231 detail: "Could not create an Antigravity runtime temp directory.",
232 cause,
233 }),
234 ),
235 ),
236 (directory) =>
237 fileSystem
238 .remove(directory, { recursive: true, force: true })
239 .pipe(
240 Effect.catch(() =>
241 Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
242 ),
243 ),
244 );
245 const runtime = yield* makeAntigravityAcpRuntime({
246 ...input,
247 runtimeVersion: executable.version,
248 authMethod: auth.authMethod,
249 childProcessSpawner: spawner,
250 spawn: buildAntigravityAcpSpawnInput({
251 installation: executable,
252 profile,
253 cwd: input.cwd,
254 baseEnv: processEnvironment,
255 auth,
256 runtimeTempDirectory,
257 }),
258 }).pipe(Effect.provideService(Crypto.Crypto, crypto));
259 return {
260 ...runtime,
261 start: () =>
262 runtime
263 .start()
264 .pipe(
265 Effect.tapError((cause): Effect.Effect<void> =>
266 input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)
267 ? provider.onAuthRequired
268 : Effect.void,
269 ),
270 ),
271 };
272 });
273​
274 const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
275 input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
276 ) {
277 const cwd = yield* fileSystem
278 .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
279 .pipe(
280 Effect.mapError(
281 () =>
282 new ProviderSetupError({
283 instanceId,
284 operation: "start",
285 detail: "Could not create an Antigravity setup workspace.",
286 }),
287 ),
288 );
289 let sessionId: string | undefined;
290 yield* Effect.addFinalizer(() =>
291 removeAntigravitySessionFiles({
292 profileDirectory,
293 sessionId,
294 cwd,
295 }).pipe(
296 Effect.provideService(FileSystem.FileSystem, fileSystem),
297 Effect.provideService(Path.Path, path),
298 ),
299 );
300 const runtime = yield* makeRuntime({
301 cwd,
302 mcpServers: [],
303 ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
304 });
305 return {
306 ...runtime,
307 start: () =>
308 runtime.start().pipe(
309 Effect.tap((started) =>
310 Effect.sync(() => {
311 sessionId = started.sessionId;
312 }),
313 ),
314 ),
315 };
316 });
317​
318 const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* (
319 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
320 runtime: Pick<
321 AcpSessionRuntime.AcpSessionRuntime["Service"],
322 "getEvents" | "drainEvents" | "setModel"
323 >,
324 ) {
325 yield* provider.onSessionStarted(started);
326 yield* Stream.runForEach(runtime.getEvents(), (event) => {
327 if (event._tag === "EventStreamBarrier") {
328 return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
329 }
330 if (event._tag === "ConfigOptionsUpdated") {
331 return provider.onConfigOptionsUpdated(event.configOptions);
332 }
333 return event._tag === "AvailableCommandsUpdated"
334 ? provider.onAvailableCommands(event.availableCommands)
335 : Effect.void;
336 }).pipe(Effect.forkScoped);
337 // Thinking levels differ per model and are reported only for the selected one.
338 const configOptions = started.sessionSetupResult.configOptions ?? [];
339 const current = configOptions.find((option) => option.id === "model")?.currentValue;
340 if (antigravityThinkingConfig(configOptions) !== undefined && typeof current === "string") {
341 for (const model of [...antigravityModelOptions(configOptions), { value: current }]) {
342 yield* runtime.setModel(model.value).pipe(Effect.ignore);
343 }
344 }
345 yield* runtime.drainEvents;
346 }, Effect.scoped);
347​
348 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
349 instanceId,
350 makeRuntime: makeDisposableRuntime,
351 // A new sign-in may be another account; drop any in-flight quota read first.
352 onAuthenticated: (started, runtime) =>
353 Effect.suspend(() => provider.onSignedIn).pipe(
354 Effect.andThen(publishCatalog(started, runtime)),
355 ),
356 onSignedOut: Effect.suspend(() => provider.onSignedOut),
357 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
358 });
359​
360 // The probe must not spawn. The agent is a PyInstaller one-file bundle
361 // that unpacks about 1 GB per launch, and the health check runs every
362 // minute.
363 const probe = Effect.gen(function* () {
364 yield* modelCatalog.refreshInBackground;
365 if (authConfigIssue !== null) {
366 return yield* new ProviderSetupError({
367 instanceId,
368 operation: "configure",
369 detail: authConfigIssue,
370 });
371 }
372 const executable = yield* installation.resolve(settings.binaryPath, processEnvironment).pipe(
373 Effect.mapError(
374 (cause) =>
375 new ProviderSetupError({
376 instanceId,
377 operation: "resolve",
378 detail: cause.detail,
379 cause,
380 }),
381 ),
382 );
383 return {
384 protocolVersion: 1,
385 agentCapabilities: {
386 loadSession: true,
387 promptCapabilities: { image: true, audio: true, embeddedContext: true },
388 sessionCapabilities: { list: {}, resume: {} },
389 },
390 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
391 agentInfo: {
392 name: "antigravity-acp",
393 title: "Google Antigravity",
394 version: executable.version ?? "unknown",
395 },
396 };
397 });
398​
399 const usage = yield* makeAntigravityUsageProbe({
400 profileDirectory,
401 authMethod: auth.authMethod,
402 }).pipe(
403 Effect.provideService(FileSystem.FileSystem, fileSystem),
404 Effect.provideService(Path.Path, path),
405 Effect.provideService(Crypto.Crypto, crypto),
406 Effect.provideService(HttpClient.HttpClient, httpClient),
407 );
408 const provider = yield* makeAntigravityProvider(settings, {
409 stampIdentity: classifyModels,
410 probe,
411 probeUsage: usage.probe,
412 clearUsage: usage.clear,
413 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
414 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
415 Effect.provideService(FileSystem.FileSystem, fileSystem),
416 Effect.provideService(Path.Path, path),
417 Effect.orElseSucceed(() => false),
418 ),
419 }).pipe(
420 Effect.mapError(
421 (cause) =>
422 new ProviderDriverError({
423 driver: DRIVER,
424 instanceId,
425 detail: "Could not prepare the Antigravity provider status.",
426 cause,
427 }),
428 ),
429 );
430 const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
431 const orchestrationAdapter = yield* makeAntigravityAdapterV2({
432 instanceId,
433 selfInvocation,
434 makeRuntime,
435 withProcess: authFlow.withProcess,
436 defaultModel,
437 profileDirectory,
438 onSessionStarted: provider.onSessionStarted,
439 onSessionEvent: (event) => {
440 if (event._tag === "ConfigOptionsUpdated") {
441 return provider.onConfigOptionsUpdated(event.configOptions);
442 }
443 return event._tag === "AvailableCommandsUpdated"
444 ? provider.onAvailableCommands(event.availableCommands)
445 : Effect.void;
446 },
447 continuationRequests,
448 nativeLogging: (threadId) =>
449 makeNativeLogger({
450 nativeEventLogger: loggers.native,
451 provider: DRIVER,
452 threadId,
453 }),
454 });
455 const textGeneration = yield* makeAntigravityTextGeneration({
456 profileDirectory,
457 defaultModel,
458 withProcess: authFlow.withProcess,
459 makeRuntime: (cwd) =>
460 makeRuntime({
461 cwd,
462 mcpServers: [],
463 }),
464 });
465​
466 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
467 function* () {
468 const processScope = yield* Scope.make();
469 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
470 yield* authFlow
471 .withProcess(
472 Scope.close(processScope, Exit.void),
473 Effect.gen(function* () {
474 const runtime = yield* makeDisposableRuntime({});
475 const started = yield* runtime.start();
476 yield* publishCatalog(started, runtime);
477 }),
478 )
479 .pipe(Effect.provideService(Scope.Scope, processScope));
480 },
481 Effect.scoped,
482 Effect.timeoutOrElse({
483 duration: "90 seconds",
484 orElse: () =>
485 Effect.fail(
486 new ProviderDriverError({
487 driver: DRIVER,
488 instanceId,
489 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
490 }),
491 ),
492 }),
493 Effect.tapError((cause) =>
494 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
495 ),
496 Effect.mapError((cause) =>
497 cause._tag === "ProviderDriverError"
498 ? cause
499 : new ProviderDriverError({
500 driver: DRIVER,
501 instanceId,
502 detail: isAntigravitySignInRequiredError(cause)
503 ? "Sign in to Antigravity in provider settings before refreshing models."
504 : cause._tag === "ProviderSetupError" &&
505 (cause.operation === "configure" || cause.operation === "start")
506 ? cause.detail
507 : "Could not refresh Antigravity models. The previous model list is unchanged.",
508 cause,
509 }),
510 ),
511 );
512​
513 return {
514 instanceId,
515 driverKind: DRIVER,
516 continuationIdentity,
517 displayName,
518 accentColor,
519 enabled,
520 snapshot: provider.snapshot,
521 snapshotForCwd: (cwd) =>
522 !enabled
523 ? provider.snapshot.getSnapshot
524 : discoverAntigravitySkills({ cwd, userHome }).pipe(
525 Effect.provideService(FileSystem.FileSystem, fileSystem),
526 Effect.provideService(Path.Path, path),
527 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
528 Effect.mapError(
529 (cause) =>
530 new ProviderDriverError({
531 driver: DRIVER,
532 instanceId,
533 detail: "Could not read Antigravity workspace skills.",
534 cause,
535 }),
536 ),
537 ),
538 orchestrationAdapter,
539 textGeneration,
540 auth: authFlow.controller,
541 refreshModels,
542 } satisfies ProviderInstance;
543 }),
544};