Open History to see the last commit
1import {
2 type ModelSelection,
3 type ProviderSetupError,
4 TextGenerationError,
5} from "@t3tools/contracts";
6import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
7import { extractJsonObject } from "@t3tools/shared/schemaJson";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Ref from "effect/Ref";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import { type AcpError, AcpRequestError } from "effect-acp/errors";
19
20import { applyAntigravityAcpModelSelection } from "../provider/acp/AntigravityAcpSupport.ts";
21import { removeAntigravitySessionFiles } from "../provider/acp/AntigravitySessionFiles.ts";
22import type { AcpSessionRuntime } from "../provider/acp/AcpSessionRuntime.ts";
23import type * as TextGeneration from "./TextGeneration.ts";
24import {
25 buildBranchNamePrompt,
26 buildCommitMessagePrompt,
27 buildPrContentPrompt,
28 buildThreadTitlePrompt,
29} from "./TextGenerationPrompts.ts";
30import {
31 sanitizeCommitSubject,
32 sanitizePrTitle,
33 sanitizeThreadTitle,
34} from "./TextGenerationUtils.ts";
35
36const ANTIGRAVITY_TIMEOUT_MS = 180_000;
37const MAX_OUTPUT_CHARS = 128_000;
38const isTextGenerationError = Schema.is(TextGenerationError);
39const isNativeSessionId = Schema.is(Schema.String.check(Schema.isUUID(4)));
40const Configuration = Schema.Record(Schema.String, Schema.Unknown);
41const decodeConfiguration = Schema.decodeEffect(Schema.fromJsonString(Configuration));
42const decodeConfigurationObject = Schema.decodeUnknownEffect(Configuration);
43
44type AntigravityTextRuntime = Pick<
45 AcpSessionRuntime["Service"],
46 | "start"
47 | "setMode"
48 | "getConfigOptions"
49 | "getEvents"
50 | "setModel"
51 | "prompt"
52 | "cancel"
53 | "handleSessionUpdate"
54 | "handleRequestPermission"
55 | "handleElicitation"
56 | "handleReadTextFile"
57 | "handleWriteTextFile"
58 | "handleCreateTerminal"
59 | "handleTerminalOutput"
60 | "handleTerminalWaitForExit"
61 | "handleTerminalKill"
62 | "handleTerminalRelease"
63 | "handleUnknownExtRequest"
64>;
65
66export interface AntigravityTextGenerationOptions {
67 readonly profileDirectory: string;
68 /** Model the provider default alias selects, when the account offers it. */
69 readonly defaultModel?: Effect.Effect<string | undefined>;
70 /** Uses the instance's personal Google login, with no injected MCP servers or client tools. */
71 readonly makeRuntime: (
72 cwd: string,
73 ) => Effect.Effect<AntigravityTextRuntime, AcpError | ProviderSetupError, Scope.Scope>;
74 /** Registers the whole helper so sign-out can stop it before clearing credentials. */
75 readonly withProcess: <A, E, R>(
76 stop: Effect.Effect<void>,
77 task: Effect.Effect<A, E, R>,
78 ) => Effect.Effect<A, E | ProviderSetupError, R | Scope.Scope>;
79}
80
81/** Global hooks and MCP servers can run before a helper can deny a tool request. */
82export const isAntigravityTextGenerationAvailable = Effect.fn(
83 "isAntigravityTextGenerationAvailable",
84)(function* (profileDirectory: string) {
85 const fs = yield* FileSystem.FileSystem;
86 const path = yield* Path.Path;
87 for (const name of ["hooks.json", "mcp_config.json"]) {
88 const configurationPath = path.join(profileDirectory, "config", name);
89 if (!(yield* fs.exists(configurationPath))) {
90 continue;
91 }
92 const info = yield* fs.stat(configurationPath);
93 if (info.type !== "File" || info.size > 64_000n) {
94 return false;
95 }
96 const empty = yield* fs.readFileString(configurationPath).pipe(
97 Effect.flatMap(decodeConfiguration),
98 Effect.flatMap((configuration) =>
99 decodeConfigurationObject(
100 configuration[name === "hooks.json" ? "hooks" : "mcpServers"] ?? configuration,
101 ),
102 ),
103 Effect.map((configuration) => Object.keys(configuration).length === 0),
104 Effect.orElseSucceed(() => false),
105 );
106 if (!empty) return false;
107 }
108 return true;
109});
110
111/** Runs short-lived subscription helpers without giving them the user's workspace. */
112export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGeneration")(function* (
113 options: AntigravityTextGenerationOptions,
114) {
115 const fs = yield* FileSystem.FileSystem;
116 const path = yield* Path.Path;
117 const available = isAntigravityTextGenerationAvailable(options.profileDirectory).pipe(
118 Effect.provideService(FileSystem.FileSystem, fs),
119 Effect.provideService(Path.Path, path),
120 );
121
122 const runAntigravityJson = Effect.fn("AntigravityTextGeneration.runJson")(
123 function* <S extends Schema.Top>(input: {
124 readonly operation: keyof TextGeneration.TextGeneration["Service"];
125 readonly prompt: string;
126 readonly outputSchema: S;
127 readonly modelSelection: ModelSelection;
128 }) {
129 const { operation } = input;
130 const scope = yield* Scope.make();
131 yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));
132 const helper = Effect.gen(function* () {
133 if (!(yield* available)) {
134 return yield* new TextGenerationError({
135 operation,
136 detail:
137 "Antigravity text generation is unavailable for profiles with global hooks or MCP configuration. Select another system model.",
138 });
139 }
140
141 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-text-" });
142 let sessionId: string | undefined;
143 yield* Effect.addFinalizer(() =>
144 removeAntigravitySessionFiles({
145 profileDirectory: options.profileDirectory,
146 sessionId,
147 cwd,
148 }).pipe(
149 Effect.provideService(FileSystem.FileSystem, fs),
150 Effect.provideService(Path.Path, path),
151 ),
152 );
153
154 const rawResult = yield* Effect.gen(function* () {
155 const runtime = yield* options.makeRuntime(cwd);
156 yield* runtime.getEvents().pipe(
157 Stream.runForEach((event) =>
158 event._tag === "EventStreamBarrier"
159 ? Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid)
160 : Effect.void,
161 ),
162 Effect.forkScoped,
163 );
164 const output = yield* Ref.make("");
165 const rejected = yield* Deferred.make<never, TextGenerationError>();
166 const reject = (detail: string) =>
167 Deferred.fail(rejected, new TextGenerationError({ operation, detail })).pipe(
168 Effect.asVoid,
169 );
170 const rejectToolRequest = () =>
171 reject("Antigravity text generation requested a tool or user input.").pipe(
172 Effect.andThen(
173 Effect.fail(
174 new AcpRequestError({
175 code: -32601,
176 errorMessage: "Tools and user input are disabled for text generation.",
177 }),
178 ),
179 ),
180 );
181
182 yield* runtime.handleRequestPermission(() =>
183 reject("Antigravity text generation requested a tool permission or user input.").pipe(
184 Effect.as({ outcome: { outcome: "cancelled" as const } }),
185 ),
186 );
187 yield* runtime.handleElicitation(() =>
188 reject("Antigravity text generation requested user input.").pipe(
189 Effect.as({ action: "decline" as const }),
190 ),
191 );
192 yield* runtime.handleReadTextFile(rejectToolRequest);
193 yield* runtime.handleWriteTextFile(rejectToolRequest);
194 yield* runtime.handleCreateTerminal(rejectToolRequest);
195 yield* runtime.handleTerminalOutput(rejectToolRequest);
196 yield* runtime.handleTerminalWaitForExit(rejectToolRequest);
197 yield* runtime.handleTerminalKill(rejectToolRequest);
198 yield* runtime.handleTerminalRelease(rejectToolRequest);
199 yield* runtime.handleUnknownExtRequest(rejectToolRequest);
200 yield* runtime.handleSessionUpdate((notification) =>
201 Effect.gen(function* () {
202 const update = notification.update;
203 if (
204 update.sessionUpdate === "tool_call" ||
205 update.sessionUpdate === "tool_call_update"
206 ) {
207 return yield* reject("Antigravity attempted tool work during text generation.");
208 }
209 if (
210 notification.sessionId !== sessionId ||
211 update.sessionUpdate !== "agent_message_chunk" ||
212 update.content.type !== "text"
213 ) {
214 return;
215 }
216 const text = update.content.text;
217 const exceeded = yield* Ref.modify(output, (current) =>
218 current.length + text.length > MAX_OUTPUT_CHARS
219 ? [true, current]
220 : [false, current + text],
221 );
222 if (exceeded) {
223 return yield* reject("Antigravity text generation exceeded the output limit.");
224 }
225 }),
226 );
227
228 return yield* Effect.gen(function* () {
229 const started = yield* runtime.start();
230 sessionId = started.sessionId;
231 if (!isNativeSessionId(sessionId)) {
232 return yield* new TextGenerationError({
233 operation,
234 detail: "Antigravity returned an invalid text helper session ID.",
235 });
236 }
237 yield* runtime.setMode("default");
238 yield* applyAntigravityAcpModelSelection({
239 runtime,
240 model: input.modelSelection.model,
241 defaultModel: yield* options.defaultModel ?? Effect.undefined,
242 mapError: (cause) =>
243 new TextGenerationError({
244 operation,
245 detail: "Could not select the Antigravity model for text generation.",
246 cause,
247 }),
248 });
249
250 const result = yield* runtime.prompt({
251 prompt: [
252 {
253 type: "text",
254 text: [
255 "Use only the input below. Do not use tools, read or write files, run commands, or ask questions.",
256 "Return only the requested JSON object.",
257 "",
258 input.prompt,
259 ].join("\n"),
260 },
261 ],
262 });
263 if (yield* Deferred.isDone(rejected)) {
264 return yield* Deferred.await(rejected);
265 }
266 if (result.stopReason === "cancelled") {
267 return yield* new TextGenerationError({
268 operation,
269 detail: "Antigravity text generation was cancelled.",
270 });
271 }
272 return (yield* Ref.get(output)).trim();
273 }).pipe(
274 Effect.onInterrupt(() =>
275 runtime.cancel.pipe(Effect.timeoutOption(2_000), Effect.ignore),
276 ),
277 Effect.raceFirst(Deferred.await(rejected)),
278 );
279 }).pipe(Effect.scoped);
280
281 if ((yield* fs.readDirectory(cwd)).length > 0) {
282 return yield* new TextGenerationError({
283 operation,
284 detail: "Antigravity wrote files during text generation.",
285 });
286 }
287 if (!rawResult) {
288 return yield* new TextGenerationError({
289 operation,
290 detail: "Antigravity returned empty text generation output.",
291 });
292 }
293 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchema));
294 return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
295 Effect.mapError(
296 (cause) =>
297 new TextGenerationError({
298 operation,
299 detail: "Antigravity returned invalid structured output.",
300 cause,
301 }),
302 ),
303 );
304 }).pipe(
305 Effect.scoped,
306 Effect.timeoutOption(ANTIGRAVITY_TIMEOUT_MS),
307 Effect.flatMap(
308 Option.match({
309 onNone: () =>
310 Effect.fail(
311 new TextGenerationError({
312 operation,
313 detail: "Antigravity text generation timed out.",
314 }),
315 ),
316 onSome: Effect.succeed,
317 }),
318 ),
319 );
320
321 return yield* options
322 .withProcess(Scope.close(scope, Exit.void), helper)
323 .pipe(Effect.provideService(Scope.Scope, scope));
324 },
325 (effect, input) =>
326 effect.pipe(
327 Effect.mapError((cause) =>
328 isTextGenerationError(cause)
329 ? cause
330 : new TextGenerationError({
331 operation: input.operation,
332 detail: "Antigravity text generation failed.",
333 cause,
334 }),
335 ),
336 Effect.scoped,
337 ),
338 );
339
340 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
341 Effect.fn("AntigravityTextGeneration.generateCommitMessage")(function* (input) {
342 const generated = yield* runAntigravityJson({
343 operation: "generateCommitMessage",
344 ...buildCommitMessagePrompt({
345 branch: input.branch,
346 stagedSummary: input.stagedSummary,
347 stagedPatch: input.stagedPatch,
348 includeBranch: input.includeBranch === true,
349 policy: input.policy,
350 }),
351 modelSelection: input.modelSelection,
352 });
353 return {
354 subject: sanitizeCommitSubject(generated.subject),
355 body: generated.body.trim(),
356 ...("branch" in generated && typeof generated.branch === "string"
357 ? { branch: sanitizeFeatureBranchName(generated.branch) }
358 : {}),
359 };
360 });
361
362 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
363 Effect.fn("AntigravityTextGeneration.generatePrContent")(function* (input) {
364 const generated = yield* runAntigravityJson({
365 operation: "generatePrContent",
366 ...buildPrContentPrompt({
367 baseBranch: input.baseBranch,
368 headBranch: input.headBranch,
369 commitSummary: input.commitSummary,
370 diffSummary: input.diffSummary,
371 diffPatch: input.diffPatch,
372 policy: input.policy,
373 changeRequestTemplate: input.changeRequestTemplate,
374 }),
375 modelSelection: input.modelSelection,
376 });
377 return { title: sanitizePrTitle(generated.title), body: generated.body.trim() };
378 });
379
380 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
381 Effect.fn("AntigravityTextGeneration.generateBranchName")(function* (input) {
382 const generated = yield* runAntigravityJson({
383 operation: "generateBranchName",
384 ...buildBranchNamePrompt({
385 message: input.message,
386 attachments: input.attachments,
387 naming: input.naming,
388 }),
389 modelSelection: input.modelSelection,
390 });
391 return { branch: formatGeneratedBranchName(generated.branch, input.naming) };
392 });
393
394 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
395 Effect.fn("AntigravityTextGeneration.generateThreadTitle")(function* (input) {
396 const generated = yield* runAntigravityJson({
397 operation: "generateThreadTitle",
398 ...buildThreadTitlePrompt({
399 message: input.message,
400 previousTitle: input.previousTitle,
401 linkedContext: input.linkedContext,
402 attachments: input.attachments,
403 }),
404 modelSelection: input.modelSelection,
405 });
406 return {
407 title: sanitizeThreadTitle(generated.title),
408 ...(generated.needsRefinement ? { needsRefinement: true } : {}),
409 };
410 });
411
412 return {
413 generateCommitMessage,
414 generatePrContent,
415 generateBranchName,
416 generateThreadTitle,
417 } satisfies TextGeneration.TextGeneration["Service"];
418});