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

AntigravityProvider.ts

590 lines23.1 KB

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 Context from "effect/Context";
15import * as DateTime from "effect/DateTime";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as FiberHandle from "effect/FiberHandle";
19import * as Option from "effect/Option";
20import * as Predicate from "effect/Predicate";
21import * as Result from "effect/Result";
22import * as Stream from "effect/Stream";
23import * as SubscriptionRef from "effect/SubscriptionRef";
24import type * as EffectAcpErrors from "effect-acp/errors";
25import type * as EffectAcpSchema from "effect-acp/compat";
26​
27import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
28import { parseSessionModeState } from "@t3tools/provider-acp/server/runtimeModel";
29import { acpProviderOptionDescriptors } from "@t3tools/provider-acp/server/sessionConfig";
30import {
31 DeferringFailedCheck,
32 makeManagedServerProvider,
33} from "@t3tools/provider-core/server/managedProvider";
34import {
35 makeManualOnlyProviderMaintenanceCapabilities,
36 type ProviderMaintenanceCapabilities,
37} from "@t3tools/provider-core/server/maintenanceResolver";
38import {
39 buildServerProvider,
40 isCommandMissingCause,
41 type ServerProviderDraft,
42} from "@t3tools/provider-core/server/snapshotProbe";
43import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usageLimits";
44​
45import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts";
46​
47const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] });
48const MAX_WORKSPACE_SNAPSHOTS = 32;
49const HEALTH_CHECK_TIMEOUT_MS = 90_000;
50const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity.";
51const AUTH_UNCHECKED_MESSAGE =
52 "Antigravity is installed. Google account access is not checked yet.";
53// Set while a finished quota read republishes, so that health check does not read again.
54const PublishingUsage = Context.Reference<boolean>("t3/provider/AntigravityPublishingUsage", {
55 defaultValue: () => false,
56});
57​
58type SessionSetupResult = Pick<
59 AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
60 "configOptions" | "models"
61>;
62​
63type ThinkingConfig = NonNullable<ReturnType<typeof antigravityThinkingConfig>>;
64​
65/** Thinking options each model reported when selected; `null` means it has none. */
66export type AntigravityThinkingLevels = ReadonlyMap<string, ThinkingConfig | null>;
67​
68function thinkingCapabilities(config: ThinkingConfig | null | undefined) {
69 const descriptor = config
70 ? acpProviderOptionDescriptors({ configOptions: [config], modeState: undefined })[0]
71 : undefined;
72 if (descriptor?.type !== "select") return EMPTY_MODEL_CAPABILITIES;
73 return createModelCapabilities({ optionDescriptors: [descriptor] });
75​
76export function buildAntigravityModelsFromSession(
77 setup: SessionSetupResult,
78 thinkingLevels: AntigravityThinkingLevels = new Map(),
79): ReadonlyArray<ServerProviderModel> {
80 const config = setup.configOptions?.find(
81 (option) => option.id === "model" || option.category === "model",
82 );
83 const currentValue =
84 config?.type === "select" ? config.currentValue : setup.models?.currentModelId;
85 const entries =
86 config?.type === "select"
87 ? config.options.flatMap((entry) => ("value" in entry ? [entry] : entry.options))
88 : config === undefined
89 ? (setup.models?.availableModels.map((model) => ({
90 value: model.modelId,
91 name: model.name,
92 })) ?? [])
93 : [];
94 const currentThinking = antigravityThinkingConfig(setup.configOptions);
95 const seen = new Set<string>();
96 // The agent can list two IDs under one name; label the later ones so the picker tells them apart.
97 const names = new Set<string>();
98 return entries.flatMap((entry): ServerProviderModel[] => {
99 if (!entry.value.trim() || seen.has(entry.value)) return [];
100 seen.add(entry.value);
101 const baseName = entry.name.trim() ? entry.name : entry.value;
102 const name = names.has(baseName) ? `${baseName} (${entry.value})` : baseName;
103 names.add(baseName);
104 const observed =
105 entry.value === currentValue ? (currentThinking ?? null) : thinkingLevels.get(entry.value);
106 return [
107 {
108 slug: entry.value,
109 name,
110 isCustom: false,
111 ...(entry.value === currentValue
112 ? { isDefault: true, aliases: [ANTIGRAVITY_DEFAULT_MODEL] }
113 : {}),
114 // Levels differ per model; an unobserved model reports none so the registry keeps its cached ones.
115 capabilities: thinkingCapabilities(observed),
116 },
117 ];
118 });
120​
121function nativeCommands(
122 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
123): ReadonlyArray<ServerProviderSlashCommand> {
124 const seen = new Set<string>();
125 return commands.flatMap((command): ServerProviderSlashCommand[] => {
126 if (!command.name.trim() || seen.has(command.name)) return [];
127 seen.add(command.name);
128 const description = command.description.trim();
129 const hint = command.input?.hint.trim();
130 return [
131 {
132 name: command.name,
133 ...(description ? { description } : {}),
134 ...(hint ? { input: { hint } } : {}),
135 },
136 ];
137 });
139​
140function isMissingInstallation(error: EffectAcpErrors.AcpError | ProviderSetupError): boolean {
141 if (error._tag === "AcpSpawnError") {
142 return (
143 isCommandMissingCause(error.cause) ||
144 (Predicate.isObject(error.cause) && error.cause.code === "ENOENT")
145 );
146 }
147 return (
148 error._tag === "ProviderSetupError" &&
149 error.operation === "resolve" &&
150 /not installed|missing|incomplete|changed on disk|does not publish/i.test(error.detail)
151 );
153​
154interface AntigravityProviderState {
155 readonly draft: ServerProviderDraft;
156 readonly authRevision: number;
158​
159interface AntigravityProviderOptions {
160 readonly environment?: NodeJS.ProcessEnv;
161 readonly stampIdentity: (snapshot: ServerProviderDraft) => Effect.Effect<ServerProvider>;
162 readonly probe: Effect.Effect<
163 EffectAcpSchema.InitializeResponse,
164 EffectAcpErrors.AcpError | ProviderSetupError
165 >;
166 readonly supportsTextGeneration: Effect.Effect<boolean>;
167 readonly probeUsage?: Effect.Effect<ServerProviderUsageLimits>;
168 readonly clearUsage?: Effect.Effect<void>;
169 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
170 readonly auth?: { readonly type: string; readonly label: string };
171 /** Modes the last session advertised, saved because initialize alone does not report them. */
172 readonly rememberedRuntimeModes?: ReadonlyArray<RuntimeMode>;
173 readonly rememberRuntimeModes?: (modes: ReadonlyArray<RuntimeMode>) => Effect.Effect<void>;
175​
176const RUNTIME_MODES_WITHOUT_AUTO = [
177 "approval-required",
178 "auto-accept-edits",
179 "full-access",
180] as const;
181​
182/** Auto is offered only where the session advertises agy's own Auto; elsewhere it runs Supervised. */
183function antigravityRuntimeModes(
184 sessionSetupResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
185): ReadonlyArray<RuntimeMode> {
186 return parseSessionModeState(sessionSetupResult)?.availableModes.some(
187 (mode) => mode.id === "auto",
188 )
189 ? ["approval-required", "auto-accept-edits", "auto", "full-access"]
190 : RUNTIME_MODES_WITHOUT_AUTO;
192​
193export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(function* (
194 settings: AntigravitySettings,
195 options: AntigravityProviderOptions,
196) {
197 const usesCredentials =
198 options.auth?.type === "gemini-api-key" || options.auth?.type === "agent-platform";
199 const signInMessage = usesCredentials
200 ? `Connect with ${options.auth.label} to use Antigravity and load models.`
201 : SIGN_IN_MESSAGE;
202 const authUncheckedMessage = usesCredentials
203 ? `Antigravity is installed. Connect with ${options.auth.label} to load models.`
204 : AUTH_UNCHECKED_MESSAGE;
205 const checkedAt = DateTime.formatIso(yield* DateTime.now);
206 const initialDraft = {
207 ...buildServerProvider({
208 presentation: {
209 displayName: "Antigravity",
210 showInteractionModeToggle: false,
211 supportedRuntimeModes: options.rememberedRuntimeModes ?? RUNTIME_MODES_WITHOUT_AUTO,
212 },
213 enabled: settings.enabled,
214 checkedAt,
215 models: [],
216 probe: {
217 installed: false,
218 version: null,
219 status: "warning",
220 auth: { status: "unknown", ...(options.auth ? { type: options.auth.type } : {}) },
221 message: settings.enabled
222 ? "Checking Antigravity availability."
223 : "Antigravity is disabled in T3 Code settings.",
224 },
225 }),
226 setup: { canAuthenticate: true, canInstall: true },
227 supportsConversationRollback: true,
228 supportsTextGeneration: false,
229 workspaceSnapshots: [],
230 } satisfies ServerProviderDraft;
231 const metadata = yield* SubscriptionRef.make<AntigravityProviderState>({
232 draft: initialDraft,
233 authRevision: 0,
234 });
235 // Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them.
236 const discoveredSkills = new Map<string, ServerProvider["skills"]>();
237 const thinkingLevels = new Map<string, ThinkingConfig | null>();
238 const observeThinkingLevels = (
239 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
240 ) => {
241 const model = configOptions?.find(
242 (option) => option.id === "model" || option.category === "model",
243 );
244 if (model?.type === "select" && model.currentValue) {
245 thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null);
246 }
247 };
248 const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* (
249 previous: ReadonlyArray<RuntimeMode> | undefined,
250 next: ReadonlyArray<RuntimeMode>,
251 ) {
252 if (options.rememberRuntimeModes && previous?.join() !== next.join()) {
253 yield* options.rememberRuntimeModes(next);
254 }
255 });
256 const getSnapshot = SubscriptionRef.get(metadata).pipe(
257 Effect.flatMap((state) => options.stampIdentity(state.draft)),
258 );
259​
260 // The quota read can take 30 seconds, so it never blocks readiness or a session start.
261 // One read runs at a time; sign-in and sign-out interrupt it so a stale account never lands.
262 const usageRead = yield* FiberHandle.make();
263 const republish = yield* Deferred.make<Effect.Effect<ServerProvider>>();
264 const scope = yield* Effect.scope;
265 const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {
266 if (!options.probeUsage || (yield* PublishingUsage)) return;
267 yield* FiberHandle.run(
268 usageRead,
269 options.probeUsage.pipe(
270 Effect.flatMap((probed) =>
271 SubscriptionRef.update(metadata, (state) => ({
272 ...state,
273 draft: {
274 ...state.draft,
275 usageLimits: resolveUsageLimitsAfterProbe({
276 published: state.draft.usageLimits,
277 probed,
278 }),
279 },
280 })),
281 ),
282 // Enrichment cannot change published limits; a health check publishes them.
283 Effect.andThen(
284 Deferred.await(republish).pipe(
285 Effect.flatten,
286 Effect.provideService(PublishingUsage, true),
287 Effect.ignoreCause({ log: true }),
288 Effect.forkIn(scope),
289 ),
290 ),
291 ),
292 // Store the fiber before it runs, so a sign-out during the read can interrupt it.
293 { onlyIfMissing: true, startImmediately: false },
294 );
295 });
296 const resetUsage = Effect.gen(function* () {
297 yield* FiberHandle.clear(usageRead);
298 if (options.clearUsage) yield* options.clearUsage;
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 usageLimits: missingInstallation ? undefined : draft.usageLimits,
349 ...(missingInstallation
350 ? {
351 models: [],
352 slashCommands: [],
353 skills: [],
354 workspaceSnapshots: [],
355 supportsTextGeneration: false,
356 }
357 : {}),
358 ...(initialized !== undefined
359 ? {
360 supportsTextGeneration:
361 supportsTextGeneration && draft.auth.status !== "unauthenticated",
362 }
363 : {}),
364 ...(message ? { message } : {}),
365 },
366 } satisfies AntigravityProviderState;
367 };
368 // This state is published as it changes, so a failure the managed provider discards stays out.
369 const deferFailure = errorMessage !== undefined && (yield* DeferringFailedCheck);
370 const next = yield* SubscriptionRef.modifySome(metadata, (state) => {
371 const checked = applyCheck(state);
372 const stored = deferFailure && state.draft.status === "ready" ? state : checked;
373 return [checked, stored === state ? Option.none() : Option.some(stored)];
374 });
375 if (initialized !== undefined) yield* refreshUsage();
376 return yield* options.stampIdentity(next.draft);
377 });
378​
379 const maintenanceCapabilities =
380 options.maintenanceCapabilities ??
381 makeManualOnlyProviderMaintenanceCapabilities({
382 provider: ProviderDriverKind.make("antigravity"),
383 packageName: null,
384 });
385 const managed = yield* makeManagedServerProvider({
386 resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
387 getSettings: Effect.succeed(settings),
388 streamSettings: Stream.empty,
389 haveSettingsChanged: () => false,
390 initialSnapshot: () => getSnapshot,
391 checkProvider: checkProvider(),
392 enrichSnapshot: ({ publishSnapshot }) =>
393 SubscriptionRef.changes(metadata).pipe(
394 Stream.runForEach((state) =>
395 options.stampIdentity(state.draft).pipe(Effect.flatMap(publishSnapshot)),
396 ),
397 ),
398 });
399 yield* Deferred.succeed(republish, managed.refresh);
400​
401 const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
402 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
403 cwd?: string,
404 ) {
405 if (!settings.enabled) return;
406 observeThinkingLevels(started.sessionSetupResult.configOptions);
407 const before = yield* SubscriptionRef.get(metadata);
408 const supportsTextGeneration = yield* options.supportsTextGeneration;
409 const updatedAt = DateTime.formatIso(yield* DateTime.now);
410 const supportedRuntimeModes = antigravityRuntimeModes(started.sessionSetupResult);
411 const previousModes = yield* SubscriptionRef.modify(metadata, (state) => {
412 if (
413 state.authRevision !== before.authRevision &&
414 state.draft.auth.status === "unauthenticated"
415 ) {
416 return [supportedRuntimeModes, state] as const;
417 }
418 const { message: _previousMessage, ...draft } = state.draft;
419 const workspaces = draft.workspaceSnapshots ?? [];
420 const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined;
421 const next = {
422 authRevision: state.authRevision + 1,
423 draft: {
424 ...draft,
425 installed: true,
426 status: "ready",
427 version: started.initializeResult.agentInfo?.version || draft.version,
428 auth: {
429 status: "authenticated",
430 type: options.auth?.type ?? "oauth-personal",
431 label: options.auth?.label ?? "Google account",
432 },
433 checkedAt: updatedAt,
434 models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels),
435 supportedRuntimeModes,
436 supportsTextGeneration,
437 ...(cwd
438 ? {
439 workspaceSnapshots: [
440 ...workspaces.filter((entry) => entry.cwd !== cwd),
441 {
442 cwd,
443 checkedAt: updatedAt,
444 slashCommands: workspace?.slashCommands ?? draft.slashCommands,
445 skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [],
446 },
447 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
448 }
449 : {}),
450 },
451 } satisfies AntigravityProviderState;
452 return [draft.supportedRuntimeModes, next] as const;
453 });
454 yield* rememberRuntimeModes(previousModes, supportedRuntimeModes);
455 if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage();
456 });
457​
458 const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
459 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
460 ) {
461 observeThinkingLevels(configOptions);
462 const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels);
463 yield* SubscriptionRef.update(metadata, (state) => {
464 if (state.draft.auth.status !== "authenticated") return state;
465 return { ...state, draft: { ...state.draft, models } };
466 });
467 });
468​
469 const onAvailableCommands = Effect.fn("AntigravityProvider.onAvailableCommands")(function* (
470 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
471 cwd?: string,
472 ) {
473 if (!settings.enabled) return;
474 const slashCommands = nativeCommands(commands);
475 const updatedAt = DateTime.formatIso(yield* DateTime.now);
476 yield* SubscriptionRef.update(metadata, (state) => {
477 if (state.draft.auth.status === "unauthenticated") return state;
478 return {
479 ...state,
480 draft: {
481 ...state.draft,
482 slashCommands,
483 ...(cwd
484 ? {
485 workspaceSnapshots: [
486 ...(state.draft.workspaceSnapshots ?? []).filter((entry) => entry.cwd !== cwd),
487 {
488 cwd,
489 checkedAt: updatedAt,
490 slashCommands,
491 skills:
492 state.draft.workspaceSnapshots?.find((entry) => entry.cwd === cwd)?.skills ??
493 discoveredSkills.get(cwd) ??
494 [],
495 },
496 ].slice(-MAX_WORKSPACE_SNAPSHOTS),
497 }
498 : {}),
499 },
500 };
501 });
502 });
503​
504 const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {
505 yield* resetUsage;
506 if (!settings.enabled) return;
507 const updatedAt = DateTime.formatIso(yield* DateTime.now);
508 const previousModes = yield* SubscriptionRef.modify(metadata, (state) => [
509 state.draft.supportedRuntimeModes,
510 {
511 authRevision: state.authRevision + 1,
512 draft: {
513 ...state.draft,
514 auth: {
515 status: "unauthenticated",
516 ...(usesCredentials ? options.auth : {}),
517 },
518 status: "warning",
519 message: signInMessage,
520 checkedAt: updatedAt,
521 models: [],
522 slashCommands: [],
523 skills: [],
524 workspaceSnapshots: [],
525 supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO,
526 supportsTextGeneration: false,
527 usageLimits: undefined,
528 },
529 } satisfies AntigravityProviderState,
530 ]);
531 yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO);
532 discoveredSkills.clear();
533 thinkingLevels.clear();
534 });
535​
536 const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* (
537 cwd: string,
538 skills?: ServerProvider["skills"],
539 ) {
540 if (skills) {
541 discoveredSkills.set(cwd, skills);
542 yield* SubscriptionRef.update(metadata, (state) =>
543 state.draft.workspaceSnapshots?.some((entry) => entry.cwd === cwd)
544 ? {
545 ...state,
546 draft: {
547 ...state.draft,
548 workspaceSnapshots: state.draft.workspaceSnapshots.map((entry) =>
549 entry.cwd === cwd ? { ...entry, skills } : entry,
550 ),
551 },
552 }
553 : state,
554 );
555 }
556 const snapshot = yield* getSnapshot;
557 const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd);
558 const resolvedSkills = skills ?? workspace?.skills ?? discoveredSkills.get(cwd) ?? [];
559 return workspace
560 ? { ...snapshot, slashCommands: workspace.slashCommands, skills: resolvedSkills }
561 : { ...snapshot, skills: resolvedSkills };
562 });
563​
564 return {
565 snapshot: { ...managed, getSnapshot },
566 onSessionStarted,
567 onConfigOptionsUpdated,
568 onAvailableCommands,
569 // The new sign-in may be another account. Clear and republish its limits so a failed read
570 // cannot fall back to them; the session start then reads the new account's limits.
571 onSignedIn: resetUsage.pipe(
572 Effect.andThen(
573 SubscriptionRef.update(metadata, (state) => {
574 const { usageLimits: _previousAccount, ...draft } = state.draft;
575 return { ...state, draft };
576 }),
577 ),
578 Effect.andThen(
579 Deferred.await(republish).pipe(
580 Effect.flatten,
581 Effect.provideService(PublishingUsage, true),
582 ),
583 ),
584 Effect.asVoid,
585 ),
586 onSignedOut: clearAccountMetadata(),
587 onAuthRequired: clearAccountMetadata(),
588 snapshotForCwd,
589 };
590});