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