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