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

AntigravityTextGeneration.ts

337 lines12.6 KB

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