import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { ANTIGRAVITY_DEFAULT_MODEL, ProviderDriverKind, type AntigravitySettings, type ProviderSetupError, type ServerProvider, type ServerProviderModel, type ServerProviderSlashCommand, type ServerProviderUsageLimits, } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FiberHandle from "effect/FiberHandle"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import type * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { acpProviderOptionDescriptors } from "@t3tools/provider-acp/server/sessionConfig"; import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider"; import { makeManualOnlyProviderMaintenanceCapabilities, type ProviderMaintenanceCapabilities, } from "@t3tools/provider-core/server/maintenanceResolver"; import { buildServerProvider, isCommandMissingCause, type ServerProviderDraft, } from "@t3tools/provider-core/server/snapshotProbe"; import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usageLimits"; import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts"; const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] }); const MAX_WORKSPACE_SNAPSHOTS = 32; const HEALTH_CHECK_TIMEOUT_MS = 90_000; // A keyring waiting on an unlock prompt must not hold up a health check or session start. const STORED_ACCOUNT_READ_TIMEOUT_MS = 5_000; const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity."; const AUTH_UNCHECKED_MESSAGE = "Antigravity is installed. Google account access is not checked yet."; // Set while a finished quota read republishes, so that health check does not read again. const PublishingUsage = Context.Reference("t3/provider/AntigravityPublishingUsage", { defaultValue: () => false, }); type SessionSetupResult = Pick< AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"], "configOptions" | "models" >; type ThinkingConfig = NonNullable>; /** Thinking options each model reported when selected; `null` means it has none. */ export type AntigravityThinkingLevels = ReadonlyMap; function thinkingCapabilities(config: ThinkingConfig | null | undefined, observed: boolean) { const descriptor = config ? acpProviderOptionDescriptors({ configOptions: [config], modeState: undefined })[0] : undefined; if (descriptor?.type !== "select") return EMPTY_MODEL_CAPABILITIES; // Another model's selected level is not this model's default. const { currentValue: _currentValue, ...unobserved } = descriptor; return createModelCapabilities({ optionDescriptors: [observed ? descriptor : unobserved] }); } export function buildAntigravityModelsFromSession( setup: SessionSetupResult, thinkingLevels: AntigravityThinkingLevels = new Map(), ): ReadonlyArray { const config = setup.configOptions?.find( (option) => option.id === "model" || option.category === "model", ); const currentValue = config?.type === "select" ? config.currentValue : setup.models?.currentModelId; const entries = config?.type === "select" ? config.options.flatMap((entry) => ("value" in entry ? [entry] : entry.options)) : config === undefined ? (setup.models?.availableModels.map((model) => ({ value: model.modelId, name: model.name, })) ?? []) : []; const currentThinking = antigravityThinkingConfig(setup.configOptions); const seen = new Set(); // The agent can list two IDs under one name; label the later ones so the picker tells them apart. const names = new Set(); return entries.flatMap((entry): ServerProviderModel[] => { if (!entry.value.trim() || seen.has(entry.value)) return []; seen.add(entry.value); const baseName = entry.name.trim() ? entry.name : entry.value; const name = names.has(baseName) ? `${baseName} (${entry.value})` : baseName; names.add(baseName); const observed = entry.value === currentValue ? (currentThinking ?? null) : thinkingLevels.get(entry.value); return [ { slug: entry.value, name, isCustom: false, ...(entry.value === currentValue ? { isDefault: true, aliases: [ANTIGRAVITY_DEFAULT_MODEL] } : {}), capabilities: observed === undefined ? thinkingCapabilities(currentThinking, false) : thinkingCapabilities(observed, true), }, ]; }); } function nativeCommands( commands: ReadonlyArray, ): ReadonlyArray { const seen = new Set(); return commands.flatMap((command): ServerProviderSlashCommand[] => { if (!command.name.trim() || seen.has(command.name)) return []; seen.add(command.name); const description = command.description.trim(); const hint = command.input?.hint.trim(); return [ { name: command.name, ...(description ? { description } : {}), ...(hint ? { input: { hint } } : {}), }, ]; }); } function isMissingInstallation(error: EffectAcpErrors.AcpError | ProviderSetupError): boolean { if (error._tag === "AcpSpawnError") { return ( isCommandMissingCause(error.cause) || (Predicate.isObject(error.cause) && error.cause.code === "ENOENT") ); } return ( error._tag === "ProviderSetupError" && error.operation === "resolve" && /not installed|missing|incomplete|does not publish/i.test(error.detail) ); } interface AntigravityProviderState { readonly draft: ServerProviderDraft; readonly authRevision: number; } /** The sign-in the CLI will use next, read from its credential store. */ export type AntigravityStoredAccount = | { readonly status: "signed-in"; readonly email: string | undefined; readonly shared: boolean } | { readonly status: "signed-out" } | { readonly status: "unknown" }; interface AntigravityProviderOptions { readonly environment?: NodeJS.ProcessEnv; readonly stampIdentity: (snapshot: ServerProviderDraft) => Effect.Effect; readonly probe: Effect.Effect< EffectAcpSchema.InitializeResponse, EffectAcpErrors.AcpError | ProviderSetupError >; readonly supportsTextGeneration: Effect.Effect; readonly probeUsage?: Effect.Effect; readonly clearUsage?: Effect.Effect; readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities; readonly auth?: { readonly type: string; readonly label: string }; readonly readStoredAccount?: Effect.Effect; } export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(function* ( settings: AntigravitySettings, options: AntigravityProviderOptions, ) { const usesCredentials = options.auth?.type === "gemini-api-key" || options.auth?.type === "agent-platform"; const signInMessage = usesCredentials ? `Connect with ${options.auth.label} to use Antigravity and load models.` : SIGN_IN_MESSAGE; const authUncheckedMessage = usesCredentials ? `Antigravity is installed. Connect with ${options.auth.label} to load models.` : AUTH_UNCHECKED_MESSAGE; const authenticatedAuth = (account: AntigravityStoredAccount | undefined) => { const label = options.auth?.label ?? "Google account"; const signedIn = account?.status === "signed-in" ? account : undefined; return { status: "authenticated" as const, type: options.auth?.type ?? "oauth-personal", label: signedIn?.shared ? `${label} (shared)` : label, ...(signedIn?.email ? { email: signedIn.email } : {}), }; }; const readStoredAccount = (auth: ServerProviderDraft["auth"]) => auth.status === "authenticated" && options.readStoredAccount ? options.readStoredAccount.pipe( Effect.timeoutOption(STORED_ACCOUNT_READ_TIMEOUT_MS), Effect.map(Option.getOrElse((): AntigravityStoredAccount => ({ status: "unknown" }))), ) : Effect.undefined; // The previous account's limits must not show, or stay as a fallback, under the new email. const isOtherAccount = ( account: AntigravityStoredAccount | undefined, published: ServerProviderDraft["auth"], ) => account?.status === "signed-in" && account.email !== undefined && published.email !== undefined && account.email !== published.email; const checkedAt = DateTime.formatIso(yield* DateTime.now); const initialDraft = { ...buildServerProvider({ presentation: { displayName: "Antigravity", showInteractionModeToggle: false, // No automatic review, so Auto falls back to Supervised instead of approving everything. supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"], }, enabled: settings.enabled, checkedAt, models: [], probe: { installed: false, version: null, status: "warning", auth: { status: "unknown", ...(options.auth ? { type: options.auth.type } : {}) }, message: settings.enabled ? "Checking Antigravity availability." : "Antigravity is disabled in T3 Code settings.", }, }), setup: { canAuthenticate: true, canInstall: true }, supportsConversationRollback: false, supportsTextGeneration: false, workspaceSnapshots: [], } satisfies ServerProviderDraft; const metadata = yield* SubscriptionRef.make({ draft: initialDraft, authRevision: 0, }); // Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them. const discoveredSkills = new Map(); const thinkingLevels = new Map(); const observeThinkingLevels = ( configOptions: ReadonlyArray | null | undefined, ) => { const model = configOptions?.find( (option) => option.id === "model" || option.category === "model", ); if (model?.type === "select" && model.currentValue) { thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null); } }; const getSnapshot = SubscriptionRef.get(metadata).pipe( Effect.flatMap((state) => options.stampIdentity(state.draft)), ); // The quota read can take 30 seconds, so it never blocks readiness or a session start. // One read runs at a time; sign-in and sign-out interrupt it so a stale account never lands. const usageRead = yield* FiberHandle.make(); const republish = yield* Deferred.make>(); const scope = yield* Effect.scope; const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () { if (!options.probeUsage || (yield* PublishingUsage)) return; yield* FiberHandle.run( usageRead, options.probeUsage.pipe( Effect.flatMap((probed) => SubscriptionRef.update(metadata, (state) => ({ ...state, draft: { ...state.draft, usageLimits: resolveUsageLimitsAfterProbe({ published: state.draft.usageLimits, probed, }), }, })), ), // Enrichment cannot change published limits; a health check publishes them. Effect.andThen( Deferred.await(republish).pipe( Effect.flatten, Effect.provideService(PublishingUsage, true), Effect.ignoreCause({ log: true }), Effect.forkIn(scope), ), ), ), // Store the fiber before it runs, so a sign-out during the read can interrupt it. { onlyIfMissing: true, startImmediately: false }, ); }); const resetUsage = Effect.gen(function* () { yield* FiberHandle.clear(usageRead); if (options.clearUsage) yield* options.clearUsage; }); /** With `onlyAtRevision`, a sign-in recorded after that revision is kept. */ const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* ( onlyAtRevision?: number, ) { yield* resetUsage; if (!settings.enabled) return; const updatedAt = DateTime.formatIso(yield* DateTime.now); const cleared = yield* SubscriptionRef.modify(metadata, (state) => onlyAtRevision !== undefined && state.authRevision !== onlyAtRevision ? [false, state] : [ true, { authRevision: state.authRevision + 1, draft: { ...state.draft, auth: { status: "unauthenticated", ...(usesCredentials ? options.auth : {}), }, status: "warning", message: signInMessage, checkedAt: updatedAt, models: [], slashCommands: [], skills: [], workspaceSnapshots: [], supportsTextGeneration: false, usageLimits: undefined, }, } satisfies AntigravityProviderState, ], ); if (!cleared) return; discoveredSkills.clear(); thinkingLevels.clear(); }); const checkProvider = Effect.fn("checkAntigravityProvider")(function* () { if (!settings.enabled) return yield* getSnapshot; const previous = yield* SubscriptionRef.get(metadata); // Antigravity 1.5 keeps one Google sign-in per machine, so another instance or the // Antigravity app may have replaced or removed it since this instance's last session. const account = yield* readStoredAccount(previous.draft.auth); if (account?.status === "signed-out") yield* clearAccountMetadata(previous.authRevision); const before = yield* SubscriptionRef.get(metadata); // A session start during the read already published a newer account. const signedIn = account?.status === "signed-in" && before.authRevision === previous.authRevision ? account : undefined; const accountChanged = isOtherAccount(signedIn, before.draft.auth); if (accountChanged) yield* FiberHandle.clear(usageRead); const timeoutMs = resolveProviderProbeTimeoutMs( "antigravity", HEALTH_CHECK_TIMEOUT_MS, options.environment, ); const result = yield* options.probe.pipe(Effect.timeoutOption(timeoutMs), Effect.result); const initialized = Result.isSuccess(result) && Option.isSome(result.success) ? result.success.value : undefined; const version = initialized?.agentInfo?.version; const failure = Result.isFailure(result) ? result.failure : undefined; const missingInstallation = failure !== undefined && isMissingInstallation(failure); const errorMessage = initialized !== undefined ? undefined : failure?._tag === "ProviderSetupError" ? failure.detail.trim() || "Antigravity could not complete its local health check." : missingInstallation ? "Antigravity ACP runtime is not installed or its executable could not be found." : failure ? "Antigravity could not complete its local health check." : `Antigravity did not respond to its local health check within ${timeoutMs / 1_000} seconds.`; const supportsTextGeneration = initialized !== undefined ? yield* options.supportsTextGeneration : false; const updatedAt = DateTime.formatIso(yield* DateTime.now); const next = yield* SubscriptionRef.updateAndGet(metadata, (state) => { if (state.authRevision !== before.authRevision) return state; const { message: _previousMessage, ...draft } = state.draft; const authenticated = draft.auth.status === "authenticated"; const message = errorMessage ?? (authenticated ? undefined : draft.auth.status === "unauthenticated" ? signInMessage : authUncheckedMessage); return { ...state, draft: { ...draft, ...(signedIn && authenticated ? { auth: authenticatedAuth(signedIn) } : {}), installed: !missingInstallation, // Lightweight custom-launcher probes lack versions; preserve the real handshake's version. version: version === "unknown" ? draft.version : version || draft.version, status: errorMessage ? "error" : authenticated ? "ready" : "warning", checkedAt: updatedAt, usageLimits: missingInstallation || accountChanged ? undefined : draft.usageLimits, ...(missingInstallation ? { models: [], slashCommands: [], skills: [], workspaceSnapshots: [], supportsTextGeneration: false, } : {}), ...(initialized !== undefined ? { supportsTextGeneration: supportsTextGeneration && draft.auth.status !== "unauthenticated", } : {}), ...(message ? { message } : {}), }, } satisfies AntigravityProviderState; }); if (initialized !== undefined) yield* refreshUsage(); return yield* options.stampIdentity(next.draft); }); const maintenanceCapabilities = options.maintenanceCapabilities ?? makeManualOnlyProviderMaintenanceCapabilities({ provider: ProviderDriverKind.make("antigravity"), packageName: null, }); const managed = yield* makeManagedServerProvider({ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities), getSettings: Effect.succeed(settings), streamSettings: Stream.empty, haveSettingsChanged: () => false, initialSnapshot: () => getSnapshot, checkProvider: checkProvider(), enrichSnapshot: ({ publishSnapshot }) => SubscriptionRef.changes(metadata).pipe( Stream.runForEach((state) => options.stampIdentity(state.draft).pipe(Effect.flatMap(publishSnapshot)), ), ), }); yield* Deferred.succeed(republish, managed.refresh); const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* ( started: AcpSessionRuntime.AcpSessionRuntimeStartResult, cwd?: string, ) { if (!settings.enabled) return; observeThinkingLevels(started.sessionSetupResult.configOptions); const before = yield* SubscriptionRef.get(metadata); const supportsTextGeneration = yield* options.supportsTextGeneration; const account = yield* readStoredAccount({ status: "authenticated" }); const accountChanged = isOtherAccount(account, before.draft.auth); if (accountChanged) yield* FiberHandle.clear(usageRead); const updatedAt = DateTime.formatIso(yield* DateTime.now); yield* SubscriptionRef.update(metadata, (state) => { if ( state.authRevision !== before.authRevision && state.draft.auth.status === "unauthenticated" ) { return state; } const { message: _previousMessage, ...draft } = state.draft; const workspaces = draft.workspaceSnapshots ?? []; const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined; return { authRevision: state.authRevision + 1, draft: { ...draft, ...(accountChanged ? { usageLimits: undefined } : {}), installed: true, status: "ready", version: started.initializeResult.agentInfo?.version || draft.version, auth: account?.status === "unknown" && draft.auth.status === "authenticated" ? draft.auth : authenticatedAuth(account), checkedAt: updatedAt, models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), supportsTextGeneration, ...(cwd ? { workspaceSnapshots: [ ...workspaces.filter((entry) => entry.cwd !== cwd), { cwd, checkedAt: updatedAt, slashCommands: workspace?.slashCommands ?? draft.slashCommands, skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [], }, ].slice(-MAX_WORKSPACE_SNAPSHOTS), } : {}), }, } satisfies AntigravityProviderState; }); if (accountChanged || !before.draft.usageLimits || before.draft.usageLimits.unavailable) { yield* refreshUsage(); } }); const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* ( configOptions: ReadonlyArray, ) { observeThinkingLevels(configOptions); const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels); yield* SubscriptionRef.update(metadata, (state) => { if (state.draft.auth.status !== "authenticated") return state; return { ...state, draft: { ...state.draft, models } }; }); }); const onAvailableCommands = Effect.fn("AntigravityProvider.onAvailableCommands")(function* ( commands: ReadonlyArray, cwd?: string, ) { if (!settings.enabled) return; const slashCommands = nativeCommands(commands); const updatedAt = DateTime.formatIso(yield* DateTime.now); yield* SubscriptionRef.update(metadata, (state) => { if (state.draft.auth.status === "unauthenticated") return state; return { ...state, draft: { ...state.draft, slashCommands, ...(cwd ? { workspaceSnapshots: [ ...(state.draft.workspaceSnapshots ?? []).filter((entry) => entry.cwd !== cwd), { cwd, checkedAt: updatedAt, slashCommands, skills: state.draft.workspaceSnapshots?.find((entry) => entry.cwd === cwd)?.skills ?? discoveredSkills.get(cwd) ?? [], }, ].slice(-MAX_WORKSPACE_SNAPSHOTS), } : {}), }, }; }); }); const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* ( cwd: string, skills?: ServerProvider["skills"], ) { if (skills) { discoveredSkills.set(cwd, skills); yield* SubscriptionRef.update(metadata, (state) => state.draft.workspaceSnapshots?.some((entry) => entry.cwd === cwd) ? { ...state, draft: { ...state.draft, workspaceSnapshots: state.draft.workspaceSnapshots.map((entry) => entry.cwd === cwd ? { ...entry, skills } : entry, ), }, } : state, ); } const snapshot = yield* getSnapshot; const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd); const resolvedSkills = skills ?? workspace?.skills ?? discoveredSkills.get(cwd) ?? []; return workspace ? { ...snapshot, slashCommands: workspace.slashCommands, skills: resolvedSkills } : { ...snapshot, skills: resolvedSkills }; }); return { snapshot: { ...managed, getSnapshot }, onSessionStarted, onConfigOptionsUpdated, onAvailableCommands, // The new sign-in may be another account. Clear and republish its limits so a failed read // cannot fall back to them; the session start then reads the new account's limits. onSignedIn: resetUsage.pipe( Effect.andThen( SubscriptionRef.update(metadata, (state) => { const { usageLimits: _previousAccount, ...draft } = state.draft; return { ...state, draft }; }), ), Effect.andThen( Deferred.await(republish).pipe( Effect.flatten, Effect.provideService(PublishingUsage, true), ), ), Effect.asVoid, ), onSignedOut: clearAccountMetadata(), onAuthRequired: clearAccountMetadata(), snapshotForCwd, }; });