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