Open History to see the last commit
1import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 ProviderDriverKind,
4 type AntigravitySettings,
5 type ProviderSetupError,
6 type ServerProvider,
7 type ServerProviderModel,
8 type ServerProviderSlashCommand,
9 type ServerProviderUsageLimits,
10} from "@t3tools/contracts";
11import { createModelCapabilities } from "@t3tools/shared/model";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import * as FiberHandle from "effect/FiberHandle";
17import * as Option from "effect/Option";
18import * as Predicate from "effect/Predicate";
19import * as Result from "effect/Result";
20import * as Stream from "effect/Stream";
21import * as SubscriptionRef from "effect/SubscriptionRef";
22import type * as EffectAcpErrors from "effect-acp/errors";
23import type * as EffectAcpSchema from "effect-acp/compat";
24
25import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
26import { acpProviderOptionDescriptors } from "@t3tools/provider-acp/server/sessionConfig";
27import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
28import {
29 makeManualOnlyProviderMaintenanceCapabilities,
30 type ProviderMaintenanceCapabilities,
31} from "@t3tools/provider-core/server/maintenanceResolver";
32import {
33 buildServerProvider,
34 isCommandMissingCause,
35 type ServerProviderDraft,
36} from "@t3tools/provider-core/server/snapshotProbe";
37import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usageLimits";
38
39import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts";
40
41const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] });
42const MAX_WORKSPACE_SNAPSHOTS = 32;
43const HEALTH_CHECK_TIMEOUT = "90 seconds";
44const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity.";
45const AUTH_UNCHECKED_MESSAGE =
46 "Antigravity is installed. Google account access is not checked yet.";
47// Set while a finished quota read republishes, so that health check does not read again.
48const PublishingUsage = Context.Reference<boolean>("t3/provider/AntigravityPublishingUsage", {
49 defaultValue: () => false,
50});
51
52type SessionSetupResult = Pick<
53 AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
54 "configOptions" | "models"
55>;
56
57type ThinkingConfig = NonNullable<ReturnType<typeof antigravityThinkingConfig>>;
58
59/** Thinking options each model reported when selected; `null` means it has none. */
60export type AntigravityThinkingLevels = ReadonlyMap<string, ThinkingConfig | null>;
61
62function thinkingCapabilities(config: ThinkingConfig | null | undefined, observed: boolean) {
63 const descriptor = config
64 ? acpProviderOptionDescriptors({ configOptions: [config], modeState: undefined })[0]
65 : undefined;
66 if (descriptor?.type !== "select") return EMPTY_MODEL_CAPABILITIES;
67 // Another model's selected level is not this model's default.
68 const { currentValue: _currentValue, ...unobserved } = descriptor;
69 return createModelCapabilities({ optionDescriptors: [observed ? descriptor : unobserved] });
70}
71
72export function buildAntigravityModelsFromSession(
73 setup: SessionSetupResult,
74 thinkingLevels: AntigravityThinkingLevels = new Map(),
75): ReadonlyArray<ServerProviderModel> {
76 const config = setup.configOptions?.find(
77 (option) => option.id === "model" || option.category === "model",
78 );
79 const currentValue =
80 config?.type === "select" ? config.currentValue : setup.models?.currentModelId;
81 const entries =
82 config?.type === "select"
83 ? config.options.flatMap((entry) => ("value" in entry ? [entry] : entry.options))
84 : config === undefined
85 ? (setup.models?.availableModels.map((model) => ({
86 value: model.modelId,
87 name: model.name,
88 })) ?? [])
89 : [];
90 const currentThinking = antigravityThinkingConfig(setup.configOptions);
91 const seen = new Set<string>();
92 // The agent can list two IDs under one name; label the later ones so the picker tells them apart.
93 const names = new Set<string>();
94 return entries.flatMap((entry): ServerProviderModel[] => {
95 if (!entry.value.trim() || seen.has(entry.value)) return [];
96 seen.add(entry.value);
97 const baseName = entry.name.trim() ? entry.name : entry.value;
98 const name = names.has(baseName) ? `${baseName} (${entry.value})` : baseName;
99 names.add(baseName);
100 const observed =
101 entry.value === currentValue ? (currentThinking ?? null) : thinkingLevels.get(entry.value);
102 return [
103 {
104 slug: entry.value,
105 name,
106 isCustom: false,
107 ...(entry.value === currentValue
108 ? { isDefault: true, aliases: [ANTIGRAVITY_DEFAULT_MODEL] }
109 : {}),
110 capabilities:
111 observed === undefined
112 ? thinkingCapabilities(currentThinking, false)
113 : thinkingCapabilities(observed, true),
114 },
115 ];
116 });
117}
118
119function nativeCommands(
120 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
121): ReadonlyArray<ServerProviderSlashCommand> {
122 const seen = new Set<string>();
123 return commands.flatMap((command): ServerProviderSlashCommand[] => {
124 if (!command.name.trim() || seen.has(command.name)) return [];
125 seen.add(command.name);
126 const description = command.description.trim();
127 const hint = command.input?.hint.trim();
128 return [
129 {
130 name: command.name,
131 ...(description ? { description } : {}),
132 ...(hint ? { input: { hint } } : {}),
133 },
134 ];
135 });
136}
137
138function isMissingInstallation(error: EffectAcpErrors.AcpError | ProviderSetupError): boolean {
139 if (error._tag === "AcpSpawnError") {
140 return (
141 isCommandMissingCause(error.cause) ||
142 (Predicate.isObject(error.cause) && error.cause.code === "ENOENT")
143 );
144 }
145 return (
146 error._tag === "ProviderSetupError" &&
147 error.operation === "resolve" &&
148 /not installed|missing|incomplete|does not publish/i.test(error.detail)
149 );
150}
151
152interface AntigravityProviderState {
153 readonly draft: ServerProviderDraft;
154 readonly authRevision: number;
155}
156
157interface AntigravityProviderOptions {
158 readonly stampIdentity: (snapshot: ServerProviderDraft) => Effect.Effect<ServerProvider>;
159 readonly probe: Effect.Effect<
160 EffectAcpSchema.InitializeResponse,
161 EffectAcpErrors.AcpError | ProviderSetupError
162 >;
163 readonly supportsTextGeneration: Effect.Effect<boolean>;
164 readonly probeUsage?: Effect.Effect<ServerProviderUsageLimits>;
165 readonly clearUsage?: Effect.Effect<void>;
166 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
167 readonly auth?: { readonly type: string; readonly label: string };
168}
169
170export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(function* (
171 settings: AntigravitySettings,
172 options: AntigravityProviderOptions,
173) {
174 const usesCredentials =
175 options.auth?.type === "gemini-api-key" || options.auth?.type === "agent-platform";
176 const signInMessage = usesCredentials
177 ? `Connect with ${options.auth.label} to use Antigravity and load models.`
178 : SIGN_IN_MESSAGE;
179 const authUncheckedMessage = usesCredentials
180 ? `Antigravity is installed. Connect with ${options.auth.label} to load models.`
181 : AUTH_UNCHECKED_MESSAGE;
182 const checkedAt = DateTime.formatIso(yield* DateTime.now);
183 const initialDraft = {
184 ...buildServerProvider({
185 presentation: { displayName: "Antigravity", showInteractionModeToggle: false },
186 enabled: settings.enabled,
187 checkedAt,
188 models: [],
189 probe: {
190 installed: false,
191 version: null,
192 status: "warning",
193 auth: { status: "unknown", ...(options.auth ? { type: options.auth.type } : {}) },
194 message: settings.enabled
195 ? "Checking Antigravity availability."
196 : "Antigravity is disabled in T3 Code settings.",
197 },
198 }),
199 setup: { canAuthenticate: true, canInstall: true },
200 supportsConversationRollback: false,
201 supportsTextGeneration: false,
202 workspaceSnapshots: [],
203 } satisfies ServerProviderDraft;
204 const metadata = yield* SubscriptionRef.make<AntigravityProviderState>({
205 draft: initialDraft,
206 authRevision: 0,
207 });
208 // Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them.
209 const discoveredSkills = new Map<string, ServerProvider["skills"]>();
210 const thinkingLevels = new Map<string, ThinkingConfig | null>();
211 const observeThinkingLevels = (
212 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
213 ) => {
214 const model = configOptions?.find(
215 (option) => option.id === "model" || option.category === "model",
216 );
217 if (model?.type === "select" && model.currentValue) {
218 thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null);
219 }
220 };
221 const getSnapshot = SubscriptionRef.get(metadata).pipe(
222 Effect.flatMap((state) => options.stampIdentity(state.draft)),
223 );
224
225 // The quota read can take 30 seconds, so it never blocks readiness or a session start.
226 // One read runs at a time; sign-in and sign-out interrupt it so a stale account never lands.
227 const usageRead = yield* FiberHandle.make();
228 const republish = yield* Deferred.make<Effect.Effect<ServerProvider>>();
229 const scope = yield* Effect.scope;
230 const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {
231 if (!options.probeUsage || (yield* PublishingUsage)) return;
232 yield* FiberHandle.run(
233 usageRead,
234 options.probeUsage.pipe(
235 Effect.flatMap((probed) =>
236 SubscriptionRef.update(metadata, (state) => ({
237 ...state,
238 draft: {
239 ...state.draft,
240 usageLimits: resolveUsageLimitsAfterProbe({
241 published: state.draft.usageLimits,
242 probed,
243 }),
244 },
245 })),
246 ),
247 // Enrichment cannot change published limits; a health check publishes them.
248 Effect.andThen(
249 Deferred.await(republish).pipe(
250 Effect.flatten,
251 Effect.provideService(PublishingUsage, true),
252 Effect.ignoreCause({ log: true }),
253 Effect.forkIn(scope),
254 ),
255 ),
256 ),
257 // Store the fiber before it runs, so a sign-out during the read can interrupt it.
258 { onlyIfMissing: true, startImmediately: false },
259 );
260 });
261 const resetUsage = Effect.gen(function* () {
262 yield* FiberHandle.clear(usageRead);
263 if (options.clearUsage) yield* options.clearUsage;
264 });
265
266 const checkProvider = Effect.fn("checkAntigravityProvider")(function* () {
267 if (!settings.enabled) return yield* getSnapshot;
268 const before = yield* SubscriptionRef.get(metadata);
269 const result = yield* options.probe.pipe(
270 Effect.timeoutOption(HEALTH_CHECK_TIMEOUT),
271 Effect.result,
272 );
273 const initialized =
274 Result.isSuccess(result) && Option.isSome(result.success) ? result.success.value : undefined;
275 const version = initialized?.agentInfo?.version;
276 const failure = Result.isFailure(result) ? result.failure : undefined;
277 const missingInstallation = failure !== undefined && isMissingInstallation(failure);
278 const errorMessage =
279 initialized !== undefined
280 ? undefined
281 : failure?._tag === "ProviderSetupError"
282 ? failure.detail.trim() || "Antigravity could not complete its local health check."
283 : missingInstallation
284 ? "Antigravity ACP runtime is not installed or its executable could not be found."
285 : failure
286 ? "Antigravity could not complete its local health check."
287 : `Antigravity did not respond to its local health check within ${HEALTH_CHECK_TIMEOUT}.`;
288 const supportsTextGeneration =
289 initialized !== undefined ? yield* options.supportsTextGeneration : false;
290 const updatedAt = DateTime.formatIso(yield* DateTime.now);
291 const next = yield* SubscriptionRef.updateAndGet(metadata, (state) => {
292 if (state.authRevision !== before.authRevision) return state;
293 const { message: _previousMessage, ...draft } = state.draft;
294 const authenticated = draft.auth.status === "authenticated";
295 const message =
296 errorMessage ??
297 (authenticated
298 ? undefined
299 : draft.auth.status === "unauthenticated"
300 ? signInMessage
301 : authUncheckedMessage);
302 return {
303 ...state,
304 draft: {
305 ...draft,
306 installed: !missingInstallation,
307 // Lightweight custom-launcher probes lack versions; preserve the real handshake's version.
308 version: version === "unknown" ? draft.version : version || draft.version,
309 status: errorMessage ? "error" : authenticated ? "ready" : "warning",
310 checkedAt: updatedAt,
311 usageLimits: missingInstallation ? undefined : draft.usageLimits,
312 ...(missingInstallation
313 ? {
314 models: [],
315 slashCommands: [],
316 skills: [],
317 workspaceSnapshots: [],
318 supportsTextGeneration: false,
319 }
320 : {}),
321 ...(initialized !== undefined
322 ? {
323 supportsTextGeneration:
324 supportsTextGeneration && draft.auth.status !== "unauthenticated",
325 }
326 : {}),
327 ...(message ? { message } : {}),
328 },
329 } satisfies AntigravityProviderState;
330 });
331 if (initialized !== undefined) yield* refreshUsage();
332 return yield* options.stampIdentity(next.draft);
333 });
334
335 const maintenanceCapabilities =
336 options.maintenanceCapabilities ??
337 makeManualOnlyProviderMaintenanceCapabilities({
338 provider: ProviderDriverKind.make("antigravity"),
339 packageName: null,
340 });
341 const managed = yield* makeManagedServerProvider({
342 resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
343 getSettings: Effect.succeed(settings),
344 streamSettings: Stream.empty,
345 haveSettingsChanged: () => false,
346 initialSnapshot: () => getSnapshot,
347 checkProvider: checkProvider(),
348 enrichSnapshot: ({ publishSnapshot }) =>
349 SubscriptionRef.changes(metadata).pipe(
350 Stream.runForEach((state) =>
351 options.stampIdentity(state.draft).pipe(Effect.flatMap(publishSnapshot)),
352 ),
353 ),
354 });
355 yield* Deferred.succeed(republish, managed.refresh);
356
357 const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
358 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
359 cwd?: string,
360 ) {
361 if (!settings.enabled) return;
362 observeThinkingLevels(started.sessionSetupResult.configOptions);
363 const before = yield* SubscriptionRef.get(metadata);
364 const supportsTextGeneration = yield* options.supportsTextGeneration;
365 const updatedAt = DateTime.formatIso(yield* DateTime.now);
366 yield* SubscriptionRef.update(metadata, (state) => {
367 if (
368 state.authRevision !== before.authRevision &&
369 state.draft.auth.status === "unauthenticated"
370 ) {
371 return state;
372 }
373 const { message: _previousMessage, ...draft } = state.draft;
374 const workspaces = draft.workspaceSnapshots ?? [];
375 const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined;
376 return {
377 authRevision: state.authRevision + 1,
378 draft: {
379 ...draft,
380 installed: true,
381 status: "ready",
382 version: started.initializeResult.agentInfo?.version || draft.version,
383 auth: {
384 status: "authenticated",
385 type: options.auth?.type ?? "oauth-personal",
386 label: options.auth?.label ?? "Google account",
387 },
388 checkedAt: updatedAt,
389 models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels),
390 supportsTextGeneration,
391 ...(cwd
392 ? {
393 workspaceSnapshots: [
394 ...workspaces.filter((entry) => entry.cwd !== cwd),
395 {
396 cwd,
397 checkedAt: updatedAt,
398 slashCommands: workspace?.slashCommands ?? draft.slashCommands,
399 skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [],
400 },
401 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
402 }
403 : {}),
404 },
405 } satisfies AntigravityProviderState;
406 });
407 if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage();
408 });
409
410 const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
411 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
412 ) {
413 observeThinkingLevels(configOptions);
414 const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels);
415 yield* SubscriptionRef.update(metadata, (state) => {
416 if (state.draft.auth.status !== "authenticated") return state;
417 return { ...state, draft: { ...state.draft, models } };
418 });
419 });
420
421 const onAvailableCommands = Effect.fn("AntigravityProvider.onAvailableCommands")(function* (
422 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
423 cwd?: string,
424 ) {
425 if (!settings.enabled) return;
426 const slashCommands = nativeCommands(commands);
427 const updatedAt = DateTime.formatIso(yield* DateTime.now);
428 yield* SubscriptionRef.update(metadata, (state) => {
429 if (state.draft.auth.status === "unauthenticated") return state;
430 return {
431 ...state,
432 draft: {
433 ...state.draft,
434 slashCommands,
435 ...(cwd
436 ? {
437 workspaceSnapshots: [
438 ...(state.draft.workspaceSnapshots ?? []).filter((entry) => entry.cwd !== cwd),
439 {
440 cwd,
441 checkedAt: updatedAt,
442 slashCommands,
443 skills:
444 state.draft.workspaceSnapshots?.find((entry) => entry.cwd === cwd)?.skills ??
445 discoveredSkills.get(cwd) ??
446 [],
447 },
448 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
449 }
450 : {}),
451 },
452 };
453 });
454 });
455
456 const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {
457 yield* resetUsage;
458 if (!settings.enabled) return;
459 const updatedAt = DateTime.formatIso(yield* DateTime.now);
460 yield* SubscriptionRef.update(
461 metadata,
462 (state) =>
463 ({
464 authRevision: state.authRevision + 1,
465 draft: {
466 ...state.draft,
467 auth: {
468 status: "unauthenticated",
469 ...(usesCredentials ? options.auth : {}),
470 },
471 status: "warning",
472 message: signInMessage,
473 checkedAt: updatedAt,
474 models: [],
475 slashCommands: [],
476 skills: [],
477 workspaceSnapshots: [],
478 supportsTextGeneration: false,
479 usageLimits: undefined,
480 },
481 }) satisfies AntigravityProviderState,
482 );
483 discoveredSkills.clear();
484 thinkingLevels.clear();
485 });
486
487 const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* (
488 cwd: string,
489 skills?: ServerProvider["skills"],
490 ) {
491 if (skills) {
492 discoveredSkills.set(cwd, skills);
493 yield* SubscriptionRef.update(metadata, (state) =>
494 state.draft.workspaceSnapshots?.some((entry) => entry.cwd === cwd)
495 ? {
496 ...state,
497 draft: {
498 ...state.draft,
499 workspaceSnapshots: state.draft.workspaceSnapshots.map((entry) =>
500 entry.cwd === cwd ? { ...entry, skills } : entry,
501 ),
502 },
503 }
504 : state,
505 );
506 }
507 const snapshot = yield* getSnapshot;
508 const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd);
509 const resolvedSkills = skills ?? workspace?.skills ?? discoveredSkills.get(cwd) ?? [];
510 return workspace
511 ? { ...snapshot, slashCommands: workspace.slashCommands, skills: resolvedSkills }
512 : { ...snapshot, skills: resolvedSkills };
513 });
514
515 return {
516 snapshot: { ...managed, getSnapshot },
517 onSessionStarted,
518 onConfigOptionsUpdated,
519 onAvailableCommands,
520 // The new sign-in may be another account. Clear and republish its limits so a failed read
521 // cannot fall back to them; the session start then reads the new account's limits.
522 onSignedIn: resetUsage.pipe(
523 Effect.andThen(
524 SubscriptionRef.update(metadata, (state) => {
525 const { usageLimits: _previousAccount, ...draft } = state.draft;
526 return { ...state, draft };
527 }),
528 ),
529 Effect.andThen(
530 Deferred.await(republish).pipe(
531 Effect.flatten,
532 Effect.provideService(PublishingUsage, true),
533 ),
534 ),
535 Effect.asVoid,
536 ),
537 onSignedOut: clearAccountMetadata(),
538 onAuthRequired: clearAccountMetadata(),
539 snapshotForCwd,
540 };
541});