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

AntigravityDriver.ts

526 lines19.2 KB

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