The best way to control Claude Code, Codex and more from any computer or phone

main
ts 715 lines 26.8 KB
Raw
1 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
2 import {
3 AntigravitySettings,
4 ProviderDriverKind,
5 ProviderSetupError,
6 settingsSecretLiteral,
7 } from "@t3tools/contracts";
8 import * as HostProcess from "@t3tools/shared/HostProcess";
9 import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
10 import {
11 NodeRuntimeUnavailableError,
12 nodeRuntimeUnavailableMessage,
13 } from "@t3tools/shared/nodeRuntime";
14 import * as Digest from "effect/crypto/Digest";
15 import * as SecureRandom from "effect/crypto/SecureRandom";
16 import * as Deferred from "effect/Deferred";
17 import * as Effect from "effect/Effect";
18 import * as Exit from "effect/Exit";
19 import * as Fiber from "effect/Fiber";
20 import * as FileSystem from "effect/FileSystem";
21 import * as Path from "effect/Path";
22 import * as Schema from "effect/Schema";
23 import * as Scope from "effect/Scope";
24 import * as Stream from "effect/Stream";
25 import * as ChildProcess from "effect/process/ChildProcess";
26 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
27 import { HttpClient } from "effect/http";
28 import * as AcpErrors from "effect-acp/errors";
29
30 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
31 import {
32 isAntigravityTextGenerationAvailable,
33 makeAntigravityTextGeneration,
34 } from "../../textGeneration/AntigravityTextGeneration.ts";
35 import { makeAntigravityAuth, type AntigravityAuth } from "../AntigravityAuth.ts";
36 import * as AntigravityInstallation from "../AntigravityInstallation.ts";
37 import { brokenRuntimeError } from "../providerCompatibility.ts";
38 import * as AntigravityUsage from "./AntigravityUsage.ts";
39 import {
40 antigravityAuthConfigIssue,
41 antigravityAuthLabel,
42 antigravityAuthUsesBrowser,
43 buildAntigravityAcpSpawnInput,
44 isAntigravitySignInRequiredError,
45 prepareAntigravityProfile,
46 resolveAntigravityInstanceDirectories,
47 type AntigravityAuthConfig,
48 } from "../antigravityAuthSupport.ts";
49 import {
50 antigravityModelOptions,
51 antigravitySessionMode,
52 antigravityThinkingConfig,
53 makeAntigravityAcpRuntime,
54 type AntigravityAcpRuntimeInput,
55 } from "../acp/AntigravityAcpSupport.ts";
56 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
57 import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
58 import {
59 removeAntigravitySessionFiles,
60 retireAntigravityRuntimeTempDirs,
61 } from "../acp/AntigravitySessionFiles.ts";
62 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
63 import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
64 import {
65 makeAntigravityAdapterV2,
66 type AntigravityAdapterV2RuntimeInput,
67 } from "../../orchestration-v2/Adapters/AntigravityAdapterV2.ts";
68 import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
69 import { ProviderDriverError } from "../Errors.ts";
70 import { makeAntigravityProvider } from "../AntigravityProvider.ts";
71 import { makeAntigravityUsageProbe } from "../antigravityUsageLimits.ts";
72 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
73 import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
74 import {
75 defaultProviderContinuationIdentity,
76 type ProviderDriver,
77 type ProviderInstance,
78 } from "@t3tools/provider-core/server/driver";
79 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
80 import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
81 import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts";
82
83 const DRIVER = ProviderDriverKind.make("antigravity");
84 const decodeSettings = Schema.decodeSync(AntigravitySettings);
85 const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError);
86 const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
87 const isProviderSetupError = Schema.is(ProviderSetupError);
88 const isAcpErrorDetails = Schema.is(Schema.Struct({ details: Schema.String }));
89 const REFRESH_FAILED =
90 "Could not refresh Antigravity models. The previous model list is unchanged.";
91 const PYTHON_SOCKS_REQUIRED = "python-socks is required to use a SOCKS proxy";
92
93 // Keep upstream diagnostics in cause; only recognized, fixed text reaches clients.
94 function refreshFailureDetail(cause: unknown) {
95 return isAcpRequestError(cause) &&
96 cause.operation === "receive-response" &&
97 isAcpErrorDetails(cause.data) &&
98 cause.data.details.includes(PYTHON_SOCKS_REQUIRED)
99 ? `${REFRESH_FAILED} Antigravity reported: ${PYTHON_SOCKS_REQUIRED}`
100 : REFRESH_FAILED;
101 }
102
103 export type AntigravityDriverEnv =
104 | AntigravityInstallation.AntigravityInstallation
105 | ProviderHost.ProviderHost
106 | ChildProcessSpawner.ChildProcessSpawner
107 | Digest.Digest
108 | SecureRandom.SecureRandom
109 | FileSystem.FileSystem
110 | HttpClient.HttpClient
111 | IdAllocator.IdAllocatorV2
112 | McpProviderSessions.McpProviderSessions
113 | ModelCatalog.ModelCatalog
114 | Path.Path
115 | ProviderEventLoggers.ProviderEventLoggers;
116
117 export const AntigravityDriver: ProviderDriver<
118 AntigravitySettings,
119 AntigravityDriverEnv,
120 AntigravityUsage.AntigravityUsage
121 > = {
122 driverKind: DRIVER,
123 metadata: { displayName: "Antigravity", supportsMultipleInstances: true },
124 configSchema: AntigravitySettings,
125 defaultConfig: () => decodeSettings({}),
126 usage: AntigravityUsage.antigravityUsageReader,
127 create: Effect.fn("AntigravityDriver.create")(function* ({
128 instanceId,
129 displayName,
130 accentColor,
131 environment,
132 enabled,
133 config,
134 }) {
135 const digest = yield* Digest.Digest;
136 const random = yield* SecureRandom.SecureRandom;
137 const fileSystem = yield* FileSystem.FileSystem;
138 const httpClient = yield* HttpClient.HttpClient;
139 const path = yield* Path.Path;
140 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
141 const host = yield* ProviderHost.ProviderHost;
142 const selfInvocation = yield* resolveSelfInvocation();
143 const installation = yield* AntigravityInstallation.AntigravityInstallation;
144 const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
145 const modelCatalog = yield* ModelCatalog.ModelCatalog;
146 const currentCatalog = modelCatalog.current(DRIVER);
147 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
148 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
149 const settings = { ...config, enabled } satisfies AntigravitySettings;
150 const auth: AntigravityAuthConfig = {
151 authMethod: settings.authMethod,
152 // The instance registry has already read a referenced key from its secret provider.
153 apiKey: settingsSecretLiteral(settings.apiKey),
154 gcpProject: settings.gcpProject,
155 gcpLocation: settings.gcpLocation,
156 };
157 const authConfigIssue = antigravityAuthConfigIssue(auth);
158 const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);
159 const userHome = resolveAntigravityUserHome(
160 yield* HostProcess.Platform,
161 processEnvironment,
162 yield* HostProcess.HomeDirectory,
163 );
164 const directories = yield* resolveAntigravityInstanceDirectories(
165 host.paths.stateDir,
166 instanceId,
167 ).pipe(
168 Effect.provideService(Digest.Digest, digest),
169 Effect.provideService(Path.Path, path),
170 Effect.mapError(
171 (cause) =>
172 new ProviderDriverError({
173 driver: DRIVER,
174 instanceId,
175 detail: "Could not resolve the Antigravity profile directory.",
176 cause,
177 }),
178 ),
179 );
180 const profileDirectory = directories.profile;
181 for (const directory of [
182 directories.runtimeTemp,
183 path.join(profileDirectory, "antigravity-acp", "tmp"),
184 ]) {
185 const removeRetired = yield* retireAntigravityRuntimeTempDirs(directory).pipe(
186 Effect.provideService(FileSystem.FileSystem, fileSystem),
187 Effect.provideService(Path.Path, path),
188 );
189 yield* Effect.forkScoped(removeRetired);
190 }
191 const continuationIdentity = defaultProviderContinuationIdentity({
192 driverKind: DRIVER,
193 instanceId,
194 });
195 const stampIdentity = withInstanceIdentity({
196 instanceId,
197 driverKind: DRIVER,
198 displayName,
199 accentColor,
200 continuationGroupKey: continuationIdentity.continuationKey,
201 });
202 const classifyModels = (draft: ServerProviderDraft) =>
203 currentCatalog.pipe(
204 Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),
205 );
206
207 const prepareSpawn = Effect.fn("AntigravityDriver.prepareSpawn")(function* (
208 cwd: string,
209 baseEnv: NodeJS.ProcessEnv,
210 ): Effect.fn.Return<
211 {
212 readonly executable: AntigravityInstallation.AntigravityExecutable;
213 readonly spawn: AcpSessionRuntime.AcpSpawnInput;
214 },
215 AcpErrors.AcpError | ProviderSetupError,
216 Scope.Scope
217 > {
218 if (authConfigIssue !== null) {
219 return yield* new ProviderSetupError({
220 instanceId,
221 operation: "configure",
222 detail: authConfigIssue,
223 });
224 }
225 const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe(
226 Effect.mapError(
227 (cause) =>
228 new ProviderSetupError({
229 instanceId,
230 operation: "resolve",
231 detail: cause.detail,
232 cause,
233 }),
234 ),
235 );
236 const profile = yield* prepareAntigravityProfile({
237 profileDirectory,
238 baseEnv: processEnvironment,
239 auth,
240 userHome,
241 tempDirectory: directories.runtimeTemp,
242 }).pipe(
243 Effect.provideService(FileSystem.FileSystem, fileSystem),
244 Effect.provideService(Path.Path, path),
245 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
246 Effect.mapError((cause) =>
247 isNodeRuntimeUnavailableError(cause.cause)
248 ? new ProviderSetupError({
249 instanceId,
250 operation: "start",
251 detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
252 cause,
253 })
254 : cause,
255 ),
256 );
257 // Use one directory per process; shared cleanup could delete files another session still reads.
258 // Remove after the child dies, best-effort on Windows where handles may outlive the kill;
259 // the next driver start sweeps leftovers.
260 const runtimeTempDirectory = yield* Effect.acquireRelease(
261 fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
262 Effect.mapError(
263 (cause) =>
264 new ProviderSetupError({
265 instanceId,
266 operation: "start",
267 detail: "Could not create an Antigravity runtime temp directory.",
268 cause,
269 }),
270 ),
271 ),
272 (directory) =>
273 fileSystem
274 .remove(directory, { recursive: true, force: true })
275 .pipe(
276 Effect.catch(() =>
277 Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
278 ),
279 ),
280 );
281 return {
282 executable,
283 spawn: buildAntigravityAcpSpawnInput({
284 installation: executable,
285 profile,
286 cwd,
287 baseEnv,
288 auth,
289 runtimeTempDirectory,
290 }),
291 };
292 });
293
294 const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
295 input: AntigravityAdapterV2RuntimeInput,
296 ): Effect.fn.Return<
297 AcpSessionRuntime.AcpSessionRuntime["Service"],
298 AcpErrors.AcpError | ProviderSetupError,
299 Scope.Scope
300 > {
301 // `buildAntigravityAcpSpawnInput` sets `extendEnv: false`, so thread variables only reach the
302 // agent's shell through `baseEnv`.
303 const { processEnvironment: threadEnvironment, ...runtimeInput } = input;
304 const { executable, spawn } = yield* prepareSpawn(
305 runtimeInput.cwd,
306 threadEnvironment === undefined
307 ? processEnvironment
308 : { ...processEnvironment, ...threadEnvironment },
309 );
310 const runtime = yield* makeAntigravityAcpRuntime({
311 ...runtimeInput,
312 runtimeVersion: executable.version,
313 authMethod: auth.authMethod,
314 childProcessSpawner: spawner,
315 spawn,
316 }).pipe(Effect.provideService(SecureRandom.SecureRandom, random));
317 // A custom or PATH executable has no version until it answers initialize.
318 const startCompatible = Effect.fn("AntigravityDriver.startCompatible")(function* () {
319 const version = (yield* runtime.initialize()).agentInfo?.version;
320 const advisory = version ? yield* installation.compatibility(version) : undefined;
321 const refused =
322 version &&
323 brokenRuntimeError({
324 instanceId,
325 name: "Antigravity",
326 version,
327 advisory,
328 action:
329 executable.source === "managed"
330 ? "Update it in Antigravity setup"
331 : `Update the Antigravity executable at ${executable.executablePath}`,
332 });
333 if (refused) {
334 return yield* new AcpErrors.AcpTransportError({ detail: refused.detail, cause: refused });
335 }
336 return yield* runtime.start();
337 });
338 return {
339 ...runtime,
340 setMode: (modeId: string) =>
341 runtime.getModeState.pipe(
342 Effect.flatMap((modeState) =>
343 runtime.setMode(antigravitySessionMode(modeId, modeState)),
344 ),
345 ),
346 start: () =>
347 startCompatible().pipe(
348 Effect.tapError((cause): Effect.Effect<void> =>
349 runtimeInput.onAuthorizationUrl === undefined &&
350 isAntigravitySignInRequiredError(cause)
351 ? provider.onAuthRequired
352 : Effect.void,
353 ),
354 ),
355 };
356 });
357
358 const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
359 input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
360 ) {
361 const cwd = yield* fileSystem
362 .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
363 .pipe(
364 Effect.mapError(
365 () =>
366 new ProviderSetupError({
367 instanceId,
368 operation: "start",
369 detail: "Could not create an Antigravity setup workspace.",
370 }),
371 ),
372 );
373 let sessionId: string | undefined;
374 yield* Effect.addFinalizer(() =>
375 removeAntigravitySessionFiles({
376 profileDirectory,
377 sessionId,
378 cwd,
379 }).pipe(
380 Effect.provideService(FileSystem.FileSystem, fileSystem),
381 Effect.provideService(Path.Path, path),
382 ),
383 );
384 const runtime = yield* makeRuntime({
385 cwd,
386 mcpServers: [],
387 ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
388 });
389 return {
390 ...runtime,
391 start: () =>
392 runtime.start().pipe(
393 Effect.tap((started) =>
394 Effect.sync(() => {
395 sessionId = started.sessionId;
396 }),
397 ),
398 ),
399 };
400 });
401
402 // The agy CLI ignores T3's browser helper during ACP `authenticate`, so Google sign-in runs its
403 // remote-friendly `--login`, which stores the sign-in where the ACP process reads it.
404 const codeLogin = Effect.fn("AntigravityDriver.codeLogin")(function* (input: {
405 readonly onAuthorizationUrl: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
406 }) {
407 if (auth.authMethod !== "oauth-personal") return undefined;
408 const cwd = yield* fileSystem
409 .makeTempDirectoryScoped({ prefix: "t3-antigravity-login-" })
410 .pipe(
411 Effect.mapError(
412 () =>
413 new ProviderSetupError({
414 instanceId,
415 operation: "start",
416 detail: "Could not create an Antigravity setup workspace.",
417 }),
418 ),
419 );
420 const { spawn } = yield* prepareSpawn(cwd, processEnvironment);
421 const failed = (detail: string, cause?: unknown) =>
422 new ProviderSetupError({ instanceId, operation: "start", detail, cause });
423 // Without a display it prints the link only, instead of opening a browser on this machine.
424 const { DISPLAY: _display, WAYLAND_DISPLAY: _wayland, ...env } = spawn.env ?? {};
425 const child = yield* spawner
426 .spawn(
427 ChildProcess.make(spawn.command, [...spawn.args, "--login"], {
428 cwd,
429 env,
430 extendEnv: false,
431 shell: false,
432 }),
433 )
434 .pipe(Effect.mapError((cause) => failed("Could not start Antigravity sign-in.", cause)));
435 const code = yield* Deferred.make<string>();
436 yield* Stream.fromEffect(Deferred.await(code)).pipe(
437 Stream.map((response) => `${response}\n`),
438 Stream.encodeText,
439 Stream.run(child.stdin),
440 Effect.ignore,
441 Effect.forkScoped,
442 );
443 const output = yield* child.stdout.pipe(
444 Stream.decodeText(),
445 Stream.splitLines,
446 Stream.map((line) => line.trim()),
447 Stream.runForEach((line) =>
448 line.startsWith("https://accounts.google.com/")
449 ? input.onAuthorizationUrl(line)
450 : Effect.void,
451 ),
452 Effect.forkScoped,
453 );
454 yield* Stream.runDrain(child.stderr).pipe(Effect.ignore, Effect.forkScoped);
455 return {
456 submit: (response: string) => Deferred.succeed(code, response).pipe(Effect.asVoid),
457 completed: Effect.gen(function* () {
458 // Stdout closes when the process exits, or this fails first on an unusable link.
459 yield* Fiber.join(output).pipe(
460 Effect.mapError((cause) =>
461 failed("Antigravity returned an invalid Google sign-in link.", cause),
462 ),
463 );
464 const exitCode = yield* child.exitCode.pipe(
465 Effect.mapError((cause) => failed("Antigravity sign-in stopped unexpectedly.", cause)),
466 );
467 if (Number(exitCode) !== 0) {
468 return yield* failed(
469 "Antigravity could not finish Google sign-in. Start sign-in again.",
470 );
471 }
472 }),
473 };
474 });
475
476 const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* (
477 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
478 runtime: Pick<
479 AcpSessionRuntime.AcpSessionRuntime["Service"],
480 "getEvents" | "drainEvents" | "setModel"
481 >,
482 ) {
483 yield* provider.onSessionStarted(started);
484 yield* authFlow.onSignedInElsewhere;
485 yield* Stream.runForEach(runtime.getEvents(), (event) => {
486 if (event._tag === "EventStreamBarrier") {
487 return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
488 }
489 if (event._tag === "ConfigOptionsUpdated") {
490 return provider.onConfigOptionsUpdated(event.configOptions);
491 }
492 return event._tag === "AvailableCommandsUpdated"
493 ? provider.onAvailableCommands(event.availableCommands)
494 : Effect.void;
495 }).pipe(Effect.forkScoped);
496 // Thinking levels differ per model and are reported only for the selected one.
497 const configOptions = started.sessionSetupResult.configOptions ?? [];
498 const current = configOptions.find((option) => option.id === "model")?.currentValue;
499 if (antigravityThinkingConfig(configOptions) !== undefined && typeof current === "string") {
500 for (const model of [...antigravityModelOptions(configOptions), { value: current }]) {
501 yield* runtime.setModel(model.value).pipe(Effect.ignore);
502 }
503 }
504 yield* runtime.drainEvents;
505 }, Effect.scoped);
506
507 const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
508 instanceId,
509 makeRuntime: makeDisposableRuntime,
510 // A new sign-in may be another account; drop any in-flight quota read first.
511 onAuthenticated: (started, runtime) =>
512 Effect.suspend(() => provider.onSignedIn).pipe(
513 Effect.andThen(publishCatalog(started, runtime)),
514 ),
515 onSignedOut: Effect.suspend(() => provider.onSignedOut),
516 usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
517 codeLogin,
518 });
519
520 // The probe must not spawn. The agent is a PyInstaller one-file bundle
521 // that unpacks about 1 GB per launch, and the health check runs every
522 // minute.
523 const probe = Effect.gen(function* () {
524 yield* modelCatalog.refreshInBackground;
525 if (authConfigIssue !== null) {
526 return yield* new ProviderSetupError({
527 instanceId,
528 operation: "configure",
529 detail: authConfigIssue,
530 });
531 }
532 const executable = yield* installation.resolve(settings.binaryPath, processEnvironment).pipe(
533 Effect.mapError(
534 (cause) =>
535 new ProviderSetupError({
536 instanceId,
537 operation: "resolve",
538 detail: cause.detail,
539 cause,
540 }),
541 ),
542 );
543 return {
544 protocolVersion: 1,
545 agentCapabilities: {
546 loadSession: true,
547 promptCapabilities: { image: true, audio: true, embeddedContext: true },
548 sessionCapabilities: { list: {}, resume: {} },
549 },
550 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
551 agentInfo: {
552 name: "antigravity-acp",
553 title: "Google Antigravity",
554 version: executable.version ?? "unknown",
555 },
556 };
557 });
558
559 const usage = yield* makeAntigravityUsageProbe({
560 profileDirectory,
561 authMethod: auth.authMethod,
562 }).pipe(
563 Effect.provideService(FileSystem.FileSystem, fileSystem),
564 Effect.provideService(Path.Path, path),
565 Effect.provideService(Digest.Digest, digest),
566 Effect.provideService(HttpClient.HttpClient, httpClient),
567 );
568 const provider = yield* makeAntigravityProvider(settings, {
569 environment: processEnvironment,
570 stampIdentity: classifyModels,
571 probe,
572 probeUsage: usage.probe,
573 clearUsage: usage.clear,
574 auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
575 supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
576 Effect.provideService(FileSystem.FileSystem, fileSystem),
577 Effect.provideService(Path.Path, path),
578 Effect.orElseSucceed(() => false),
579 ),
580 }).pipe(
581 Effect.mapError(
582 (cause) =>
583 new ProviderDriverError({
584 driver: DRIVER,
585 instanceId,
586 detail: "Could not prepare the Antigravity provider status.",
587 cause,
588 }),
589 ),
590 );
591 const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
592 const orchestrationAdapter = yield* makeAntigravityAdapterV2({
593 instanceId,
594 selfInvocation,
595 makeRuntime,
596 withProcess: authFlow.withProcess,
597 defaultModel,
598 supportsNativeGoals: provider.snapshot.getSnapshot.pipe(
599 Effect.map(
600 (snapshot) => snapshot.slashCommands?.some((command) => command.name === "goal") === true,
601 ),
602 ),
603 profileDirectory,
604 onSessionStarted: (started, cwd) =>
605 provider.onSessionStarted(started, cwd).pipe(Effect.andThen(authFlow.onSignedInElsewhere)),
606 onSessionEvent: (event, cwd) => {
607 if (event._tag === "ConfigOptionsUpdated") {
608 return provider.onConfigOptionsUpdated(event.configOptions);
609 }
610 return event._tag === "AvailableCommandsUpdated"
611 ? provider.onAvailableCommands(event.availableCommands, cwd)
612 : Effect.void;
613 },
614 continuationRequests,
615 nativeLogging: (threadId) =>
616 makeNativeLogger({
617 nativeEventLogger: loggers.native,
618 provider: DRIVER,
619 threadId,
620 }),
621 });
622 const textGeneration = yield* makeAntigravityTextGeneration({
623 profileDirectory,
624 defaultModel,
625 withProcess: authFlow.withProcess,
626 makeRuntime: (cwd) =>
627 makeRuntime({
628 cwd,
629 mcpServers: [],
630 }),
631 });
632
633 const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
634 function* () {
635 const processScope = yield* Scope.make();
636 yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
637 yield* authFlow
638 .withProcess(
639 Scope.close(processScope, Exit.void),
640 Effect.gen(function* () {
641 const runtime = yield* makeDisposableRuntime({});
642 const started = yield* runtime.start();
643 yield* publishCatalog(started, runtime);
644 }),
645 )
646 .pipe(Effect.provideService(Scope.Scope, processScope));
647 },
648 Effect.scoped,
649 Effect.timeoutOrElse({
650 duration: "90 seconds",
651 orElse: () =>
652 Effect.fail(
653 new ProviderDriverError({
654 driver: DRIVER,
655 instanceId,
656 detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
657 }),
658 ),
659 }),
660 Effect.tapError((cause) =>
661 isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
662 ),
663 Effect.mapError((cause) =>
664 cause._tag === "ProviderDriverError"
665 ? cause
666 : new ProviderDriverError({
667 driver: DRIVER,
668 instanceId,
669 detail: isAntigravitySignInRequiredError(cause)
670 ? "Sign in to Antigravity in provider settings before refreshing models."
671 : cause._tag === "ProviderSetupError" &&
672 (cause.operation === "configure" || cause.operation === "start")
673 ? cause.detail
674 : cause._tag === "AcpTransportError" &&
675 isProviderSetupError(cause.cause) &&
676 cause.cause.operation === "runtime"
677 ? cause.cause.detail
678 : refreshFailureDetail(cause),
679 cause,
680 }),
681 ),
682 );
683
684 return {
685 instanceId,
686 driverKind: DRIVER,
687 continuationIdentity,
688 displayName,
689 accentColor,
690 enabled,
691 snapshot: provider.snapshot,
692 snapshotForCwd: (cwd) =>
693 !enabled
694 ? provider.snapshot.getSnapshot
695 : discoverAntigravitySkills({ cwd, userHome, profileDirectory }).pipe(
696 Effect.provideService(FileSystem.FileSystem, fileSystem),
697 Effect.provideService(Path.Path, path),
698 Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
699 Effect.mapError(
700 (cause) =>
701 new ProviderDriverError({
702 driver: DRIVER,
703 instanceId,
704 detail: "Could not read Antigravity workspace skills.",
705 cause,
706 }),
707 ),
708 ),
709 orchestrationAdapter,
710 textGeneration,
711 auth: authFlow.controller,
712 refreshModels,
713 } satisfies ProviderInstance;
714 }),
715 };