Add Antigravity (agy) provider via an ACP compatibility bridge #4497
Closedagentool(GitHub profile, opens in a new tab)wants to merge 57 commits into
main fromrefs/pull/4497/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/provider/acp/antigravity/agyBridge.ts line 253Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ if (map[sessionId] === conversationId) {83+ return;84+ }85+ map[sessionId] = conversationId;86+ NodeFS.writeFileSync(target, JSON.stringify(map, null, 2));87+ } catch {88+ // Losing the mapping costs conversation continuity on the next resume,89+ // which is not worth failing a turn over.90+ }91+}92+93+function lookupConversationId(sessionId: string): string | undefined {94+ const mapped = readSessionMap()[sessionId]?.trim();95+ if (mapped) {96+ return mapped;97+ }98+ // A caller may hand back an Antigravity conversation UUID directly.99+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)100+ ? sessionId101+ : undefined;102+}apps/server/src/provider/acp/antigravity/agyBridge.ts line 1630Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +376,21 @@376+ }377+ if (result.emittedAssistantText) {378+ input.assistantText.emitted = true;379+ }380+ }381+ }382+}383+384+/**385+ * Hooks report `transcript_full.jsonl`; the sibling `transcript.jsonl` holds386+ * the same steps without internal model chatter and is the better stream to387+ * render.388+ */389+function resolveTranscriptPath(state: AgyTurnState): string | undefined {390+ const reported = state.transcriptPath;391+ if (!reported) {392+ return undefined;393+ }394+ const condensed = reported.replace(/transcript_full\.jsonl$/, "transcript.jsonl");395+ return NodeFS.existsSync(condensed) ? condensed : reported;396+}apps/server/src/provider/acp/antigravity/agyBridge.ts line 1581Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +361,21 @@361+ }362+ } catch {363+ chunk = "";364+ }365+366+ const lines = chunk.length > 0 ? input.cursor.push(chunk) : [];367+ const allLines = input.final ? [...lines, ...input.cursor.flush()] : lines;368+ for (const line of allLines) {369+ const record = parseTranscriptLine(line);370+ if (!record) {371+ continue;372+ }373+ const result = transcriptRecordUpdates(record, input.state);374+ for (const update of result.updates) {375+ sendSessionUpdate(input.sessionId, update);376+ }377+ if (result.emittedAssistantText) {378+ input.assistantText.emitted = true;379+ }380+ }381+ }apps/server/src/provider/acp/antigravity/agyBridge.ts line 2191Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +573,21 @@573+ }574+ const prompt = renderPrompt(session, params["prompt"]);575+ if (prompt === null) {576+ sendError(id, -32602, "session/prompt requires at least one text block");577+ return;578+ }579+ const outcome = await runTurn(sessionId, session, prompt);580+ if (outcome.failure) {581+ sendError(id, -32000, `Antigravity turn failed: ${outcome.failure}`);582+ return;583+ }584+ sendResult(id, { stopReason: outcome.stopReason });585+ return;586+ }587+ case "session/cancel": {588+ const sessionId = typeof params["sessionId"] === "string" ? params["sessionId"] : undefined;589+ if (sessionId) {590+ cancelledSessions.add(sessionId);591+ }592+ activeChild?.kill("SIGTERM");593+ return;apps/server/src/provider/Layers/AntigravityAdapter.ts line 526OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +506,21 @@506+ provider: PROVIDER,507+ threadId: input.threadId,508+ turnId,509+ payload: { model: ctx.session.model },510+ });511+ }512+513+ // The bridge declares no image capability: `agy --print` takes text514+ // only, so attachments cannot be forwarded.515+ const promptParts: Array<EffectAcpSchema.ContentBlock> = [];516+ if (input.input?.trim()) {517+ promptParts.push({ type: "text", text: input.input.trim() });518+ }519+ if (promptParts.length === 0) {520+ return yield* new ProviderAdapterValidationError({521+ provider: PROVIDER,522+ operation: "sendTurn",523+ issue:524+ "Turn requires non-empty text. Antigravity print mode does not accept attachments.",525+ });526+ }
- apps/server/src/provider/Layers/AntigravityAdapter.ts line 1633Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +606,21 @@606+607+ const respondToUserInput: AntigravityAdapterShape["respondToUserInput"] = (608+ threadId,609+ requestId,610+ ) =>611+ Effect.gen(function* () {612+ yield* requireSession(threadId);613+ return yield* new ProviderAdapterRequestError({614+ provider: PROVIDER,615+ method: "session/user_input",616+ detail: `Antigravity print mode cannot ask questions; unknown request: ${requestId}`,617+ });618+ });619+620+ const readThread: AntigravityAdapterShape["readThread"] = (threadId) =>621+ Effect.gen(function* () {622+ const ctx = yield* requireSession(threadId);623+ return { threadId, turns: ctx.turns };624+ });625+626+ const rollbackThread: AntigravityAdapterShape["rollbackThread"] = (threadId, numTurns) =>apps/server/src/provider/acp/antigravity/agyBridge.ts lines 104 to 105OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +85,21 @@85+ map[sessionId] = conversationId;86+ NodeFS.writeFileSync(target, JSON.stringify(map, null, 2));87+ } catch {88+ // Losing the mapping costs conversation continuity on the next resume,89+ // which is not worth failing a turn over.90+ }91+}92+93+/**94+ * Map a bridge session id to the Antigravity conversation it should resume.95+ *96+ * The persisted map is the only authority. Bridge session ids are themselves97+ * random UUIDs, so an id that merely looks like a conversation id is98+ * indistinguishable from one the bridge minted — falling back to the shape of99+ * the string would make `session/load` resume a conversation that never100+ * existed whenever the map is missing or unreadable. Returning `undefined`101+ * starts a fresh conversation, which is the recoverable outcome.102+ */103+function lookupConversationId(sessionId: string): string | undefined {104+ return readSessionMap()[sessionId]?.trim() || undefined;105+}apps/server/src/provider/acp/antigravity/agyBridge.ts lines 426 to 426OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +406,21 @@406+ return undefined;407+ }408+ const condensed = reported.replace(/transcript_full\.jsonl$/, "transcript.jsonl");409+ state.resolvedTranscriptPath = NodeFS.existsSync(condensed) ? condensed : reported;410+ return state.resolvedTranscriptPath;411+}412+413+async function runTurn(414+ sessionId: string,415+ session: BridgeSession,416+ prompt: string,417+): Promise<TurnOutcome> {418+ // A cancel that raced the end of an earlier turn must not decide this one.419+ cancelledSessions.delete(sessionId);420+ const hookDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agy-hookout-"));421+ const hookWorkspace = createHookWorkspace();422+ const command = process.env["T3_AGY_COMMAND"]?.trim() || "agy";423+ const state = makeAgyTurnState(session.conversationId);424+ const seenHooks = new Set<string>();425+ const cursor = new AgyTranscriptCursor();426+ const transcriptOffset = { value: 0 };apps/server/src/provider/Layers/AntigravityAdapter.ts lines 1049 to 1066Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +433,21 @@433+ yield* offerRuntimeEvent(434+ makeAcpContentDeltaEvent({435+ stamp: yield* makeEventStamp(),436+ provider: PROVIDER,437+ threadId: ctx.threadId,438+ turnId: ctx.activeTurnId,439+ ...(event.itemId ? { itemId: event.itemId } : {}),440+ text: event.text,441+ rawPayload: event.rawPayload,442+ }),443+ );444+ return;445+ }446+ }),447+ ),448+ ).pipe(449+ Effect.catch((cause) =>450+ Effect.logError("Failed to process Antigravity runtime notification.", { cause }),451+ ),452+ Effect.forkChild,453+ );apps/server/src/provider/Layers/AntigravityAdapter.ts line 531OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +511,21 @@511+512+ return yield* Effect.gen(function* () {513+ ctx.activeTurnId = turnId;514+ ctx.session = {515+ ...ctx.session,516+ activeTurnId: turnId,517+ updatedAt: yield* nowIso,518+ };519+520+ if (steeringTurnId === undefined) {521+ yield* offerRuntimeEvent({522+ type: "turn.started",523+ ...(yield* makeEventStamp()),524+ provider: PROVIDER,525+ threadId: input.threadId,526+ turnId,527+ payload: { model: ctx.session.model },528+ });529+ }530+531+ const result = yield* ctx.acp
- apps/server/src/provider/acp/antigravity/agyBridge.ts line 435OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +415,21 @@415+ session: BridgeSession,416+ prompt: string,417+): Promise<TurnOutcome> {418+ // A cancel that raced the end of an earlier turn must not decide this one.419+ cancelledSessions.delete(sessionId);420+ const hookDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agy-hookout-"));421+ const hookWorkspace = createHookWorkspace();422+ const command = process.env["T3_AGY_COMMAND"]?.trim() || "agy";423+ const state = makeAgyTurnState(session.conversationId);424+ const seenHooks = new Set<string>();425+ const cursor = new AgyTranscriptCursor();426+ const transcriptOffset = { value: 0 };427+ const assistantText = { emitted: false };428+429+ const child = NodeChildProcess.spawn(command, buildAgyArgs(session, hookWorkspace, prompt), {430+ cwd: session.cwd,431+ env: { ...process.env, [HOOK_DIR_ENV]: hookDir },432+ stdio: ["ignore", "pipe", "pipe"],433+ });434+ activeChild = child;435+ activeTurnSessionId = sessionId;
- apps/server/src/provider/Layers/AntigravityAdapter.ts line 1699Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +879,21 @@879+880+ const stopAll: AntigravityAdapterShape["stopAll"] = () =>881+ Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });882+883+ yield* Effect.addFinalizer(() =>884+ Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(885+ Effect.catch((cause) =>886+ Effect.logError("Failed to emit Antigravity session shutdown event.", { cause }),887+ ),888+ Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),889+ Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),890+ ),891+ );892+893+ const streamEvents = Stream.fromPubSub(runtimeEventPubSub);894+895+ return {896+ provider: PROVIDER,897+ // `agy --model` is applied when the bridge spawns the CLI, so switching898+ // models mid-session is not possible.899+ capabilities: { sessionModelSwitch: "in-session" },apps/server/src/provider/Layers/AntigravityAdapter.ts line 1593Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +780,21 @@780+ turnId,781+ payload: { state, stopReason },782+ });783+ }).pipe(Effect.catch(() => Effect.void)),784+ ),785+ );786+ });787+788+ const interruptTurn: AntigravityAdapterShape["interruptTurn"] = (threadId) =>789+ Effect.gen(function* () {790+ const ctx = yield* requireSession(threadId);791+ yield* Effect.ignore(792+ ctx.acp.cancel.pipe(793+ Effect.mapError((error) =>794+ mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),795+ ),796+ ),797+ );798+ });799+800+ // `agy` itself always runs with permissions skipped — print mode cannotapps/server/src/provider/Layers/AntigravityAdapter.ts line 783OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +763,21 @@763+ const { activeTurnId: _endedTurnId, ...endedSession } = ctx.session;764+ ctx.session = { ...endedSession, status: "ready", updatedAt: yield* nowIso };765+ }766+ // A prompt that failed or was interrupted after `turn.started`767+ // still owes consumers a terminal event; without one the turn768+ // renders as running forever even though sendTurn already769+ // returned an error.770+ const state = !promptSucceeded771+ ? "failed"772+ : stopReason === "cancelled"773+ ? "cancelled"774+ : "completed";775+ yield* offerRuntimeEvent({776+ type: "turn.completed",777+ ...(yield* makeEventStamp()),778+ provider: PROVIDER,779+ threadId: input.threadId,780+ turnId,781+ payload: { state, stopReason },782+ });783+ }).pipe(Effect.catch(() => Effect.void)),apps/server/src/provider/Layers/AntigravityAdapter.ts line 856Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +435,21 @@435+ );436+ const resolved = yield* Deferred.await(decision);437+ pendingApprovals.delete(requestId);438+ yield* offerRuntimeEvent(439+ makeAcpRequestResolvedEvent({440+ stamp: yield* makeEventStamp(),441+ provider: PROVIDER,442+ threadId: input.threadId,443+ turnId,444+ requestId: RuntimeRequestId.make(requestId),445+ permissionRequest,446+ decision: resolved,447+ }),448+ );449+ const optionId =450+ resolved === "cancel" ? undefined : selectPermissionOptionId(params, resolved);451+ return {452+ outcome: optionId453+ ? { outcome: "selected" as const, optionId }454+ : ({ outcome: "cancelled" } as const),455+ };apps/server/src/provider/Layers/AntigravityAdapter.ts line 298OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +278,21 @@278+ if (!ctx || ctx.stopped) {279+ return Effect.fail(280+ new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),281+ );282+ }283+ return Effect.succeed(ctx);284+ };285+286+ const stopSessionInternal = (ctx: AntigravitySessionContext) =>287+ Effect.gen(function* () {288+ if (ctx.stopped) return;289+ ctx.stopped = true;290+ // Anything still waiting on a human is cancelled, which the bridge291+ // turns into a denial. Left pending, the hook would block its tool292+ // until its own timeout with no one able to answer.293+ const pending = approvalsByThread.get(ctx.threadId);294+ if (pending) {295+ for (const [, approval] of pending) {296+ yield* Deferred.succeed(approval.decision, "cancel");297+ }298+ approvalsByThread.delete(ctx.threadId);apps/server/src/provider/acp/antigravity/agyBridge.ts line 728OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +708,21 @@708+ try {709+ const length = stats.size - input.transcriptOffset.value;710+ const buffer = Buffer.alloc(length);711+ NodeFS.readSync(fd, buffer, 0, length, input.transcriptOffset.value);712+ chunk = buffer.toString("utf8");713+ input.transcriptOffset.value = stats.size;714+ } finally {715+ NodeFS.closeSync(fd);716+ }717+ }718+ } catch {719+ chunk = "";720+ }721+722+ const lines = chunk.length > 0 ? input.cursor.push(chunk) : [];723+ let allLines = input.final ? [...lines, ...input.cursor.flush()] : lines;724+ // Reading always starts at byte 0, so the first batch of a resumed725+ // conversation carries every prior turn. Trim once, then stream.726+ if (!input.state.transcriptPrimed && allLines.length > 0) {727+ allLines = [...dropPriorTurnRecords(allLines)];728+ input.state.transcriptPrimed = true;apps/server/src/provider/acp/antigravity/agyBridge.ts line 784Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +420,21 @@420+ payload,421+ // Snapshot the file here, while the hook still brackets the tool call.422+ ...(agyToolKind(payload?.toolCall?.name) === "edit"423+ ? { capturedFileText: captureFileText(agyTargetPath(payload?.toolCall)) }424+ : {}),425+ };426+ const name = `${process.hrtime.bigint().toString().padStart(24, "0")}-${event}.json`;427+ // Write then rename so the poller never observes a partial file.428+ const finalPath = NodePath.join(hookDir, name);429+ const tempPath = `${finalPath}.tmp`;430+ NodeFS.writeFileSync(tempPath, JSON.stringify(record));431+ NodeFS.renameSync(tempPath, finalPath);432+433+ // With approvals on, this process is the gate: block until the bridge434+ // reports the user's answer. `deny` here genuinely stops the tool —435+ // Antigravity reports the reason back to the model.436+ if (approvalRequired() && event === "pre-tool-use" && payload?.toolCall) {437+ const decision = await awaitDecision(hookDir, name);438+ process.stdout.write(JSON.stringify(decision));439+ return;440+ }
- apps/server/src/provider/acp/antigravity/agyBridge.ts line 1347Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +687,21 @@687+ }688+ }689+ // The hook process is blocked until a decision file appears, so this has690+ // to be started for every announced tool call.691+ if (approvalRequired() && hook.event === "pre-tool-use" && hook.payload?.toolCall) {692+ requestToolApproval({693+ sessionId: input.sessionId,694+ hookDir: input.hookDir,695+ hookName: name,696+ payload: hook.payload,697+ });698+ }699+ }700+701+ const transcriptPath = resolveTranscriptPath(input.state);702+ if (transcriptPath) {703+ let chunk = "";704+ try {705+ const stats = NodeFS.statSync(transcriptPath);706+ if (stats.size > input.transcriptOffset.value) {707+ const fd = NodeFS.openSync(transcriptPath, "r");apps/server/src/provider/acp/antigravity/agyBridge.ts line 785Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +421,21 @@421+ // Snapshot the file here, while the hook still brackets the tool call.422+ ...(agyToolKind(payload?.toolCall?.name) === "edit"423+ ? { capturedFileText: captureFileText(agyTargetPath(payload?.toolCall)) }424+ : {}),425+ };426+ const name = `${process.hrtime.bigint().toString().padStart(24, "0")}-${event}.json`;427+ // Write then rename so the poller never observes a partial file.428+ const finalPath = NodePath.join(hookDir, name);429+ const tempPath = `${finalPath}.tmp`;430+ NodeFS.writeFileSync(tempPath, JSON.stringify(record));431+ NodeFS.renameSync(tempPath, finalPath);432+433+ // With approvals on, this process is the gate: block until the bridge434+ // reports the user's answer. `deny` here genuinely stops the tool —435+ // Antigravity reports the reason back to the model.436+ if (approvalRequired() && event === "pre-tool-use" && payload?.toolCall) {437+ const decision = await awaitDecision(hookDir, name);438+ process.stdout.write(JSON.stringify(decision));439+ return;440+ }441+ } catch {apps/server/src/provider/Layers/AntigravityAdapter.ts line 1112Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +594,21 @@594+ });595+ yield* offerRuntimeEvent({596+ type: "session.state.changed",597+ ...(yield* makeEventStamp()),598+ provider: PROVIDER,599+ threadId: input.threadId,600+ payload: { state: "ready", reason: "Antigravity ACP session ready" },601+ });602+ yield* offerRuntimeEvent({603+ type: "thread.started",604+ ...(yield* makeEventStamp()),605+ provider: PROVIDER,606+ threadId: input.threadId,607+ payload: { providerThreadId: started.sessionId },608+ });609+610+ return session;611+ }).pipe(Effect.scoped),612+ );613+614+ const sendTurn: AntigravityAdapterShape["sendTurn"] = (input) =>
- apps/server/src/provider/acp/antigravity/agyBridge.ts line 1347Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +845,21 @@845+ !input.final &&846+ approvalRequired() &&847+ hook.event === "pre-tool-use" &&848+ hook.payload?.toolCall849+ ) {850+ requestToolApproval({851+ sessionId: input.sessionId,852+ hookDir: input.hookDir,853+ hookName: name,854+ payload: hook.payload,855+ });856+ }857+ }858+859+ const transcriptPath = resolveTranscriptPath(input.state);860+ if (transcriptPath) {861+ let chunk = "";862+ try {863+ const stats = NodeFS.statSync(transcriptPath);864+ if (stats.size > input.transcriptOffset.value) {865+ const fd = NodeFS.openSync(transcriptPath, "r");apps/server/src/provider/Layers/AntigravityAdapter.ts line 1112Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +636,21 @@636+ });637+ yield* offerRuntimeEvent({638+ type: "session.state.changed",639+ ...(yield* makeEventStamp()),640+ provider: PROVIDER,641+ threadId: input.threadId,642+ payload: { state: "ready", reason: "Antigravity ACP session ready" },643+ });644+ yield* offerRuntimeEvent({645+ type: "thread.started",646+ ...(yield* makeEventStamp()),647+ provider: PROVIDER,648+ threadId: input.threadId,649+ payload: { providerThreadId: started.sessionId },650+ });651+652+ return session;653+ }).pipe(Effect.scoped),654+ );655+656+ const sendTurn: AntigravityAdapterShape["sendTurn"] = (input) =>apps/server/src/provider/acp/antigravity/agyBridge.ts line 2330Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1313,21 @@1313+ if (typeof target === "string" && pending["id"] !== undefined) {1314+ queuedPromptGenerations.set(pending["id"], cancelGeneration(target));1315+ }1316+ }1317+ queue = queue1318+ .then(() => handleRequest(pending))1319+ .catch((error: unknown) => {1320+ // Every request must be answered. Swallowing a handler failure would1321+ // leave the client blocked on a response that never arrives.1322+ if (pending["id"] !== undefined) {1323+ const detail = error instanceof Error ? error.message : String(error);1324+ sendError(pending["id"], -32603, `internal bridge error: ${detail}`);1325+ }1326+ });1327+ }1328+ }1329+1330+ // stdin closed: no approval can still be answered, so unblock the hooks1331+ // waiting on them (they fail closed) rather than letting them time out.1332+ failPendingOutbound("T3 Code disconnected before approving this tool call");1333+ await queue;apps/server/src/provider/acp/antigravity/agyBridge.ts line 110OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +90,21 @@90+ * Layout confirmed against real conversations:91+ * `<appDataDir>/brain/<conversation-uuid>/.system_generated/logs/`.92+ */93+function transcriptDirFor(conversationId: string): string {94+ const appDataDir =95+ process.env["T3_AGY_APP_DATA_DIR"]?.trim() ||96+ NodePath.join(NodeOS.homedir(), ".gemini", "antigravity-cli");97+ return NodePath.join(appDataDir, "brain", conversationId, ".system_generated", "logs");98+}99+100+/**101+ * Bytes already in a resumed conversation's transcript before this turn runs.102+ *103+ * A positive baseline, taken before `agy` is spawned, is what makes "records104+ * from earlier turns" precise. Inferring the boundary from the last105+ * `USER_INPUT` record cannot: the file always contains previous ones, so a106+ * poll landing before the new marker is written would treat an earlier turn's107+ * output as live. Returns 0 when the file cannot be measured, which falls back108+ * to the marker heuristic rather than skipping the turn's own output.109+ */110+function transcriptBaseline(conversationId: string | undefined): number {
- apps/server/src/provider/Layers/AntigravityAdapter.ts line 784OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +764,21 @@764+ ...(yield* makeEventStamp()),765+ provider: PROVIDER,766+ threadId: input.threadId,767+ turnId,768+ payload: { model: ctx.session.model },769+ });770+ // Marked only after the event is actually out, so a failed publish771+ // cannot let another prompt emit a completion for a turn nobody772+ // saw start.773+ ctx.startedTurnIds.add(turnId);774+ }775+ // Rechecked here rather than only at accept time: everything above776+ // yields, and an interrupt during any of it means this prompt must777+ // not reach the agent.778+ if (ctx.cancelEpoch !== acceptedEpoch) {779+ stopReason = "cancelled";780+ return {781+ threadId: input.threadId,782+ turnId,783+ resumeCursor: ctx.session.resumeCursor,784+ };
- apps/server/src/provider/acp/antigravity/agyBridge.ts line 1770Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1454,21 @@1454+ state.transcriptPrimed = true;1455+ state.resolvedTranscriptPath = baseline.path;1456+ }1457+ const assistantText = { emitted: false };1458+ const turnToken: TurnToken = { sessionId, live: true };1459+ // Published so an out-of-band fence covering this epoch can retire the turn1460+ // rather than being recorded for an arrival that already happened.1461+ activeTurnEpoch = promptEpoch;1462+ activeTurnToken = turnToken;1463+ activeChild = child;1464+ if (child.pid !== undefined) {1465+ // Tracking is released the moment it ends, so nothing ever signals a group1466+ // id that is no longer ours.1467+ forgetChildOnExit(child);1468+ }1469+ // A cancel during startup had no process to signal; deliver it now.1470+ if (cancelledSessions.has(sessionId)) {1471+ killActiveChild();1472+ }1473+1474+ let stdout = "";@@ -0,0 +1063,21 @@1063+ return;1064+ }1065+ if (pendingKills.has(child)) {1066+ // Already signalled — a fence and the cancel behind it both land here. A1067+ // second timer would be another delayed signal nobody cancels.1068+ return;1069+ }1070+ if (child.exitCode !== null || child.signalCode !== null) {1071+ // Leader already gone: the spawn-time handler has this, or has run.1072+ signalGroupOf(child, pid, "SIGKILL");1073+ return;1074+ }1075+ signalGroupOf(child, pid, "SIGTERM");1076+ const pending: { readonly pid: number; timer?: ReturnType<typeof setTimeout> } = { pid };1077+ pendingKills.set(child, pending);1078+ // The group is killed when the leader exits by the handler installed at1079+ // spawn, so nothing needs attaching here.1080+ //1081+ // Backstop for a leader that ignores SIGTERM outright. Safe to target by1082+ // group, because the leader is by definition still alive if this fires.1083+ const escalation = setTimeout(() => {
- apps/server/src/provider/Layers/AntigravityAdapter.ts line 1589Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1412,21 @@1412+ Effect.flatMap(() =>1413+ // Still running this long after a cancel means the bridge is1414+ // not processing notifications. Interrupting the RPC alone1415+ // would settle the turn here while a detached `agy` kept1416+ // running tools, so the session goes instead: closing its scope1417+ // ends the bridge process, whose own exit handler kills the1418+ // `agy` process group.1419+ //1420+ // The turn is named rather than checked here: this fiber woke1421+ // ten seconds late, and the check has to happen under the same1422+ // gate that claims the stop or a turn that settled meanwhile1423+ // takes its replacement down with it.1424+ Effect.ignore(1425+ stopSessionInternal(ctx, cancelledTurnId, () =>1426+ ctx.awaitingBridgeAck.has(cancelledTurnId),1427+ ),1428+ ),1429+ ),1430+ ),1431+ ctx.scope,1432+ );apps/server/src/provider/Layers/AntigravityAdapter.ts line 1065Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +928,21 @@928+ );929+ return;930+ }931+ }),932+ ),933+ ).pipe(934+ Effect.catch((cause) =>935+ Effect.logError("Failed to process Antigravity runtime notification.", { cause }),936+ ),937+ // However this consumer ends — teardown, a defect while stamping,938+ // an interrupt — it fires the same signal drains wait on. Without939+ // it a consumer that died on its own would leave every later drain940+ // queuing a barrier nobody can acknowledge, hanging `sendTurn`941+ // while it holds the prompt gate.942+ Effect.onExit(() => Effect.ignore(Deferred.succeed(ctx.teardownSignal, undefined))),943+ // Forked into the session's own scope, not the calling fiber's.944+ // `startSession` can run inside a short-lived request fiber, and a945+ // child fork would die with it while the session and its bridge946+ // live on — taking every future event with it, and now also947+ // tripping the signal above so drains stop waiting.948+ Effect.forkIn(sessionScope),apps/server/src/provider/acp/antigravity/agyBridge.ts line 1760OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1740,21 @@1740+ // would otherwise sit here and stop something sent much later. A prompt1741+ // carrying an epoch is already covered by the mark and consumes no1742+ // marker, so this only ever applies to an untagged one.1743+ if (queuedUntagged(sessionId) > 0) {1744+ unscopedCancels.add(sessionId);1745+ }1746+ return;1747+ }1748+ if (sessionId && sessions.has(sessionId) && sessionId === activeTurnSessionId) {1749+ // Only the turn actually running is stopped, and only when its epoch1750+ // has been cancelled. A prompt accepted after the fence carries a1751+ // higher epoch and must survive this notification, which the runtime1752+ // forks and can therefore deliver late.1753+ //1754+ // Judged by the running turn's own mode, not by anything the session1755+ // did earlier. A turn whose prompt carried no epoch cannot be scoped by1756+ // a mark it never contributed to, so it takes plain ACP semantics; one1757+ // that carried an epoch is stopped only if that epoch was cancelled.1758+ if (activeTurnEpoch === undefined || activeTurnEpoch <= cancelledThrough(sessionId)) {1759+ cancelledSessions.add(sessionId);1760+ killActiveChild();
- apps/server/src/provider/Layers/AntigravityAdapter.ts line 1046Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +927,21 @@927+ makeAcpContentDeltaEvent({928+ stamp: yield* makeEventStamp(),929+ provider: PROVIDER,930+ threadId: ctx.threadId,931+ turnId: ctx.activeTurnId,932+ ...(event.itemId ? { itemId: event.itemId } : {}),933+ text: event.text,934+ rawPayload: event.rawPayload,935+ }),936+ );937+ return;938+ }939+ }).pipe(940+ // Per event, not around the whole stream. Catching outside the941+ // drain meant one unprocessable notification ended the consumer942+ // for good: every later event was lost, and the turn events943+ // that depend on it stopped being attributed even though944+ // prompts kept completing.945+ Effect.catchCause((cause) =>946+ Effect.logError("Failed to process Antigravity runtime notification.", { cause }),947+ ),apps/server/src/provider/acp/antigravity/agyBridge.ts line 2189Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1809,21 @@1809+ cancelledThroughEpoch.set(sessionId, Math.max(cancelledThrough(sessionId), cancelEpoch));1810+ }1811+ if (sessionId !== activeTurnSessionId) {1812+ // No turn running for it yet. An untagged prompt has no epoch to be1813+ // measured against, so it needs a marker — banked only when one is1814+ // genuinely waiting, or a cancel that merely arrived after its own turn1815+ // finished would sit here and stop something sent much later.1816+ if (queuedUntagged(sessionId) > 0) {1817+ unscopedCancels.add(sessionId);1818+ }1819+ return;1820+ }1821+ // Only the turn actually running is stopped, and only when its epoch has1822+ // been cancelled: a prompt accepted after the fence carries a higher one1823+ // and must survive this notification, which the runtime forks and can1824+ // therefore deliver late. A turn whose prompt carried no epoch cannot be1825+ // scoped by a mark it never contributed to, so it takes plain ACP1826+ // semantics.1827+ if (activeTurnEpoch === undefined || activeTurnEpoch <= cancelledThrough(sessionId)) {1828+ cancelledSessions.add(sessionId);1829+ killActiveChild();
- @@ -0,0 +243,21 @@243+ const value = (parsed as { conversationId?: unknown }).conversationId;244+ return typeof value === "string" ? value.trim() || undefined : undefined;245+ } catch {246+ return undefined;247+ }248+}249+250+// ── JSON-RPC plumbing ─────────────────────────────────────────────────251+252+/**253+ * Set while stdout has reported that it is behind.254+ *255+ * Node buffers whatever `write` cannot hand over immediately, so ignoring its256+ * return value turns a slow reader into unbounded growth inside this process.257+ * Polling pauses while this is set. Nothing is lost by waiting: the transcript258+ * stays on disk and is read from its own byte offset, so a skipped poll only259+ * defers work to the next one.260+ */261+let stdoutBlocked = false;262+263+function writeMessage(value: unknown): void {
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:
810156ec-965c-45a6-adec-efe614966a73You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
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