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

AntigravityDriver.ts

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