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

AntigravityDriver.ts

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