Open History to see the last commit
1import { ProviderSetupError, TextGenerationError } from "@t3tools/contracts";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Ref from "effect/Ref";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11import * as Stream from "effect/Stream";
12import { type AcpError, AcpRequestError } from "effect-acp/errors";
13
14import { applyAntigravityAcpModelSelection } from "../provider/acp/AntigravityAcpSupport.ts";
15import { removeAntigravitySessionFiles } from "../provider/acp/AntigravitySessionFiles.ts";
16import {
17 ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
18 isAntigravitySignInRequiredError,
19} from "../provider/antigravityAuthSupport.ts";
20import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
21import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
22
23const ANTIGRAVITY_TIMEOUT_MS = 180_000;
24const MAX_OUTPUT_CHARS = 128_000;
25const isTextGenerationError = Schema.is(TextGenerationError);
26const isProviderSetupError = Schema.is(ProviderSetupError);
27const isNativeSessionId = Schema.is(Schema.String.check(Schema.isUUID(4)));
28const Configuration = Schema.Record(Schema.String, Schema.Unknown);
29const decodeConfiguration = Schema.decodeEffect(Schema.fromJsonString(Configuration));
30const decodeConfigurationObject = Schema.decodeUnknownEffect(Configuration);
31
32type AntigravityTextRuntime = Pick<
33 AcpSessionRuntime.AcpSessionRuntime["Service"],
34 | "start"
35 | "setMode"
36 | "getConfigOptions"
37 | "getEvents"
38 | "setModel"
39 | "setConfigOption"
40 | "prompt"
41 | "cancel"
42 | "handleSessionUpdate"
43 | "handleRequestPermission"
44 | "handleElicitation"
45 | "handleReadTextFile"
46 | "handleWriteTextFile"
47 | "handleCreateTerminal"
48 | "handleTerminalOutput"
49 | "handleTerminalWaitForExit"
50 | "handleTerminalKill"
51 | "handleTerminalRelease"
52 | "handleUnknownExtRequest"
53>;
54
55export interface AntigravityTextGenerationOptions {
56 readonly profileDirectory: string;
57 readonly defaultModel?: Effect.Effect<string | undefined>;
58 readonly makeRuntime: (
59 cwd: string,
60 ) => Effect.Effect<AntigravityTextRuntime, AcpError | ProviderSetupError, Scope.Scope>;
61 readonly withProcess: <A, E, R>(
62 stop: Effect.Effect<void>,
63 task: Effect.Effect<A, E, R>,
64 ) => Effect.Effect<A, E | ProviderSetupError, R | Scope.Scope>;
65}
66
67/** Global hooks and MCP servers can run before a helper can deny a tool request. */
68export const isAntigravityTextGenerationAvailable = Effect.fn(
69 "isAntigravityTextGenerationAvailable",
70)(function* (profileDirectory: string) {
71 const fs = yield* FileSystem.FileSystem;
72 const path = yield* Path.Path;
73 for (const name of ["hooks.json", "mcp_config.json"]) {
74 const configurationPath = path.join(profileDirectory, "config", name);
75 if (!(yield* fs.exists(configurationPath))) {
76 continue;
77 }
78 const info = yield* fs.stat(configurationPath);
79 if (info.type !== "File" || info.size > 64_000n) {
80 return false;
81 }
82 // CLI 1.5.8 writes a 0-byte mcp_config.json before any server exists.
83 const empty = yield* fs.readFileString(configurationPath).pipe(
84 Effect.flatMap((text) =>
85 text.trim().length === 0
86 ? Effect.succeed(true)
87 : decodeConfiguration(text).pipe(
88 Effect.flatMap((configuration) =>
89 decodeConfigurationObject(
90 configuration[name === "hooks.json" ? "hooks" : "mcpServers"] ?? configuration,
91 ),
92 ),
93 Effect.map((configuration) => Object.keys(configuration).length === 0),
94 ),
95 ),
96 Effect.orElseSucceed(() => false),
97 );
98 if (!empty) return false;
99 }
100 return true;
101});
102
103export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGeneration")(function* (
104 options: AntigravityTextGenerationOptions,
105) {
106 const fs = yield* FileSystem.FileSystem;
107 const path = yield* Path.Path;
108 const hasOnlyRuntimeDirectories = Effect.fn(
109 "AntigravityTextGeneration.hasOnlyRuntimeDirectories",
110 )(function* (cwd: string) {
111 const root = yield* fs.realPath(cwd);
112 // ACP creates these empty skill directories before the first prompt.
113 const allowed = new Set([
114 path.join(root, ".agents"),
115 path.join(root, ".agents", "skills"),
116 path.join(root, ".gemini"),
117 path.join(root, ".gemini", "skills"),
118 ]);
119 const directories = [root];
120 for (const directory of directories) {
121 for (const name of yield* fs.readDirectory(directory)) {
122 const entry = path.join(directory, name);
123 if (
124 !allowed.has(entry) ||
125 (yield* fs.realPath(entry)) !== entry ||
126 (yield* fs.stat(entry)).type !== "Directory"
127 ) {
128 return false;
129 }
130 directories.push(entry);
131 }
132 }
133 return true;
134 });
135
136 const available = isAntigravityTextGenerationAvailable(options.profileDirectory).pipe(
137 Effect.provideService(FileSystem.FileSystem, fs),
138 Effect.provideService(Path.Path, path),
139 );
140
141 const runAntigravityJson = Effect.fn("AntigravityTextGeneration.runJson")(
142 function* <S extends Schema.Top>(input: TextGenerationOperations.Request<S>) {
143 const { operation } = input;
144 const scope = yield* Scope.make();
145 yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));
146 const helper = Effect.gen(function* () {
147 if (!(yield* available)) {
148 return yield* new TextGenerationError({
149 operation,
150 detail:
151 "Antigravity text generation is unavailable for profiles with global hooks or MCP configuration. Select another system model.",
152 });
153 }
154
155 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-text-" });
156 let sessionId: string | undefined;
157 yield* Effect.addFinalizer(() =>
158 removeAntigravitySessionFiles({
159 profileDirectory: options.profileDirectory,
160 sessionId,
161 cwd,
162 }).pipe(
163 Effect.provideService(FileSystem.FileSystem, fs),
164 Effect.provideService(Path.Path, path),
165 ),
166 );
167
168 const rawResult = yield* Effect.gen(function* () {
169 const runtime = yield* options.makeRuntime(cwd);
170 yield* runtime.getEvents().pipe(
171 Stream.runForEach((event) =>
172 event._tag === "EventStreamBarrier"
173 ? Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid)
174 : Effect.void,
175 ),
176 Effect.forkScoped,
177 );
178 const output = yield* Ref.make("");
179 const rejected = yield* Deferred.make<never, TextGenerationError>();
180 const reject = (detail: string) =>
181 Deferred.fail(rejected, new TextGenerationError({ operation, detail })).pipe(
182 Effect.asVoid,
183 );
184 const rejectToolRequest = () =>
185 reject("Antigravity text generation requested a tool or user input.").pipe(
186 Effect.andThen(
187 Effect.fail(
188 new AcpRequestError({
189 code: -32601,
190 errorMessage: "Tools and user input are disabled for text generation.",
191 }),
192 ),
193 ),
194 );
195
196 yield* runtime.handleRequestPermission(() =>
197 reject("Antigravity text generation requested a tool permission or user input.").pipe(
198 Effect.as({ outcome: { outcome: "cancelled" as const } }),
199 ),
200 );
201 yield* runtime.handleElicitation(() =>
202 reject("Antigravity text generation requested user input.").pipe(
203 Effect.as({ action: "decline" as const }),
204 ),
205 );
206 yield* runtime.handleReadTextFile(rejectToolRequest);
207 yield* runtime.handleWriteTextFile(rejectToolRequest);
208 yield* runtime.handleCreateTerminal(rejectToolRequest);
209 yield* runtime.handleTerminalOutput(rejectToolRequest);
210 yield* runtime.handleTerminalWaitForExit(rejectToolRequest);
211 yield* runtime.handleTerminalKill(rejectToolRequest);
212 yield* runtime.handleTerminalRelease(rejectToolRequest);
213 yield* runtime.handleUnknownExtRequest(rejectToolRequest);
214 yield* runtime.handleSessionUpdate((notification) =>
215 Effect.gen(function* () {
216 const update = notification.update;
217 if (
218 update.sessionUpdate === "tool_call" ||
219 update.sessionUpdate === "tool_call_update"
220 ) {
221 return yield* reject("Antigravity attempted tool work during text generation.");
222 }
223 if (
224 notification.sessionId !== sessionId ||
225 update.sessionUpdate !== "agent_message_chunk" ||
226 update.content.type !== "text"
227 ) {
228 return;
229 }
230 const text = update.content.text;
231 const exceeded = yield* Ref.modify(output, (current) =>
232 current.length + text.length > MAX_OUTPUT_CHARS
233 ? [true, current]
234 : [false, current + text],
235 );
236 if (exceeded) {
237 return yield* reject("Antigravity text generation exceeded the output limit.");
238 }
239 }),
240 );
241
242 return yield* Effect.gen(function* () {
243 const started = yield* runtime.start();
244 sessionId = started.sessionId;
245 if (!isNativeSessionId(sessionId)) {
246 return yield* new TextGenerationError({
247 operation,
248 detail: "Antigravity returned an invalid text helper session ID.",
249 });
250 }
251 yield* runtime.setMode("default");
252 yield* applyAntigravityAcpModelSelection({
253 runtime,
254 model: input.modelSelection.model,
255 defaultModel: yield* options.defaultModel ?? Effect.undefined,
256 mapError: (cause) =>
257 new TextGenerationError({
258 operation,
259 detail: "Could not select the Antigravity model for text generation.",
260 cause,
261 }),
262 });
263
264 const result = yield* runtime.prompt({
265 prompt: [
266 {
267 type: "text",
268 text: [
269 "Use only the input below. Do not use tools, read or write files, run commands, or ask questions.",
270 "Return only the requested JSON object.",
271 "",
272 input.prompt,
273 ].join("\n"),
274 },
275 ],
276 });
277 if (yield* Deferred.isDone(rejected)) {
278 return yield* Deferred.await(rejected);
279 }
280 if (result.stopReason === "cancelled") {
281 return yield* new TextGenerationError({
282 operation,
283 detail: "Antigravity text generation was cancelled.",
284 });
285 }
286 return (yield* Ref.get(output)).trim();
287 }).pipe(
288 Effect.onInterrupt(() =>
289 runtime.cancel.pipe(Effect.timeoutOption(2_000), Effect.ignore),
290 ),
291 Effect.raceFirst(Deferred.await(rejected)),
292 );
293 }).pipe(Effect.scoped);
294
295 if (!(yield* hasOnlyRuntimeDirectories(cwd))) {
296 return yield* new TextGenerationError({
297 operation,
298 detail: "Antigravity wrote files during text generation.",
299 });
300 }
301 if (!rawResult) {
302 return yield* new TextGenerationError({
303 operation,
304 detail: "Antigravity returned empty text generation output.",
305 });
306 }
307 return yield* TextGenerationOperations.decodeJsonReply(input, "Antigravity", rawResult);
308 }).pipe(
309 Effect.scoped,
310 Effect.timeoutOption(ANTIGRAVITY_TIMEOUT_MS),
311 Effect.flatMap(
312 Option.match({
313 onNone: () =>
314 Effect.fail(
315 new TextGenerationError({
316 operation,
317 detail: "Antigravity text generation timed out.",
318 }),
319 ),
320 onSome: Effect.succeed,
321 }),
322 ),
323 );
324
325 return yield* options
326 .withProcess(Scope.close(scope, Exit.void), helper)
327 .pipe(Effect.provideService(Scope.Scope, scope));
328 },
329 (effect, input) =>
330 effect.pipe(
331 Effect.mapError((cause) =>
332 isTextGenerationError(cause)
333 ? cause
334 : new TextGenerationError({
335 operation: input.operation,
336 detail: isProviderSetupError(cause)
337 ? cause.detail
338 : isAntigravitySignInRequiredError(cause)
339 ? ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE
340 : "Antigravity text generation failed.",
341 cause,
342 }),
343 ),
344 Effect.scoped,
345 ),
346 );
347
348 return TextGenerationOperations.fromRunner(
349 "AntigravityTextGeneration",
350 TextGenerationOperations.withoutInvestigation("Antigravity", runAntigravityJson),
351 );
352});