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

AntigravityProvider.ts

415 lines15.3 KB

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