feat(provider): add Antigravity (Google AGY) provider integration & ACP bridge #4995
Closedumarfaruq0z(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromrefs/pull/4995/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- @@ -0,0 +983,21 @@983+): Promise<TurnOutcome> {984+ // A cancel that raced the end of an earlier turn must not decide this one.985+ cancelledSessions.delete(sessionId);986+ // Claimed before any setup work: spawning `agy` takes long enough that a987+ // cancel can land first, and cancels are only honoured for the session988+ // holding this claim. Leaving it unset until after the spawn would silently989+ // drop those, letting an auto-approving child run on past a cancelled turn.990+ activeTurnSessionId = sessionId;991+ // Measured before `agy` starts: whatever the transcript already holds992+ // belongs to earlier turns of the conversation being resumed.993+ const baseline = transcriptBaseline(session.conversationId);994+ let hookDir: string | undefined;995+ let hookWorkspace: string | undefined;996+ let attachmentDir: string | undefined;997+ let child: NodeChildProcess.ChildProcess;998+ try {999+ hookDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agy-hookout-"));1000+ hookWorkspace = createHookWorkspace();1001+ const attachments = stageAttachments(prompt.attachments);1002+ attachmentDir = attachments.dir;1003+ const command = process.env["T3_AGY_COMMAND"]?.trim() || "agy";@@ -0,0 +432,21 @@432+ const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);433+ if (versionOutput.code !== 0) {434+ yield* Effect.logWarning("Antigravity CLI version probe exited with a non-zero status.", {435+ exitCode: versionOutput.code,436+ });437+ return buildServerProvider({438+ presentation: ANTIGRAVITY_PRESENTATION,439+ enabled: settings.enabled,440+ checkedAt,441+ models: fallbackModels,442+ probe: {443+ installed: true,444+ version,445+ status: "error",446+ auth: { status: "unknown" },447+ message: "Antigravity CLI is installed but failed to run.",448+ },449+ });450+ }451+452+ const discoveryResult = yield* discoverAntigravityModels(settings, environment).pipe(@@ -0,0 +1325,21 @@1325+ const target = (pending["params"] as Record<string, unknown> | undefined)?.["sessionId"];1326+ if (typeof target === "string" && pending["id"] !== undefined) {1327+ queuedPromptGenerations.set(pending["id"], cancelGeneration(target));1328+ }1329+ }1330+ queue = queue1331+ .then(() => handleRequest(pending))1332+ .catch((error: unknown) => {1333+ // Every request must be answered. Swallowing a handler failure would1334+ // leave the client blocked on a response that never arrives.1335+ if (pending["id"] !== undefined) {1336+ const detail = error instanceof Error ? error.message : String(error);1337+ sendError(pending["id"], -32603, `internal bridge error: ${detail}`);1338+ }1339+ });1340+ }1341+ }1342+1343+ // stdin closed: no approval can still be answered, so unblock the hooks1344+ // waiting on them (they fail closed) rather than letting them time out.1345+ failPendingOutbound("T3 Code disconnected before approving this tool call");@@ -0,0 +241,21 @@241+ optionDescriptors: [242+ {243+ id: "reasoningEffort",244+ label: "Reasoning",245+ type: "select",246+ options,247+ ...(options.find((o) => o.isDefault)?.id248+ ? { currentValue: options.find((o) => o.isDefault)!.id }249+ : {}),250+ },251+ ],252+ });253+ }254+255+ result.push({256+ slug: data.defaultSlug,257+ name,258+ isCustom: false,259+ capabilities,260+ });261+ }@@ -0,0 +860,21 @@860+ hook.event === "pre-tool-use" &&861+ hook.payload?.toolCall862+ ) {863+ requestToolApproval({864+ sessionId: input.sessionId,865+ hookDir: input.hookDir,866+ hookName: name,867+ payload: hook.payload,868+ });869+ }870+ }871+872+ const transcriptPath = resolveTranscriptPath(input.state);873+ if (transcriptPath) {874+ let chunk = "";875+ try {876+ const stats = NodeFS.statSync(transcriptPath);877+ if (stats.size > input.transcriptOffset.value) {878+ const fd = NodeFS.openSync(transcriptPath, "r");879+ try {880+ const length = stats.size - input.transcriptOffset.value;@@ -0,0 +155,21 @@155+ _meta: { antigravity: { event: "transcript", recordType: type, stepIdx: stepIndex } },156+ },157+ ],158+ emittedAssistantText: false,159+ };160+}161+162+/**163+ * Drop transcript records belonging to earlier turns.164+ *165+ * One conversation keeps a single append-only transcript, and every turn opens166+ * with a `USER_INPUT` record, so the last one in the file marks where the167+ * current turn begins. Resuming a conversation starts reading at byte 0 — the168+ * turn's own records cannot be located any other way — which without this trim169+ * would replay every prior assistant message as new output.170+ *171+ * Applied only to the first batch of a turn. Returns the input unchanged when172+ * no `USER_INPUT` is present, which is the correct read for a transcript whose173+ * opening record has not been written yet.174+ */175+export function dropPriorTurnRecords(lines: ReadonlyArray<string>): ReadonlyArray<string> {@@ -0,0 +946,21 @@946+function flushTerminal(sessionId: string, state: AgyTurnState, stepIdx: number): void {947+ const terminal = state.pendingTerminal.get(stepIdx);948+ if (!terminal) {949+ return;950+ }951+ state.pendingTerminal.delete(stepIdx);952+ sendSessionUpdate(sessionId, terminal);953+}954+955+/**956+ * Hooks report `transcript_full.jsonl`; the sibling `transcript.jsonl` holds957+ * the same steps without internal model chatter and is the better stream to958+ * render.959+ *960+ * The choice is pinned for the rest of the turn. `transcriptOffset` and the961+ * line cursor are byte positions into whichever file was picked, so switching962+ * once the condensed file appears would resume reading at an offset that means963+ * nothing in the new file — skipping records, or re-emitting ones already964+ * streamed from the other one.965+ */966+function resolveTranscriptPath(state: AgyTurnState): string | undefined {@@ -0,0 +1163,21 @@1163+ // Images ride in as `resource_link` blocks (an ACP baseline type)1164+ // rather than inline base64, so the `image` capability stays off.1165+ promptCapabilities: { image: false, audio: false, embeddedContext: false },1166+ mcpCapabilities: { http: false, sse: false },1167+ },1168+ authMethods: [],1169+ // The bridge has no version of its own; it ships with the server, so1170+ // that is the version worth reporting. The Antigravity CLI version is1171+ // reported separately by the provider snapshot (`agy --version`).1172+ agentInfo: { name: "Antigravity", version: packageJson.version },1173+ });1174+ return;1175+ }1176+ // Antigravity manages its own Google sign-in; there is nothing for the1177+ // client to authenticate against, but the handshake still requires a1178+ // successful reply.1179+ case "authenticate": {1180+ sendResult(id, {});1181+ return;1182+ }1183+ case "session/new":@@ -0,0 +735,21 @@735+736+ // `agy` binds the model with a `--model` flag on each spawn, and that737+ // flag composes with `--conversation` — verified against the CLI: a738+ // resumed conversation answers on the new model with its history739+ // intact. Applied before `turn.started` so the announced model is the740+ // one the turn actually runs on.741+ const turnModelSelection =742+ input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;743+ const requestedModelId = turnModelSelection?.model744+ ? resolveAntigravityBaseModelId(turnModelSelection.model)745+ : undefined;746+ if (requestedModelId !== undefined && requestedModelId !== ctx.currentModelId) {747+ yield* ctx.acp748+ .setSessionModel(requestedModelId)749+ .pipe(750+ Effect.mapError((cause) =>751+ mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),752+ ),753+ );754+ ctx.currentModelId = requestedModelId;755+ ctx.session = { ...ctx.session, model: turnModelSelection?.model ?? ctx.session.model };@@ -0,0 +223,21 @@223+224+ for (const [baseSlug, data] of groups.entries()) {225+ const name = formatAntigravityModelName(baseSlug);226+ const effortList = Array.from(data.efforts);227+228+ let capabilities: ModelCapabilities = EMPTY_CAPABILITIES;229+ if (effortList.length > 0) {230+ const options = effortList.map((eff) => ({231+ id: eff,232+ label: eff.charAt(0).toUpperCase() + eff.slice(1),233+ ...(eff === "high" || effortList.length === 1 ? { isDefault: true } : {}),234+ }));235+ const hasDefault = options.some((opt) => opt.isDefault);236+ if (!hasDefault && options.length > 0) {237+ (options[options.length - 1] as { isDefault?: boolean }).isDefault = true;238+ }239+240+ capabilities = createModelCapabilities({241+ optionDescriptors: [242+ {243+ id: "reasoningEffort",
- @@ -0,0 +3,21 @@3+import * as Effect from "effect/Effect";4+import * as FileSystem from "effect/FileSystem";5+import * as Path from "effect/Path";6+import * as Schema from "effect/Schema";7+import { AntigravitySettings } from "@t3tools/contracts";8+9+import {10+ buildInitialAntigravityProviderSnapshot,11+ checkAntigravityProviderStatus,12+} from "./AntigravityProvider.ts";13+14+const decodeAntigravitySettings = Schema.decodeSync(AntigravitySettings);15+16+const isWindows = process.platform === "win32";17+18+/**19+ * Creates a Node.js-backed script stub that runs identically on Windows and Unix.20+ */21+function makeNodeStub(dir: string, fileName: string, jsCode: string): string {22+ const fs = require("node:fs");23+ const path = require("node:path");@@ -0,0 +22,21 @@22+import * as Result from "effect/Result";23+import { HttpClient } from "effect/unstable/http";24+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";25+import { createModelCapabilities } from "@t3tools/shared/model";26+import { resolveSpawnCommand } from "@t3tools/shared/shell";27+28+import {29+ buildServerProvider,30+ isCommandMissingCause,31+ parseGenericCliVersion,32+ providerModelsFromSettings,33+ spawnAndCollect,34+ type ServerProviderDraft,35+} from "../providerSnapshot.ts";36+import {37+ enrichProviderSnapshotWithVersionAdvisory,38+ type ProviderMaintenanceCapabilities,39+} from "../providerMaintenance.ts";40+import * as NodeFS from "node:fs";41+import * as NodeOS from "node:os";42+import * as NodePath from "node:path";@@ -0,0 +400,21 @@400+ ? {401+ mcpServers: [402+ {403+ type: "http" as const,404+ name: "t3-code",405+ url: mcpSession.endpoint,406+ headers: [{ name: "Authorization", value: mcpSession.authorizationHeader }],407+ },408+ ],409+ }410+ : {}),411+ ...acpNativeLoggers,412+ }).pipe(413+ Effect.provideService(Crypto.Crypto, crypto),414+ Effect.provideService(Scope.Scope, sessionScope),415+ Effect.mapError(416+ (cause) =>417+ new ProviderAdapterProcessError({418+ provider: PROVIDER,419+ threadId: input.threadId,420+ detail: cause.message,
- @@ -0,0 +149,21 @@149+ if (raw.schemaVersion !== ANTIGRAVITY_RESUME_VERSION) return undefined;150+ if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;151+ return { sessionId: raw.sessionId.trim() };152+}153+154+/**155+ * Reasoning effort for `agy --effort`, read from the model option selections.156+ * Antigravity accepts only low/medium/high.157+ */158+function resolveEffortSelection(159+ options:160+ | ReadonlyArray<{ readonly id: string; readonly value: string | boolean }>161+ | null162+ | undefined,163+): string | undefined {164+ // Option values are a string/boolean union across providers; only a string165+ // effort is meaningful here.166+ const raw = options?.find((option) => option.id === "effort")?.value;167+ const effort = typeof raw === "string" ? raw.trim().toLowerCase() : undefined;168+ return effort === "low" || effort === "medium" || effort === "high" ? effort : undefined;169+}@@ -0,0 +140,21 @@140+ discoveredPlanType = "enterprise";141+ } else if (142+ obj["consumerOnboardingComplete"] === true ||143+ obj["onboardingComplete"] === true144+ ) {145+ discoveredPlanType = "pro";146+ }147+ }148+ }149+ } catch {150+ // Fall through151+ }152+ }153+154+ const label = antigravityAccountAuthLabel(discoveredPlanType);155+156+ return {157+ status: "authenticated",158+ ...(label ? { label } : {}),159+ ...(discoveredEmail ? { email: discoveredEmail } : {}),160+ };@@ -0,0 +996,21 @@996+ let attachmentDir: string | undefined;997+ let child: NodeChildProcess.ChildProcess;998+ try {999+ hookDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agy-hookout-"));1000+ hookWorkspace = createHookWorkspace();1001+ const attachments = stageAttachments(prompt.attachments);1002+ attachmentDir = attachments.dir;1003+ const command = process.env["T3_AGY_COMMAND"]?.trim() || "agy";1004+ child = NodeChildProcess.spawn(1005+ command,1006+ buildAgyArgs({1007+ session,1008+ hookWorkspace,1009+ attachmentDir,1010+ promptText: composePromptText(prompt.baseText, attachments.staged, prompt.remoteUris),1011+ }),1012+ {1013+ cwd: session.cwd,1014+ env: { ...process.env, [HOOK_DIR_ENV]: hookDir },1015+ stdio: ["ignore", "pipe", "pipe"],1016+ },
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
273d1970-649c-4e9e-afe9-14c08bfc64aeYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share