Open History to see the last commit
1import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
2import {
3 ANTIGRAVITY_DEFAULT_MODEL,
4 ProviderDriverKind,
5 type AntigravitySettings,
6 type ProviderSetupError,
7 type RuntimeMode,
8 type ServerProvider,
9 type ServerProviderModel,
10 type ServerProviderSlashCommand,
11} from "@t3tools/contracts";
12import { createModelCapabilities } from "@t3tools/shared/model";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Equal from "effect/Equal";
16import * as Option from "effect/Option";
17import * as Predicate from "effect/Predicate";
18import * as Result from "effect/Result";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import type * as EffectAcpErrors from "effect-acp/errors";
22import type * as EffectAcpSchema from "effect-acp/compat";
23
24import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
25import { parseSessionModeState } from "@t3tools/provider-acp/server/runtimeModel";
26import { acpProviderOptionDescriptors } from "@t3tools/provider-acp/server/sessionConfig";
27import {
28 DeferringFailedCheck,
29 makeManagedServerProvider,
30} from "@t3tools/provider-core/server/managedProvider";
31import {
32 makeManualOnlyProviderMaintenanceCapabilities,
33 type ProviderMaintenanceCapabilities,
34} from "@t3tools/provider-core/server/maintenanceResolver";
35import {
36 buildServerProvider,
37 isCommandMissingCause,
38 type ServerProviderDraft,
39} from "@t3tools/provider-core/server/snapshotProbe";
40
41import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts";
42
43const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] });
44const MAX_WORKSPACE_SNAPSHOTS = 32;
45const HEALTH_CHECK_TIMEOUT_MS = 90_000;
46const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity.";
47const AUTH_UNCHECKED_MESSAGE =
48 "Antigravity is installed. Google account access is not checked yet.";
49
50type SessionSetupResult = Pick<
51 AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
52 "configOptions" | "models"
53>;
54
55type ThinkingConfig = NonNullable<ReturnType<typeof antigravityThinkingConfig>>;
56
57/** Thinking options each model reported when selected; `null` means it has none. */
58export type AntigravityThinkingLevels = ReadonlyMap<string, ThinkingConfig | null>;
59
60function thinkingCapabilities(config: ThinkingConfig | null | undefined) {
61 const descriptor = config
62 ? acpProviderOptionDescriptors({ configOptions: [config], modeState: undefined })[0]
63 : undefined;
64 if (descriptor?.type !== "select") return EMPTY_MODEL_CAPABILITIES;
65 return createModelCapabilities({ optionDescriptors: [descriptor] });
66}
67
68function selectOptionValues(config: ThinkingConfig): ReadonlyArray<string> {
69 return config.options.flatMap((entry) =>
70 "value" in entry ? [entry.value] : entry.options.map((option) => option.value),
71 );
72}
73
74function mergeLiveThinkingConfig(
75 existing: ThinkingConfig | null | undefined,
76 next: ThinkingConfig | null,
77): ThinkingConfig | null | undefined {
78 if (existing === undefined) return undefined;
79 if (next === null) return null;
80 if (existing === null) return undefined;
81 return selectOptionValues(next).includes(existing.currentValue)
82 ? { ...next, currentValue: existing.currentValue }
83 : next;
84}
85
86function sessionModelSlug(setup: SessionSetupResult): string | undefined {
87 const config = setup.configOptions?.find(
88 (option) => option.id === "model" || option.category === "model",
89 );
90 return config?.type === "select" ? config.currentValue : setup.models?.currentModelId;
91}
92
93export function buildAntigravityModelsFromSession(
94 setup: SessionSetupResult,
95 thinkingLevels: AntigravityThinkingLevels = new Map(),
96 options?: {
97 readonly defaultModel?: string | undefined;
98 readonly authoritative?: boolean;
99 },
100): ReadonlyArray<ServerProviderModel> {
101 const config = setup.configOptions?.find(
102 (option) => option.id === "model" || option.category === "model",
103 );
104 const currentValue =
105 config?.type === "select" ? config.currentValue : setup.models?.currentModelId;
106 const entries =
107 config?.type === "select"
108 ? config.options.flatMap((entry) => ("value" in entry ? [entry] : entry.options))
109 : config === undefined
110 ? (setup.models?.availableModels.map((model) => ({
111 value: model.modelId,
112 name: model.name,
113 })) ?? [])
114 : [];
115 const authoritative = options?.authoritative ?? true;
116 const defaultModel =
117 options?.defaultModel !== undefined
118 ? entries.some((entry) => entry.value === options.defaultModel)
119 ? options.defaultModel
120 : currentValue
121 : authoritative
122 ? currentValue
123 : undefined;
124 const currentThinking = antigravityThinkingConfig(setup.configOptions);
125 const seen = new Set<string>();
126 // The agent can list two IDs under one name; label the later ones so the picker tells them apart.
127 const names = new Set<string>();
128 return entries.flatMap((entry): ServerProviderModel[] => {
129 if (!entry.value.trim() || seen.has(entry.value)) return [];
130 seen.add(entry.value);
131 const baseName = entry.name.trim() ? entry.name : entry.value;
132 const name = names.has(baseName) ? `${baseName} (${entry.value})` : baseName;
133 names.add(baseName);
134 const observed =
135 authoritative && entry.value === currentValue
136 ? (currentThinking ?? null)
137 : thinkingLevels.get(entry.value);
138 return [
139 {
140 slug: entry.value,
141 name,
142 isCustom: false,
143 ...(entry.value === defaultModel
144 ? { isDefault: true, aliases: [ANTIGRAVITY_DEFAULT_MODEL] }
145 : {}),
146 // Levels differ per model; an unobserved model reports none so the registry keeps its cached ones.
147 capabilities: thinkingCapabilities(observed),
148 },
149 ];
150 });
151}
152
153function nativeCommands(
154 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
155): ReadonlyArray<ServerProviderSlashCommand> {
156 const seen = new Set<string>();
157 return commands.flatMap((command): ServerProviderSlashCommand[] => {
158 if (!command.name.trim() || seen.has(command.name)) return [];
159 seen.add(command.name);
160 const description = command.description.trim();
161 const hint = command.input?.hint.trim();
162 return [
163 {
164 name: command.name,
165 ...(description ? { description } : {}),
166 ...(hint ? { input: { hint } } : {}),
167 },
168 ];
169 });
170}
171
172function isMissingInstallation(error: EffectAcpErrors.AcpError | ProviderSetupError): boolean {
173 if (error._tag === "AcpSpawnError") {
174 return (
175 isCommandMissingCause(error.cause) ||
176 (Predicate.isObject(error.cause) && error.cause.code === "ENOENT")
177 );
178 }
179 return (
180 error._tag === "ProviderSetupError" &&
181 error.operation === "resolve" &&
182 /not installed|missing|incomplete|changed on disk|does not publish/i.test(error.detail)
183 );
184}
185
186interface AntigravityProviderState {
187 readonly draft: ServerProviderDraft;
188 readonly authRevision: number;
189}
190
191interface AntigravityProviderOptions {
192 readonly environment?: NodeJS.ProcessEnv;
193 readonly stampIdentity: (snapshot: ServerProviderDraft) => Effect.Effect<ServerProvider>;
194 readonly probe: Effect.Effect<
195 EffectAcpSchema.InitializeResponse,
196 EffectAcpErrors.AcpError | ProviderSetupError
197 >;
198 readonly supportsTextGeneration: Effect.Effect<boolean>;
199 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
200 readonly auth?: { readonly type: string; readonly label: string };
201 /** Modes the last session advertised, saved because initialize alone does not report them. */
202 readonly rememberedRuntimeModes?: ReadonlyArray<RuntimeMode>;
203 readonly rememberRuntimeModes?: (modes: ReadonlyArray<RuntimeMode>) => Effect.Effect<void>;
204}
205
206const RUNTIME_MODES_WITHOUT_AUTO = [
207 "approval-required",
208 "auto-accept-edits",
209 "full-access",
210] as const;
211
212/** Auto is offered only where the session advertises agy's own Auto; elsewhere it runs Supervised. */
213function antigravityRuntimeModes(
214 sessionSetupResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
215): ReadonlyArray<RuntimeMode> {
216 return parseSessionModeState(sessionSetupResult)?.availableModes.some(
217 (mode) => mode.id === "auto",
218 )
219 ? ["approval-required", "auto-accept-edits", "auto", "full-access"]
220 : RUNTIME_MODES_WITHOUT_AUTO;
221}
222
223export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(function* (
224 settings: AntigravitySettings,
225 options: AntigravityProviderOptions,
226) {
227 const usesCredentials =
228 options.auth?.type === "gemini-api-key" || options.auth?.type === "agent-platform";
229 const signInMessage = usesCredentials
230 ? `Connect with ${options.auth.label} to use Antigravity and load models.`
231 : SIGN_IN_MESSAGE;
232 const authUncheckedMessage = usesCredentials
233 ? `Antigravity is installed. Connect with ${options.auth.label} to load models.`
234 : AUTH_UNCHECKED_MESSAGE;
235 const checkedAt = DateTime.formatIso(yield* DateTime.now);
236 const initialDraft = {
237 ...buildServerProvider({
238 presentation: {
239 displayName: "Antigravity",
240 showInteractionModeToggle: false,
241 supportedRuntimeModes: options.rememberedRuntimeModes ?? RUNTIME_MODES_WITHOUT_AUTO,
242 },
243 enabled: settings.enabled,
244 checkedAt,
245 models: [],
246 probe: {
247 installed: false,
248 version: null,
249 status: "warning",
250 auth: { status: "unknown", ...(options.auth ? { type: options.auth.type } : {}) },
251 message: settings.enabled
252 ? "Checking Antigravity availability."
253 : "Antigravity is disabled in T3 Code settings.",
254 },
255 }),
256 setup: { canAuthenticate: true, canInstall: true },
257 supportsConversationRollback: true,
258 supportsTextGeneration: false,
259 workspaceSnapshots: [],
260 } satisfies ServerProviderDraft;
261 const metadata = yield* SubscriptionRef.make<AntigravityProviderState>({
262 draft: initialDraft,
263 authRevision: 0,
264 });
265 // Skills from the registry's last scan of each folder. A folder without them stays pending so it is scanned.
266 const discoveredSkills = new Map<string, ServerProvider["skills"]>();
267 // Commands of folders whose draft entry a skill scan dropped, so later scans still report them.
268 const workspaceCommands = new Map<string, ServerProvider["slashCommands"]>();
269 const thinkingLevels = new Map<string, ThinkingConfig | null>();
270 let defaultModelSlug: string | undefined;
271 const observeThinkingLevels = (
272 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
273 authoritative: boolean,
274 ) => {
275 const model = configOptions?.find(
276 (option) => option.id === "model" || option.category === "model",
277 );
278 if (model?.type !== "select" || !model.currentValue) return;
279 const next = antigravityThinkingConfig(configOptions) ?? null;
280 if (authoritative) {
281 thinkingLevels.set(model.currentValue, next);
282 return;
283 }
284 const merged = mergeLiveThinkingConfig(thinkingLevels.get(model.currentValue), next);
285 if (merged !== undefined) {
286 thinkingLevels.set(model.currentValue, merged);
287 }
288 };
289 const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* (
290 previous: ReadonlyArray<RuntimeMode> | undefined,
291 next: ReadonlyArray<RuntimeMode>,
292 ) {
293 if (options.rememberRuntimeModes && previous?.join() !== next.join()) {
294 yield* options.rememberRuntimeModes(next);
295 }
296 });
297 const getSnapshot = SubscriptionRef.get(metadata).pipe(
298 Effect.flatMap((state) => options.stampIdentity(state.draft)),
299 );
300
301 const checkProvider = Effect.fn("checkAntigravityProvider")(function* () {
302 if (!settings.enabled) return yield* getSnapshot;
303 const before = yield* SubscriptionRef.get(metadata);
304 const timeoutMs = resolveProviderProbeTimeoutMs(
305 "antigravity",
306 HEALTH_CHECK_TIMEOUT_MS,
307 options.environment,
308 );
309 const result = yield* options.probe.pipe(Effect.timeoutOption(timeoutMs), Effect.result);
310 const initialized =
311 Result.isSuccess(result) && Option.isSome(result.success) ? result.success.value : undefined;
312 const version = initialized?.agentInfo?.version;
313 const failure = Result.isFailure(result) ? result.failure : undefined;
314 const missingInstallation = failure !== undefined && isMissingInstallation(failure);
315 const errorMessage =
316 initialized !== undefined
317 ? undefined
318 : failure?._tag === "ProviderSetupError"
319 ? failure.detail.trim() || "Antigravity could not complete its local health check."
320 : missingInstallation
321 ? "Antigravity ACP runtime is not installed or its executable could not be found."
322 : failure
323 ? "Antigravity could not complete its local health check."
324 : `Antigravity did not respond to its local health check within ${timeoutMs / 1_000} seconds.`;
325 const supportsTextGeneration =
326 initialized !== undefined ? yield* options.supportsTextGeneration : false;
327 const updatedAt = DateTime.formatIso(yield* DateTime.now);
328 const applyCheck = (state: AntigravityProviderState) => {
329 if (state.authRevision !== before.authRevision) return state;
330 const { message: _previousMessage, ...draft } = state.draft;
331 const authenticated = draft.auth.status === "authenticated";
332 const message =
333 errorMessage ??
334 (authenticated
335 ? undefined
336 : draft.auth.status === "unauthenticated"
337 ? signInMessage
338 : authUncheckedMessage);
339 return {
340 ...state,
341 draft: {
342 ...draft,
343 installed: !missingInstallation,
344 // Lightweight custom-launcher probes lack versions; preserve the real handshake's version.
345 version: version === "unknown" ? draft.version : version || draft.version,
346 status: errorMessage ? "error" : authenticated ? "ready" : "warning",
347 checkedAt: updatedAt,
348 ...(missingInstallation
349 ? {
350 models: [],
351 slashCommands: [],
352 skills: [],
353 workspaceSnapshots: [],
354 supportsTextGeneration: false,
355 }
356 : {}),
357 ...(initialized !== undefined
358 ? {
359 supportsTextGeneration:
360 supportsTextGeneration && draft.auth.status !== "unauthenticated",
361 }
362 : {}),
363 ...(message ? { message } : {}),
364 },
365 } satisfies AntigravityProviderState;
366 };
367 // This state is published as it changes, so a failure the managed provider discards stays out.
368 const deferFailure = errorMessage !== undefined && (yield* DeferringFailedCheck);
369 const next = yield* SubscriptionRef.modifySome(metadata, (state) => {
370 const checked = applyCheck(state);
371 const stored = deferFailure && state.draft.status === "ready" ? state : checked;
372 return [checked, stored === state ? Option.none() : Option.some(stored)];
373 });
374 return yield* options.stampIdentity(next.draft);
375 });
376
377 const maintenanceCapabilities =
378 options.maintenanceCapabilities ??
379 makeManualOnlyProviderMaintenanceCapabilities({
380 provider: ProviderDriverKind.make("antigravity"),
381 packageName: null,
382 });
383 const managed = yield* makeManagedServerProvider({
384 resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
385 getSettings: Effect.succeed(settings),
386 streamSettings: Stream.empty,
387 haveSettingsChanged: () => false,
388 initialSnapshot: () => getSnapshot,
389 checkProvider: checkProvider(),
390 enrichSnapshot: ({ publishSnapshot }) =>
391 SubscriptionRef.changes(metadata).pipe(
392 Stream.runForEach((state) =>
393 options.stampIdentity(state.draft).pipe(Effect.flatMap(publishSnapshot)),
394 ),
395 ),
396 });
397
398 const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
399 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
400 cwd?: string,
401 session?: { readonly resumed?: boolean },
402 ) {
403 if (!settings.enabled) return;
404 const authoritative = session?.resumed !== true;
405 if (authoritative) {
406 const modelSlug = sessionModelSlug(started.sessionSetupResult);
407 if (modelSlug) defaultModelSlug = modelSlug;
408 }
409 observeThinkingLevels(started.sessionSetupResult.configOptions, authoritative);
410 const before = yield* SubscriptionRef.get(metadata);
411 const supportsTextGeneration = yield* options.supportsTextGeneration;
412 const updatedAt = DateTime.formatIso(yield* DateTime.now);
413 const supportedRuntimeModes = antigravityRuntimeModes(started.sessionSetupResult);
414 const previousModes = yield* SubscriptionRef.modify(metadata, (state) => {
415 if (
416 state.authRevision !== before.authRevision &&
417 state.draft.auth.status === "unauthenticated"
418 ) {
419 return [supportedRuntimeModes, state] as const;
420 }
421 const { message: _previousMessage, ...draft } = state.draft;
422 const workspaces = draft.workspaceSnapshots ?? [];
423 const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined;
424 const skills = cwd ? discoveredSkills.get(cwd) : undefined;
425 const next = {
426 authRevision: state.authRevision + 1,
427 draft: {
428 ...draft,
429 installed: true,
430 status: "ready",
431 version: started.initializeResult.agentInfo?.version || draft.version,
432 auth: {
433 status: "authenticated",
434 type: options.auth?.type ?? "oauth-personal",
435 label: options.auth?.label ?? "Google account",
436 },
437 checkedAt: updatedAt,
438 models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels, {
439 defaultModel: defaultModelSlug,
440 authoritative,
441 }),
442 supportedRuntimeModes,
443 supportsTextGeneration,
444 ...(cwd
445 ? {
446 workspaceSnapshots: [
447 ...workspaces.filter((entry) => entry.cwd !== cwd),
448 {
449 cwd,
450 checkedAt: updatedAt,
451 slashCommands:
452 workspace?.slashCommands ?? workspaceCommands.get(cwd) ?? draft.slashCommands,
453 skills: skills ?? workspace?.skills ?? [],
454 ...(skills ? {} : { slashCommandsPending: true }),
455 },
456 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
457 }
458 : {}),
459 },
460 } satisfies AntigravityProviderState;
461 return [draft.supportedRuntimeModes, next] as const;
462 });
463 yield* rememberRuntimeModes(previousModes, supportedRuntimeModes);
464 });
465
466 const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
467 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
468 update?: { readonly fromCatalogProbe?: boolean },
469 ) {
470 // Only catalog probes report a model's default level; live sessions carry per-thread overrides.
471 const authoritative = update?.fromCatalogProbe === true;
472 observeThinkingLevels(configOptions, authoritative);
473 const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels, {
474 defaultModel: defaultModelSlug,
475 authoritative,
476 });
477 yield* SubscriptionRef.updateSome(metadata, (state) => {
478 if (state.draft.auth.status !== "authenticated" || Equal.equals(state.draft.models, models)) {
479 return Option.none();
480 }
481 return Option.some({ ...state, draft: { ...state.draft, models } });
482 });
483 });
484
485 const onAvailableCommands = Effect.fn("AntigravityProvider.onAvailableCommands")(function* (
486 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
487 cwd?: string,
488 ) {
489 if (!settings.enabled) return;
490 const slashCommands = nativeCommands(commands);
491 const updatedAt = DateTime.formatIso(yield* DateTime.now);
492 const skills = cwd ? discoveredSkills.get(cwd) : undefined;
493 yield* SubscriptionRef.update(metadata, (state) => {
494 if (state.draft.auth.status === "unauthenticated") return state;
495 return {
496 ...state,
497 draft: {
498 ...state.draft,
499 slashCommands,
500 ...(cwd
501 ? {
502 workspaceSnapshots: [
503 ...(state.draft.workspaceSnapshots ?? []).filter((entry) => entry.cwd !== cwd),
504 {
505 cwd,
506 checkedAt: updatedAt,
507 slashCommands,
508 skills:
509 skills ??
510 state.draft.workspaceSnapshots?.find((entry) => entry.cwd === cwd)?.skills ??
511 [],
512 ...(skills ? {} : { slashCommandsPending: true }),
513 },
514 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
515 }
516 : {}),
517 },
518 };
519 });
520 });
521
522 const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {
523 if (!settings.enabled) return;
524 const updatedAt = DateTime.formatIso(yield* DateTime.now);
525 const previousModes = yield* SubscriptionRef.modify(metadata, (state) => [
526 state.draft.supportedRuntimeModes,
527 {
528 authRevision: state.authRevision + 1,
529 draft: {
530 ...state.draft,
531 auth: {
532 status: "unauthenticated",
533 ...(usesCredentials ? options.auth : {}),
534 },
535 status: "warning",
536 message: signInMessage,
537 checkedAt: updatedAt,
538 models: [],
539 slashCommands: [],
540 skills: [],
541 workspaceSnapshots: [],
542 supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO,
543 supportsTextGeneration: false,
544 },
545 } satisfies AntigravityProviderState,
546 ]);
547 yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO);
548 discoveredSkills.clear();
549 workspaceCommands.clear();
550 thinkingLevels.clear();
551 defaultModelSlug = undefined;
552 });
553
554 const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* (
555 cwd: string,
556 skills?: ServerProvider["skills"],
557 ) {
558 const snapshot = yield* getSnapshot;
559 const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd);
560 if (skills) {
561 discoveredSkills.set(cwd, skills);
562 if (workspace) workspaceCommands.set(cwd, workspace.slashCommands);
563 // The registry keeps the folder it scans. Changing the entry mid-scan would discard the scan.
564 yield* SubscriptionRef.updateSome(metadata, (state) =>
565 state.draft.workspaceSnapshots?.some((entry) => entry.cwd === cwd)
566 ? Option.some({
567 ...state,
568 draft: {
569 ...state.draft,
570 workspaceSnapshots: state.draft.workspaceSnapshots.filter(
571 (entry) => entry.cwd !== cwd,
572 ),
573 },
574 })
575 : Option.none(),
576 );
577 }
578 const resolvedSkills = skills ?? workspace?.skills ?? discoveredSkills.get(cwd) ?? [];
579 const slashCommands = workspace?.slashCommands ?? workspaceCommands.get(cwd);
580 return slashCommands
581 ? { ...snapshot, slashCommands, skills: resolvedSkills }
582 : { ...snapshot, skills: resolvedSkills };
583 });
584
585 return {
586 snapshot: { ...managed, getSnapshot },
587 onSessionStarted,
588 onConfigOptionsUpdated,
589 onAvailableCommands,
590 onSignedOut: clearAccountMetadata(),
591 onAuthRequired: clearAccountMetadata(),
592 snapshotForCwd,
593 };
594});