π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(antigravity): run Antigravity over ACP so follow-ups steer the running turn (#23764)
Mocha75f054efccd9
diff --git a/apps/cli/src/commands/hetero/index.ts b/apps/cli/src/commands/hetero/index.tsindex f471c28ee86..9b94bc882c9 100644--- a/apps/cli/src/commands/hetero/index.ts+++ b/apps/cli/src/commands/hetero/index.ts@@ -918,7 +918,7 @@ const exec = async (options: ExecOptions): Promise<void> => {return { code: 1, signal: null as NodeJS.Signals | null };});- // Stream events (steering Claude Code or native Codex, see withHeteroSteer); each is optionally written as JSONL+ // Stream events (steering Claude Code, native Codex or Antigravity, see withHeteroSteer); each is optionally written as JSONL// and pushed into the ingester. A resume `error` is withheld and flags a retry instead.let resumeNotFound = false;let sawTerminalError = false;@@ -1072,9 +1072,9 @@ const exec = async (options: ExecOptions): Promise<void> => {// receives text while the process is running, not only the terminal assistant snapshot.includePartialMessages: options.type === 'claude-code',initialModel: usesHeterogeneousSessionInitialModel(options.type) ? options.model : undefined,- // Keep Claude Code's and Antigravity's stdin open while they can still use- // input (live steer / background tasks).- liveInput: options.type === 'claude-code' || options.type === 'antigravity',+ // Keep Claude Code's stdin open while it can still use input: closing it+ // early makes print mode kill background tasks after 10 minutes.+ liveInput: options.type === 'claude-code',operationId,// Claude Code permission mode, Codex Plan switch....dispatchedModeSpawnOptions(options.type, resolved),diff --git a/apps/cli/src/utils/heteroSteer.test.ts b/apps/cli/src/utils/heteroSteer.test.tsindex 7f6fb2ba657..5037248111a 100644--- a/apps/cli/src/utils/heteroSteer.test.ts+++ b/apps/cli/src/utils/heteroSteer.test.ts@@ -207,23 +207,6 @@ describe('withHeteroSteer', () => {expect(giveBack).toHaveBeenCalledWith({ messageId: 'msg-1', operationId: 'op-1' });});- it('omits acceptsImages when the handle declares supportsSteerImages: false', async () => {- const { client, wait } = createClient([]);- const stream = createStream();-- const out = collect(- withHeteroSteer(- { events: stream.events, sendUserMessage: async () => true, supportsSteerImages: false },- { getTrpcClient: async () => client, operationId: 'op-1' },- ),- );- await vi.waitFor(() => expect(wait).toHaveBeenCalled());- stream.end();- await out;-- expect(wait.mock.calls[0][0]).not.toHaveProperty('acceptsImages');- });-it('gives a refused message back and stops polling', async () => {const { client, giveBack, wait } = createClient([{ content: 'hi', messageId: 'msg-1' }]);const stream = createStream();diff --git a/apps/cli/src/utils/heteroSteer.ts b/apps/cli/src/utils/heteroSteer.tsindex 40f20fecb57..1d361af45e1 100644--- a/apps/cli/src/utils/heteroSteer.ts+++ b/apps/cli/src/utils/heteroSteer.ts@@ -94,7 +94,6 @@ interface SteerableHandle {sendUserMessage?: (prompt: AgentPromptInput, options?: { uuid?: string }) => Promise<boolean>;setCollaborationMode?: (mode: CodexCollaborationMode) => Promise<void>;supportsSteerImageAttachments?: true;- supportsSteerImages?: boolean;}const RETRY_MS = 2000;@@ -117,14 +116,15 @@ const isMainStreamStart = (event: { data?: any; type: string }) =>event.type === 'stream_start' && !event.data?.subagent;/**- * Stream a Claude Code or native Codex run's events while typing the+ * Stream a Claude Code, native Codex or Antigravity run's events while typing the* follow-ups the user queues behind it into the live session (steer), instead* of leaving them for the next turn.** Polls `aiAgent.waitHeteroSteer` for as long as the run streams and its* session takes input; a message the session refuses goes back with* `aiAgent.returnHeteroSteer`. The agent reports every message it picks up- * (Claude Code replays it, Codex echoes its client id):+ * (Claude Code replays it, Codex echoes its client id, Antigravity ends the+ * prompt it interrupts):* the replay of a delivery is forwarded for the server to write the message* into the conversation; any other replay (the run's own prompt) is dropped.* Once the server answered, the next main `stream_start` carries `liveSteer`@@ -217,7 +217,7 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(...(acceptsControl && { acceptsControl: true }),...(handle.supportsSteerImageAttachments && { acceptsImageAttachments: true }),// The session takes image blocks, so pasted images come along.- ...(handle.supportsSteerImages !== false && { acceptsImages: true }),+ acceptsImages: true,// The first poll answers at once, so the run is marked steerable early....(!answered && { blockMs: 1 }),...(waitingForUser() && { holdSteer: true }),diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 274ec66ea3d..a7c2f0da58c 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -482,6 +482,10 @@ export default class HeterogeneousAgentCtr {dispatchCodexPrompt(this.codexAppServerHost(), params, session, {appServerEnabled: !!(session.useCodexAppServer || this.isCodexAppServerLabEnabled),}),+ 'antigravity': async (params, session) => {+ await this.sendPromptWithAcp(params, session);+ return true;+ },'copilot': async (params, session) => {await this.sendPromptWithAcp(params, session);return true;@@ -2310,16 +2314,11 @@ export default class HeterogeneousAgentCtr {reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));});- // In stdin mode, write the prepared payload; close stdin unless live (Claude Code / Antigravity).+ // In stdin mode, write the prepared payload; close stdin unless live (Claude Code always is).if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);const live = !!spawnPlan.liveInput;- session.liveInput = writeCliPrompt(- proc.stdin as Writable,- spawnPlan.stdinPayload,- live,- session.agentType,- );+ session.liveInput = writeCliPrompt(proc.stdin as Writable, spawnPlan.stdinPayload, live);}session.process = proc;@@ -2343,7 +2342,7 @@ export default class HeterogeneousAgentCtr {// file-change diff/stat tracker when `agentType === 'codex'`, so this// controller stays agent-agnostic.const pipeline = new AgentStreamPipeline({- ...(session.liveInput && { adapter: createLiveCliAdapter(session.liveInput) }),+ ...(session.liveInput && { adapter: createLiveCliAdapter() }),agentType: session.agentType,cwd,env: spawnEnv,diff --git a/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.tsindex 8c789e4bec3..f3651e3f534 100644--- a/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts@@ -1,9 +1,6 @@-import { mkdtemp, readFile, rm } from 'node:fs/promises';-import { tmpdir } from 'node:os';-import path from 'node:path';import { PassThrough } from 'node:stream';-import { AntigravityLiveInput, ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';+import { ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';import { describe, expect, it, vi } from 'vitest';import { endLiveCliRun, writeCliPrompt } from '../heterogeneousAgentLiveInput';@@ -78,43 +75,44 @@ describe('steerAgentSession', () => {);});- it('steers a live Antigravity CLI with text and image attachments', async () => {- const stdin = new PassThrough();- const written = readLines(stdin);- const liveInput = new AntigravityLiveInput(stdin);- const agy = session({ agentType: 'antigravity', command: 'agy', liveInput });-- await expect(steerAgentSession(agy, params, '/tmp')).resolves.toEqual({- status: 'accepted',+ it('steers a running Antigravity ACP session with text and image blocks', async () => {+ const steer = vi.fn(() => true);+ const agy = session({+ agentType: 'antigravity',+ antigravityAcpSession: { steer } as unknown as AgentSession['antigravityAcpSession'],+ command: 'agy',});- await new Promise((resolve) => setImmediate(resolve));+ const image = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ';- expect(written[0]).toEqual({- event: 'user',- message: { content: expect.stringContaining('also run the tests') },- });- expect(liveInput.takeSteerUuid()).toBe('steer-1');+ await expect(+ steerAgentSession(+ agy,+ { ...params, imageList: [{ id: 'img-1', url: `data:image/png;base64,${image}` }] },+ '/tmp',+ ),+ ).resolves.toEqual({ status: 'accepted' });- const cacheDir = await mkdtemp(path.join(tmpdir(), 'agy-desktop-steer-test-'));- const image = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ';- try {- await expect(- steerAgentSession(- agy,- {- ...params,- imageList: [{ id: 'img-1', url: `data:image/png;base64,${image}` }],- messageId: 'steer-image',- },- cacheDir,- ),- ).resolves.toEqual({ status: 'accepted' });- const filePath = JSON.parse(written[1].message.content.match(/^- (".+")$/m)![1]);- expect(await readFile(filePath)).toEqual(Buffer.from(image, 'base64'));- expect(liveInput.takeSteerUuid()).toBe('steer-image');- } finally {- await rm(cacheDir, { force: true, recursive: true });- }+ expect(steer).toHaveBeenCalledWith(+ [+ { text: expect.stringContaining('also run the tests'), type: 'text' },+ { data: image, mimeType: 'image/png', type: 'image' },+ ],+ 'steer-1',+ );+ });++ it('refuses an Antigravity steer the session cannot take, so it runs as the next turn', async () => {+ const steer = vi.fn(() => false);+ const running = session({+ agentType: 'antigravity',+ antigravityAcpSession: { steer } as unknown as AgentSession['antigravityAcpSession'],+ });+ await expect(steerAgentSession(running, params, '/tmp')).resolves.toEqual({+ status: 'rejected',+ });+ await expect(+ steerAgentSession(session({ agentType: 'antigravity' }), params, '/tmp'),+ ).resolves.toEqual({ status: 'rejected' });});it('steers a Pi run', async () => {diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts b/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.tsindex 5c412d532de..1622e501087 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts@@ -1,36 +1,29 @@import type { Writable } from 'node:stream';-import {- AntigravityAdapter,- ClaudeCodeAdapter,- type HeterogeneousAgentType,-} from '@lobechat/heterogeneous-agents';+import { ClaudeCodeAdapter } from '@lobechat/heterogeneous-agents';import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';import {- AntigravityLiveInput,ClaudeCodeLiveInput,- resolveAntigravityLiveRuntimeEnd,resolveClaudeCodeLiveRuntimeEnd,} from '@lobechat/heterogeneous-agents/spawn';-export type LiveCliInput = AntigravityLiveInput | ClaudeCodeLiveInput;+export type LiveCliInput = ClaudeCodeLiveInput;/*- * Claude Code and Antigravity spawned on this machine keep their stdin open,- * like under `lh hetero exec`, so follow-up messages can be steered into the- * live session. The run ends once at process exit, by the rule shared with `lh`.+ * Claude Code spawned on this machine keeps its stdin open, like under+ * `lh hetero exec`, so follow-up messages can be steered into the live+ * session. The run ends once at process exit, by the rule shared with `lh`.*//*** Write the prompt to the CLI's stdin. With `live`, stdin stays open for as- * long as the session can still use input (`ClaudeCodeLiveInput` or- * `AntigravityLiveInput`); otherwise it is closed after the prompt.+ * long as the session can still use input (`ClaudeCodeLiveInput`); otherwise+ * it is closed after the prompt.*/export const writeCliPrompt = (stdin: Writable,payload: string,live: boolean,- agentType: HeterogeneousAgentType | string = 'claude-code',): LiveCliInput | undefined => {if (!live) {stdin.write(payload, () => {@@ -39,8 +32,7 @@ export const writeCliPrompt = (return;}- const input =- agentType === 'antigravity' ? new AntigravityLiveInput(stdin) : new ClaudeCodeLiveInput(stdin);+ const input = new ClaudeCodeLiveInput(stdin);input.send(payload);return input;};@@ -50,19 +42,11 @@ export const writeCliPrompt = (* background task's completion wakes, or the one answering a steer), so the* runtime ends once, at process exit.*/-export const createLiveCliAdapter = (liveInput?: LiveCliInput) => {- if (liveInput instanceof AntigravityLiveInput) {- return new AntigravityAdapter({- runtimeEndStrategy: 'on-transport-close',- takeNextSteerUuid: () => liveInput.takeSteerUuid(),- });- }-- return new ClaudeCodeAdapter({+export const createLiveCliAdapter = () =>+ new ClaudeCodeAdapter({runtimeEndStrategy: 'on-transport-close',signalBackgroundTaskCompletion: true,});-};/*** The runtime end a live session reports at a process exit the host did not@@ -74,9 +58,6 @@ export const endLiveCliRun = (input: LiveCliInput | undefined,exit: { code: number | null; sawError: boolean; signal: NodeJS.Signals | null },): AgentStreamEvent[] => {- const end =- input instanceof AntigravityLiveInput- ? resolveAntigravityLiveRuntimeEnd(input.lastTurn, { ...exit, killedByHost: false })- : resolveClaudeCodeLiveRuntimeEnd(input?.lastTurn, { ...exit, killedByHost: false });+ const end = resolveClaudeCodeLiveRuntimeEnd(input?.lastTurn, { ...exit, killedByHost: false });return end ? pipeline.completeRuntime(end) : [];};diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts b/apps/desktop/src/main/controllers/heterogeneousAgentPermission.tsindex eed7062fa68..0740f1f4678 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts@@ -9,7 +9,6 @@ import {} from '@lobechat/heterogeneous-agents/claudeCodePermission';import type {AgentStreamEvent,- AntigravityLiveInput,ClaudeAgentSdkSession,ClaudeCodeLiveInput,} from '@lobechat/heterogeneous-agents/spawn';@@ -38,11 +37,10 @@ export const attachCliPermissionPrompts = ({}: {bridge: AskUserBridge;emit: (event: AgentStreamEvent) => void;- live: AntigravityLiveInput | ClaudeCodeLiveInput;+ live: ClaudeCodeLiveInput;operationId: string;permissionMode: HeteroPermissionMode;}): void => {- if (!('sendControlRequest' in live)) return;const isRoot = isRunningAsRoot();attachClaudeCodePermissionResponder(live, {ask: askThroughBridge(bridge),@@ -68,7 +66,7 @@ export const attachCliPermissionPrompts = ({/** The parts of a local run a control request reaches: the SDK query, or the CLI stdin. */interface ControllableSession {- liveInput?: AntigravityLiveInput | ClaudeCodeLiveInput;+ liveInput?: ClaudeCodeLiveInput;sdkSession?: ClaudeAgentSdkSession;}@@ -83,8 +81,7 @@ export const setSessionPermissionMode = async (): Promise<HeteroPermissionMode> => {if (session?.sdkSession) return session.sdkSession.setPermissionMode(mode);const live = session?.liveInput;- if (!live || !('sendControlRequest' in live))- throw new Error('This run cannot switch its permission mode');+ if (!live) throw new Error('This run cannot switch its permission mode');return setClaudeCodePermissionMode((request) => live.sendControlRequest(request), mode, {isRoot: isRunningAsRoot(),});@@ -100,7 +97,6 @@ export const stopSessionBackgroundTask = async (): Promise<void> => {if (session?.sdkSession) return session.sdkSession.stopTask(taskId);const live = session?.liveInput;- if (!live || !('sendControlRequest' in live))- throw new Error('This run cannot stop a single background task');+ if (!live) throw new Error('This run cannot stop a single background task');await stopClaudeCodeTask((request) => live.sendControlRequest(request), taskId);};diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex 8177acf3e83..7399b9da698 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -7,7 +7,6 @@ import type { AskUserBridge, AskUserBridgeOptions } from '@lobechat/heterogeneouimport { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocol';import type { PiRpcSession } from '@lobechat/heterogeneous-agents/rpc';import type {- AntigravityLiveInput,ClaudeAgentSdkSession,ClaudeCodeLiveInput,CodexThreadSession,@@ -15,6 +14,9 @@ import type {} from '@lobechat/heterogeneous-agents/spawn';import {AcpRpcResponseError,+ AntigravityAcpSession,+ buildAntigravityAcpLaunch,+ buildAntigravityAcpPrompt,buildCopilotAcpArgs,buildCopilotAcpPrompt,buildCursorAcpArgs,@@ -32,6 +34,7 @@ import {DevinAcpSession,DroidAcpSession,GrokAcpSession,+ isAntigravityAcpSessionNotFoundError,isCopilotAcpSessionNotFoundError,isCursorAcpSessionNotFoundError,isDevinAcpSessionNotFoundError,@@ -134,6 +137,8 @@ export interface SendPromptParams {export interface AgentSession {agentSessionId?: string;agentType: HeterogeneousAgentType;+ /** Active Antigravity ACP run; follow-ups are steered into it. */+ antigravityAcpSession?: AntigravityAcpSession;appServerSession?: CodexThreadSession;args: string[];/**@@ -157,8 +162,8 @@ export interface AgentSession {env?: Record<string, string>;grokAcpSession?: GrokAcpSession;hostedProviderBinding?: HostedProviderBinding;- /** Open input of a live CLI run (Claude Code or Antigravity). */- liveInput?: AntigravityLiveInput | ClaudeCodeLiveInput;+ /** Open input of a live CLI run (Claude Code). */+ liveInput?: ClaudeCodeLiveInput;model?: string;modelSource?: string;modelVerificationLastAttemptAt?: number;@@ -228,6 +233,20 @@ export const getAcpResumeError = (): HeterogeneousAgentSessionError | undefined => {if (!session.resumeSessionId) return;+ if (session.agentType === 'antigravity' && isAntigravityAcpSessionNotFoundError(error)) {+ return {+ agentType: 'antigravity',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ command: session.command,+ details: { code: error.rpcError.code, message: error.rpcError.message },+ message:+ 'The saved Antigravity conversation could not be found, so a new conversation will start.',+ resumeSessionId: session.resumeSessionId,+ stderr: error.message,+ workingDirectory: session.cwd,+ };+ }+if (session.agentType === 'copilot' && isCopilotAcpSessionNotFoundError(error)) {return {agentType: 'copilot',@@ -319,6 +338,10 @@ export const getAcpResumeError = (};export const interruptActiveAcpSession = async (session: AgentSession): Promise<boolean> => {+ if (session.antigravityAcpSession) {+ session.antigravityAcpSession.interrupt();+ return true;+ }if (session.copilotAcpSession) {session.copilotAcpSession.interrupt();return true;@@ -348,6 +371,7 @@ export const interruptActiveAcpSession = async (session: AgentSession): Promise<export const closeActiveAcpSessions = (session: AgentSession): void => {for (const active of [+ session.antigravityAcpSession,session.copilotAcpSession,session.devinAcpSession,session.grokAcpSession,@@ -426,6 +450,7 @@ const runInteractiveAcpSession = async (}: {acpSession: InteractiveAcpSession;activeSessionKey:+ | 'antigravityAcpSession'| 'copilotAcpSession'| 'cursorAcpSession'| 'devinAcpSession'@@ -436,7 +461,8 @@ const runInteractiveAcpSession = async (session: AgentSession;stderrChunks: string[];traceSession: CliTraceSession | undefined;- transport: 'copilot-acp' | 'cursor-acp' | 'devin-acp' | 'droid-acp' | 'trae-acp';+ transport:+ 'antigravity-acp' | 'copilot-acp' | 'cursor-acp' | 'devin-acp' | 'droid-acp' | 'trae-acp';},): Promise<void> => {try {@@ -475,7 +501,15 @@ const runInteractiveAcpSession = async (});} finally {await cleanup?.();- if (activeSessionKey === 'copilotAcpSession' && session.copilotAcpSession === acpSession) {+ if (+ activeSessionKey === 'antigravityAcpSession' &&+ session.antigravityAcpSession === acpSession+ ) {+ session.antigravityAcpSession = undefined;+ } else if (+ activeSessionKey === 'copilotAcpSession' &&+ session.copilotAcpSession === acpSession+ ) {session.copilotAcpSession = undefined;} else if (activeSessionKey === 'cursorAcpSession' && session.cursorAcpSession === acpSession) {session.cursorAcpSession = undefined;@@ -625,6 +659,42 @@ export const sendPromptWithAcpSession = async (sessionId: session.sessionId,});+ if (session.agentType === 'antigravity') {+ const prompt = await buildAntigravityAcpPrompt(promptInput, { cacheDir: host.fileCacheDir });+ const tracePayload = `${JSON.stringify(prompt)}\n`;+ const traceSession = await host.createCliTraceSession({+ cliArgs: buildAntigravityAcpLaunch(session.args).args,+ cwd,+ imageList: params.imageList ?? [],+ session,+ stdinPayload: tracePayload,+ });+ void host.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);+ if (session.cancelledByUs) {+ await host.completeCancelledSessionBeforeLaunch(session);+ return;+ }+ const antigravityAcpSession = new AntigravityAcpSession({+ ...createCommonOptions(traceSession),+ onModel: (model) => {+ session.model = model;+ session.modelSource = 'antigravity-acp';+ },+ prompt,+ });+ session.antigravityAcpSession = antigravityAcpSession;+ await runInteractiveAcpSession(host, {+ acpSession: antigravityAcpSession,+ activeSessionKey: 'antigravityAcpSession',+ isResumeError: isAntigravityAcpSessionNotFoundError,+ session,+ stderrChunks,+ traceSession,+ transport: 'antigravity-acp',+ });+ return;+ }+if (session.agentType === 'cursor') {const prompt = buildCursorAcpPrompt(promptInput);const tracePayload = `${JSON.stringify(prompt)}\n`;diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSteer.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSteer.tsindex bbfb6c8deba..6d8cfade77f 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSteer.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSteer.ts@@ -2,6 +2,7 @@ import { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocoimport { toPiRpcPrompt } from '@lobechat/heterogeneous-agents/rpc';import {buildAgentInput,+ buildAntigravityAcpPrompt,buildClaudeSdkUserMessageFromStreamJson,buildCodexAppServerInput,} from '@lobechat/heterogeneous-agents/spawn';@@ -50,8 +51,9 @@ const unsupported: SteerSessionResult = { status: 'unsupported' };* Deliver a user message into a session's running turn β the native steer of* each runtime: Claude Code (SDK input stream, or a live CLI's stdin, read at* its next tool boundary β never `priority: 'now'`, which aborts the running- * tool), Codex app-server `turn/steer`, Pi `steer`. Runtimes with- * no such channel (ACP agents, one-shot CLIs) answer `unsupported`.+ * tool), Codex app-server `turn/steer`, Pi `steer`, Antigravity another ACP+ * `session/prompt`. Runtimes with no such channel (other ACP agents, one-shot+ * CLIs) answer `unsupported`.** A failure while writing is thrown: the caller cannot tell whether the agent* got the message, so it must not send it again on its own.@@ -83,11 +85,10 @@ export const steerAgentSession = async (}if (session.agentType === 'antigravity') {- const live = session.liveInput;- if (!live) return session.process ? unsupported : rejected;- if (!live.isOpen) return rejected;- const plan = await buildAgentInput('antigravity', promptInput, { cacheDir });- return live.send(plan.stdin, params.messageId) ? accepted : rejected;+ const acp = session.antigravityAcpSession;+ if (!acp) return rejected;+ const prompt = await buildAntigravityAcpPrompt(promptInput, { cacheDir });+ return acp.steer(prompt, params.messageId) ? accepted : rejected;}if (session.appServerSession) {diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.test.tsindex 1762d87707d..f1fad4e0249 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.test.ts@@ -1,35 +1,13 @@-import { buildAgentInput } from '@lobechat/heterogeneous-agents/spawn';import { describe, expect, it } from 'vitest';import { getHeterogeneousAgentDriver } from '../index';import { antigravityDriver } from './antigravity';describe('antigravityDriver', () => {- it('registers the native driver and resumes using text on stdin', async () => {+ it('is registered and routes prompts through the native ACP session', async () => {expect(getHeterogeneousAgentDriver('antigravity')).toBe(antigravityDriver);- const plan = await antigravityDriver.buildSpawnPlan({- args: ['--effort', 'high'],- helpers: { buildAgentInput },- promptInput: 'hello\nworld',- resumeSessionId: 'conv-1',- });- expect(plan.args).toEqual([- '--input-format',- 'stream-json',- '--output-format',- 'stream-json',- '--dangerously-skip-permissions',- '--settings',- '{"agentMode":"","allowNonWorkspaceAccess":true,"enableTerminalSandbox":false}',- '--conversation',- 'conv-1',- '--effort',- 'high',- ]);- expect(plan.liveInput).toBe(true);- expect(JSON.parse(plan.stdinPayload!)).toEqual({- event: 'user',- message: { content: 'hello\nworld' },- });+ await expect(antigravityDriver.buildSpawnPlan({} as never)).rejects.toThrow(+ 'native ACP session',+ );});});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.tsindex a8f7ba5f9a3..b3c27ebff22 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.ts@@ -1,14 +1,7 @@-import { buildAntigravityArgs } from '@lobechat/heterogeneous-agents/spawn';-import type { HeterogeneousAgentDriver } from '../types';export const antigravityDriver: HeterogeneousAgentDriver = {- async buildSpawnPlan({ args, helpers, promptInput, resumeSessionId }) {- const input = await helpers.buildAgentInput('antigravity', promptInput);- return {- args: buildAntigravityArgs({ extraArgs: args, resumeSessionId }),- liveInput: true,- stdinPayload: input.stdin,- };+ async buildSpawnPlan() {+ throw new Error('Antigravity prompts must run through the native ACP session');},};diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/antigravityToolPersistence.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/antigravityToolPersistence.test.tsindex ab6c5d7d629..aa4bc6a9ecb 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/antigravityToolPersistence.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/antigravityToolPersistence.test.ts@@ -8,15 +8,24 @@ const operationId = 'op-antigravity-test';const topicId = 'topic-antigravity-test';const assistantMessageId = 'assistant-antigravity-test';-const toolUpdate = (index: number, state: 'ACTIVE' | 'DONE', info: Record<string, unknown>) => ({- event: 'step_update',- step_update: {- conversation_id: 'conversation-test',- state,- step_index: index,- step_type: 'tool',- tool_info: { name: 'run_command', ...info },- },+/** `agy acp` session updates, shaped as recorded from agy 1.5.15. */+const toolCall = (toolCallId: string, CommandLine: string) => ({+ args: { CommandLine },+ kind: 'execute',+ name: 'run_command',+ rawInput: { CommandLine },+ sessionUpdate: 'tool_call',+ status: 'in_progress',+ title: CommandLine,+ toolCallId,+});++const toolDone = (toolCallId: string, output: string, status = 'completed') => ({+ content: [{ content: { text: output, type: 'text' }, type: 'content' }],+ name: 'run_command',+ sessionUpdate: 'tool_call_update',+ status,+ toolCallId,});const createReplay = async () => {@@ -31,7 +40,7 @@ const createReplay = async () => {});};const ingestRaw = async (raw: unknown) => ingestEvents(adapter.adapt(raw));- await ingestRaw({ conversation_id: 'conversation-test', event: 'init' });+ await ingestRaw({ sessionId: 'agy-session', type: 'antigravity_session' });return {...harness,adapter,@@ -41,98 +50,66 @@ const createReplay = async () => {};};-describe('Antigravity adapter β coordinator β tool persistence', () => {+describe('Antigravity ACP adapter β coordinator β tool persistence', () => {beforeEach(() => __resetOperationStatesForTesting());afterEach(() => __resetOperationStatesForTesting());- it.each(['ACTIVE', 'DONE'] as const)(- 'persists parameters first supplied in a later %s update',- async (state) => {- const replay = await createReplay();- await replay.ingestRaw(toolUpdate(1, 'ACTIVE', {}));- await replay.ingestRaw(- toolUpdate(1, state, { output: 'hello', parameters: { CommandLine: 'echo hello' } }),- );- if (state === 'ACTIVE') {- await replay.ingestRaw(toolUpdate(1, 'DONE', { output: 'hello' }));- }+ it('persists a command with its arguments and output under the assistant', async () => {+ const replay = await createReplay();+ await replay.ingestRaw(toolCall('call-1', 'echo hello'));+ await replay.ingestRaw(toolDone('call-1', 'hello'));- expect(replay.tools()).toHaveLength(1);- const tool = await replay.messageModel.findById(replay.tools()[0].id);- expect(tool).toMatchObject({- content: 'hello',- parentId: assistantMessageId,- plugin: { arguments: '{"CommandLine":"echo hello"}' },- });- expect(replay.messages.get(assistantMessageId)?.tools).toMatchObject([- { arguments: '{"CommandLine":"echo hello"}', result_msg_id: tool!.id },- ]);- },- );+ expect(replay.tools()).toHaveLength(1);+ const tool = await replay.messageModel.findById(replay.tools()[0].id);+ expect(tool).toMatchObject({+ content: 'hello',+ parentId: assistantMessageId,+ plugin: { apiName: 'run_command', arguments: '{"CommandLine":"echo hello"}' },+ });+ expect(replay.messages.get(assistantMessageId)?.tools).toMatchObject([+ { arguments: '{"CommandLine":"echo hello"}', result_msg_id: tool!.id },+ ]);+ });- it('does not publish a parameterless pending tool in another tool batch', async () => {+ it('keeps parallel commands apart when they finish out of order', async () => {const replay = await createReplay();- await replay.ingestRaw(toolUpdate(1, 'ACTIVE', {}));- await replay.ingestRaw(- toolUpdate(2, 'DONE', { output: 'second', parameters: { CommandLine: 'echo second' } }),- );- expect(replay.tools().map((message) => message.plugin.arguments)).toEqual([- '{"CommandLine":"echo second"}',- ]);+ await replay.ingestRaw(toolCall('call-1', 'echo first'));+ await replay.ingestRaw(toolCall('call-2', 'echo second'));+ await replay.ingestRaw(toolDone('call-2', 'second'));+ await replay.ingestRaw(toolDone('call-1', 'first'));- await replay.ingestRaw(- toolUpdate(1, 'DONE', { output: 'first', parameters: { CommandLine: 'echo first' } }),- );- expect(replay.tools()).toHaveLength(2);- expect(replay.tools().find((message) => message.content === 'first')?.plugin.arguments).toBe(- '{"CommandLine":"echo first"}',- );+ expect(+ Object.fromEntries(+ replay.tools().map((message) => [message.plugin.arguments, message.content]),+ ),+ ).toEqual({+ '{"CommandLine":"echo first"}': 'first',+ '{"CommandLine":"echo second"}': 'second',+ });});- it.each([undefined, {}])(- 'persists completed tools with empty parameters (%j)',- async (parameters) => {- const replay = await createReplay();- await replay.ingestRaw(toolUpdate(1, 'DONE', { output: 'done', parameters }));- expect(replay.tools()).toHaveLength(1);- expect(replay.tools()[0]).toMatchObject({- content: 'done',- parentId: assistantMessageId,- plugin: { arguments: '{}' },- });- },- );+ it('marks a failed command as an error result', async () => {+ const replay = await createReplay();+ await replay.ingestRaw(toolCall('call-1', 'false'));+ await replay.ingestRaw(toolDone('call-1', 'exit 1', 'failed'));++ expect(replay.tools()).toHaveLength(1);+ expect(replay.tools()[0]).toMatchObject({ content: 'exit 1', parentId: assistantMessageId });+ });- it.each(['flush', 'ERROR', 'SUCCESS'] as const)(- 'materializes an unfinished tool before settling it on %s',- async (terminal) => {- const replay = await createReplay();- await replay.ingestRaw(toolUpdate(1, 'ACTIVE', {}));- if (terminal === 'flush') {- await replay.ingestEvents(replay.adapter.flush());- } else {- await replay.ingestRaw({- event: 'result',- result: {- conversation_id: 'conversation-test',- response: 'Finished.',- status: terminal,- },- });- }- await replay.ingestEvents(replay.adapter.flush());+ it('settles a command that was still running when the run was stopped', async () => {+ const replay = await createReplay();+ await replay.ingestRaw(toolCall('call-1', 'sleep 20'));+ await replay.ingestRaw({ stopReason: 'cancelled', type: 'antigravity_prompt_completed' });+ await replay.ingestEvents(replay.adapter.flush());- expect(replay.tools()).toHaveLength(1);- const tool = replay.tools()[0];- expect(tool).toMatchObject({- content: 'Antigravity ended before this tool returned a result.',- parentId: assistantMessageId,- plugin: { arguments: '{}' },- pluginError: { message: 'Antigravity ended before this tool returned a result.' },- });- expect(replay.messages.get(assistantMessageId)?.tools).toMatchObject([- { result_msg_id: tool.id },- ]);- },- );+ expect(replay.tools()).toHaveLength(1);+ expect(replay.tools()[0]).toMatchObject({+ parentId: assistantMessageId,+ plugin: { arguments: '{"CommandLine":"sleep 20"}' },+ });+ expect(replay.messages.get(assistantMessageId)?.tools).toMatchObject([+ { result_msg_id: replay.tools()[0].id },+ ]);+ });});diff --git a/packages/heterogeneous-agents/src/adapters/antigravity.test.ts b/packages/heterogeneous-agents/src/adapters/antigravity.test.tsdeleted file mode 100644index c06b912313f..00000000000--- a/packages/heterogeneous-agents/src/adapters/antigravity.test.ts+++ /dev/null@@ -1,377 +0,0 @@-import { describe, expect, it } from 'vitest';--import { createAdapter } from '../registry';-import type { HeterogeneousAgentEvent } from '../types';-import { AntigravityAdapter } from './antigravity';--const init = { conversation_id: 'conv-1', event: 'init', init: { model: 'gemini-test' } };-const step = (index: number, fields: Record<string, unknown> = {}) => ({- event: 'step_update',- step_update: {- conversation_id: 'conv-1',- state: 'DONE',- step_index: index,- step_type: 'agent_response',- ...fields,- },-});-const result = (fields: Record<string, unknown> = {}) => ({- event: 'result',- result: { conversation_id: 'conv-1', response: 'hello\n', status: 'SUCCESS', ...fields },-});-const text = (events: HeterogeneousAgentEvent[]) =>- events- .filter((e) => e.type === 'stream_chunk' && e.data.chunkType === 'text')- .map((e) => e.data.content)- .join('');-const tool = (index: number, fields: Record<string, unknown> = {}) =>- step(index, {- step_type: 'tool',- tool_info: {- name: 'run_command',- parameters: { CommandLine: 'echo hello' },- output: 'hello\n',- },- ...fields,- });--describe('AntigravityAdapter', () => {- it('registers native agy and captures its conversation/model', () => {- const adapter = createAdapter('antigravity');- expect(adapter).toBeInstanceOf(AntigravityAdapter);- expect(adapter.adapt(init)[0]).toMatchObject({- data: { model: 'gemini-test', provider: 'antigravity', sessionId: 'conv-1' },- type: 'stream_start',- });- expect(adapter.sessionId).toBe('conv-1');- });-- it('concatenates ACTIVE and DONE deltas without echoing result.response', () => {- const adapter = new AntigravityAdapter();- const events = [- init,- step(2, { state: 'ACTIVE', text_delta: 'hel' }),- step(2, { text_delta: 'lo\n' }),- result(),- ].flatMap((raw) => adapter.adapt(raw));- expect(text(events)).toBe('hello\n');- expect(events.filter((e) => e.type === 'stream_end')).toHaveLength(1);- expect(adapter.flush()).toEqual([]);- expect(adapter.validateCompletion()).toEqual([]);- });-- it('keeps repeated text fragments and ignores a duplicate DONE step', () => {- const adapter = new AntigravityAdapter();- const events = [- init,- step(2, { state: 'ACTIVE', text_delta: 'ha' }),- step(2, { text_delta: 'ha' }),- step(2, { text_delta: 'ha' }),- ].flatMap((raw) => adapter.adapt(raw));- expect(text(events)).toBe('haha');- });-- it('creates a completed-only tool before its result and starts the next assistant separately', () => {- const adapter = new AntigravityAdapter();- const events = [- init,- step(1, { text_delta: 'Checking.' }),- tool(3),- tool(4),- step(6, { text_delta: 'hello\n' }),- result(),- ].flatMap((raw) => adapter.adapt(raw));- const calls = events.filter(- (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',- );- expect(calls[1].data.toolsCalling).toHaveLength(2);- const toolResults = events.filter((e) => e.type === 'tool_result');- expect(toolResults.map((e) => e.data.toolCallId)).toEqual(['agy_conv-1_3', 'agy_conv-1_4']);- expect(toolResults.every((e) => e.stepIndex === 0)).toBe(true);- expect(events.indexOf(calls[0])).toBeLessThan(events.indexOf(toolResults[0]));- expect(events.filter((e) => e.type === 'stream_start')[1]).toMatchObject({- data: { newStep: true },- stepIndex: 1,- });- expect(text(events)).toBe('Checking.hello\n');- });-- it('starts each tool once with its final arguments so trace recorders keep the tool step', () => {- const adapter = new AntigravityAdapter();- // Clone like the IPC/stdout bridge, so later payload mutation cannot hide stale args.- const adapt = (raw: unknown) => structuredClone(adapter.adapt(raw));- const events: HeterogeneousAgentEvent[] = [- init,- tool(3, { state: 'ACTIVE', tool_info: { name: 'run_command' } }),- tool(3),- ].flatMap(adapt);- const calls = events.filter(- (e) => e.type === 'stream_chunk' && e.data.chunkType === 'tools_calling',- );- expect(calls).toHaveLength(1);- expect(calls[0].data.toolsCalling[0].arguments).toBe('{"CommandLine":"echo hello"}');- const starts = events.filter((e) => e.type === 'tool_start');- expect(starts).toHaveLength(1);- expect(events.indexOf(calls[0])).toBeLessThan(events.indexOf(starts[0]));- expect(starts[0].data).toEqual({- toolCallId: 'agy_conv-1_3',- toolCalling: {- apiName: 'run_command',- arguments: '{"CommandLine":"echo hello"}',- id: 'agy_conv-1_3',- identifier: 'antigravity',- type: 'default',- },- });- expect(events.indexOf(starts[0])).toBeLessThan(- events.findIndex((e) => e.type === 'tool_result'),- );- });-- it('publishes explicitly empty parameters without waiting for completion', () => {- const adapter = new AntigravityAdapter();- adapter.adapt(init);- const events = adapter.adapt(- tool(3, { state: 'ACTIVE', tool_info: { name: 'list_resources', parameters: {} } }),- );- expect(events.map((e) => e.type)).toEqual(['stream_chunk', 'tool_start']);- expect(events[0].data.toolsCalling[0].arguments).toBe('{}');- });-- it('matches a tool completion without a name to its existing step', () => {- const adapter = new AntigravityAdapter();- const events = [- init,- tool(3, {- state: 'ACTIVE',- tool_info: { name: 'view_file', parameters: { path: 'marker.txt' } },- }),- tool(3, { tool_info: { output: 'file contents' } }),- step(4, { text_delta: 'hello\n' }),- result(),- ].flatMap((raw) => adapter.adapt(raw));-- expect(events.filter((e) => e.type === 'tool_result').map((e) => e.data)).toEqual([- { content: 'file contents', isError: false, toolCallId: 'agy_conv-1_3' },- ]);- expect(text(events)).toBe('hello\n');- expect(events.filter((e) => e.type === 'error')).toEqual([]);- });-- it('reports a missing tool completion even when the turn succeeds', () => {- const adapter = new AntigravityAdapter();- const events = [- init,- tool(3, { state: 'ACTIVE' }),- step(4, { text_delta: 'hello\n' }),- result(),- ].flatMap((raw) => adapter.adapt(raw));-- expect(events.find((e) => e.type === 'tool_result')?.data).toMatchObject({- isError: true,- toolCallId: 'agy_conv-1_3',- });- expect(events.find((e) => e.type === 'error')?.data).toMatchObject({- code: 'incomplete_tool_result',- });- expect(text(events)).toBe('hello\n');- });-- it('starts an interrupted tool before settling it', () => {- const adapter = new AntigravityAdapter();- adapter.adapt(init);- adapter.adapt(tool(3, { state: 'ACTIVE', tool_info: { name: 'run_command' } }));- expect(adapter.flush().map((e) => e.type)).toEqual([- 'stream_chunk',- 'tool_start',- 'tool_result',- 'tool_end',- 'stream_end',- ]);- });-- it('updates a running tool with its final arguments and error exactly once', () => {- const adapter = new AntigravityAdapter();- adapter.adapt(init);- adapter.adapt(tool(3, { state: 'ACTIVE', tool_info: { name: 'write_to_file' } }));- const completed = tool(3, {- tool_info: {- name: 'write_to_file',- parameters: { path: 'test.txt' },- error: { type: 'DENIED', message: 'Permission denied' },- },- });- const events = adapter.adapt(completed);- expect(events[0].data.toolsCalling[0].arguments).toBe('{"path":"test.txt"}');- expect(events.find((e) => e.type === 'tool_result')?.data).toMatchObject({- content: 'Permission denied',- isError: true,- toolCallId: 'agy_conv-1_3',- });- expect(events.find((e) => e.type === 'tool_end')?.data.isSuccess).toBe(false);- expect(adapter.adapt(completed)).toEqual([]);- });-- it('settles unfinished tools on interruption and detects missing terminal results', () => {- const adapter = new AntigravityAdapter();- adapter.adapt(init);- adapter.adapt(tool(3, { state: 'ACTIVE' }));- expect(adapter.flush().find((e) => e.type === 'tool_result')?.data).toMatchObject({- isError: true,- toolCallId: 'agy_conv-1_3',- });- expect(adapter.validateCompletion()[0]).toMatchObject({- type: 'error',- data: { code: 'incomplete_response' },- });- expect(adapter.flush()).toEqual([]);- expect(adapter.validateCompletion()).toEqual([]);- });-- it('classifies missing login using the Antigravity sign-in guide', () => {- const adapter = new AntigravityAdapter();- expect(- adapter.adapt(result({ status: 'ERROR', error: 'authentication required', response: '' })),- ).toContainEqual(- expect.objectContaining({- type: 'error',- data: expect.objectContaining({- agentType: 'antigravity',- code: 'auth_required',- command: 'agy',- }),- }),- );- });-- it('preserves quota guidance when the terminal error also mentions authentication', () => {- const adapter = new AntigravityAdapter();- const detail = "Authentication required: You've hit your weekly limit. Resets tomorrow.";- expect(adapter.adapt(result({ status: 'ERROR', error: detail }))).toContainEqual(- expect.objectContaining({- type: 'error',- data: expect.objectContaining({- agentType: 'antigravity',- code: 'rate_limit',- details: { kind: 'usage_limit' },- message: detail,- rateLimitInfo: { rateLimitType: 'seven_day', status: 'rejected' },- }),- }),- );- });-- it.each(['ERROR', 'CANCELED', 'INTERRUPTED', 'INVALID', 'WAITING', 'RUNNING'])(- 'does not treat terminal %s as success',- (status) => {- const adapter = new AntigravityAdapter();- expect(adapter.adapt(result({ status })).some((e) => e.type === 'error')).toBe(true);- expect(adapter.validateCompletion()).toEqual([]);- },- );-- it('uses result-only text as a fallback, including after tool work', () => {- const adapter = new AntigravityAdapter();- const events = [init, step(1, { text_delta: 'Checking.' }), tool(3), result()].flatMap((raw) =>- adapter.adapt(raw),- );- expect(text(events)).toBe('Checking.hello\n');- expect(events.filter((e) => e.type === 'stream_start')[1].stepIndex).toBe(1);- });-- it('keeps resumed cumulative usage separate from this turn', () => {- const adapter = new AntigravityAdapter();- const events = [- init,- step(20, {- text_delta: 'hello\n',- usage: {- input_tokens: 278,- cache_read_tokens: 30214,- output_tokens: 4,- thinking_tokens: 1,- },- }),- result({ usage: { input_tokens: 30662, cache_read_tokens: 30214, output_tokens: 8 } }),- ].flatMap((raw) => adapter.adapt(raw));- const metadata = events.filter(- (e) => e.type === 'step_complete' && e.data.phase === 'turn_metadata',- );- expect(metadata).toHaveLength(1);- expect(metadata[0].data.usage).toMatchObject({- inputCacheMissTokens: 278,- totalInputTokens: 30492,- totalOutputTokens: 4,- outputReasoningTokens: 1,- });- // The cumulative result total must not reach recorders as the run total.- expect(events.some((e) => e.type === 'step_complete' && e.data.phase === 'result_usage')).toBe(- false,- );- });-- it('ignores malformed, unknown, and child-conversation events', () => {- const adapter = new AntigravityAdapter();- adapter.adapt(init);- for (const raw of [- null,- [],- {},- { event: 'future' },- step(-1),- step(1, { conversation_id: 'child', text_delta: 'hidden' }),- ]) {- expect(adapter.adapt(raw)).toEqual([]);- }- });-- it('adapts multi-turn liveInput streams and emits user_message replay for steered turns', () => {- const steerQueue = ['steer-uuid-1'];- const adapter = new AntigravityAdapter({- runtimeEndStrategy: 'on-transport-close',- takeNextSteerUuid: () => steerQueue.shift(),- });- const events = [- init,- step(0, { state: 'DONE', step_type: 'user_input' }),- step(1, { state: 'DONE', step_type: 'agent_response', text_delta: 'turn1' }),- result({ num_turns: 1, response: 'turn1' }),- step(2, { state: 'DONE', step_type: 'user_input' }),- step(3, { state: 'DONE', step_type: 'agent_response', text_delta: 'turn2' }),- result({ num_turns: 2, response: 'turn2' }),- ].flatMap((raw) => adapter.adapt(raw));-- expect(text(events)).toBe('turn1turn2');- const replays = events.filter(- (e) => e.type === 'step_complete' && e.data.phase === 'user_message',- );- expect(replays).toHaveLength(1);- expect(replays[0].data).toEqual({ phase: 'user_message', uuid: 'steer-uuid-1' });- expect(adapter.validateCompletion()).toEqual([]);- });-- it('reports incomplete_response when a steered live turn ends without a final result', () => {- const steerQueue = ['steer-uuid-1'];- const adapter = new AntigravityAdapter({- runtimeEndStrategy: 'on-transport-close',- takeNextSteerUuid: () => steerQueue.shift(),- });- for (const raw of [- init,- step(0, { state: 'DONE', step_type: 'user_input' }),- step(1, { state: 'DONE', step_type: 'agent_response', text_delta: 'turn1' }),- result({ num_turns: 1, response: 'turn1' }),- step(2, { state: 'DONE', step_type: 'user_input' }),- step(3, { state: 'ACTIVE', step_type: 'agent_response', text_delta: 'partial' }),- ]) {- adapter.adapt(raw);- }-- const validation = adapter.validateCompletion();- expect(validation).toHaveLength(1);- expect(validation[0]).toMatchObject({- data: { agentType: 'antigravity', code: 'incomplete_response' },- type: 'error',- });- });-});diff --git a/packages/heterogeneous-agents/src/adapters/antigravity.ts b/packages/heterogeneous-agents/src/adapters/antigravity.tsdeleted file mode 100644index d2f775bdec8..00000000000--- a/packages/heterogeneous-agents/src/adapters/antigravity.ts+++ /dev/null@@ -1,377 +0,0 @@-import { isRecord, pickString, toRecord, type UnknownRecord } from '@lobechat/utils/object';--import { classifyCliMessageError } from '../errors/classifyCliMessageError';-import type {- AgentEventAdapter,- HeterogeneousAgentEvent,- ToolCallPayload,- UsageData,-} from '../types';--const IDENTIFIER = 'antigravity';--interface PendingTool {- payload: ToolCallPayload;- started?: boolean;- stepIndex: number;-}--const tokenCount = (value: unknown): number =>- typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;--const extractUsage = (raw: unknown): UsageData | undefined => {- if (!isRecord(raw)) return;- const inputCacheMissTokens = tokenCount(raw.input_tokens);- const inputCachedTokens = tokenCount(raw.cache_read_tokens);- const totalOutputTokens = tokenCount(raw.output_tokens);- const outputReasoningTokens = Math.min(tokenCount(raw.thinking_tokens), totalOutputTokens);- // agy's input_tokens/total_tokens exclude cache reads (see the second turn- // in its headless stream-input example). Our totals include cached input.- const totalInputTokens = inputCacheMissTokens + inputCachedTokens;- return {- inputCachedTokens,- inputCacheMissTokens,- outputReasoningTokens,- outputTextTokens: totalOutputTokens - outputReasoningTokens,- totalInputTokens,- totalOutputTokens,- totalTokens: totalInputTokens + totalOutputTokens,- };-};--const stringifyOutput = (value: unknown): string =>- typeof value === 'string' ? value : value === undefined ? '' : JSON.stringify(value);--export interface AntigravityAdapterOptions {- /**- * When stdin stays open across turns (liveInput / steer), keep accepting- * subsequent turns after a `SUCCESS` `result` instead of closing the adapter- * on the first turn's result.- */- runtimeEndStrategy?: 'on-result' | 'on-transport-close';- /**- * Shift the next steered message UUID when `agy` starts a subsequent- * `user_input` step, so the adapter can emit `step_complete { phase: 'user_message', uuid }`.- */- takeNextSteerUuid?: () => string | undefined;-}--/**- * Native agy NDJSON protocol, not the Gemini/Claude stream-json protocol.- * https://antigravity.google/docs/cli/headless/- * Supports both one-shot turns and multi-turn liveInput steering while stdin remains open.- */-export class AntigravityAdapter implements AgentEventAdapter {- sessionId?: string;-- private completedSteps = new Set<number>();- private flushed = false;- private hasResponseText = false;- private latestTurnCompleted = false;- private model?: string;- private pendingTools = new Map<number, PendingTool>();- private resultReceived = false;- private completionValidated = false;- private responseStep?: number;- private readonly runtimeEndStrategy: 'on-result' | 'on-transport-close';- private seenInitialUserInput = false;- private seenUserInputSteps = new Set<number>();- private stepIndex = 0;- private stepTools: ToolCallPayload[] = [];- private streamOpen = false;- private readonly takeNextSteerUuid?: () => string | undefined;- private toolSinceResponse = false;- private usageByStep = new Map<number, UsageData>();-- constructor(options: AntigravityAdapterOptions = {}) {- this.runtimeEndStrategy = options.runtimeEndStrategy ?? 'on-result';- this.takeNextSteerUuid = options.takeNextSteerUuid;- }-- adapt(raw: unknown): HeterogeneousAgentEvent[] {- if (this.flushed || this.resultReceived || !isRecord(raw)) return [];- if (raw.event === 'init') {- this.latestTurnCompleted = false;- this.sessionId = pickString(raw.conversation_id);- this.model = pickString(toRecord(raw.init)?.model);- return this.openStream();- }- if (raw.event === 'result' && isRecord(raw.result)) return this.handleResult(raw.result);- if (raw.event !== 'step_update' || !isRecord(raw.step_update)) return [];-- const step = raw.step_update;- const index = step.step_index;- if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0) return [];- // Child conversations must never leak into the parent's assistant bubble.- const conversationId = pickString(step.conversation_id);- if (this.sessionId && conversationId && conversationId !== this.sessionId) return [];- this.sessionId ??= conversationId;- if (this.completedSteps.has(index)) return [];- this.latestTurnCompleted = false;-- const events: HeterogeneousAgentEvent[] = [];- if (step.step_type === 'user_input') {- if (!this.seenUserInputSteps.has(index)) {- this.seenUserInputSteps.add(index);- if (!this.seenInitialUserInput) {- this.seenInitialUserInput = true;- } else {- const uuid = this.takeNextSteerUuid?.();- if (uuid) {- events.push(...this.closeStream());- events.push(this.event('step_complete', { phase: 'user_message', uuid }));- }- }- }- } else if (step.step_type === 'agent_response') {- if (- this.toolSinceResponse ||- (this.responseStep !== undefined && this.responseStep !== index)- ) {- events.push(...this.closeStream());- this.stepIndex += 1;- this.stepTools = [];- this.hasResponseText = false;- }- events.push(...this.openStream());- this.toolSinceResponse = false;- this.responseStep = index;- if (typeof step.text_delta === 'string' && step.text_delta) {- this.hasResponseText = true;- events.push(this.event('stream_chunk', { chunkType: 'text', content: step.text_delta }));- }- } else if (step.step_type === 'tool' || isRecord(step.subagent_info)) {- events.push(...this.handleTool(index, step));- }-- if (step.state === 'DONE') {- this.completedSteps.add(index);- const usage = extractUsage(step.usage);- if (usage) this.usageByStep.set(index, usage);- }- return events;- }-- flush(): HeterogeneousAgentEvent[] {- if (this.flushed) return [];- this.flushed = true;- return [- ...this.settlePendingTools('Antigravity ended before this tool returned a result.'),- ...this.closeStream(),- ];- }-- validateCompletion(): HeterogeneousAgentEvent[] {- if (this.resultReceived || this.latestTurnCompleted || this.completionValidated) return [];- this.completionValidated = true;- return [- this.event('error', {- agentType: IDENTIFIER,- code: 'incomplete_response',- message: 'Antigravity exited without a final result. Update agy and retry.',- }),- ];- }-- private openStream(): HeterogeneousAgentEvent[] {- if (this.streamOpen) return [];- this.streamOpen = true;- return [- this.event('stream_start', {- model: this.model,- newStep: this.stepIndex > 0,- provider: IDENTIFIER,- sessionId: this.sessionId,- }),- ];- }-- private closeStream(): HeterogeneousAgentEvent[] {- const events: HeterogeneousAgentEvent[] = [];- if (this.usageByStep.size) {- const usage = [...this.usageByStep.values()].reduce((total, next) => ({- inputCachedTokens: (total.inputCachedTokens ?? 0) + (next.inputCachedTokens ?? 0),- inputCacheMissTokens: total.inputCacheMissTokens + next.inputCacheMissTokens,- outputReasoningTokens:- (total.outputReasoningTokens ?? 0) + (next.outputReasoningTokens ?? 0),- outputTextTokens: (total.outputTextTokens ?? 0) + (next.outputTextTokens ?? 0),- totalInputTokens: total.totalInputTokens + next.totalInputTokens,- totalOutputTokens: total.totalOutputTokens + next.totalOutputTokens,- totalTokens: total.totalTokens + next.totalTokens,- }));- events.push(- this.event('step_complete', {- model: this.model,- phase: 'turn_metadata',- provider: IDENTIFIER,- usage,- }),- );- this.usageByStep.clear();- }- if (this.streamOpen) {- events.push(this.event('stream_end', {}));- this.streamOpen = false;- }- return events;- }-- private handleTool(index: number, step: UnknownRecord): HeterogeneousAgentEvent[] {- const info = toRecord(step.tool_info);- const subagents = toRecord(step.subagent_info);- const name = pickString(info?.name) ?? pickString(step.tool_name);- let pending = this.pendingTools.get(index);- if (!pending && !name && !subagents) return [];- const events = this.openStream();- this.toolSinceResponse = true;- const args = JSON.stringify(info?.parameters ?? subagents ?? {});- if (!pending) {- const payload: ToolCallPayload = {- apiName: name ?? 'subagents',- arguments: args,- id: `agy_${this.sessionId ?? 'session'}_${index}`,- identifier: IDENTIFIER,- type: 'default',- };- pending = { payload, stepIndex: this.stepIndex };- this.pendingTools.set(index, pending);- } else if (info?.parameters !== undefined) {- pending.payload.arguments = args;- }- // Persistence snapshots tools_calling, while trace recorders snapshot tool_start.- // Neither may publish a name-only ACTIVE update with placeholder arguments.- if (info?.parameters !== undefined || step.state === 'DONE')- events.push(...this.startTool(pending));- if (step.state === 'DONE') {- const error = toRecord(info?.error);- const output = stringifyOutput(info?.output ?? subagents);- const errorText = pickString(error?.message) ?? stringifyOutput(info?.error);- const content = [output, errorText].filter(Boolean).join('\n');- events.push(...this.toolResult(pending, content, info?.error != null));- this.pendingTools.delete(index);- }- return events;- }-- private startTool(tool: PendingTool): HeterogeneousAgentEvent[] {- if (tool.started) return [];- tool.started = true;- this.stepTools.push(tool.payload);- return [- this.event(- 'stream_chunk',- {- chunkType: 'tools_calling',- toolsCalling: this.stepTools.map((payload) => ({ ...payload })),- },- tool.stepIndex,- ),- this.event(- 'tool_start',- { toolCalling: { ...tool.payload }, toolCallId: tool.payload.id },- tool.stepIndex,- ),- ];- }-- private toolResult(- tool: PendingTool,- content: string,- isError: boolean,- ): HeterogeneousAgentEvent[] {- return [- ...this.startTool(tool),- this.event('tool_result', { content, isError, toolCallId: tool.payload.id }, tool.stepIndex),- this.event(- 'tool_end',- {- isSuccess: !isError,- payload: { toolCalling: tool.payload },- result: { content, success: !isError },- toolCallId: tool.payload.id,- },- tool.stepIndex,- ),- ];- }-- private settlePendingTools(message: string): HeterogeneousAgentEvent[] {- const events = [...this.pendingTools.values()].flatMap((tool) =>- this.toolResult(tool, message, true),- );- this.pendingTools.clear();- return events;- }-- private handleResult(result: UnknownRecord): HeterogeneousAgentEvent[] {- const keepOpenForMoreTurns =- this.runtimeEndStrategy === 'on-transport-close' && result.status === 'SUCCESS';- if (!keepOpenForMoreTurns) this.resultReceived = true;- this.latestTurnCompleted = true;- this.sessionId ??= pickString(result.conversation_id);- const hasPendingTools = this.pendingTools.size > 0;- // Materialize unfinished tools in their owning turn before a fallback response opens a new one.- const events = this.settlePendingTools('Antigravity ended before this tool returned a result.');- if (result.status === 'SUCCESS') {- // result.response repeats the streamed answer. Use it only when no final- // response was streamed, never as another delta after agent_response.- if (- (!this.hasResponseText || this.toolSinceResponse) &&- typeof result.response === 'string' &&- result.response- ) {- if (this.toolSinceResponse) {- events.push(...this.closeStream());- this.stepIndex += 1;- }- events.push(- ...this.openStream(),- this.event('stream_chunk', { chunkType: 'text', content: result.response }),- );- }- if (hasPendingTools) {- events.push(- this.event('error', {- agentType: IDENTIFIER,- code: 'incomplete_tool_result',- message: 'Antigravity completed without returning all tool results.',- }),- );- }- } else {- const detail =- pickString(result.error) ||- `Antigravity ended with status ${String(result.status ?? 'unknown')}.`;- events.push(- this.event(- 'error',- classifyCliMessageError({ agentType: IDENTIFIER, detail }) ?? {- agentType: IDENTIFIER,- code: 'antigravity_run_error',- message: detail,- },- ),- );- }- events.push(...this.closeStream());- if (keepOpenForMoreTurns) {- this.hasResponseText = false;- this.responseStep = undefined;- this.toolSinceResponse = false;- this.stepTools = [];- this.stepIndex += 1;- }- // Result counters are cumulative across a resumed conversation, so they are- // not emitted as `result_usage`: trace recorders treat that phase as the- // run total. Step_update usage (turn_metadata) is the only per-run source.- return events;- }-- private event(- type: HeterogeneousAgentEvent['type'],- data: unknown,- stepIndex = this.stepIndex,- ): HeterogeneousAgentEvent {- return { data, stepIndex, timestamp: Date.now(), type };- }-}diff --git a/packages/heterogeneous-agents/src/adapters/antigravityAcp.ts b/packages/heterogeneous-agents/src/adapters/antigravityAcp.tsnew file mode 100644index 00000000000..4b6151acf31--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/antigravityAcp.ts@@ -0,0 +1,69 @@+import { isRecord } from '@lobechat/utils/object';++import { classifyCliMessageError } from '../errors/classifyCliMessageError';+import type { HeterogeneousAgentEvent, UsageData } from '../types';+import { TraeAcpAdapter } from './traeAcp';++const IDENTIFIER = 'antigravity';++const tokenCount = (value: unknown): number =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;++/**+ * `agy acp` reports `inputTokens` without cache reads (`totalTokens` is input+ * + cached reads + output), unlike the ACP usage shape the base adapter+ * assumes. Our totals include cached input.+ */+const toAntigravityUsage = (raw: unknown): UsageData | undefined => {+ if (!isRecord(raw)) return;+ const inputCacheMissTokens = tokenCount(raw.inputTokens);+ const inputCachedTokens = tokenCount(raw.cachedReadTokens);+ const totalOutputTokens = tokenCount(raw.outputTokens);+ if (!inputCacheMissTokens && !inputCachedTokens && !totalOutputTokens) return;+ const outputReasoningTokens = Math.min(tokenCount(raw.thoughtTokens), totalOutputTokens);+ const totalInputTokens = inputCacheMissTokens + inputCachedTokens;+ return {+ inputCachedTokens: inputCachedTokens || undefined,+ inputCacheMissTokens,+ outputReasoningTokens: outputReasoningTokens || undefined,+ outputTextTokens: totalOutputTokens - outputReasoningTokens,+ totalInputTokens,+ totalOutputTokens,+ totalTokens: totalInputTokens + totalOutputTokens,+ };+};++/**+ * Maps `agy acp` session updates (the standard ACP vocabulary) into the shared+ * event contract, plus the steer delivery the session reports as+ * `antigravity_user_message` once agy took a message into the running turn.+ */+export class AntigravityAcpAdapter extends TraeAcpAdapter {+ constructor() {+ super({ eventPrefix: IDENTIFIER, provider: IDENTIFIER });+ }++ override adapt(value: unknown): HeterogeneousAgentEvent[] {+ if (!isRecord(value)) return [];+ if (value.type === `${IDENTIFIER}_user_message`) {+ if (typeof value.uuid !== 'string' || !value.uuid) return [];+ // What the model does next answers the message, in a step of its own.+ this.stream.pendingStepBoundary = true;+ return [this.stream.event('step_complete', { phase: 'user_message', uuid: value.uuid })];+ }+ const events = super.adapt(value);+ if (value.type !== `${IDENTIFIER}_error`) return events;+ // Sign-in and quota failures carry the status guide the UI renders for them.+ const classified = classifyCliMessageError({+ agentType: IDENTIFIER,+ detail: typeof value.message === 'string' ? value.message : undefined,+ });+ return classified+ ? events.map((event) => (event.type === 'error' ? { ...event, data: classified } : event))+ : events;+ }++ protected override toUsageData(usage: unknown): UsageData | undefined {+ return toAntigravityUsage(usage);+ }+}diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.tsindex 01f573f9710..7471b205d1a 100644--- a/packages/heterogeneous-agents/src/adapters/index.ts+++ b/packages/heterogeneous-agents/src/adapters/index.ts@@ -1,5 +1,5 @@export { AmpAdapter } from './amp';-export { AntigravityAdapter, type AntigravityAdapterOptions } from './antigravity';+export { AntigravityAcpAdapter } from './antigravityAcp';export { ClaudeCodeAdapter } from './claudeCode';export { ClaudeCodeSdkAdapter } from './claudeCodeSdk';export { CodeBuddyAdapter } from './codeBuddy';diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex 1d004a051ec..34669ed2748 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -1,7 +1,6 @@export {AmpAdapter,- AntigravityAdapter,- type AntigravityAdapterOptions,+ AntigravityAcpAdapter,ClaudeCodeAdapter,CodeBuddyAdapter,CopilotAcpAdapter,diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.tsindex 29899de650b..be173c40f19 100644--- a/packages/heterogeneous-agents/src/registry.ts+++ b/packages/heterogeneous-agents/src/registry.ts@@ -7,7 +7,7 @@import {AmpAdapter,- AntigravityAdapter,+ AntigravityAcpAdapter,ClaudeCodeAdapter,ClaudeCodeSdkAdapter,CodeBuddyAdapter,@@ -34,7 +34,7 @@ interface AgentRegistryEntry {const localAgentRegistry = {'antigravity': {- createAdapter: () => new AntigravityAdapter(),+ createAdapter: () => new AntigravityAcpAdapter(),},'amp': {createAdapter: () => new AmpAdapter(),diff --git a/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts b/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.tsindex 89a34d04022..7191fc2d17d 100644--- a/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts@@ -4,18 +4,20 @@ import { PassThrough } from 'node:stream';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { resolveHeterogeneousAgentCommand } from '../config';+import { AntigravityAcpSession, buildAntigravityAcpPrompt } from './antigravityAcpSession';import { isPathLikeCommand } from './cliSpawn';import { buildCopilotAcpPrompt, CopilotAcpSession } from './copilotAcpSession';import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';import { buildDevinAcpPrompt, DevinAcpSession } from './devinAcpSession';import { buildDroidAcpPrompt, DroidAcpSession } from './droidAcpSession';import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';+import { getHeterogeneousAgentSpawnEnv } from './presetEnv';import type { SpawnAgentHandle, SpawnAgentOptions } from './spawnAgent';import { buildTraeAcpPrompt, TraeAcpSession } from './traeAcpSession';import { assertSpawnableWorkingDirectory } from './workingDirectory';/**- * ACP runtimes (Cursor, Devin, Droid, Grok, TRAE) behind the ordinary+ * ACP runtimes (Antigravity, Cursor, Devin, Droid, Grok, TRAE) behind the ordinary* `SpawnAgentHandle` contract returned by `spawnAgent`.*/@@ -140,10 +142,12 @@ const createAcpSpawnHandle = (bridge: ReturnType<typeof createAcpSpawnBridge>,session: AcpSpawnSession,getSessionId: () => string | undefined = () => session.sessionId,+ extra: Pick<SpawnAgentHandle, 'sendUserMessage' | 'supportsSteerImageAttachments'> = {},): SpawnAgentHandle => {const { exit, interrupt, kill } = bridge.attach(session);return {+ ...extra,events: bridge.events,exit,interrupt,@@ -158,6 +162,45 @@ const createAcpSpawnHandle = (};};+/**+ * Antigravity (`agy acp`): the handle also takes follow-ups mid-run+ * (`sendUserMessage`), which the session steers into the running turn.+ */+export const spawnAntigravityAcpAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+): Promise<SpawnAgentHandle> => {+ const prompt = await buildAntigravityAcpPrompt(options.prompt, options.inputOptions);+ const bridge = createAcpSpawnBridge();+ const session = new AntigravityAcpSession({+ args: options.extraArgs ?? [],+ clientVersion: 'lobehub-cli',+ commandPath: command,+ cwd,+ detached: options.detached,+ env: getHeterogeneousAgentSpawnEnv('antigravity', options.env, process.env),+ onEvents: bridge.onEvents,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ return createAcpSpawnHandle(bridge, session, undefined, {+ sendUserMessage: async (followUp, sendOptions) => {+ if (!sendOptions?.uuid) return false;+ const blocks = await buildAntigravityAcpPrompt(followUp, options.inputOptions);+ return session.steer(blocks, sendOptions.uuid);+ },+ // Uploaded images go in as image blocks of the steered prompt.+ supportsSteerImageAttachments: true,+ });+};+export const spawnGrokAcpAgent = async (options: SpawnAgentOptions,command: string,diff --git a/packages/heterogeneous-agents/src/spawn/antigravity.test.ts b/packages/heterogeneous-agents/src/spawn/antigravity.test.tsindex dbdaf5f7cb2..3617c7f58d6 100644--- a/packages/heterogeneous-agents/src/spawn/antigravity.test.ts+++ b/packages/heterogeneous-agents/src/spawn/antigravity.test.ts@@ -1,39 +1,35 @@import { describe, expect, it } from 'vitest';-import { buildAntigravityArgs } from './antigravity';-import { buildAgentInput } from './input/buildAgentInput';+import { buildAntigravityAcpLaunch } from './antigravity';-describe('Antigravity process input', () => {- it('sends long prompts as one JSONL stdin message rather than Windows command-line arguments', async () => {- const prompt = 'δΈζ "quoted"\n& echo %USERPROFILE% '.repeat(5000);- const input = await buildAgentInput('antigravity', prompt);- expect(input.args).toEqual([]);- expect(input.stdin.split('\n')).toHaveLength(2);- expect(JSON.parse(input.stdin)).toEqual({ event: 'user', message: { content: prompt } });+describe('buildAntigravityAcpLaunch', () => {+ it('runs the ACP server with auto-approved tools and moves selectors into the session', () => {+ expect(+ buildAntigravityAcpLaunch([+ '--model',+ 'gemini-4-neon-xhigh',+ '--effort=high',+ '--mode',+ 'plan',+ '--add-dir',+ '/repo/shared',+ ]),+ ).toEqual({+ args: ['acp', '--dangerously-skip-permissions', '--add-dir', '/repo/shared'],+ effort: 'high',+ mode: 'plan',+ model: 'gemini-4-neon-xhigh',+ });+ expect(buildAntigravityAcpLaunch()).toEqual({+ args: ['acp', '--dangerously-skip-permissions'],+ });});- it('resumes the exact conversation in YOLO mode while retaining user model settings', () => {- expect(- buildAntigravityArgs({- extraArgs: ['--model', 'custom-model', '--effort', 'high'],- resumeSessionId: 'conv-1',- }),- ).toEqual([- '--input-format',- 'stream-json',- '--output-format',- 'stream-json',+ it('does not repeat a user-supplied --dangerously-skip-permissions', () => {+ expect(buildAntigravityAcpLaunch(['--dangerously-skip-permissions']).args).toEqual([+ 'acp','--dangerously-skip-permissions',- '--settings',- '{"agentMode":"","allowNonWorkspaceAccess":true,"enableTerminalSandbox":false}',- '--conversation',- 'conv-1',- '--model',- 'custom-model',- '--effort',- 'high',]);- expect(buildAntigravityArgs({})).toContain('--dangerously-skip-permissions');});it.each([@@ -41,12 +37,17 @@ describe('Antigravity process input', () => {'--input-format','--prompt-interactive=hello','--remote-control',+ '--settings={}','-i','-p','--continue','--conversation=other','--',- ])('rejects custom %s that breaks protocol or session ownership', (flag) => {- expect(() => buildAntigravityArgs({ extraArgs: [flag] })).toThrow('LobeHub manages');+ ])('rejects %s, which LobeHub owns over ACP', (flag) => {+ expect(() => buildAntigravityAcpLaunch([flag])).toThrow('LobeHub manages');+ });++ it('rejects a selector flag without a value', () => {+ expect(() => buildAntigravityAcpLaunch(['--model'])).toThrow('needs a value');});});diff --git a/packages/heterogeneous-agents/src/spawn/antigravity.ts b/packages/heterogeneous-agents/src/spawn/antigravity.tsindex c5de032810f..aea296a6a2a 100644--- a/packages/heterogeneous-agents/src/spawn/antigravity.ts+++ b/packages/heterogeneous-agents/src/spawn/antigravity.ts@@ -1,12 +1,3 @@-/** agy reads a single JSONL user message, then finishes the turn when stdin closes. */-export const ANTIGRAVITY_BASE_ARGS = [- '--input-format',- 'stream-json',- '--output-format',- 'stream-json',- '--dangerously-skip-permissions',-] as const;-/** A Connect service can inherit an old SSH session that makes agy skip the desktop keyring. */export const getAntigravitySpawnEnv = <T extends Record<string, string | undefined>>(env: T): T => {if (env.LOBEHUB_CONNECT_SERVICE !== '1') return env;@@ -18,53 +9,67 @@ export const getAntigravitySpawnEnv = <T extends Record<string, string | undefinreturn childEnv;};-// agy 1.5.7+ defaults to Auto on supported systems. Use per-run settings-// so Full access does not depend on the CLI's saved sandbox or startup mode.-const FULL_ACCESS_SETTINGS = JSON.stringify({- agentMode: '',- allowNonWorkspaceAccess: true,- enableTerminalSandbox: false,-});--interface AntigravitySpawnArgsOptions {- extraArgs?: string[];- resumeSessionId?: string;-}-+/**+ * Flags LobeHub owns: the ACP session carries the prompt, output and+ * conversation, and `agy acp` has no per-run `--settings`.+ */const MANAGED_FLAGS = new Set(['--',+ '--continue',+ '--conversation','--input-format','--output-format','--print','--prompt','--prompt-interactive','--remote-control',+ '--settings',+ '-c','-i','-p',- '--continue',- '-c',- '--conversation',]);-export const buildAntigravityArgs = ({- extraArgs = [],- resumeSessionId,-}: AntigravitySpawnArgsOptions): string[] => {- const conflicting = extraArgs.find((arg) => MANAGED_FLAGS.has(arg.split('=')[0]));- if (conflicting) {- throw new Error(- `LobeHub manages Antigravity's prompt, output and session flags: ${conflicting}`,- );- }+/** Selector flags applied through ACP `session/set_config_option` instead of argv. */+const SESSION_CONFIG_FLAGS = {+ '--effort': 'effort',+ '--mode': 'mode',+ '--model': 'model',+} as const;++export interface AntigravityAcpLaunch {+ /** Full `agy` argv. */+ args: string[];+ effort?: string;+ mode?: string;+ model?: string;+}- const hasCustomPermissionSettings = extraArgs.some((arg) =>- ['--mode', '--sandbox', '--settings'].includes(arg.split('=')[0]),- );+/**+ * Split user/selector args into the `agy acp` argv and the session options+ * ACP sets per session (`--model` full ids such as `gemini-4-neon-xhigh`,+ * `--effort`, `--mode`). Tool permissions are always auto-approved, as the+ * print-mode runs were.+ */+export const buildAntigravityAcpLaunch = (extraArgs: string[] = []): AntigravityAcpLaunch => {+ const launch: AntigravityAcpLaunch = { args: ['acp', '--dangerously-skip-permissions'] };++ for (let index = 0; index < extraArgs.length; index += 1) {+ const arg = extraArgs[index];+ const [flag, inlineValue] = arg.split(/=(.*)/s, 2);+ if (MANAGED_FLAGS.has(flag)) {+ throw new Error(`LobeHub manages Antigravity's prompt, session and settings flags: ${flag}`);+ }++ const key = SESSION_CONFIG_FLAGS[flag as keyof typeof SESSION_CONFIG_FLAGS];+ if (!key) {+ if (arg !== '--dangerously-skip-permissions') launch.args.push(arg);+ continue;+ }++ const value = inlineValue ?? extraArgs[++index];+ if (!value?.trim()) throw new Error(`Antigravity flag ${flag} needs a value`);+ launch[key] = value.trim();+ }- return [- ...ANTIGRAVITY_BASE_ARGS,- ...(hasCustomPermissionSettings ? [] : ['--settings', FULL_ACCESS_SETTINGS]),- ...(resumeSessionId ? ['--conversation', resumeSessionId] : []),- ...extraArgs,- ];+ return launch;};diff --git a/packages/heterogeneous-agents/src/spawn/antigravityAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/antigravityAcpSession.test.tsnew file mode 100644index 00000000000..c994ed5d3e5--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/antigravityAcpSession.test.ts@@ -0,0 +1,605 @@+import type { ChildProcess } from 'node:child_process';+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';++import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ AntigravityAcpSession,+ type AntigravityAcpSessionOptions,+ isAntigravityAcpSessionNotFoundError,+} from './antigravityAcpSession';++const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));++vi.mock('node:child_process', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return { ...actual, spawn: spawnMock };+});++interface RpcMessage {+ error?: { code: number; message: string };+ id?: number | string;+ method?: string;+ params?: Record<string, any>;+ result?: unknown;+}++const SESSION_ID = 'agy-session-1';++/** `model` select values as agy 1.5.15 lists them: families, plus fixed-tier slugs. */+const MODEL_OPTIONS = [+ 'gemini-4-neon',+ 'gemini-3.8-flash',+ 'gemini-pro-orchestrator',+ 'gpt-oss-120b-medium',+];+/** Models whose thinking tier is fixed: agy offers no `thought_level` for them. */+const FIXED_TIER_MODELS = new Set(['gemini-pro-orchestrator', 'gpt-oss-120b-medium']);++const configOptions = (model: string, level: string, mode = 'default') => [+ {+ currentValue: model,+ id: 'model',+ options: MODEL_OPTIONS.map((value) => ({ name: value, value })),+ },+ ...(FIXED_TIER_MODELS.has(model)+ ? []+ : [{ currentValue: level, id: 'thought_level', options: [] }]),+ { currentValue: mode, id: 'mode', options: [] },+];++const AVAILABLE_MODELS = [+ { modelId: 'gemini-4-neon-high' },+ { modelId: 'gemini-4-neon-xhigh' },+ { modelId: 'gemini-3.8-flash-low' },+ { modelId: 'gemini-pro-orchestrator' },+ { modelId: 'gpt-oss-120b-medium' },+];++type PromptHandler = (+ prompt: RpcMessage,+ agent: { finish: (id: RpcMessage['id'], result: unknown) => void; update: (u: unknown) => void },+) => void;++/**+ * A fake `agy acp` following the behaviour recorded from agy 1.5.15: another+ * `session/prompt` while one is pending ends the pending one with `end_turn`,+ * and `session/cancel` ends the pending one with `cancelled`.+ */+const createAgy = ({+ newError,+ loadError,+ onPrompt,+ replayOnLoad = false,+ resumeError,+ steerAnswerInSameChunk,+}: {+ loadError?: { code: number; message: string };+ newError?: { code: number; message: string };+ onPrompt?: PromptHandler;+ replayOnLoad?: boolean;+ resumeError?: { code: number; message: string };+ /** Write the steered prompt's first text in the same stdout chunk as the end of the prompt it interrupts. */+ steerAnswerInSameChunk?: string;+} = {}) => {+ const child = new EventEmitter() as ChildProcess;+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const requests: RpcMessage[] = [];+ let model = 'gemini-4-neon';+ let level = 'high';+ let mode = 'default';+ let pendingPrompt: RpcMessage | undefined;+ const send = (message: Record<string, unknown>) =>+ stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);+ const update = (sessionUpdate: unknown, sessionId = SESSION_ID) =>+ send({ method: 'session/update', params: { sessionId, update: sessionUpdate } });+ const finish = (id: RpcMessage['id'], result: unknown) => {+ if (pendingPrompt?.id === id) pendingPrompt = undefined;+ send({ id, result });+ };+ const sessionResult = () => ({+ configOptions: configOptions(model, level, mode),+ models: { availableModels: AVAILABLE_MODELS },+ sessionId: SESSION_ID,+ });++ Object.assign(child, {+ kill: vi.fn(() => true),+ killed: false,+ pid: 4242,+ stderr,+ stdin: {+ end: vi.fn(),+ once: vi.fn(),+ write: vi.fn((chunk: string) => {+ const message = JSON.parse(chunk.trim()) as RpcMessage;+ requests.push(message);+ queueMicrotask(() => {+ const params = message.params ?? {};+ switch (message.method) {+ case 'initialize': {+ send({+ id: message.id,+ result: {+ agentCapabilities: {+ promptCapabilities: { image: true },+ sessionCapabilities: { load: {}, resume: {} },+ },+ protocolVersion: 1,+ },+ });+ return;+ }+ case 'session/new': {+ send(+ newError+ ? { error: newError, id: message.id }+ : { id: message.id, result: sessionResult() },+ );+ return;+ }+ case 'session/resume': {+ send(+ resumeError+ ? { error: resumeError, id: message.id }+ : { id: message.id, result: sessionResult() },+ );+ return;+ }+ case 'session/load': {+ if (loadError) {+ send({ error: loadError, id: message.id });+ return;+ }+ if (replayOnLoad) {+ update({+ content: { text: 'old reply', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ });+ }+ send({ id: message.id, result: sessionResult() });+ return;+ }+ case 'session/set_config_option': {+ if (params.configId === 'model') {+ const variant = /^(.*)-(low|medium|high|xhigh)$/.exec(params.value);+ if (MODEL_OPTIONS.includes(params.value)) {+ model = params.value;+ } else if (variant && MODEL_OPTIONS.includes(variant[1])) {+ [, model, level] = variant;+ } else {+ send({+ error: { code: -32_602, message: `Unknown model ID: ${params.value}` },+ id: message.id,+ });+ return;+ }+ }+ if (params.configId === 'thought_level') {+ if (FIXED_TIER_MODELS.has(model)) {+ send({+ error: {+ code: -32_602,+ message: `Thinking level "${params.value}" is not offered for model "${model}"`,+ },+ id: message.id,+ });+ return;+ }+ level = params.value;+ }+ if (params.configId === 'mode') mode = params.value;+ send({+ id: message.id,+ result: { configOptions: configOptions(model, level, mode) },+ });+ return;+ }+ case 'session/cancel': {+ if (pendingPrompt) finish(pendingPrompt.id, { stopReason: 'cancelled' });+ return;+ }+ case 'session/prompt': {+ // A prompt arriving mid-turn ends the pending one (agy's steer).+ const ended = {+ stopReason: 'end_turn',+ usage: {+ cachedReadTokens: 10,+ inputTokens: 100,+ outputTokens: 20,+ thoughtTokens: 5,+ },+ };+ if (pendingPrompt && steerAnswerInSameChunk !== undefined) {+ const lines = [+ { id: pendingPrompt.id, result: ended },+ {+ method: 'session/update',+ params: { sessionId: SESSION_ID, update: textChunk(steerAnswerInSameChunk) },+ },+ ];+ stdout.write(+ lines.map((line) => `${JSON.stringify({ jsonrpc: '2.0', ...line })}\n`).join(''),+ );+ pendingPrompt = undefined;+ } else if (pendingPrompt) {+ finish(pendingPrompt.id, ended);+ }+ pendingPrompt = message;+ onPrompt?.(message, { finish, update });+ return;+ }+ }+ });+ return true;+ }),+ },+ stdout,+ });++ return { child, requests, update };+};++const textChunk = (text: string) => ({+ content: { text, type: 'text' },+ sessionUpdate: 'agent_message_chunk',+});++const createSession = (+ agy: ReturnType<typeof createAgy>,+ overrides: Partial<AntigravityAcpSessionOptions> = {},+) => {+ spawnMock.mockReturnValue(agy.child);+ const events: AgentStreamEvent[] = [];+ const onModel = vi.fn();+ const onSessionId = vi.fn();+ const session = new AntigravityAcpSession({+ args: [],+ clientVersion: 'test',+ commandPath: 'agy',+ cwd: '/repo',+ env: {} as NodeJS.ProcessEnv,+ onEvents: (batch) => {+ events.push(...batch);+ },+ onModel,+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId,+ onStderr: () => {},+ operationId: 'op-1',+ prompt: [{ text: 'hello', type: 'text' }],+ sessionId: 'lobe-session',+ ...overrides,+ });+ return { events, onModel, onSessionId, session };+};++const methods = (requests: RpcMessage[]) => requests.map((request) => request.method);++afterEach(() => {+ spawnMock.mockReset();+});++describe('AntigravityAcpSession', () => {+ it('starts agy acp, applies the selected model, effort and mode, then streams the turn', async () => {+ const agy = createAgy({+ onPrompt: (prompt, { finish, update }) => {+ update({+ name: 'run_command',+ rawInput: { CommandLine: 'id -un' },+ sessionUpdate: 'tool_call',+ status: 'in_progress',+ toolCallId: 'call-1',+ });+ update({+ content: [{ content: { text: 'mocha', type: 'text' }, type: 'content' }],+ sessionUpdate: 'tool_call_update',+ status: 'completed',+ toolCallId: 'call-1',+ });+ update(textChunk('done'));+ finish(prompt.id, {+ stopReason: 'end_turn',+ usage: {+ cachedReadTokens: 14_118,+ inputTokens: 18_618,+ outputTokens: 312,+ thoughtTokens: 0,+ },+ });+ },+ });+ const { events, onModel, onSessionId, session } = createSession(agy, {+ args: ['--model', 'gemini-3.8-flash', '--effort', 'low', '--mode', 'accept-edits'],+ prompt: [+ { text: 'look', type: 'text' },+ { data: 'iVBORw0KGgo=', mimeType: 'image/png', type: 'image' },+ ],+ });++ await session.run();++ expect(spawnMock).toHaveBeenCalledWith(+ 'agy',+ ['acp', '--dangerously-skip-permissions'],+ expect.objectContaining({ cwd: '/repo' }),+ );+ expect(methods(agy.requests)).toEqual([+ 'initialize',+ 'session/new',+ 'session/set_config_option',+ 'session/set_config_option',+ 'session/set_config_option',+ 'session/prompt',+ ]);+ expect(agy.requests.slice(2, 5).map((request) => request.params)).toEqual([+ { configId: 'model', sessionId: SESSION_ID, value: 'gemini-3.8-flash' },+ { configId: 'thought_level', sessionId: SESSION_ID, value: 'low' },+ { configId: 'mode', sessionId: SESSION_ID, value: 'accept-edits' },+ ]);+ expect(agy.requests[5].params?.prompt).toEqual([+ { text: 'look', type: 'text' },+ { data: 'iVBORw0KGgo=', mimeType: 'image/png', type: 'image' },+ ]);+ expect(onSessionId).toHaveBeenCalledWith(SESSION_ID);+ expect(onModel).toHaveBeenCalledWith('gemini-3.8-flash-low');++ const toolStart = events.find((event) => event.type === 'tool_start');+ expect(toolStart?.data.toolCalling).toMatchObject({+ apiName: 'run_command',+ arguments: '{"CommandLine":"id -un"}',+ identifier: 'antigravity',+ });+ expect(events.find((event) => event.type === 'tool_result')?.data).toMatchObject({+ content: 'mocha',+ isError: false,+ });+ expect(+ events.filter((event) => event.type === 'stream_chunk' && event.data.chunkType === 'text'),+ ).toHaveLength(1);+ // agy reports input without cache reads; totals include them.+ expect(+ events.find((event) => event.type === 'step_complete' && event.data.phase === 'turn_metadata')+ ?.data.usage,+ ).toMatchObject({+ inputCachedTokens: 14_118,+ inputCacheMissTokens: 18_618,+ totalInputTokens: 32_736,+ totalOutputTokens: 312,+ totalTokens: 33_048,+ });+ expect(events.at(-1)).toMatchObject({+ data: { stopReason: 'end_turn' },+ type: 'agent_runtime_end',+ });+ });++ it.each([+ // The selector splits `gpt-oss-120b-medium` into a model and an effort.+ { args: ['--model', 'gpt-oss-120b', '--effort', 'medium'], model: 'gpt-oss-120b-medium' },+ { args: ['--model', 'gpt-oss-120b'], model: 'gpt-oss-120b-medium' },+ {+ args: ['--model', 'gemini-pro-orchestrator', '--effort', 'high'],+ model: 'gemini-pro-orchestrator',+ },+ ])(+ 'selects a fixed-tier model by its full slug and sets no effort ($args)',+ async ({ args, model }) => {+ const agy = createAgy({+ onPrompt: (prompt, { finish }) => finish(prompt.id, { stopReason: 'end_turn' }),+ });+ const { events, onModel, session } = createSession(agy, { args });++ await session.run();++ expect(+ agy.requests+ .filter((request) => request.method === 'session/set_config_option')+ .map((request) => request.params),+ ).toEqual([{ configId: 'model', sessionId: SESSION_ID, value: model }]);+ expect(onModel).toHaveBeenCalledWith(model);+ expect(events.some((event) => event.type === 'error')).toBe(false);+ },+ );++ it('steers a follow-up into the running turn and ends the run with the last prompt', async () => {+ let steered: ((value?: unknown) => void) | undefined;+ const steeredPrompt = new Promise((resolve) => (steered = resolve));+ const agy = createAgy({+ onPrompt: (prompt, { finish, update }) => {+ const text = prompt.params?.prompt?.[0]?.text;+ if (text === 'run sleep') {+ update({+ name: 'run_command',+ rawInput: { CommandLine: 'sleep 20' },+ sessionUpdate: 'tool_call',+ status: 'in_progress',+ toolCallId: 'call-sleep',+ });+ return;+ }+ steered?.();+ setTimeout(() => {+ update({+ content: [{ content: { text: 'done1', type: 'text' }, type: 'content' }],+ sessionUpdate: 'tool_call_update',+ status: 'completed',+ toolCallId: 'call-sleep',+ });+ update(textChunk('FIRST BANANA'));+ finish(prompt.id, {+ stopReason: 'end_turn',+ usage: { cachedReadTokens: 1, inputTokens: 50, outputTokens: 7, thoughtTokens: 0 },+ });+ }, 0);+ },+ });+ const { events, session } = createSession(agy, {+ prompt: [{ text: 'run sleep', type: 'text' }],+ });++ expect(session.steer([{ text: 'too early', type: 'text' }], 'msg-early')).toBe(false);+ const run = session.run();+ await vi.waitFor(() => expect(events.some((event) => event.type === 'tool_start')).toBe(true));++ expect(session.steer([{ text: 'add BANANA', type: 'text' }], 'msg-steer')).toBe(true);+ await steeredPrompt;+ await run;++ expect(methods(agy.requests).filter((method) => method === 'session/prompt')).toHaveLength(2);+ const types = events.map((event) =>+ event.type === 'step_complete' ? `step_complete:${event.data.phase}` : event.type,+ );+ const confirmed = types.indexOf('step_complete:user_message');+ expect(confirmed).toBeGreaterThan(types.indexOf('tool_start'));+ expect(events[confirmed].data).toEqual({ phase: 'user_message', uuid: 'msg-steer' });+ // The answer to the steer opens a step of its own.+ const answer = events.find(+ (event) => event.type === 'stream_chunk' && event.data.content === 'FIRST BANANA',+ );+ expect(answer!.stepIndex).toBeGreaterThan(events[confirmed].stepIndex);+ expect(events.filter((event) => event.type === 'agent_runtime_end')).toHaveLength(1);+ expect(+ events.find((event) => event.type === 'step_complete' && event.data.phase === 'turn_metadata')+ ?.data.usage,+ ).toMatchObject({ totalInputTokens: 161, totalOutputTokens: 27 });+ expect(session.steer([{ text: 'late', type: 'text' }], 'msg-late')).toBe(false);+ });++ it('confirms a steer before its answer when both arrive in one stdout chunk', async () => {+ const agy = createAgy({+ onPrompt: (prompt, { finish }) => {+ if (prompt.params?.prompt?.[0]?.text === 'add BANANA') {+ setTimeout(() => finish(prompt.id, { stopReason: 'end_turn' }), 0);+ }+ },+ steerAnswerInSameChunk: 'FIRST BANANA',+ });+ const { events, session } = createSession(agy);+ const run = session.run();+ await vi.waitFor(() => expect(methods(agy.requests).includes('session/prompt')).toBe(true));++ expect(session.steer([{ text: 'add BANANA', type: 'text' }], 'msg-steer')).toBe(true);+ await run;++ const confirmed = events.findIndex(+ (event) => event.type === 'step_complete' && event.data.phase === 'user_message',+ );+ const answer = events.findIndex(+ (event) => event.type === 'stream_chunk' && event.data.content === 'FIRST BANANA',+ );+ expect(confirmed).toBeGreaterThanOrEqual(0);+ expect(answer).toBeGreaterThan(confirmed);+ expect(events[answer].stepIndex).toBeGreaterThan(events[confirmed].stepIndex);+ });++ it('ends as interrupted when stopped after a steer, and refuses further steers', async () => {+ const agy = createAgy({ onPrompt: () => {} });+ const { events, session } = createSession(agy);+ const run = session.run();+ await vi.waitFor(() => expect(methods(agy.requests).includes('session/prompt')).toBe(true));++ expect(session.steer([{ text: 'more', type: 'text' }], 'msg-1')).toBe(true);+ await vi.waitFor(() =>+ expect(methods(agy.requests).filter((method) => method === 'session/prompt')).toHaveLength(2),+ );+ session.interrupt();+ expect(session.steer([{ text: 'after stop', type: 'text' }], 'msg-2')).toBe(false);+ await run;++ expect(methods(agy.requests)).toContain('session/cancel');+ expect(+ events.find((event) => event.type === 'step_complete' && event.data.phase === 'user_message')+ ?.data,+ ).toEqual({ phase: 'user_message', uuid: 'msg-1' });+ expect(events.at(-1)).toMatchObject({+ data: { reason: 'interrupted', stopReason: 'cancelled' },+ type: 'agent_runtime_end',+ });+ });++ it('resumes the saved conversation without replaying it', async () => {+ const agy = createAgy({+ onPrompt: (prompt, { finish, update }) => {+ update(textChunk('PINEAPPLE'));+ finish(prompt.id, { stopReason: 'end_turn' });+ },+ });+ const { events, session } = createSession(agy, { resumeSessionId: SESSION_ID });+ await session.run();++ expect(methods(agy.requests).slice(0, 3)).toEqual([+ 'initialize',+ 'session/resume',+ 'session/prompt',+ ]);+ expect(agy.requests[1].params).toEqual({ cwd: '/repo', mcpServers: [], sessionId: SESSION_ID });+ expect(events.find((event) => event.type === 'stream_chunk')?.data.content).toBe('PINEAPPLE');+ });++ it('falls back to session/load when resume fails and drops the replayed history', async () => {+ const agy = createAgy({+ onPrompt: (prompt, { finish, update }) => {+ update(textChunk('new reply'));+ finish(prompt.id, { stopReason: 'end_turn' });+ },+ replayOnLoad: true,+ resumeError: {+ code: -32_603,+ message: 'Failed to read session; retry, or load it with session/load',+ },+ });+ const { events, session } = createSession(agy, { resumeSessionId: SESSION_ID });+ await session.run();++ expect(methods(agy.requests).slice(1, 3)).toEqual(['session/resume', 'session/load']);+ const texts = events.flatMap((event) =>+ event.type === 'stream_chunk' && event.data.chunkType === 'text' ? [event.data.content] : [],+ );+ expect(texts).toEqual(['new reply']);+ });++ it('reports a conversation agy no longer has as a missing resume session', async () => {+ const agy = createAgy({+ loadError: { code: -32_002, message: 'Session not found: gone' },+ resumeError: { code: -32_603, message: 'Failed to read session gone' },+ });+ const { session } = createSession(agy, { resumeSessionId: 'gone' });++ const error = await session.run().catch((cause) => cause);+ expect(isAntigravityAcpSessionNotFoundError(error)).toBe(true);+ expect(String(error.message)).toMatch(/session not found/i);+ });++ it('turns a signed-out agy into the Antigravity sign-in guide', async () => {+ const agy = createAgy({ newError: { code: -32_000, message: 'Authentication required' } });+ const { events, session } = createSession(agy);++ await expect(session.run()).rejects.toThrow('Authentication required');+ expect(events.find((event) => event.type === 'error')?.data).toMatchObject({+ agentType: 'antigravity',+ message: 'Antigravity could not authenticate. Run `agy` and sign in, then retry.',+ });+ });++ it('keeps subagent conversations out of the parent stream', async () => {+ const agy = createAgy({+ onPrompt: (prompt, { finish }) => {+ agy.update(textChunk('child output'), 'child-session');+ agy.update(textChunk('parent output'));+ finish(prompt.id, { stopReason: 'end_turn' });+ },+ });+ const { events, session } = createSession(agy);+ await session.run();++ const texts = events.flatMap((event) =>+ event.type === 'stream_chunk' && event.data.chunkType === 'text' ? [event.data.content] : [],+ );+ expect(texts).toEqual(['parent output']);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/antigravityAcpSession.ts b/packages/heterogeneous-agents/src/spawn/antigravityAcpSession.tsnew file mode 100644index 00000000000..67805bc7fff--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/antigravityAcpSession.ts@@ -0,0 +1,430 @@+import { isRecord } from '@lobechat/utils/object';++import type { AgentPromptInput } from '../protocol';+import type { AcpAgentSessionOptions } from './acpAgentSession';+import {+ ACP_PROTOCOL_VERSION,+ AcpAgentSession,+ selectAcpPermissionOption,+} from './acpAgentSession';+import type { AcpRpcMessage } from './acpStdioClient';+import { AcpRpcResponseError, AcpServerRequestError } from './acpStdioClient';+import { buildAntigravityAcpLaunch } from './antigravity';+import type { BuildAgentInputOptions } from './input';+import type { TraeAcpPromptBlock } from './traeAcpSession';+import { buildTraeAcpPrompt } from './traeAcpSession';++const TRANSPORT = 'antigravity-acp' as const;++export type AntigravityAcpPromptBlock = TraeAcpPromptBlock;++interface AntigravityAcpInitializeResult {+ agentCapabilities?: {+ promptCapabilities?: { image?: boolean };+ sessionCapabilities?: { resume?: unknown };+ };+ protocolVersion?: number | string;+}++interface AntigravityAcpSessionResult {+ configOptions?: unknown;+ models?: { availableModels?: unknown };+ sessionId?: string;+}++interface AntigravityAcpPromptResult {+ stopReason?: string;+ usage?: unknown;+}++/** A follow-up written to agy that the run has not confirmed as read yet. */+interface UnconfirmedSteer {+ /** Its position among the run's prompts (the first prompt is 0). */+ index: number;+ uuid: string;+}++const USAGE_FIELDS = ['inputTokens', 'outputTokens', 'cachedReadTokens', 'thoughtTokens'] as const;++type UsageTotals = Record<(typeof USAGE_FIELDS)[number], number>;++const findConfigOption = (configOptions: unknown, id: string) =>+ Array.isArray(configOptions)+ ? configOptions.find((value) => isRecord(value) && value.id === id)+ : undefined;++const configValue = (configOptions: unknown, id: string): string | undefined => {+ const option = findConfigOption(configOptions, id);+ return isRecord(option) && typeof option.currentValue === 'string'+ ? option.currentValue+ : undefined;+};++/** Values of a select option, flattening grouped options. */+const configOptionValues = (configOptions: unknown, id: string): string[] => {+ const option = findConfigOption(configOptions, id);+ const collect = (entries: unknown): string[] =>+ Array.isArray(entries)+ ? entries.flatMap((entry) => {+ if (!isRecord(entry)) return [];+ if (Array.isArray(entry.options)) return collect(entry.options);+ return typeof entry.value === 'string' ? [entry.value] : [];+ })+ : [];+ return isRecord(option) ? collect(option.options) : [];+};++const availableModelIds = (result: AntigravityAcpSessionResult): Set<string> => {+ const models = result.models?.availableModels;+ return new Set(+ Array.isArray(models)+ ? models.flatMap((model) =>+ isRecord(model) && typeof model.modelId === 'string' ? [model.modelId] : [],+ )+ : [],+ );+};++/**+ * The `model` value agy takes for a selection. The selector groups `agy models`+ * slugs into a model and an effort (`gpt-oss-120b` + `medium`), but a model+ * whose thinking tier is fixed only exists under its full slug+ * (`gpt-oss-120b-medium`).+ */+const resolveModelValue = (+ model: string,+ effort: string | undefined,+ sessionResult: AntigravityAcpSessionResult,+): string => {+ const known = new Set([+ ...configOptionValues(sessionResult.configOptions, 'model'),+ ...availableModelIds(sessionResult),+ ]);+ if (known.size === 0 || known.has(model)) return model;+ if (effort && known.has(`${model}-${effort}`)) return `${model}-${effort}`;+ const variants = [...known].filter((id) => id.startsWith(`${model}-`));+ return variants.length === 1 ? variants[0] : model;+};++export interface AntigravityAcpSessionOptions extends AcpAgentSessionOptions {+ onModel?: (model: string) => void;+ prompt: AntigravityAcpPromptBlock[];+}++export const buildAntigravityAcpPrompt = (+ prompt: AgentPromptInput,+ options: BuildAgentInputOptions = {},+): Promise<AntigravityAcpPromptBlock[]> => buildTraeAcpPrompt(prompt, options);++/** The response to a `session/prompt`: it carries a stop reason, or failed as one. */+const isPromptResponse = (message: AcpRpcMessage): boolean => {+ if (message.method !== undefined || message.id === undefined) return false;+ if (message.error) return message.requestMethod === 'session/prompt';+ return isRecord(message.result) && 'stopReason' in message.result;+};++/** `session/resume` and `session/load` both failed to find the saved conversation. */+export const isAntigravityAcpSessionNotFoundError = (+ error: unknown,+): error is AcpRpcResponseError =>+ error instanceof AcpRpcResponseError &&+ error.method === 'session/load' &&+ /session not found/i.test(error.rpcError.message ?? '');++/**+ * Antigravity over `agy acp`. One run is one user turn; a message the user+ * sends while it runs is steered in with another `session/prompt`: agy ends+ * the pending prompt (`end_turn`) and carries on with the new one inside the+ * same work. The run ends when the latest prompt settles.+ */+export class AntigravityAcpSession extends AcpAgentSession<+ AntigravityAcpInitializeResult,+ AntigravityAcpSessionOptions+> {+ /** Session updates before the prompt (a `session/load` replay) are history, not output. */+ private acceptUpdates = false;+ /** Read confirmations, chained so each lands before any update that follows it. */+ private confirmations: Promise<void> = Promise.resolve();+ private readonly launch: ReturnType<typeof buildAntigravityAcpLaunch>;+ /** Prompt responses handled so far, in stdout order. */+ private promptResponses = 0;+ /** Steered prompts written to agy, in order, that the run has not settled yet. */+ private readonly steers: Promise<AntigravityAcpPromptResult>[] = [];+ private steerCount = 0;+ private steerable = false;+ private readonly unconfirmedSteers: UnconfirmedSteer[] = [];+ private usage: UsageTotals = {+ cachedReadTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+ thoughtTokens: 0,+ };++ constructor(options: AntigravityAcpSessionOptions) {+ const launch = buildAntigravityAcpLaunch(options.args);+ super(options, {+ args: launch.args,+ pipeline: { agentType: 'antigravity', cwd: options.cwd },+ processLabel: 'Antigravity ACP',+ transport: TRANSPORT,+ });+ this.launch = launch;+ }++ get sessionId(): string | undefined {+ return this.acpSessionId;+ }++ /**+ * Write a user message into the running turn. `false` when the run takes no+ * input now (not prompting yet, interrupted, or settling): nothing was+ * written, so the message can wait for the next run. agy confirms it read+ * the message when the prompt it interrupts returns, reported as+ * `step_complete { phase: 'user_message', uuid }`.+ */+ steer(prompt: AntigravityAcpPromptBlock[], uuid: string): boolean {+ const sessionId = this.acpSessionId;+ if (!this.steerable || !sessionId || this.closedByHost) return false;++ const result = this.client.request<AntigravityAcpPromptResult>(+ 'session/prompt',+ { prompt, sessionId },+ false,+ );+ // Settled in order by `settlePrompt`; a closed transport must not surface+ // as an unhandled rejection before the run gets to it.+ result.catch(() => {});+ this.steers.push(result);++ const index = ++this.steerCount;+ // The prompt before it already returned: agy starts on this one now.+ if (this.promptResponses >= index) this.confirmSteer(uuid);+ else this.unconfirmedSteers.push({ index, uuid });+ return true;+ }++ override interrupt(): void {+ this.steerable = false;+ super.interrupt();+ }++ protected buildInitializeParams(): unknown {+ return {+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ clientInfo: { name: 'lobehub', title: 'LobeHub', version: this.options.clientVersion },+ protocolVersion: ACP_PROTOCOL_VERSION,+ };+ }++ protected validateInitialized(initialized: AntigravityAcpInitializeResult): void {+ if (+ initialized.protocolVersion !== ACP_PROTOCOL_VERSION &&+ initialized.protocolVersion !== String(ACP_PROTOCOL_VERSION)+ ) {+ throw new Error(+ `Antigravity ACP returned unsupported protocol version: ${String(initialized.protocolVersion)}`,+ );+ }+ if (+ this.options.prompt.some((block) => block.type === 'image') &&+ initialized.agentCapabilities?.promptCapabilities?.image !== true+ ) {+ throw new Error(+ 'This Antigravity CLI does not accept images over ACP. Update agy and retry.',+ );+ }+ }++ protected async establishSession(initialized: AntigravityAcpInitializeResult): Promise<string> {+ const sessionResult = await this.openSession(initialized);+ const sessionId = sessionResult.sessionId ?? this.options.resumeSessionId;+ if (!sessionId) throw new Error('Antigravity ACP returned no session id');++ const model = await this.applySessionConfig(sessionId, sessionResult);+ if (model) {+ this.pipeline.configureSession({ model });+ this.options.onModel?.(model);+ }+ this.options.onSessionId(sessionId);+ await this.pushToPipeline({ model, sessionId, type: 'antigravity_session' });+ return sessionId;+ }++ protected onBeforePrompt(): void {+ this.acceptUpdates = true;+ this.steerable = true;+ }++ protected buildPromptParams(sessionId: string): unknown {+ return { prompt: this.options.prompt, sessionId };+ }++ /**+ * The first prompt settled; settle every message steered in after it, in+ * order. Each was confirmed as read when the prompt before it returned.+ */+ protected override async settlePrompt(result: unknown): Promise<void> {+ let last = (isRecord(result) ? result : {}) as AntigravityAcpPromptResult;+ this.addUsage(last.usage);+ for (;;) {+ await this.client.drain();+ const next = this.steers.shift();+ if (!next) break;+ last = await next;+ this.addUsage(last.usage);+ }+ this.steerable = false;+ await this.confirmations;++ const used = Object.values(this.usage).some((value) => value > 0);+ await this.pushToPipeline({+ stopReason: last.stopReason,+ type: 'antigravity_prompt_completed',+ ...(used && { usage: { ...this.usage } }),+ });+ }++ protected async onRunFailure(error: Error): Promise<void> {+ this.steerable = false;+ await this.pushToPipeline({ message: error.message, type: 'antigravity_error' });+ await this.emitEvents(await this.pipeline.flush());+ }++ protected async onRunCancelled(): Promise<void> {+ this.steerable = false;+ await this.pushToPipeline({ stopReason: 'cancelled', type: 'antigravity_prompt_completed' });+ }++ protected onHostClose(): void {+ this.steerable = false;+ }++ protected async handleAgentMessage(message: AcpRpcMessage): Promise<void> {+ await this.confirmations;+ if (isPromptResponse(message)) {+ // Each steer ends the prompt before it, so this is when agy read the+ // next one. Confirm it here, in stdout order, so the answer to it that+ // follows in the same output opens a step of its own.+ this.promptResponses += 1;+ const next = this.unconfirmedSteers[0];+ if (next && next.index <= this.promptResponses) {+ this.unconfirmedSteers.shift();+ await this.confirmSteer(next.uuid);+ }+ return;+ }+ if (!this.acceptUpdates || message.method !== 'session/update') return;+ const params = isRecord(message.params) ? message.params : undefined;+ if (!isRecord(params?.update)) return;+ // Subagent conversations must never leak into the parent's assistant bubble.+ if (typeof params.sessionId === 'string' && params.sessionId !== this.acpSessionId) return;+ await this.pushToPipeline(params.update);+ }++ /**+ * `--dangerously-skip-permissions` makes agy approve tools itself; should it+ * still ask, approve as the print-mode runs did.+ */+ protected handleServerRequest(message: AcpRpcMessage): unknown {+ if (message.method !== 'session/request_permission') {+ throw new AcpServerRequestError(-32_601, `Unsupported ACP client request: ${message.method}`);+ }+ const optionId = selectAcpPermissionOption(message.params, [+ (option) => option.kind === 'allow_always',+ (option) => option.kind === 'allow_once',+ ]);+ return optionId+ ? { outcome: { optionId, outcome: 'selected' } }+ : { outcome: { outcome: 'cancelled' } };+ }++ /**+ * Resume without replaying history; agy points sessions it cannot resume to+ * `session/load`, whose replay arrives before the prompt and is dropped.+ */+ private async openSession(+ initialized: AntigravityAcpInitializeResult,+ ): Promise<AntigravityAcpSessionResult> {+ const params = { cwd: this.options.cwd, mcpServers: [] };+ const resumeSessionId = this.options.resumeSessionId;+ if (!resumeSessionId) {+ return this.client.request<AntigravityAcpSessionResult>('session/new', params);+ }++ const resumeParams = { ...params, sessionId: resumeSessionId };+ if (initialized.agentCapabilities?.sessionCapabilities?.resume !== undefined) {+ try {+ return await this.client.request<AntigravityAcpSessionResult>(+ 'session/resume',+ resumeParams,+ );+ } catch (error) {+ if (!(error instanceof AcpRpcResponseError)) throw error;+ }+ }+ const loaded = await this.client.request<AntigravityAcpSessionResult>(+ 'session/load',+ resumeParams,+ );+ await this.client.drain();+ return loaded;+ }++ /**+ * Apply the selected model (a full id such as `gemini-4-neon-xhigh`, which+ * agy splits into model and thinking level), effort and mode. Returns the+ * model the session runs.+ */+ private async applySessionConfig(+ sessionId: string,+ sessionResult: AntigravityAcpSessionResult,+ ): Promise<string | undefined> {+ let configOptions = sessionResult.configOptions;+ const set = async (configId: string, value: string) => {+ const result = await this.client.request<{ configOptions?: unknown }>(+ 'session/set_config_option',+ { configId, sessionId, value },+ );+ if (result.configOptions !== undefined) configOptions = result.configOptions;+ };++ const { effort, mode } = this.launch;+ const model =+ this.launch.model && this.launch.model !== 'default'+ ? resolveModelValue(this.launch.model, effort, sessionResult)+ : undefined;+ if (model) await set('model', model);+ // Models with a fixed thinking tier (GPT-OSS, Orchestrator) offer no+ // thought_level, and agy rejects setting one.+ if (effort && findConfigOption(configOptions, 'thought_level')) {+ await set('thought_level', effort);+ }+ if (mode) await set('mode', mode);++ const family = configValue(configOptions, 'model');+ if (!family) return model;+ const level = configValue(configOptions, 'thought_level');+ const variant = level ? `${family}-${level}` : undefined;+ return variant && availableModelIds(sessionResult).has(variant) ? variant : family;+ }++ private confirmSteer(uuid: string): Promise<void> {+ const confirmed = this.confirmations.then(() =>+ this.pushToPipeline({ type: 'antigravity_user_message', uuid }),+ );+ // Awaited by the next message and by `settlePrompt`.+ confirmed.catch(() => {});+ this.confirmations = confirmed;+ return confirmed;+ }++ private addUsage(usage: unknown): void {+ if (!isRecord(usage)) return;+ for (const field of USAGE_FIELDS) {+ const value = usage[field];+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {+ this.usage[field] += value;+ }+ }+ }+}diff --git a/packages/heterogeneous-agents/src/spawn/antigravityLiveInput.test.ts b/packages/heterogeneous-agents/src/spawn/antigravityLiveInput.test.tsdeleted file mode 100644index 26d3c2f8924..00000000000--- a/packages/heterogeneous-agents/src/spawn/antigravityLiveInput.test.ts+++ /dev/null@@ -1,116 +0,0 @@-import { PassThrough } from 'node:stream';--import { describe, expect, it } from 'vitest';--import { AntigravityLiveInput, resolveAntigravityLiveRuntimeEnd } from './antigravityLiveInput';--describe('AntigravityLiveInput', () => {- it('closes stdin after a single successful turn when no steered messages are pending', () => {- const stdin = new PassThrough();- const writes: string[] = [];- stdin.on('data', (chunk) => writes.push(chunk.toString()));-- const live = new AntigravityLiveInput(stdin);- expect(live.send('{"event":"user","message":{"content":"first"}}\n')).toBe(true);- expect(live.isOpen).toBe(true);-- live.observe('{"event":"init","conversation_id":"c1"}\n');- live.observe(- '{"event":"step_update","step_update":{"step_index":0,"state":"DONE","step_type":"user_input"}}\n',- );- live.observe('{"event":"result","result":{"status":"SUCCESS","num_turns":1}}\n');-- expect(live.isOpen).toBe(false);- expect(live.lastTurn).toEqual({ ok: true, status: 'SUCCESS' });- expect(live.send('{"event":"user","message":{"content":"late"}}\n', 'u-late')).toBe(false);- expect(writes).toHaveLength(1);- });-- it('keeps stdin open across turn boundaries while a steered message is pending, then closes when idle', () => {- const stdin = new PassThrough();- const writes: string[] = [];- stdin.on('data', (chunk) => writes.push(chunk.toString()));-- const live = new AntigravityLiveInput(stdin);- expect(live.send('{"event":"user","message":{"content":"first"}}\n')).toBe(true);- live.observe('{"event":"init","conversation_id":"c1"}\n');- live.observe(- '{"event":"step_update","step_update":{"step_index":0,"state":"DONE","step_type":"user_input"}}\n',- );-- // Steer arrives while turn 1 is still running- expect(live.send('{"event":"user","message":{"content":"steer"}}\n', 'u-steer')).toBe(true);- live.observe('{"event":"result","result":{"status":"SUCCESS","num_turns":1}}\n');-- // Stdin stays open because u-steer has not been picked up yet- expect(live.isOpen).toBe(true);- expect(live.takeSteerUuid()).toBe('u-steer');- expect(live.takeSteerUuid()).toBeUndefined();-- // Turn 2 picks up u-steer and completes- live.observe(- '{"event":"step_update","step_update":{"step_index":4,"state":"DONE","step_type":"user_input"}}\n',- );- expect(live.isOpen).toBe(true);- live.observe('{"event":"result","result":{"status":"SUCCESS","num_turns":2}}\n');-- expect(live.isOpen).toBe(false);- expect(live.lastTurn).toEqual({ ok: true, status: 'SUCCESS' });- expect(writes).toHaveLength(2);- });-- it('closes immediately on a failed turn even when a steered message is queued', () => {- const stdin = new PassThrough();- const live = new AntigravityLiveInput(stdin);- live.send('{"event":"user","message":{"content":"first"}}\n');- live.send('{"event":"user","message":{"content":"steer"}}\n', 'u-steer');- live.observe('{"event":"result","result":{"status":"ERROR","error":"boom"}}\n');-- expect(live.isOpen).toBe(false);- expect(live.lastTurn).toEqual({ ok: false, status: 'ERROR' });- });-- it('ignores child-conversation user_input updates when tracking pending steers', () => {- const stdin = new PassThrough();- const live = new AntigravityLiveInput(stdin);- live.send('{"event":"user","message":{"content":"first"}}\n');- live.observe('{"event":"init","conversation_id":"parent-conv"}\n');- live.observe(- '{"event":"step_update","step_update":{"conversation_id":"parent-conv","step_index":0,"state":"DONE","step_type":"user_input"}}\n',- );-- // Queue a steer for the parent conversation- expect(live.send('{"event":"user","message":{"content":"steer"}}\n', 'u-steer')).toBe(true);- // Child subagent conversation emits its own user_input β must NOT consume parent's pending steer- live.observe(- '{"event":"step_update","step_update":{"conversation_id":"child-conv","step_index":1,"state":"DONE","step_type":"user_input"}}\n',- );- // Parent turn 1 completes: stdin must stay open because u-steer is still pending- live.observe('{"event":"result","result":{"conversation_id":"parent-conv","status":"SUCCESS"}}\n');-- expect(live.isOpen).toBe(true);- expect(live.takeSteerUuid()).toBe('u-steer');- });-});--describe('resolveAntigravityLiveRuntimeEnd', () => {- const cleanExit = { code: 0, killedByHost: false, sawError: false, signal: null };-- it('returns complete only on a clean exit after a successful turn', () => {- expect(resolveAntigravityLiveRuntimeEnd({ ok: true, status: 'SUCCESS' }, cleanExit)).toEqual({- reason: 'complete',- transport: 'cli-live',- });- expect(resolveAntigravityLiveRuntimeEnd({ ok: false, status: 'ERROR' }, cleanExit)).toBeUndefined();- expect(resolveAntigravityLiveRuntimeEnd(undefined, cleanExit)).toBeUndefined();- expect(- resolveAntigravityLiveRuntimeEnd({ ok: true }, { ...cleanExit, code: 1 }),- ).toBeUndefined();- expect(- resolveAntigravityLiveRuntimeEnd({ ok: true }, { ...cleanExit, killedByHost: true }),- ).toBeUndefined();- expect(- resolveAntigravityLiveRuntimeEnd({ ok: true }, { ...cleanExit, sawError: true }),- ).toBeUndefined();- });-});diff --git a/packages/heterogeneous-agents/src/spawn/antigravityLiveInput.ts b/packages/heterogeneous-agents/src/spawn/antigravityLiveInput.tsdeleted file mode 100644index fff80de494a..00000000000--- a/packages/heterogeneous-agents/src/spawn/antigravityLiveInput.ts+++ /dev/null@@ -1,210 +0,0 @@-import type { Writable } from 'node:stream';--/**- * How long a live Antigravity session may sit between turns with no stdout- * before stdin is closed anyway.- */-const DEFAULT_IDLE_CLOSE_MS = 30 * 60 * 1000;--const readIdleCloseMs = (): number => {- const value = Number(process.env.LOBE_ANTIGRAVITY_LIVE_INPUT_IDLE_MS);- return Number.isFinite(value) && value > 0 ? value : DEFAULT_IDLE_CLOSE_MS;-};--/** How the session's most recent turn ended. */-export interface AntigravityTurnOutcome {- ok: boolean;- status?: string;-}--/** How a live Antigravity process ended, as its host saw it. */-export interface AntigravityLiveExit {- code: number | null;- /** The host killed the process (cancel, stop, quit): its own path reports that end. */- killedByHost: boolean;- /** The run already reported an error event: that error is its end. */- sawError: boolean;- signal: NodeJS.Signals | null;-}--/**- * The runtime end a live Antigravity session (stdin kept open, see- * `AntigravityLiveInput`) reports once, at process exit.- */-export const resolveAntigravityLiveRuntimeEnd = (- lastTurn: AntigravityTurnOutcome | undefined,- exit: AntigravityLiveExit,-): Record<string, unknown> | undefined => {- if (!lastTurn?.ok || exit.killedByHost || exit.sawError) return;- if (exit.code !== 0) return;-- return { reason: 'complete', transport: 'cli-live' };-};--export interface AntigravityLiveInputOptions {- idleCloseMs?: number;-}--/**- * Keeps an Antigravity (`--input-format stream-json --output-format stream-json`)- * stdin open while a turn is active or steered follow-ups remain unconsumed,- * then closes stdin as soon as the session becomes idle so the process exits cleanly.- */-export class AntigravityLiveInput {- private closed = false;- private readonly idleCloseMs: number;- private idleTimer: ReturnType<typeof setTimeout> | undefined;- private initialUserInputSeen = false;- private lastOutcome: AntigravityTurnOutcome | undefined;- private lineBuffer = '';- private readonly pendingAdapterUuids: string[] = [];- private readonly seenUserInputSteps = new Set<number>();- private sessionId: string | undefined;- private turnOpen = false;- private readonly unconsumed: string[] = [];-- constructor(- private readonly stdin: Writable,- options: AntigravityLiveInputOptions = {},- ) {- this.idleCloseMs = options.idleCloseMs ?? readIdleCloseMs();- stdin.on?.('close', () => this.markClosed());- stdin.on?.('error', () => this.markClosed());- }-- get isOpen(): boolean {- return !this.closed && !this.stdin.destroyed && !this.stdin.writableEnded;- }-- get lastTurn(): AntigravityTurnOutcome | undefined {- return this.lastOutcome;- }-- /**- * Write one stream-json `user` line into the session. When `uuid` is given- * (a steered follow-up), stdin stays open across turn boundaries until `agy`- * picks up that message and finishes its turn.- */- send(stdinLine: string, uuid?: string): boolean {- if (!this.isOpen) return false;- if (uuid) {- this.unconsumed.push(uuid);- this.pendingAdapterUuids.push(uuid);- }- this.stdin.write(stdinLine);- this.clearIdleTimer();- return true;- }-- /** Pop the next steered message UUID for `AntigravityAdapter` to confirm. */- takeSteerUuid(): string | undefined {- return this.pendingAdapterUuids.shift();- }-- /** Feed raw stdout bytes from the child process. */- observe(chunk: string | Buffer): void {- this.lineBuffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');-- for (;;) {- const newline = this.lineBuffer.indexOf('\n');- if (newline === -1) break;- const line = this.lineBuffer.slice(0, newline).trim();- this.lineBuffer = this.lineBuffer.slice(newline + 1);- if (!line) continue;-- try {- this.observeMessage(JSON.parse(line));- } catch {- // Non-JSON diagnostics are ignored by the adapter too.- }- }-- if (this.closed) return;- if (this.turnOpen) this.clearIdleTimer();- else this.armIdleTimer();- }-- /** stdout ended: flush any trailing partial line and close stdin. */- finish(): void {- if (this.lineBuffer.trim()) this.observe('\n');- this.close();- }-- close(): void {- if (this.closed) return;- this.markClosed();- this.stdin.end();- }-- private observeMessage(message: any): void {- if (!message || typeof message !== 'object') return;-- if (message.event === 'init') {- if (typeof message.conversation_id === 'string' && message.conversation_id) {- this.sessionId = message.conversation_id;- }- this.openTurn();- return;- }-- if (message.event === 'step_update' && message.step_update && typeof message.step_update === 'object') {- const step = message.step_update;- const conversationId =- typeof step.conversation_id === 'string' && step.conversation_id- ? step.conversation_id- : undefined;- // Child conversations must never consume the parent run's pending steer count.- if (this.sessionId && conversationId && conversationId !== this.sessionId) return;- this.sessionId ??= conversationId;- if (step.step_type === 'user_input') {- const index = typeof step.step_index === 'number' ? step.step_index : undefined;- const isNewStep = index === undefined || !this.seenUserInputSteps.has(index);- if (isNewStep) {- if (index !== undefined) this.seenUserInputSteps.add(index);- if (this.initialUserInputSeen) {- this.unconsumed.shift();- } else {- this.initialUserInputSeen = true;- }- }- }- this.openTurn();- return;- }-- if (message.event === 'result' && message.result && typeof message.result === 'object') {- this.turnOpen = false;- const status = typeof message.result.status === 'string' ? message.result.status : undefined;- this.lastOutcome = { ok: status === 'SUCCESS', status };- if (status !== 'SUCCESS') this.close();- else this.closeIfIdle();- }- }-- private openTurn(): void {- this.turnOpen = true;- this.lastOutcome = undefined;- }-- private closeIfIdle(): void {- if (this.turnOpen || this.unconsumed.length > 0) return;- this.close();- }-- private armIdleTimer(): void {- this.clearIdleTimer();- this.idleTimer = setTimeout(() => this.close(), this.idleCloseMs);- this.idleTimer.unref?.();- }-- private clearIdleTimer(): void {- if (!this.idleTimer) return;- clearTimeout(this.idleTimer);- this.idleTimer = undefined;- }-- private markClosed(): void {- this.closed = true;- this.clearIdleTimer();- }-}diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex c9daa53920a..839cae3580b 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -176,6 +176,7 @@ export interface HeterogeneousAgentRuntimeStatus {state: HeterogeneousAgentRuntimeState;transport:| 'acp-stdio'+ | 'antigravity-acp'| 'claude-sdk'| 'cli-spawn'| 'codex-app-server'diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 3bdf316cc6b..adc157ca954 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -51,14 +51,18 @@ export {type AgentStreamPipelineOptions,type UploadHeterogeneousImage,} from './agentStreamPipeline';-export { ANTIGRAVITY_BASE_ARGS, buildAntigravityArgs } from './antigravity';export {- type AntigravityLiveExit,- AntigravityLiveInput,- type AntigravityLiveInputOptions,- type AntigravityTurnOutcome,- resolveAntigravityLiveRuntimeEnd,-} from './antigravityLiveInput';+ type AntigravityAcpLaunch,+ buildAntigravityAcpLaunch,+ getAntigravitySpawnEnv,+} from './antigravity';+export {+ type AntigravityAcpPromptBlock,+ AntigravityAcpSession,+ type AntigravityAcpSessionOptions,+ buildAntigravityAcpPrompt,+ isAntigravityAcpSessionNotFoundError,+} from './antigravityAcpSession';export {classifyHeteroProcessFailure,type ClassifyHeteroProcessFailureParams,diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.tsindex c26589bab64..634e0488076 100644--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts@@ -192,51 +192,6 @@ describe('buildAgentInput', () => {});});- describe('antigravity', () => {- it('references every attached image in the text stream and materializes distinct bytes', async () => {- const header = Buffer.concat([PNG_BYTES, Buffer.alloc(64)]);- const images = [- Buffer.concat([header, Buffer.from('a')]),- Buffer.concat([header, Buffer.from('b')]),- ];-- const plan = await buildAgentInput(- 'antigravity',- [- { text: 'Compare the two images', type: 'text' },- ...images.map((image) => ({- source: {- data: image.toString('base64'),- mediaType: 'image/png',- type: 'base64' as const,- },- type: 'image' as const,- })),- ],- { cacheDir: tmp },- );-- const {- event,- message: { content },- } = JSON.parse(plan.stdin);- expect(event).toBe('user');- expect(content).toContain('Compare the two images');- const paths = [...content.matchAll(/^- (".+")$/gm)].map(([, value]) => JSON.parse(value));- expect(paths).toHaveLength(2);- expect(await Promise.all(paths.map((filePath) => readFile(filePath)))).toEqual(images);- });-- it('reports a missing attachment instead of sending a prompt without the image', async () => {- const filePath = path.join(tmp, 'missing.png');- await expect(- buildAgentInput('antigravity', [- { source: { path: filePath, type: 'path' }, type: 'image' },- ]),- ).rejects.toMatchObject({ code: 'ENOENT', path: filePath });- });- });-describe('codex', () => {it('puts text on stdin and emits no --image flags when there are no images', async () => {const plan = await buildAgentInput('codex', 'just text');diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.tsindex f2e35b3f03d..69b6af4621d 100644--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts@@ -182,7 +182,6 @@ const buildQoderInput = async (* extra CLI args required to attach images. The single source of truth for* how each external agent CLI receives multimodal input.*- * - `antigravity`: stream-json text on stdin with local paths for the built-in image reader* - `amp` / `claude-code` / `codebuddy`: stream-json on stdin with text + base64 image content blocks* - `codex`: raw text on stdin + repeatable `--image <path>` flags* - `kimi-code`: `--prompt <text>` with materialized image paths referenced in the text@@ -201,21 +200,6 @@ export const buildAgentInput = async (const blocks = toBlocks(prompt);switch (agentType) {- case 'antigravity': {- // agy rejects image blocks in stream-json, but its built-in file reader accepts images.- const imagePaths = await resolvePathInputImagePaths(blocks, options);- const attachments = imagePaths.length- ? [- 'Use your built-in image-reading tool to inspect the attached images before answering:',- ...imagePaths.map((imagePath) => `- ${JSON.stringify(path.resolve(imagePath))}`),- ].join('\n')- : '';- const content = [collectText(blocks), attachments].filter(Boolean).join('\n\n');- return {- args: [],- stdin: `${JSON.stringify({ event: 'user', message: { content } })}\n`,- };- }case 'amp':case 'claude-code':case 'codebuddy': {diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.antigravity.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.antigravity.test.tsindex b3410789c5f..fb917fa2152 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.antigravity.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.antigravity.test.ts@@ -70,10 +70,10 @@ describe('resolveCliCommand β Antigravity', () => {vi.resetModules();});- it('detects Antigravity stream-json and preserves prerelease/build versions', async () => {+ it('detects Antigravity with ACP and preserves prerelease/build versions', async () => {callExecFile('/Users/x/.local/bin/agy\n');callExecFile('1.2.13-beta.1+build.5');- callExecFile('', '--input-format --output-format stream-json --conversation');+ callExecFile('', 'acp Start the Agent Client Protocol (ACP) stdio server');const { detectHeterogeneousCliCommand } = await importModule();expect(await detectHeterogeneousCliCommand('antigravity', 'agy')).toMatchObject({available: true,@@ -82,7 +82,7 @@ describe('resolveCliCommand β Antigravity', () => {});});- it('rejects older agy versions that cannot stream input or resume', async () => {+ it('rejects older agy versions without the ACP server', async () => {callExecFile('1.0.7');callExecFile('Usage: agy --print --output-format json');const { detectHeterogeneousCliCommand } = await importModule();@@ -97,7 +97,7 @@ describe('resolveCliCommand β Antigravity', () => {try {callExecFileError(new Error('not found'));callExecFile('1.2.13');- callExecFile('--input-format --output-format stream-json --conversation');+ callExecFile('acp Start the Agent Client Protocol (ACP) stdio server');const { detectHeterogeneousCliCommand } = await importModule();expect(await detectHeterogeneousCliCommand('antigravity', 'agy')).toMatchObject({available: true,@@ -121,7 +121,7 @@ describe('resolveCliCommand β Antigravity', () => {callExecFileError(new Error('no registry PATH'));callExecFileError(new Error('no registry PATH'));callExecFile('1.2.13');- callExecFile('--input-format --output-format stream-json --conversation');+ callExecFile('acp Start the Agent Client Protocol (ACP) stdio server');const { detectHeterogeneousCliCommand } = await importModule();expect(await detectHeterogeneousCliCommand('antigravity', 'agy')).toMatchObject({available: true,diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex ac369398bb7..51576fa54ea 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -693,7 +693,9 @@ export const detectValidatedCommand = async (const HETEROGENEOUS_CLI_AGENT_OPTIONS = {'antigravity': {- validateHelpKeywords: ['--input-format', '--output-format', '--conversation', 'stream-json'],+ // `agy --help` lists the ACP server from 1.5.6, the release that steers a+ // running turn when another prompt arrives.+ validateHelpKeywords: ['Agent Client Protocol'],validatePattern:/^(?:(?:agy|antigravity(?: cli)?) (?:version )?)?v?\d+\.\d+\.\d+(?:-[\dA-Z.-]+)?(?:\+[\dA-Z.-]+)?$/i,},diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.antigravity.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.antigravity.test.tsindex b5852d092f5..ba8ff380389 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.antigravity.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.antigravity.test.ts@@ -1,254 +1,64 @@-import type * as childProcess from 'node:child_process';-import { EventEmitter } from 'node:events';-import { mkdtemp, readFile, rm } from 'node:fs/promises';-import type * as os from 'node:os';-import { tmpdir } from 'node:os';-import path from 'node:path';-import { PassThrough } from 'node:stream';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import * as resolveCliCommand from './resolveCliCommand';--const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];-let nextFakeProc: any = null;--vi.mock('node:child_process', async () => {- const actual = await vi.importActual<typeof childProcess>('node:child_process');- return {- ...actual,- spawn: vi.fn((command: string, args: string[], options: any) => {- spawnCalls.push({ args, command, options });- return nextFakeProc;- }),- };+import type * as AntigravityAcpSessionModule from './antigravityAcpSession';+import { spawnAgent } from './spawnAgent';++const { sessions } = vi.hoisted(() => ({ sessions: [] as any[] }));++vi.mock('./antigravityAcpSession', async (importOriginal) => {+ const actual = await importOriginal<typeof AntigravityAcpSessionModule>();+ class FakeAntigravityAcpSession {+ nativeId: string | undefined;+ steer = vi.fn(() => true);+ constructor(readonly options: any) {+ sessions.push(this);+ }+ get sessionId() {+ return this.nativeId;+ }+ close() {}+ interrupt() {}+ async run() {+ this.nativeId = 'agy-session-1';+ }+ }+ return { ...actual, AntigravityAcpSession: FakeAntigravityAcpSession };});-vi.mock('node:os', async () => {- const actual = await vi.importActual<typeof os>('node:os');- return { ...actual, platform: vi.fn(() => 'linux') };-});--vi.mock('./resolveCliCommand', async () => {- const actual = await vi.importActual<typeof resolveCliCommand>('./resolveCliCommand');- return { ...actual, detectHeterogeneousCliCommand: vi.fn() };-});--/** A child that replays `stdoutChunks` once started, then exits cleanly. */-const createFakeProc = ({ stdoutChunks }: { stdoutChunks: string[] }) => {- const proc = new EventEmitter() as any;- const stdout = new PassThrough();- const stderr = new PassThrough();- const stdinWrites: string[] = [];- proc.stdout = stdout;- proc.stderr = stderr;- proc.stdin = {- end: vi.fn(),- once: vi.fn(),- write: vi.fn((chunk: string, cb?: () => void) => {- stdinWrites.push(chunk);- cb?.();- return true;- }),- };- proc.kill = vi.fn();- proc.killed = false;- proc.pid = 12_345;-- const start = () => {- setImmediate(() => {- for (const c of stdoutChunks) stdout.write(c);- stdout.end();- stderr.end();- proc.emit('exit', 0, null);- });- };-- return { proc, start, stdinWrites };-};-describe('spawnAgent β Antigravity', () => {beforeEach(() => {- spawnCalls.length = 0;- nextFakeProc = null;- vi.mocked(resolveCliCommand.detectHeterogeneousCliCommand).mockResolvedValue({- available: true,- path: 'agy',- });+ sessions.length = 0;});- it('spawns Antigravity, streams native events and preserves the resumed conversation', async () => {- const fake = createFakeProc({- stdoutChunks: [- JSON.stringify({ event: 'init', conversation_id: 'agy-session', init: {} }) + '\n',- JSON.stringify({- event: 'step_update',- step_update: {- conversation_id: 'agy-session',- step_index: 8,- step_type: 'agent_response',- state: 'DONE',- text_delta: 'continued',- },- }) + '\n',- JSON.stringify({- event: 'result',- result: { conversation_id: 'agy-session', status: 'SUCCESS', response: 'continued' },- }) + '\n',- ],- });- nextFakeProc = fake.proc;- const { spawnAgent } = await import('./spawnAgent');+ it('runs over ACP and steers follow-ups into the session', async () => {const handle = await spawnAgent({agentType: 'antigravity',- operationId: 'op-agy',- prompt: 'continue',- resumeSessionId: 'agy-session',+ command: 'agy',+ cwd: process.cwd(),+ env: { LOBEHUB_CONNECT_SERVICE: '1', SSH_CONNECTION: '1 2 3 4' },+ extraArgs: ['--model', 'gemini-4-neon-xhigh'],+ operationId: 'op-1',+ prompt: 'hello',+ resumeSessionId: 'agy-session-0',});- fake.start();- const events = [];- for await (const event of handle.events) events.push(event);- await handle.exit;- expect(spawnCalls[0].command).toBe('agy');- expect(spawnCalls[0].options.shell).not.toBe(true);- expect(spawnCalls[0].args).toEqual([- '--input-format',- 'stream-json',- '--output-format',- 'stream-json',- '--dangerously-skip-permissions',- '--settings',- '{"agentMode":"","allowNonWorkspaceAccess":true,"enableTerminalSandbox":false}',- '--conversation',- 'agy-session',- ]);- expect(JSON.parse(fake.stdinWrites[0])).toEqual({- event: 'user',- message: { content: 'continue' },- });- expect(fake.proc.stdin.end).toHaveBeenCalled();- expect(- events.filter((event) => event.type === 'stream_chunk' && event.data.chunkType === 'text'),- ).toHaveLength(1);- expect(events.some((event) => event.type === 'error')).toBe(false);- });- it('steers a follow-up with an image without closing the live session', async ({- onTestFinished,- }) => {- const fake = createFakeProc({- stdoutChunks: [- JSON.stringify({ event: 'init', conversation_id: 'agy-live', init: {} }) + '\n',- JSON.stringify({- event: 'step_update',- step_update: {- conversation_id: 'agy-live',- state: 'DONE',- step_index: 0,- step_type: 'user_input',- },- }) + '\n',- JSON.stringify({- event: 'step_update',- step_update: {- conversation_id: 'agy-live',- state: 'DONE',- step_index: 1,- step_type: 'agent_response',- text_delta: 'first',- },- }) + '\n',- JSON.stringify({- event: 'result',- result: {- conversation_id: 'agy-live',- num_turns: 1,- response: 'first',- status: 'SUCCESS',- },- }) + '\n',- JSON.stringify({- event: 'step_update',- step_update: {- conversation_id: 'agy-live',- state: 'DONE',- step_index: 2,- step_type: 'user_input',- },- }) + '\n',- JSON.stringify({- event: 'step_update',- step_update: {- conversation_id: 'agy-live',- state: 'DONE',- step_index: 3,- step_type: 'agent_response',- text_delta: 'steered',- },- }) + '\n',- JSON.stringify({- event: 'result',- result: {- conversation_id: 'agy-live',- num_turns: 2,- response: 'steered',- status: 'SUCCESS',- },- }) + '\n',- ],- });- nextFakeProc = fake.proc;- const { spawnAgent } = await import('./spawnAgent');- const cacheDir = await mkdtemp(path.join(tmpdir(), 'agy-steer-test-'));- onTestFinished(() => rm(cacheDir, { force: true, recursive: true }));- const image = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ', 'base64');- const handle = await spawnAgent({- agentType: 'antigravity',- inputOptions: { cacheDir },- liveInput: true,- operationId: 'op-agy-live',- prompt: 'initial',+ const [session] = sessions;+ expect(session.options).toMatchObject({+ args: ['--model', 'gemini-4-neon-xhigh'],+ commandPath: 'agy',+ prompt: [{ text: 'hello', type: 'text' }],+ resumeSessionId: 'agy-session-0',});+ // A Connect service must not hand agy an inherited SSH session.+ expect(session.options.env.SSH_CONNECTION).toBeUndefined();+ expect(handle.supportsSteerImageAttachments).toBe(true);- expect(handle.sendUserMessage).toBeDefined();- expect(handle.supportsSteerImages).not.toBe(false);- expect(fake.proc.stdin.end).not.toHaveBeenCalled();+ await expect(handle.sendUserMessage!('no id')).resolves.toBe(false);+ await expect(handle.sendUserMessage!('follow up', { uuid: 'msg-1' })).resolves.toBe(true);+ expect(session.steer).toHaveBeenCalledWith([{ text: 'follow up', type: 'text' }], 'msg-1');- await expect(- handle.sendUserMessage!(- [- { text: 'follow up', type: 'text' },- {- source: { data: image.toString('base64'), mediaType: 'image/png', type: 'base64' },- type: 'image',- },- ],- { uuid: 'steer-1' },- ),- ).resolves.toBe(true);- const {- event,- message: { content },- } = JSON.parse(fake.stdinWrites[1]);- expect(event).toBe('user');- expect(content).toContain('follow up');- const filePath = JSON.parse(content.match(/^- (".+")$/m)![1]);- expect(await readFile(filePath)).toEqual(image);-- fake.start();- const events = [];- for await (const event of handle.events) events.push(event);await handle.exit;-- expect(- events.some(- (event) =>- event.type === 'step_complete' &&- event.data.phase === 'user_message' &&- event.data.uuid === 'steer-1',- ),- ).toBe(true);- expect(events.some((event) => event.type === 'agent_runtime_end')).toBe(true);- expect(fake.proc.stdin.end).toHaveBeenCalled();+ // Read lazily: agy names the session only once it is set up.+ expect(handle.sessionId).toBe('agy-session-1');});});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex dbb72a227f7..3a4948e83e9 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -7,7 +7,6 @@ import type { CodexCollaborationMode, HeteroPermissionMode } from '@lobechat/typimport { isHeteroPermissionMode } from '@lobechat/types';import { spawnManaged } from '@lobechat/utils/managedProcess';-import { AntigravityAdapter } from '../adapters/antigravity';import { ClaudeCodeAdapter } from '../adapters/claudeCode';import type { AskUserBridge } from '../askUser/AskUserBridge';import {@@ -20,6 +19,7 @@ import {} from '../claudeCodePermission';import { resolveHeterogeneousAgentCommand } from '../config';import {+ spawnAntigravityAcpAgent,spawnCopilotAcpAgent,spawnCursorAcpAgent,spawnDevinAcpAgent,@@ -28,8 +28,6 @@ import {spawnTraeAcpAgent,} from './acpSpawnAgent';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';-import { buildAntigravityArgs } from './antigravity';-import { AntigravityLiveInput, resolveAntigravityLiveRuntimeEnd } from './antigravityLiveInput';import {type ClaudeCodeControlRequest,type ClaudeCodeControlRequestHandle,@@ -186,9 +184,11 @@ export interface SpawnAgentHandle {request: ClaudeCodeControlRequest,) => ClaudeCodeControlRequestHandle | undefined;/**- * (Claude Code `liveInput`, native Codex) Deliver a user message into the- * running session; Claude Code reads it at its next tool boundary, or starts- * a turn for it when idle; Codex adds it to the active turn (`turn/steer`).+ * (Claude Code `liveInput`, native Codex, Antigravity) Deliver a user message+ * into the running session; Claude Code reads it at its next tool boundary,+ * or starts a turn for it when idle; Codex adds it to the active turn+ * (`turn/steer`); Antigravity takes it into the running turn (another ACP+ * `session/prompt`).* Resolves false once the session takes no input β the caller then runs the* message as a new turn instead.*/@@ -212,8 +212,6 @@ export interface SpawnAgentHandle {stderr: NodeJS.ReadableStream;/** The live session accepts uploaded images with their follow-up message. */supportsSteerImageAttachments?: true;- /** Whether the live session accepts image blocks on follow-up steer messages (defaults to true). */- supportsSteerImages?: boolean;}/**@@ -426,9 +424,6 @@ export const buildQoderArgs = ({const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {switch (params.agentType) {- case 'antigravity': {- return buildAntigravityArgs(params);- }case 'amp': {return buildAmpArgs(params);}@@ -512,6 +507,9 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentconst command = resolveHeterogeneousAgentCommand(options.agentType, options.command);const cwd = options.cwd || process.cwd();assertSpawnableWorkingDirectory(cwd);+ if (options.agentType === 'antigravity') {+ return spawnAntigravityAcpAgent(options, command, cwd);+ }if (options.agentType === 'copilot') {return spawnCopilotAcpAgent(options, command, cwd);}@@ -576,7 +574,6 @@ const spawnCliAgent = async (codexJwtFile: CodexJwtFile | undefined,): Promise<SpawnAgentHandle> => {const claudeLiveInput = options.agentType === 'claude-code' && options.liveInput === true;- const antigravityLiveInput = options.agentType === 'antigravity' && options.liveInput === true;// Prompts need someone to answer them: the live stdin and a card bridge.// Without, a picked mode still applies and fails closed (never bypass).const permissionMode = options.agentType === 'claude-code' ? options.permissionMode : undefined;@@ -628,9 +625,6 @@ const spawnCliAgent = async (const claudeLive =claudeLiveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : undefined;- const antigravityLive =- antigravityLiveInput && proc.stdin ? new AntigravityLiveInput(proc.stdin) : undefined;- const live = claudeLive ?? antigravityLive;const pipeline = new AgentStreamPipeline({// A live session can run more turns after its first `result`, so the@@ -640,12 +634,7 @@ const spawnCliAgent = async (runtimeEndStrategy: 'on-transport-close',signalBackgroundTaskCompletion: true,})- : antigravityLive- ? new AntigravityAdapter({- runtimeEndStrategy: 'on-transport-close',- takeNextSteerUuid: () => antigravityLive.takeSteerUuid(),- })- : undefined,+ : undefined,agentType: options.agentType,cwd,env: childEnv,@@ -724,8 +713,8 @@ const spawnCliAgent = async (wake();});}- if (live) {- live.send(inputPlan.stdin);+ if (claudeLive) {+ claudeLive.send(inputPlan.stdin);} else if (proc.stdin) {proc.stdin.write(inputPlan.stdin, () => {proc.stdin?.end();@@ -762,7 +751,7 @@ const spawnCliAgent = async (pipelineQueue = pipelineQueue.then(async () => {try {const events = await pipeline.flush();- live?.finish();+ claudeLive?.finish();const { code, signal } = await exit;if (code === 0 && !killedByUs) events.push(...pipeline.validateCompletion());sawErrorEvent ||= events.some((event) => event.type === 'error');@@ -774,14 +763,7 @@ const spawnCliAgent = async (sawError: sawErrorEvent,signal,})- : antigravityLive- ? resolveAntigravityLiveRuntimeEnd(antigravityLive.lastTurn, {- code,- killedByHost: killedByUs,- sawError: sawErrorEvent,- signal,- })- : undefined;+ : undefined;if (liveEnd) for (const event of pipeline.completeRuntime(liveEnd)) queue.push(event);// Kimi Code reports usage only via its on-disk session wire log, so// it can only be collected now that the process has exited. The hook@@ -809,7 +791,7 @@ const spawnCliAgent = async (// raw dump is diagnostic-only; never let it disrupt the run}}- live?.observe(chunk);+ claudeLive?.observe(chunk);enqueuePush(chunk);});stdout.on('end', enqueueFlush);@@ -873,16 +855,9 @@ const spawnCliAgent = async (// Uploaded images go in as image blocks of the same stream-json message.supportsSteerImageAttachments: true as const,}),- ...(antigravityLive && {- sendUserMessage: async (prompt: AgentPromptInput, sendOptions?: { uuid?: string }) => {- if (!antigravityLive.isOpen) return false;- const plan = await buildAgentInput('antigravity', prompt, options.inputOptions);- return antigravityLive.send(plan.stdin, sendOptions?.uuid);- },- }),kill: (signal: NodeJS.Signals = 'SIGINT') => {killedByUs = true;- live?.close();+ claudeLive?.close();killProcessTree(proc, signal, detached);},pid: proc.pid,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.antigravity.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.antigravity.test.tsindex 472f16fcbf8..3da8308ad27 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.antigravity.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.antigravity.test.ts@@ -1,4 +1,4 @@-/** Antigravity stream β tool persistence, final reply and resumable session identity. */+/** Antigravity ACP stream β tool persistence, final reply and resumable session identity. */import type { AgentEventAdapter } from '@lobechat/heterogeneous-agents';import { createAdapter } from '@lobechat/heterogeneous-agents';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -185,38 +185,34 @@ describe('heterogeneousAgentExecutor β Antigravity', () => {};it('persists native Antigravity tools, final reply and resumable conversation identity', async () => {+ // `agy acp` session updates as recorded from agy 1.5.15.const { store } = await runWithEvents([- { event: 'init', conversation_id: 'agy-conversation', init: { cwd: '/project' } },+ { model: 'gemini-4-neon-high', sessionId: 'agy-conversation', type: 'antigravity_session' },{- event: 'step_update',- step_update: {- conversation_id: 'agy-conversation',- step_index: 1,- state: 'DONE',- step_type: 'tool',- tool_info: { name: 'read_file', parameters: { path: 'hello.txt' }, output: 'hello' },- },+ kind: 'read',+ name: 'read_file',+ rawInput: { Path: 'hello.txt' },+ sessionUpdate: 'tool_call',+ status: 'in_progress',+ title: 'File hello.txt',+ toolCallId: 'call_1',},{- event: 'step_update',- step_update: {- conversation_id: 'agy-conversation',- step_index: 2,- state: 'DONE',- step_type: 'agent_response',- text_delta: 'The file says hello.',- usage: { input_tokens: 10, output_tokens: 5 },- },+ content: [{ content: { text: 'hello', type: 'text' }, type: 'content' }],+ name: 'read_file',+ sessionUpdate: 'tool_call_update',+ status: 'completed',+ toolCallId: 'call_1',},{- event: 'result',- result: {- conversation_id: 'agy-conversation',- status: 'SUCCESS',- response: 'The file says hello.',- usage: { input_tokens: 100, output_tokens: 50 },- },+ content: { text: 'The file says hello.', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ },+ {+ stopReason: 'end_turn',+ type: 'antigravity_prompt_completed',+ usage: { cachedReadTokens: 0, inputTokens: 10, outputTokens: 5, thoughtTokens: 0 },},],{ params: { heterogeneousProvider: { command: 'agy', type: 'antigravity' } } },@@ -225,8 +221,12 @@ describe('heterogeneousAgentExecutor β Antigravity', () => {const tool = mockCreateMessage.mock.calls.find(([p]) => p.role === 'tool')?.[0];expect(tool).toMatchObject({parentId: 'ast-initial',- plugin: { apiName: 'read_file', identifier: 'antigravity' },- tool_call_id: 'agy_agy-conversation_1',+ plugin: {+ apiName: 'read_file',+ arguments: '{"Path":"hello.txt"}',+ identifier: 'antigravity',+ },+ tool_call_id: 'call_1',});expect(mockUpdateToolMessage).toHaveBeenCalledWith(tool.id,