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

AntigravityTextGeneration.ts

309 lines11.7 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 available = isAntigravityTextGenerationAvailable(options.profileDirectory).pipe(
98 Effect.provideService(FileSystem.FileSystem, fs),
99 Effect.provideService(Path.Path, path),
100 );
101​
102 const runAntigravityJson = Effect.fn("AntigravityTextGeneration.runJson")(
103 function* <S extends Schema.Top>(input: TextGenerationOperations.Request<S>) {
104 const { operation } = input;
105 const scope = yield* Scope.make();
106 yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));
107 const helper = Effect.gen(function* () {
108 if (!(yield* available)) {
109 return yield* new TextGenerationError({
110 operation,
111 detail:
112 "Antigravity text generation is unavailable for profiles with global hooks or MCP configuration. Select another system model.",
113 });
114 }
115​
116 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-text-" });
117 let sessionId: string | undefined;
118 yield* Effect.addFinalizer(() =>
119 removeAntigravitySessionFiles({
120 profileDirectory: options.profileDirectory,
121 sessionId,
122 cwd,
123 }).pipe(
124 Effect.provideService(FileSystem.FileSystem, fs),
125 Effect.provideService(Path.Path, path),
126 ),
127 );
128​
129 const rawResult = yield* Effect.gen(function* () {
130 const runtime = yield* options.makeRuntime(cwd);
131 yield* runtime.getEvents().pipe(
132 Stream.runForEach((event) =>
133 event._tag === "EventStreamBarrier"
134 ? Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid)
135 : Effect.void,
136 ),
137 Effect.forkScoped,
138 );
139 const output = yield* Ref.make("");
140 const rejected = yield* Deferred.make<never, TextGenerationError>();
141 const reject = (detail: string) =>
142 Deferred.fail(rejected, new TextGenerationError({ operation, detail })).pipe(
143 Effect.asVoid,
144 );
145 const rejectToolRequest = () =>
146 reject("Antigravity text generation requested a tool or user input.").pipe(
147 Effect.andThen(
148 Effect.fail(
149 new AcpRequestError({
150 code: -32601,
151 errorMessage: "Tools and user input are disabled for text generation.",
152 }),
153 ),
154 ),
155 );
156​
157 yield* runtime.handleRequestPermission(() =>
158 reject("Antigravity text generation requested a tool permission or user input.").pipe(
159 Effect.as({ outcome: { outcome: "cancelled" as const } }),
160 ),
161 );
162 yield* runtime.handleElicitation(() =>
163 reject("Antigravity text generation requested user input.").pipe(
164 Effect.as({ action: "decline" as const }),
165 ),
166 );
167 yield* runtime.handleReadTextFile(rejectToolRequest);
168 yield* runtime.handleWriteTextFile(rejectToolRequest);
169 yield* runtime.handleCreateTerminal(rejectToolRequest);
170 yield* runtime.handleTerminalOutput(rejectToolRequest);
171 yield* runtime.handleTerminalWaitForExit(rejectToolRequest);
172 yield* runtime.handleTerminalKill(rejectToolRequest);
173 yield* runtime.handleTerminalRelease(rejectToolRequest);
174 yield* runtime.handleUnknownExtRequest(rejectToolRequest);
175 yield* runtime.handleSessionUpdate((notification) =>
176 Effect.gen(function* () {
177 const update = notification.update;
178 if (
179 update.sessionUpdate === "tool_call" ||
180 update.sessionUpdate === "tool_call_update"
181 ) {
182 return yield* reject("Antigravity attempted tool work during text generation.");
183 }
184 if (
185 notification.sessionId !== sessionId ||
186 update.sessionUpdate !== "agent_message_chunk" ||
187 update.content.type !== "text"
188 ) {
189 return;
190 }
191 const text = update.content.text;
192 const exceeded = yield* Ref.modify(output, (current) =>
193 current.length + text.length > MAX_OUTPUT_CHARS
194 ? [true, current]
195 : [false, current + text],
196 );
197 if (exceeded) {
198 return yield* reject("Antigravity text generation exceeded the output limit.");
199 }
200 }),
201 );
202​
203 return yield* Effect.gen(function* () {
204 const started = yield* runtime.start();
205 sessionId = started.sessionId;
206 if (!isNativeSessionId(sessionId)) {
207 return yield* new TextGenerationError({
208 operation,
209 detail: "Antigravity returned an invalid text helper session ID.",
210 });
211 }
212 yield* runtime.setMode("default");
213 yield* applyAntigravityAcpModelSelection({
214 runtime,
215 model: input.modelSelection.model,
216 defaultModel: yield* options.defaultModel ?? Effect.undefined,
217 mapError: (cause) =>
218 new TextGenerationError({
219 operation,
220 detail: "Could not select the Antigravity model for text generation.",
221 cause,
222 }),
223 });
224​
225 const result = yield* runtime.prompt({
226 prompt: [
227 {
228 type: "text",
229 text: [
230 "Use only the input below. Do not use tools, read or write files, run commands, or ask questions.",
231 "Return only the requested JSON object.",
232 "",
233 input.prompt,
234 ].join("\n"),
235 },
236 ],
237 });
238 if (yield* Deferred.isDone(rejected)) {
239 return yield* Deferred.await(rejected);
240 }
241 if (result.stopReason === "cancelled") {
242 return yield* new TextGenerationError({
243 operation,
244 detail: "Antigravity text generation was cancelled.",
245 });
246 }
247 return (yield* Ref.get(output)).trim();
248 }).pipe(
249 Effect.onInterrupt(() =>
250 runtime.cancel.pipe(Effect.timeoutOption(2_000), Effect.ignore),
251 ),
252 Effect.raceFirst(Deferred.await(rejected)),
253 );
254 }).pipe(Effect.scoped);
255​
256 if ((yield* fs.readDirectory(cwd)).length > 0) {
257 return yield* new TextGenerationError({
258 operation,
259 detail: "Antigravity wrote files during text generation.",
260 });
261 }
262 if (!rawResult) {
263 return yield* new TextGenerationError({
264 operation,
265 detail: "Antigravity returned empty text generation output.",
266 });
267 }
268 return yield* TextGenerationOperations.decodeJsonReply(input, "Antigravity", rawResult);
269 }).pipe(
270 Effect.scoped,
271 Effect.timeoutOption(ANTIGRAVITY_TIMEOUT_MS),
272 Effect.flatMap(
273 Option.match({
274 onNone: () =>
275 Effect.fail(
276 new TextGenerationError({
277 operation,
278 detail: "Antigravity text generation timed out.",
279 }),
280 ),
281 onSome: Effect.succeed,
282 }),
283 ),
284 );
285​
286 return yield* options
287 .withProcess(Scope.close(scope, Exit.void), helper)
288 .pipe(Effect.provideService(Scope.Scope, scope));
289 },
290 (effect, input) =>
291 effect.pipe(
292 Effect.mapError((cause) =>
293 isTextGenerationError(cause)
294 ? cause
295 : new TextGenerationError({
296 operation: input.operation,
297 detail: "Antigravity text generation failed.",
298 cause,
299 }),
300 ),
301 Effect.scoped,
302 ),
303 );
304​
305 return TextGenerationOperations.fromRunner(
306 "AntigravityTextGeneration",
307 TextGenerationOperations.withoutInvestigation("Antigravity", runAntigravityJson),
308 );
309});