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

AntigravityDriver.ts

553 lines20.3 KB

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