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

AntigravityProvider.ts

546 lines20.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 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] });
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 });
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 });
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 );
151​
152interface AntigravityProviderState {
153 readonly draft: ServerProviderDraft;
154 readonly authRevision: number;
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 };
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: {
186 displayName: "Antigravity",
187 showInteractionModeToggle: false,
188 // No automatic review, so Auto falls back to Supervised instead of approving everything.
189 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"],
190 },
191 enabled: settings.enabled,
192 checkedAt,
193 models: [],
194 probe: {
195 installed: false,
196 version: null,
197 status: "warning",
198 auth: { status: "unknown", ...(options.auth ? { type: options.auth.type } : {}) },
199 message: settings.enabled
200 ? "Checking Antigravity availability."
201 : "Antigravity is disabled in T3 Code settings.",
202 },
203 }),
204 setup: { canAuthenticate: true, canInstall: true },
205 supportsConversationRollback: false,
206 supportsTextGeneration: false,
207 workspaceSnapshots: [],
208 } satisfies ServerProviderDraft;
209 const metadata = yield* SubscriptionRef.make<AntigravityProviderState>({
210 draft: initialDraft,
211 authRevision: 0,
212 });
213 // Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them.
214 const discoveredSkills = new Map<string, ServerProvider["skills"]>();
215 const thinkingLevels = new Map<string, ThinkingConfig | null>();
216 const observeThinkingLevels = (
217 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
218 ) => {
219 const model = configOptions?.find(
220 (option) => option.id === "model" || option.category === "model",
221 );
222 if (model?.type === "select" && model.currentValue) {
223 thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null);
224 }
225 };
226 const getSnapshot = SubscriptionRef.get(metadata).pipe(
227 Effect.flatMap((state) => options.stampIdentity(state.draft)),
228 );
229​
230 // The quota read can take 30 seconds, so it never blocks readiness or a session start.
231 // One read runs at a time; sign-in and sign-out interrupt it so a stale account never lands.
232 const usageRead = yield* FiberHandle.make();
233 const republish = yield* Deferred.make<Effect.Effect<ServerProvider>>();
234 const scope = yield* Effect.scope;
235 const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {
236 if (!options.probeUsage || (yield* PublishingUsage)) return;
237 yield* FiberHandle.run(
238 usageRead,
239 options.probeUsage.pipe(
240 Effect.flatMap((probed) =>
241 SubscriptionRef.update(metadata, (state) => ({
242 ...state,
243 draft: {
244 ...state.draft,
245 usageLimits: resolveUsageLimitsAfterProbe({
246 published: state.draft.usageLimits,
247 probed,
248 }),
249 },
250 })),
251 ),
252 // Enrichment cannot change published limits; a health check publishes them.
253 Effect.andThen(
254 Deferred.await(republish).pipe(
255 Effect.flatten,
256 Effect.provideService(PublishingUsage, true),
257 Effect.ignoreCause({ log: true }),
258 Effect.forkIn(scope),
259 ),
260 ),
261 ),
262 // Store the fiber before it runs, so a sign-out during the read can interrupt it.
263 { onlyIfMissing: true, startImmediately: false },
264 );
265 });
266 const resetUsage = Effect.gen(function* () {
267 yield* FiberHandle.clear(usageRead);
268 if (options.clearUsage) yield* options.clearUsage;
269 });
270​
271 const checkProvider = Effect.fn("checkAntigravityProvider")(function* () {
272 if (!settings.enabled) return yield* getSnapshot;
273 const before = yield* SubscriptionRef.get(metadata);
274 const result = yield* options.probe.pipe(
275 Effect.timeoutOption(HEALTH_CHECK_TIMEOUT),
276 Effect.result,
277 );
278 const initialized =
279 Result.isSuccess(result) && Option.isSome(result.success) ? result.success.value : undefined;
280 const version = initialized?.agentInfo?.version;
281 const failure = Result.isFailure(result) ? result.failure : undefined;
282 const missingInstallation = failure !== undefined && isMissingInstallation(failure);
283 const errorMessage =
284 initialized !== undefined
285 ? undefined
286 : failure?._tag === "ProviderSetupError"
287 ? failure.detail.trim() || "Antigravity could not complete its local health check."
288 : missingInstallation
289 ? "Antigravity ACP runtime is not installed or its executable could not be found."
290 : failure
291 ? "Antigravity could not complete its local health check."
292 : `Antigravity did not respond to its local health check within ${HEALTH_CHECK_TIMEOUT}.`;
293 const supportsTextGeneration =
294 initialized !== undefined ? yield* options.supportsTextGeneration : false;
295 const updatedAt = DateTime.formatIso(yield* DateTime.now);
296 const next = yield* SubscriptionRef.updateAndGet(metadata, (state) => {
297 if (state.authRevision !== before.authRevision) return state;
298 const { message: _previousMessage, ...draft } = state.draft;
299 const authenticated = draft.auth.status === "authenticated";
300 const message =
301 errorMessage ??
302 (authenticated
303 ? undefined
304 : draft.auth.status === "unauthenticated"
305 ? signInMessage
306 : authUncheckedMessage);
307 return {
308 ...state,
309 draft: {
310 ...draft,
311 installed: !missingInstallation,
312 // Lightweight custom-launcher probes lack versions; preserve the real handshake's version.
313 version: version === "unknown" ? draft.version : version || draft.version,
314 status: errorMessage ? "error" : authenticated ? "ready" : "warning",
315 checkedAt: updatedAt,
316 usageLimits: missingInstallation ? undefined : draft.usageLimits,
317 ...(missingInstallation
318 ? {
319 models: [],
320 slashCommands: [],
321 skills: [],
322 workspaceSnapshots: [],
323 supportsTextGeneration: false,
324 }
325 : {}),
326 ...(initialized !== undefined
327 ? {
328 supportsTextGeneration:
329 supportsTextGeneration && draft.auth.status !== "unauthenticated",
330 }
331 : {}),
332 ...(message ? { message } : {}),
333 },
334 } satisfies AntigravityProviderState;
335 });
336 if (initialized !== undefined) yield* refreshUsage();
337 return yield* options.stampIdentity(next.draft);
338 });
339​
340 const maintenanceCapabilities =
341 options.maintenanceCapabilities ??
342 makeManualOnlyProviderMaintenanceCapabilities({
343 provider: ProviderDriverKind.make("antigravity"),
344 packageName: null,
345 });
346 const managed = yield* makeManagedServerProvider({
347 resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
348 getSettings: Effect.succeed(settings),
349 streamSettings: Stream.empty,
350 haveSettingsChanged: () => false,
351 initialSnapshot: () => getSnapshot,
352 checkProvider: checkProvider(),
353 enrichSnapshot: ({ publishSnapshot }) =>
354 SubscriptionRef.changes(metadata).pipe(
355 Stream.runForEach((state) =>
356 options.stampIdentity(state.draft).pipe(Effect.flatMap(publishSnapshot)),
357 ),
358 ),
359 });
360 yield* Deferred.succeed(republish, managed.refresh);
361​
362 const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
363 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
364 cwd?: string,
365 ) {
366 if (!settings.enabled) return;
367 observeThinkingLevels(started.sessionSetupResult.configOptions);
368 const before = yield* SubscriptionRef.get(metadata);
369 const supportsTextGeneration = yield* options.supportsTextGeneration;
370 const updatedAt = DateTime.formatIso(yield* DateTime.now);
371 yield* SubscriptionRef.update(metadata, (state) => {
372 if (
373 state.authRevision !== before.authRevision &&
374 state.draft.auth.status === "unauthenticated"
375 ) {
376 return state;
377 }
378 const { message: _previousMessage, ...draft } = state.draft;
379 const workspaces = draft.workspaceSnapshots ?? [];
380 const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined;
381 return {
382 authRevision: state.authRevision + 1,
383 draft: {
384 ...draft,
385 installed: true,
386 status: "ready",
387 version: started.initializeResult.agentInfo?.version || draft.version,
388 auth: {
389 status: "authenticated",
390 type: options.auth?.type ?? "oauth-personal",
391 label: options.auth?.label ?? "Google account",
392 },
393 checkedAt: updatedAt,
394 models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels),
395 supportsTextGeneration,
396 ...(cwd
397 ? {
398 workspaceSnapshots: [
399 ...workspaces.filter((entry) => entry.cwd !== cwd),
400 {
401 cwd,
402 checkedAt: updatedAt,
403 slashCommands: workspace?.slashCommands ?? draft.slashCommands,
404 skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [],
405 },
406 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
407 }
408 : {}),
409 },
410 } satisfies AntigravityProviderState;
411 });
412 if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage();
413 });
414​
415 const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
416 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
417 ) {
418 observeThinkingLevels(configOptions);
419 const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels);
420 yield* SubscriptionRef.update(metadata, (state) => {
421 if (state.draft.auth.status !== "authenticated") return state;
422 return { ...state, draft: { ...state.draft, models } };
423 });
424 });
425​
426 const onAvailableCommands = Effect.fn("AntigravityProvider.onAvailableCommands")(function* (
427 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
428 cwd?: string,
429 ) {
430 if (!settings.enabled) return;
431 const slashCommands = nativeCommands(commands);
432 const updatedAt = DateTime.formatIso(yield* DateTime.now);
433 yield* SubscriptionRef.update(metadata, (state) => {
434 if (state.draft.auth.status === "unauthenticated") return state;
435 return {
436 ...state,
437 draft: {
438 ...state.draft,
439 slashCommands,
440 ...(cwd
441 ? {
442 workspaceSnapshots: [
443 ...(state.draft.workspaceSnapshots ?? []).filter((entry) => entry.cwd !== cwd),
444 {
445 cwd,
446 checkedAt: updatedAt,
447 slashCommands,
448 skills:
449 state.draft.workspaceSnapshots?.find((entry) => entry.cwd === cwd)?.skills ??
450 discoveredSkills.get(cwd) ??
451 [],
452 },
453 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
454 }
455 : {}),
456 },
457 };
458 });
459 });
460​
461 const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {
462 yield* resetUsage;
463 if (!settings.enabled) return;
464 const updatedAt = DateTime.formatIso(yield* DateTime.now);
465 yield* SubscriptionRef.update(
466 metadata,
467 (state) =>
468 ({
469 authRevision: state.authRevision + 1,
470 draft: {
471 ...state.draft,
472 auth: {
473 status: "unauthenticated",
474 ...(usesCredentials ? options.auth : {}),
475 },
476 status: "warning",
477 message: signInMessage,
478 checkedAt: updatedAt,
479 models: [],
480 slashCommands: [],
481 skills: [],
482 workspaceSnapshots: [],
483 supportsTextGeneration: false,
484 usageLimits: undefined,
485 },
486 }) satisfies AntigravityProviderState,
487 );
488 discoveredSkills.clear();
489 thinkingLevels.clear();
490 });
491​
492 const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* (
493 cwd: string,
494 skills?: ServerProvider["skills"],
495 ) {
496 if (skills) {
497 discoveredSkills.set(cwd, skills);
498 yield* SubscriptionRef.update(metadata, (state) =>
499 state.draft.workspaceSnapshots?.some((entry) => entry.cwd === cwd)
500 ? {
501 ...state,
502 draft: {
503 ...state.draft,
504 workspaceSnapshots: state.draft.workspaceSnapshots.map((entry) =>
505 entry.cwd === cwd ? { ...entry, skills } : entry,
506 ),
507 },
508 }
509 : state,
510 );
511 }
512 const snapshot = yield* getSnapshot;
513 const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd);
514 const resolvedSkills = skills ?? workspace?.skills ?? discoveredSkills.get(cwd) ?? [];
515 return workspace
516 ? { ...snapshot, slashCommands: workspace.slashCommands, skills: resolvedSkills }
517 : { ...snapshot, skills: resolvedSkills };
518 });
519​
520 return {
521 snapshot: { ...managed, getSnapshot },
522 onSessionStarted,
523 onConfigOptionsUpdated,
524 onAvailableCommands,
525 // The new sign-in may be another account. Clear and republish its limits so a failed read
526 // cannot fall back to them; the session start then reads the new account's limits.
527 onSignedIn: resetUsage.pipe(
528 Effect.andThen(
529 SubscriptionRef.update(metadata, (state) => {
530 const { usageLimits: _previousAccount, ...draft } = state.draft;
531 return { ...state, draft };
532 }),
533 ),
534 Effect.andThen(
535 Deferred.await(republish).pipe(
536 Effect.flatten,
537 Effect.provideService(PublishingUsage, true),
538 ),
539 ),
540 Effect.asVoid,
541 ),
542 onSignedOut: clearAccountMetadata(),
543 onAuthRequired: clearAccountMetadata(),
544 snapshotForCwd,
545 };
546});