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

AntigravityProvider.ts

433 lines15.9 KB

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 });
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 });
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 );
114​
115interface AntigravityProviderState {
116 readonly draft: ServerProviderDraft;
117 readonly authRevision: number;
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 };
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 failure = Result.isFailure(result) ? result.failure : undefined;
181 const missingInstallation = failure !== undefined && isMissingInstallation(failure);
182 const errorMessage =
183 initialized !== undefined
184 ? undefined
185 : failure?._tag === "ProviderSetupError"
186 ? failure.detail.trim() || "Antigravity could not complete its local health check."
187 : missingInstallation
188 ? "Antigravity is not installed or its executable could not be found."
189 : failure
190 ? "Antigravity could not complete its local health check."
191 : `Antigravity did not respond to its local health check within ${HEALTH_CHECK_TIMEOUT}.`;
192 const supportsTextGeneration =
193 initialized !== undefined ? yield* options.supportsTextGeneration : false;
194 const usageLimits =
195 initialized !== undefined && options.probeUsage ? yield* options.probeUsage : undefined;
196 const updatedAt = DateTime.formatIso(yield* DateTime.now);
197 const next = yield* SubscriptionRef.updateAndGet(metadata, (state) => {
198 if (state.authRevision !== before.authRevision) return state;
199 const { message: _previousMessage, ...draft } = state.draft;
200 const authenticated = draft.auth.status === "authenticated";
201 const message =
202 errorMessage ??
203 (authenticated
204 ? undefined
205 : draft.auth.status === "unauthenticated"
206 ? SIGN_IN_MESSAGE
207 : AUTH_UNCHECKED_MESSAGE);
208 return {
209 ...state,
210 draft: {
211 ...draft,
212 installed: !missingInstallation,
213 version: initialized?.agentInfo?.version || draft.version,
214 status: errorMessage ? "error" : authenticated ? "ready" : "warning",
215 checkedAt: updatedAt,
216 usageLimits: missingInstallation
217 ? undefined
218 : resolveUsageLimitsAfterProbe({
219 published: draft.usageLimits,
220 probed: usageLimits ?? draft.usageLimits,
221 }),
222 ...(missingInstallation
223 ? {
224 models: [],
225 slashCommands: [],
226 skills: [],
227 workspaceSnapshots: [],
228 supportsTextGeneration: false,
229 }
230 : {}),
231 ...(initialized !== undefined
232 ? {
233 supportsTextGeneration:
234 supportsTextGeneration && draft.auth.status !== "unauthenticated",
235 }
236 : {}),
237 ...(message ? { message } : {}),
238 },
239 } satisfies AntigravityProviderState;
240 });
241 return yield* options.stampIdentity(next.draft);
242 });
243​
244 const maintenanceCapabilities =
245 options.maintenanceCapabilities ??
246 makeManualOnlyProviderMaintenanceCapabilities({
247 provider: ProviderDriverKind.make("antigravity"),
248 packageName: null,
249 });
250 const managed = yield* makeManagedServerProvider({
251 resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
252 getSettings: Effect.succeed(settings),
253 streamSettings: Stream.empty,
254 haveSettingsChanged: () => false,
255 initialSnapshot: () => getSnapshot,
256 checkProvider: checkProvider(),
257 enrichSnapshot: ({ publishSnapshot }) =>
258 SubscriptionRef.changes(metadata).pipe(
259 Stream.runForEach((state) =>
260 options.stampIdentity(state.draft).pipe(Effect.flatMap(publishSnapshot)),
261 ),
262 ),
263 });
264​
265 const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
266 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
267 cwd?: string,
268 ) {
269 if (!settings.enabled) return;
270 const before = yield* SubscriptionRef.get(metadata);
271 const supportsTextGeneration = yield* options.supportsTextGeneration;
272 const usageLimits =
273 options.probeUsage && (!before.draft.usageLimits || before.draft.usageLimits.unavailable)
274 ? yield* options.probeUsage
275 : before.draft.usageLimits;
276 const updatedAt = DateTime.formatIso(yield* DateTime.now);
277 yield* SubscriptionRef.update(metadata, (state) => {
278 if (
279 state.authRevision !== before.authRevision &&
280 state.draft.auth.status === "unauthenticated"
281 ) {
282 return state;
283 }
284 const { message: _previousMessage, ...draft } = state.draft;
285 const workspaces = draft.workspaceSnapshots ?? [];
286 const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined;
287 return {
288 authRevision: state.authRevision + 1,
289 draft: {
290 ...draft,
291 installed: true,
292 status: "ready",
293 version: started.initializeResult.agentInfo?.version || draft.version,
294 auth: {
295 status: "authenticated",
296 type: options.auth?.type ?? "oauth-personal",
297 label: options.auth?.label ?? "Google account",
298 },
299 checkedAt: updatedAt,
300 usageLimits: resolveUsageLimitsAfterProbe({
301 published: draft.usageLimits,
302 probed: usageLimits ?? draft.usageLimits,
303 }),
304 models: buildAntigravityModelsFromSession(started.sessionSetupResult),
305 supportsTextGeneration,
306 ...(cwd
307 ? {
308 workspaceSnapshots: [
309 ...workspaces.filter((entry) => entry.cwd !== cwd),
310 {
311 cwd,
312 checkedAt: updatedAt,
313 slashCommands: workspace?.slashCommands ?? draft.slashCommands,
314 skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [],
315 },
316 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
317 }
318 : {}),
319 },
320 } satisfies AntigravityProviderState;
321 });
322 });
323​
324 const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
325 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
326 ) {
327 const models = buildAntigravityModelsFromSession({ configOptions });
328 yield* SubscriptionRef.update(metadata, (state) => {
329 if (state.draft.auth.status !== "authenticated") return state;
330 return { ...state, draft: { ...state.draft, models } };
331 });
332 });
333​
334 const onAvailableCommands = Effect.fn("AntigravityProvider.onAvailableCommands")(function* (
335 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
336 cwd?: string,
337 ) {
338 if (!settings.enabled) return;
339 const slashCommands = nativeCommands(commands);
340 const updatedAt = DateTime.formatIso(yield* DateTime.now);
341 yield* SubscriptionRef.update(metadata, (state) => {
342 if (state.draft.auth.status === "unauthenticated") return state;
343 return {
344 ...state,
345 draft: {
346 ...state.draft,
347 slashCommands,
348 ...(cwd
349 ? {
350 workspaceSnapshots: [
351 ...(state.draft.workspaceSnapshots ?? []).filter((entry) => entry.cwd !== cwd),
352 {
353 cwd,
354 checkedAt: updatedAt,
355 slashCommands,
356 skills:
357 state.draft.workspaceSnapshots?.find((entry) => entry.cwd === cwd)?.skills ??
358 discoveredSkills.get(cwd) ??
359 [],
360 },
361 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
362 }
363 : {}),
364 },
365 };
366 });
367 });
368​
369 const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {
370 if (options.clearUsage) yield* options.clearUsage;
371 if (!settings.enabled) return;
372 const updatedAt = DateTime.formatIso(yield* DateTime.now);
373 yield* SubscriptionRef.update(
374 metadata,
375 (state) =>
376 ({
377 authRevision: state.authRevision + 1,
378 draft: {
379 ...state.draft,
380 auth: { status: "unauthenticated" },
381 status: "warning",
382 message: SIGN_IN_MESSAGE,
383 checkedAt: updatedAt,
384 models: [],
385 slashCommands: [],
386 skills: [],
387 workspaceSnapshots: [],
388 supportsTextGeneration: false,
389 usageLimits: undefined,
390 },
391 }) satisfies AntigravityProviderState,
392 );
393 discoveredSkills.clear();
394 });
395​
396 const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* (
397 cwd: string,
398 skills?: ServerProvider["skills"],
399 ) {
400 if (skills) {
401 discoveredSkills.set(cwd, skills);
402 yield* SubscriptionRef.update(metadata, (state) =>
403 state.draft.workspaceSnapshots?.some((entry) => entry.cwd === cwd)
404 ? {
405 ...state,
406 draft: {
407 ...state.draft,
408 workspaceSnapshots: state.draft.workspaceSnapshots.map((entry) =>
409 entry.cwd === cwd ? { ...entry, skills } : entry,
410 ),
411 },
412 }
413 : state,
414 );
415 }
416 const snapshot = yield* getSnapshot;
417 const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd);
418 const resolvedSkills = skills ?? workspace?.skills ?? discoveredSkills.get(cwd) ?? [];
419 return workspace
420 ? { ...snapshot, slashCommands: workspace.slashCommands, skills: resolvedSkills }
421 : { ...snapshot, skills: resolvedSkills };
422 });
423​
424 return {
425 snapshot: { ...managed, getSnapshot },
426 onSessionStarted,
427 onConfigOptionsUpdated,
428 onAvailableCommands,
429 onSignedOut: clearAccountMetadata(),
430 onAuthRequired: clearAccountMetadata(),
431 snapshotForCwd,
432 };
433});