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