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