The best way to control Claude Code, Codex and more from any computer or phone

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