🤯 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: support Antigravity local agents (#22008)
Coooolfane00695bd1f4e
diff --git a/apps/cli/src/commands/hetero/buildExtraArgs.ts b/apps/cli/src/commands/hetero/buildExtraArgs.tsnew file mode 100644index 00000000000..394e613af2a--- /dev/null+++ b/apps/cli/src/commands/hetero/buildExtraArgs.ts@@ -0,0 +1,56 @@+import { toCodexServiceTier } from '@lobechat/types';++export interface HeteroCliArgumentOptions {+ agentArg?: string[];+ effort?: string;+ /** Amp agent mode, forwarded as the native `--mode` flag. */+ mode?: string;+ model?: string;+ /**+ * Speed mode selection (Codex only). Translated into the native+ * `service_tier` config; `fast` requests the Fast (priority) tier.+ */+ speed?: string;+ type: string;+}++const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';+const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';++export const buildExtraArgs = (options: HeteroCliArgumentOptions): string[] | undefined => {+ const modelArg = options.model ? ['--model', options.model] : [];+ const selectorArgs =+ options.type === 'amp'+ ? options.mode+ ? ['--mode', options.mode]+ : []+ : options.type === 'droid' || options.type === 'trae'+ ? []+ : options.type === 'codex'+ ? [+ ...modelArg,+ ...(options.effort+ ? ['-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${options.effort}"`]+ : []),+ ...(options.speed+ ? ['-c', `${CODEX_SERVICE_TIER_CONFIG_KEY}="${toCodexServiceTier(options.speed)}"`]+ : []),+ ]+ : options.type === 'antigravity' ||+ options.type === 'claude-code' ||+ options.type === 'codebuddy' ||+ options.type === 'grok-build'+ ? [...modelArg, ...(options.effort ? ['--effort', options.effort] : [])]+ : options.type === 'cursor' ||+ options.type === 'devin' ||+ options.type === 'kimi-code' ||+ options.type === 'opencode' ||+ options.type === 'pi'+ ? modelArg+ : options.type === 'copilot' || options.type === 'qoder'+ ? [...modelArg, ...(options.effort ? ['--reasoning-effort', options.effort] : [])]+ : [];+ const extraArgs = [...(options.agentArg ?? []), ...selectorArgs];++ return extraArgs.length > 0 ? extraArgs : undefined;+};diff --git a/apps/cli/src/commands/hetero.pi.test.ts b/apps/cli/src/commands/hetero/index.pi.test.tssimilarity index 96%rename from apps/cli/src/commands/hetero.pi.test.tsrename to apps/cli/src/commands/hetero/index.pi.test.tsindex f5be27a7aac..34409b266cd 100644--- a/apps/cli/src/commands/hetero.pi.test.ts+++ b/apps/cli/src/commands/hetero/index.pi.test.ts@@ -8,7 +8,7 @@ import type * as HeteroRpc from '@lobechat/heterogeneous-agents/rpc';import { Command } from 'commander';import { afterEach, describe, expect, it, vi } from 'vitest';-import { registerHeteroCommand } from './hetero';+import { registerHeteroCommand } from './index';const { createHandle, finish, ingest } = vi.hoisted(() => ({createHandle: vi.fn(),@@ -23,12 +23,12 @@ vi.mock('@lobechat/heterogeneous-agents/rpc', async (importOriginal) => ({vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({resolveHeteroSpawnCommand: async () => ({ command: 'pi' }),}));-vi.mock('../api/client', () => ({+vi.mock('../../api/client', () => ({getTrpcClient: async () => ({aiAgent: { heteroFinish: { mutate: finish }, heteroIngest: { mutate: ingest } },}),}));-vi.mock('../utils/OperationTokenRenewal', () => ({+vi.mock('../../utils/OperationTokenRenewal', () => ({createOperationTokenRenewal: () => ({ active: true, stop: vi.fn() }),}));diff --git a/apps/cli/src/commands/hetero.startup.test.ts b/apps/cli/src/commands/hetero/index.startup.test.tssimilarity index 97%rename from apps/cli/src/commands/hetero.startup.test.tsrename to apps/cli/src/commands/hetero/index.startup.test.tsindex e23c0ef81b3..8e910370527 100644--- a/apps/cli/src/commands/hetero.startup.test.ts+++ b/apps/cli/src/commands/hetero/index.startup.test.ts@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';import { describe, expect, it } from 'vitest';-const cliEntry = fileURLToPath(new URL('../index.ts', import.meta.url));+const cliEntry = fileURLToPath(new URL('../../index.ts', import.meta.url));describe.skipIf(process.platform === 'win32')('Pi startup cancellation across real processes',diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero/index.test.tssimilarity index 98%rename from apps/cli/src/commands/hetero.test.tsrename to apps/cli/src/commands/hetero/index.test.tsindex 283edb13e8f..8e7ed771c61 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero/index.test.ts@@ -11,8 +11,8 @@ import type * as HeteroSpawn from '@lobechat/heterogeneous-agents/spawn';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';-import { registerHeteroCommand } from './hetero';+import { HeteroTraceRecorder } from '../../utils/HeteroTraceRecorder';+import { registerHeteroCommand } from './index';const {mockCreateCodexAgentHandle,@@ -51,12 +51,12 @@ vi.mock('@lobechat/heterogeneous-agents/rpc', async (importOriginal) => ({createPiRpcAgentHandle: mockCreatePiRpcAgentHandle,}));-vi.mock('../api/client', () => ({+vi.mock('../../api/client', () => ({getTrpcClient: mockGetTrpcClient,}));const { mockRenewalStop } = vi.hoisted(() => ({ mockRenewalStop: vi.fn() }));-vi.mock('../utils/OperationTokenRenewal', () => ({+vi.mock('../../utils/OperationTokenRenewal', () => ({createOperationTokenRenewal: () => ({ active: true, stop: mockRenewalStop }),}));@@ -897,49 +897,29 @@ describe('hetero exec command', () => {expect(mockSpawnAgent.mock.calls[0][0].includePartialMessages).toBe(false);});- it('passes Claude Code --model and --effort through as spawnAgent extraArgs', async () => {- mockSpawnAgent.mockReturnValue(createFakeHandle());-- await runCmd([- 'hetero',- 'exec',- '--type',- 'claude-code',- '--prompt',- 'hi',- '--model',- 'opus',- '--effort',- 'high',- ]);-- expect(mockSpawnAgent).toHaveBeenCalledTimes(1);- expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({- extraArgs: ['--model', 'opus', '--effort', 'high'],- });- });-- it('passes CodeBuddy --model and --effort through as spawnAgent extraArgs', async () => {+ it.each([+ ['antigravity', 'agy'],+ ['claude-code', 'claude'],+ ['codebuddy', 'codebuddy'],+ ])('passes %s model and effort through the CLI wrapper', async (type, command) => {mockSpawnAgent.mockReturnValue(createFakeHandle());-await runCmd(['hetero','exec','--type',- 'codebuddy',+ type,'--prompt','hi','--model',- 'gpt-5.4',+ 'custom-model','--effort',- 'high',+ 'max',]);-- expect(mockResolveHeteroSpawnCommand).toHaveBeenCalledWith('codebuddy', undefined);+ expect(mockResolveHeteroSpawnCommand).toHaveBeenCalledWith(type, undefined);expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({- agentType: 'codebuddy',- command: 'codebuddy',- extraArgs: ['--model', 'gpt-5.4', '--effort', 'high'],+ agentType: type,+ command,+ extraArgs: ['--model', 'custom-model', '--effort', 'max'],});});diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero/index.tssimilarity index 95%rename from apps/cli/src/commands/hetero.tsrename to apps/cli/src/commands/hetero/index.tsindex 64692e5007c..056b91b999c 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero/index.ts@@ -36,20 +36,21 @@ import {spawnAgent,spawnDshAcpSession,} from '@lobechat/heterogeneous-agents/spawn';-import { toCodexServiceTier } from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import type { Command } from 'commander';-import { getTrpcClient } from '../api/client';-import { cliVersion } from '../pkg';-import { CoalescingBatchIngester } from '../utils/CoalescingBatchIngester';-import { withHeteroSteer } from '../utils/heteroSteer';-import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';-import { log } from '../utils/logger';-import { createOperationHeartbeat } from '../utils/OperationHeartbeat';-import { createOperationTokenRenewal } from '../utils/OperationTokenRenewal';-import { createLocalTraceStore } from '../utils/traceStore';-import { TrpcIngestSink } from '../utils/TrpcIngestSink';+import { getTrpcClient } from '../../api/client';+import { cliVersion } from '../../pkg';+import { CoalescingBatchIngester } from '../../utils/CoalescingBatchIngester';+import { withHeteroSteer } from '../../utils/heteroSteer';+import { HeteroTraceRecorder } from '../../utils/HeteroTraceRecorder';+import { log } from '../../utils/logger';+import { createOperationHeartbeat } from '../../utils/OperationHeartbeat';+import { createOperationTokenRenewal } from '../../utils/OperationTokenRenewal';+import { createLocalTraceStore } from '../../utils/traceStore';+import { TrpcIngestSink } from '../../utils/TrpcIngestSink';+import type { HeteroCliArgumentOptions } from './buildExtraArgs';+import { buildExtraArgs } from './buildExtraArgs';const DSH_AGENT_TYPE = 'deepseek-harness';export const SUPPORTED_AGENT_TYPES = new Set<string>([@@ -90,8 +91,6 @@ const SUPPORTED_AGENT_TITLES = [const SUPPORTED_AGENT_COMMANDS = HETEROGENEOUS_AGENT_CONFIGS.map(({ defaultCommand }) => `\`${defaultCommand}\``,).join(', ');-const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';-const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';/*** Runtime factories for `lh hetero exec`. Pi uses RPC; other agents fall* through to the generic one-shot `spawnAgent`.@@ -200,18 +199,13 @@ const isMissingGrokResumeSession = (data: Record<string, unknown> | undefined):return details.method === 'session/load' && isRecord(rpcData) && rpcData.code === 'FS_NOT_FOUND';};-interface ExecOptions {- agentArg?: string[];+interface ExecOptions extends HeteroCliArgumentOptions {/** Explicit device protocol capability; unsupported native options fail closed. */codexAppServer?: boolean;command?: string;cwd?: string;- effort?: string;image?: string[];inputJson?: string;- /** Amp agent mode, forwarded as the native `--mode` flag. */- mode?: string;- model?: string;operationId?: string;prompt?: string;/**@@ -229,11 +223,6 @@ interface ExecOptions {*/render?: 'jsonl' | 'none';resume?: string;- /**- * Speed mode selection (Codex only). Translated into the native- * `service_tier` config; `fast` requests the Fast (priority) tier.- */- speed?: string;/*** Server topic id. When set, enables server-ingest mode: events are* batch-POSTed to `aiAgent.heteroIngest` in addition to (or instead of)@@ -241,51 +230,11 @@ interface ExecOptions {* server-allocated operation id.*/topic?: string;- type: string;}const collectImage = (value: string, previous: string[] = []): string[] => [...previous, value];const collectAgentArg = (value: string, previous: string[] = []): string[] => [...previous, value];-const buildExtraArgs = (- options: Pick<ExecOptions, 'agentArg' | 'effort' | 'mode' | 'model' | 'speed' | 'type'>,-): string[] | undefined => {- const modelArg = options.model ? ['--model', options.model] : [];- const selectorArgs =- options.type === 'amp'- ? options.mode- ? ['--mode', options.mode]- : []- : options.type === 'droid' || options.type === 'trae'- ? []- : options.type === 'codex'- ? [- ...modelArg,- ...(options.effort- ? ['-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${options.effort}"`]- : []),- ...(options.speed- ? ['-c', `${CODEX_SERVICE_TIER_CONFIG_KEY}="${toCodexServiceTier(options.speed)}"`]- : []),- ]- : options.type === 'claude-code' ||- options.type === 'codebuddy' ||- options.type === 'grok-build'- ? [...modelArg, ...(options.effort ? ['--effort', options.effort] : [])]- : options.type === 'cursor' ||- options.type === 'devin' ||- options.type === 'kimi-code' ||- options.type === 'opencode' ||- options.type === 'pi'- ? modelArg- : options.type === 'copilot' || options.type === 'qoder'- ? [...modelArg, ...(options.effort ? ['--reasoning-effort', options.effort] : [])]- : [];- const extraArgs = [...(options.agentArg ?? []), ...selectorArgs];-- return extraArgs.length > 0 ? extraArgs : undefined;-};-const readStdin = async (): Promise<string> => {const chunks: Buffer[] = [];for await (const chunk of process.stdin) {diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 6eec4b72795..e0ca9ca0fde 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -1,5 +1,8 @@+import type { AntigravityQuotaParams } from '@lobechat/heterogeneous-agents/quota';+import type { ClaudeCodeAccountProfiles } from '@/modules/heterogeneousAgent/claudeCodeAccounts';import type { RemoteServerAuth } from '@/modules/heterogeneousAgent/fileStorePort';+import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';import type HeterogeneousAgentImplementation from './HeterogeneousAgentImpl';import type { LhHeteroExecCancellationResult } from './HeterogeneousAgentImpl';@@ -103,6 +106,22 @@ export default class HeterogeneousAgentCtr extends ControllerModule {return (await this.getImplementation()).listModels(...args);}+ @IpcMethod()+ async getAntigravityQuota(params: AntigravityQuotaParams = {}) {+ const [{ getAntigravityQuota }, { buildInheritedSpawnEnv }] = await Promise.all([+ import('@lobechat/device-control'),+ import('./HeterogeneousAgentImpl'),+ ]);+ return getAntigravityQuota({+ ...params,+ env: {+ ...buildInheritedSpawnEnv(),+ ...buildProxyEnv(this.app.storeManager.get('networkProxy')),+ ...params.env,+ },+ });+ }+@IpcMethod()async getCodexQuota(...args: Parameters<Implementation['getCodexQuota']>) {return (await this.getImplementation()).getCodexQuota(...args);diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.tsindex 269187f2c3b..b88b06e1a7a 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts@@ -6,12 +6,19 @@ import type { RemoteServerAuth } from '@/modules/heterogeneousAgent/fileStorePorimport HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';const implementationMocks = vi.hoisted(() => ({+ quota: vi.fn(async (..._args: unknown[]) => ({ status: 'ok', groups: [] })),afterAppReady: vi.fn(),constructor: vi.fn<(app: App, remoteServerAuth?: RemoteServerAuth) => void>(),startSession: vi.fn(async (..._args: unknown[]) => ({ sessionId: 'session-1' })),}));+vi.mock('@lobechat/device-control', () => ({ getAntigravityQuota: implementationMocks.quota }));+vi.mock('@/modules/networkProxy/envBuilder', () => ({+ buildProxyEnv: () => ({ HTTPS_PROXY: 'desktop-proxy' }),+}));+vi.mock('../HeterogeneousAgentImpl', () => ({+ buildInheritedSpawnEnv: () => ({ PATH: '/base/bin' }),default: class MockHeterogeneousAgentImplementation {constructor(app: App, remoteServerAuth?: RemoteServerAuth) {implementationMocks.constructor(app, remoteServerAuth);@@ -32,6 +39,22 @@ describe('HeterogeneousAgentCtr lazy implementation', () => {vi.clearAllMocks();});+ it('queries Antigravity quota with the Desktop proxy and explicit profile overrides', async () => {+ const app = { storeManager: { get: vi.fn() } } as unknown as App;+ const controller = new HeterogeneousAgentCtr(app);+ await controller.getAntigravityQuota({+ command: '/custom/agy',+ force: true,+ env: { HTTPS_PROXY: 'profile-proxy' },+ });+ expect(implementationMocks.quota).toHaveBeenCalledWith({+ command: '/custom/agy',+ force: true,+ env: { PATH: '/base/bin', HTTPS_PROXY: 'profile-proxy' },+ });+ expect(implementationMocks.constructor).not.toHaveBeenCalled();+ });+it('defers the heavy implementation and initializes it exactly once on first use', async () => {const app = {} as App;const controller = new HeterogeneousAgentCtr(app);diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.tsindex 5e370e88ed1..789cb70bbb2 100644--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts@@ -225,6 +225,12 @@ export const aiderBinary: BinarySpec = defineCommandBinary('aider', {* All CLI agent binaries*/export const heterogeneousCliAgentBinaries = {+ 'antigravity': {+ description: 'Antigravity CLI - Google agentic coding CLI',+ detect: () => detectHeterogeneousCliCommand('antigravity', 'agy'),+ name: 'agy',+ priority: 8,+ },'amp': ampBinary,'claude-code': claudeCodeBinary,'codebuddy': codeBuddyBinary,diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.test.tsnew file mode 100644index 00000000000..51ac6908267--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.test.ts@@ -0,0 +1,32 @@+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 () => {+ 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',+ '--conversation',+ 'conv-1',+ '--effort',+ 'high',+ ]);+ expect(JSON.parse(plan.stdinPayload!)).toEqual({+ event: 'user',+ message: { content: 'hello\nworld' },+ });+ });+});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.tsnew file mode 100644index 00000000000..eb19652f99d--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/antigravity.ts@@ -0,0 +1,13 @@+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 }),+ stdinPayload: input.stdin,+ };+ },+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.tsindex 4d80a79d3ca..514a472a9fb 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts@@ -1,6 +1,7 @@import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import { ampDriver } from './drivers/amp';+import { antigravityDriver } from './drivers/antigravity';import { claudeCodeDriver } from './drivers/claudeCode';import { codeBuddyDriver } from './drivers/codeBuddy';import { codexDriver } from './drivers/codex';@@ -17,6 +18,7 @@ import { traeDriver } from './drivers/trae';import type { HeterogeneousAgentDriver } from './types';const heterogeneousAgentDrivers = {+ 'antigravity': antigravityDriver,'amp': ampDriver,'claude-code': claudeCodeDriver,'codebuddy': codeBuddyDriver,diff --git a/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.tsindex 2d933010e86..f09787a0208 100644--- a/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/project.integration.test.ts@@ -2,7 +2,7 @@import type { LobeChatDatabase } from '@lobechat/database';import { agents, knowledgeBases, workspaces } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { projectRouter } from '../../project';import { taskRouter } from '../../task';@@ -20,9 +20,13 @@ describe('Project Router Integration', () => {let userId: string;let caller: ReturnType<typeof projectRouter.createCaller>;- beforeEach(async () => {+ // Initial database migrations can exceed the default hook timeout on CI.+ beforeAll(async () => {serverDB = await getTestDB();testDB = serverDB;+ }, 60_000);++ beforeEach(async () => {userId = await createTestUser(serverDB);caller = projectRouter.createCaller(createTestContext(userId));});diff --git a/apps/server/src/routers/lambda/device/agents.ts b/apps/server/src/routers/lambda/device/agents.tsindex dd721c5ff8b..0cfac6681c2 100644--- a/apps/server/src/routers/lambda/device/agents.ts+++ b/apps/server/src/routers/lambda/device/agents.ts@@ -103,6 +103,23 @@ export const agentsRouter = router({}},),+ getAntigravityQuota: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ command: z.string().optional(),+ env: z.record(z.string(), z.string()).optional(),+ force: z.boolean().optional(),+ }),+ )+ .query(+ async ({ ctx, input }) =>+ (await deviceGateway.antigravityQuota({+ ...input,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ })) ?? null,+ ),/*** Claude Code subscription quota sampled by the device with its own local* credentials, so web clients can show live quota for a bound-device run.@@ -136,6 +153,7 @@ export const agentsRouter = router({deviceId: z.string(),env: z.record(z.string(), z.string()).optional(),type: z.enum([+ 'antigravity','codebuddy','codex','copilot',diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.tsindex 0460671f1dc..6e64b1c3d35 100644--- a/apps/server/src/routers/lambda/device/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts@@ -19,6 +19,13 @@ describe('deviceRouter procedures', () => {expect(procedures[name]._def.type).toBe(type);expect(procedures[name]._def.middlewares).toHaveLength(middlewares);});++ it('accepts Antigravity model discovery requests from connected devices', () => {+ const input = { deviceId: 'device-agy', type: 'antigravity' };+ const schema = procedures.listHeterogeneousAgentModels._def.inputs.at(-1);+ expect(schema.parse(input)).toEqual(input);+ expect(schema.safeParse({ ...input, type: 'unknown-agent' }).success).toBe(false);+ });});function expected(): Array<@@ -43,6 +50,7 @@ function expected(): Array<['deleteGitBranch', 'mutation', 12],['getAgentDeviceBindings', 'query', 12],['getAgentProfile', 'query', 12],+ ['getAntigravityQuota', 'query', 12],['getAppUpdateState', 'query', 12],['getClaudeCodeQuota', 'query', 12],['getCliUpdateState', 'query', 12],diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.tsindex 42e66ecf579..4f1f5e31890 100644--- a/apps/server/src/services/deviceGateway/agents.ts+++ b/apps/server/src/services/deviceGateway/agents.ts@@ -10,6 +10,8 @@ import {} from '@lobechat/device-gateway-client';import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import type {+ AntigravityQuotaParams,+ AntigravityQuotaSnapshot,ClaudeCodeAccountRouting,ClaudeCodeQuotaSnapshot,CodexQuotaSnapshot,@@ -19,6 +21,7 @@ import type {DeviceClient,DeviceUnavailableErrorData,HeterogeneousAgentModelCatalog,+ ListHeterogeneousAgentModelsParams,} from '@lobechat/types';import debug from 'debug';@@ -68,6 +71,27 @@ export function codexQuota(});}+/** Native agy quota; relay only, without quota-history ingestion. */+export function antigravityQuota(+ getClient: DeviceClientGetter,+ params: AntigravityQuotaParams & {+ deviceId: string;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<AntigravityQuotaSnapshot>(+ getClient,+ 'getAntigravityQuota',+ { ...params, timeout: 30_000 },+ {+ command: params.command,+ env: params.env,+ force: params.force,+ },+ );+}+/** Kimi Code subscription quota sampled from the login on a remote device. */export function kimiCodeQuota(getClient: DeviceClientGetter,@@ -95,20 +119,7 @@ export async function listHeterogeneousAgentModels(deviceId: string;env?: Record<string, string>;timeout?: number;- type:- | 'codebuddy'- | 'codex'- | 'copilot'- | 'cursor'- | 'devin'- | 'deepseek-harness'- | 'droid'- | 'grok-build'- | 'kimi-code'- | 'opencode'- | 'pi'- | 'qoder'- | 'trae';+ type: ListHeterogeneousAgentModelsParams['type'];userId: string;workspaceId?: string;},diff --git a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts b/apps/server/src/services/deviceGateway/index.rpcSurface.test.tsindex 7cb6ebd24e6..35b68abfde7 100644--- a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts+++ b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts@@ -75,6 +75,22 @@ const repo = { name: 'repo', owner: 'owner' };const env = { TOKEN: 'x' };const cases: RpcCase[] = [+ {+ address: address(30_000),+ call: (g) =>+ g.antigravityQuota({+ ...base,+ command: '/bin/agy',+ env: { AGY_PROFILE: 'test' },+ force: true,+ }),+ failure: UNDEFINED,+ name: 'antigravityQuota',+ payload: {+ method: 'getAntigravityQuota',+ params: { command: '/bin/agy', env: { AGY_PROFILE: 'test' }, force: true },+ },+ },// ─── git reads ───{address: address(15_000),@@ -602,26 +618,35 @@ describe('DeviceGateway RPC surface', () => {});describe('listHeterogeneousAgentModels', () => {- const call = () =>+ const call = (type: 'antigravity' | 'codex' = 'codex') =>new DeviceGateway().listHeterogeneousAgentModels({...base,args: ['--x'],- command: 'codex',+ command: type === 'antigravity' ? 'agy' : 'codex',cwd: '/p',env,- type: 'codex',+ type,});- it('relays the catalog RPC with a 20s budget', async () => {- configureGateway();- mockClient.invokeRpc.mockResolvedValue({ data: DATA, success: true });-- await expect(call()).resolves.toEqual(DATA);- expect(mockClient.invokeRpc).toHaveBeenCalledWith(address(20_000), {- method: 'listHeterogeneousAgentModels',- params: { args: ['--x'], command: 'codex', cwd: '/p', env, type: 'codex' },- });- });+ it.each(['antigravity', 'codex'] as const)(+ 'relays the %s catalog RPC with a 20s budget',+ async (type) => {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValue({ data: DATA, success: true });++ await expect(call(type)).resolves.toEqual(DATA);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(address(20_000), {+ method: 'listHeterogeneousAgentModels',+ params: {+ args: ['--x'],+ command: type === 'antigravity' ? 'agy' : 'codex',+ cwd: '/p',+ env,+ type,+ },+ });+ },+ );it.each([['unconfigured', undefined, 'device_unavailable', 'Device gateway is not configured'],diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex fab31fda2d6..5621385fcd2 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -303,6 +303,10 @@ export class DeviceGateway {return agents.claudeCodeQuota(this.clientGetter, ...args);}+ antigravityQuota(...args: DeviceRpcArgs<typeof agents.antigravityQuota>) {+ return agents.antigravityQuota(this.clientGetter, ...args);+ }+codexQuota(...args: DeviceRpcArgs<typeof agents.codexQuota>) {return agents.codexQuota(this.clientGetter, ...args);}diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/antigravityToolPersistence.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/antigravityToolPersistence.test.tsnew file mode 100644index 00000000000..ab6c5d7d629--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/__tests__/antigravityToolPersistence.test.ts@@ -0,0 +1,138 @@+import { createAdapter, type HeterogeneousAgentEvent } from '@lobechat/heterogeneous-agents';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { __resetOperationStatesForTesting } from '../HeterogeneousPersistenceHandler';+import { createHarness } from '../HeterogeneousPersistenceHandler/testUtils';++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 },+ },+});++const createReplay = async () => {+ const adapter = createAdapter('antigravity');+ const harness = createHarness({ assistantMessageId, operationId, topicId });+ const ingestEvents = async (events: HeterogeneousAgentEvent[]) => {+ await harness.handler.ingest({+ // Snapshot each update at the transport boundary, before adapting the next one.+ events: structuredClone(events).map((event) => ({ ...event, operationId })),+ operationId,+ topicId,+ });+ };+ const ingestRaw = async (raw: unknown) => ingestEvents(adapter.adapt(raw));+ await ingestRaw({ conversation_id: 'conversation-test', event: 'init' });+ return {+ ...harness,+ adapter,+ ingestEvents,+ ingestRaw,+ tools: () => [...harness.messages.values()].filter((message) => message.role === 'tool'),+ };+};++describe('Antigravity 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' }));+ }++ 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 },+ ]);+ },+ );++ it('does not publish a parameterless pending tool in another tool batch', 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(+ 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"}',+ );+ });++ 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.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());++ 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 },+ ]);+ },+ );+});diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 3b242cbf7b6..7fe72f8d8e4 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -80,6 +80,13 @@"ampInstallGuide.menuNotification.title": "Amp CLI not found","ampInstallGuide.reason": "LobeHub could not start Amp: {{message}}","ampInstallGuide.title": "Install Amp CLI",+ "antigravityInstallGuide.actions.openDocs": "Open Install Guide",+ "antigravityInstallGuide.actions.openSystemTools": "Open System Tools",+ "antigravityInstallGuide.afterInstall": "After installing, run `agy` and sign in with your Google account, then retry your message or click Re-detect in System Tools.",+ "antigravityInstallGuide.desc": "Antigravity needs the native agy CLI with stream-json support. Follow the install guide for your operating system and make sure the `agy` command is available.",+ "antigravityInstallGuide.menuNotification.title": "Antigravity CLI not found",+ "antigravityInstallGuide.reason": "LobeHub could not start Antigravity: {{message}}",+ "antigravityInstallGuide.title": "Install Antigravity CLI","artifact.generating": "Generating","artifact.inThread": "Cannot view in subtopic, please switch to the main conversation area to open","artifact.thinking": "Thinking",@@ -276,6 +283,7 @@"connectAgent.create.thisDevice": "This device","connectAgent.create.title": "Connect Agent","connectAgent.providerDesc.amp": "Sourcegraph coding agent CLI",+ "connectAgent.providerDesc.antigravity": "Google coding agent CLI","connectAgent.providerDesc.claude-code": "Anthropic coding agent CLI","connectAgent.providerDesc.codebuddy": "Tencent coding agent CLI","connectAgent.providerDesc.codex": "OpenAI coding agent CLI",@@ -1362,6 +1370,19 @@"groupWizard.searchTemplates": "Search templates...","groupWizard.title": "Create Group","groupWizard.useTemplate": "Use Template",+ "heteroAgent.antigravityQuota.authRequired": "Run agy in a terminal to sign in, then refresh.",+ "heteroAgent.antigravityQuota.cliNotFound": "Antigravity CLI was not found on this device. Install agy, then refresh.",+ "heteroAgent.antigravityQuota.disabled": "Unavailable",+ "heteroAgent.antigravityQuota.error": "Could not query Antigravity quota. Check the device and try again.",+ "heteroAgent.antigravityQuota.fiveHour": "5 hours",+ "heteroAgent.antigravityQuota.remainingAmount": "{{amount}} remaining",+ "heteroAgent.antigravityQuota.resetUnconfirmed": "Reset time reached. Refresh to check the latest quota.",+ "heteroAgent.antigravityQuota.stale": "Showing the last query. Refresh to confirm current quota.",+ "heteroAgent.antigravityQuota.timeout": "The quota query timed out. Check the device connection and try again.",+ "heteroAgent.antigravityQuota.title": "Antigravity quota",+ "heteroAgent.antigravityQuota.tooltip": "View Antigravity model quotas",+ "heteroAgent.antigravityQuota.unknown": "Unknown",+ "heteroAgent.antigravityQuota.unsupported": "Update agy to a version that supports structured quota queries, then refresh.","heteroAgent.apiMode.agentUnsupported": "{{name}} does not support LobeHub Provider binding.","heteroAgent.apiMode.configMissing": "Provider binding requires a provider and model. Open the agent profile to configure it.","heteroAgent.apiMode.credentialUnsupported": "The provider \"{{providerId}}\" uses an authentication method this agent does not support.",@@ -1910,6 +1931,7 @@"modelSelector.model": "Model","newAgent": "Create Agent","newAmpAgent": "Add Amp",+ "newAntigravityAgent": "Add Antigravity","newClaudeCodeAgent": "Add Claude Code","newCodeBuddyAgent": "Add CodeBuddy","newCodexAgent": "Add Codex",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 7a53e63b706..95f31c7984c 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1909,6 +1909,7 @@"settingSystemTools.tools.ag.desc": "The Silver Searcher - fast code searching tool","settingSystemTools.tools.agentBrowser.desc": "Agent-browser - headless browser automation CLI for AI agents","settingSystemTools.tools.aider.desc": "Aider - AI pair programming in your terminal",+ "settingSystemTools.tools.antigravity.desc": "Antigravity CLI - Google agentic coding CLI","settingSystemTools.tools.bun.desc": "Bun - fast JavaScript runtime and package manager","settingSystemTools.tools.bunx.desc": "bunx - Bun package runner for executing npm packages","settingSystemTools.tools.claude.desc": "Claude Code - Anthropic official agentic coding CLI",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex bdccde7693a..8f473329183 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -80,6 +80,13 @@"ampInstallGuide.menuNotification.title": "未找到 Amp CLI","ampInstallGuide.reason": "LobeHub 无法启动 Amp:{{message}}","ampInstallGuide.title": "安装 Amp CLI",+ "antigravityInstallGuide.actions.openDocs": "查看安装指南",+ "antigravityInstallGuide.actions.openSystemTools": "打开系统工具",+ "antigravityInstallGuide.afterInstall": "安装后运行 `agy` 并使用 Google 账号登录,然后重试消息或在系统工具中点击「重新检测」。",+ "antigravityInstallGuide.desc": "Antigravity 需要支持 stream-json 的原生 agy CLI。请按照对应操作系统的指南安装,并确保 `agy` 命令可用。",+ "antigravityInstallGuide.menuNotification.title": "未找到 Antigravity CLI",+ "antigravityInstallGuide.reason": "LobeHub 无法启动 Antigravity:{{message}}",+ "antigravityInstallGuide.title": "安装 Antigravity CLI","artifact.generating": "生成中","artifact.inThread": "子话题中暂不支持查看。请回到主对话区打开","artifact.thinking": "思考中",@@ -276,6 +283,7 @@"connectAgent.create.thisDevice": "本机","connectAgent.create.title": "接入助理","connectAgent.providerDesc.amp": "Sourcegraph 编码助理 CLI",+ "connectAgent.providerDesc.antigravity": "Google 编程 Agent CLI","connectAgent.providerDesc.claude-code": "Anthropic 编码助理 CLI","connectAgent.providerDesc.codebuddy": "腾讯编码助理 CLI","connectAgent.providerDesc.codex": "OpenAI 编码助理 CLI",@@ -1362,6 +1370,19 @@"groupWizard.searchTemplates": "搜索模板…","groupWizard.title": "创建群组","groupWizard.useTemplate": "使用模板",+ "heteroAgent.antigravityQuota.authRequired": "请在终端运行 agy 并登录,然后刷新。",+ "heteroAgent.antigravityQuota.cliNotFound": "此设备上未找到 Antigravity CLI,请安装 agy 后刷新。",+ "heteroAgent.antigravityQuota.disabled": "不可用",+ "heteroAgent.antigravityQuota.error": "无法查询 Antigravity 配额,请检查设备后重试。",+ "heteroAgent.antigravityQuota.fiveHour": "5 小时",+ "heteroAgent.antigravityQuota.remainingAmount": "剩余 {{amount}}",+ "heteroAgent.antigravityQuota.resetUnconfirmed": "已到重置时间,请刷新确认最新配额。",+ "heteroAgent.antigravityQuota.stale": "当前显示上次查询结果,请刷新确认最新配额。",+ "heteroAgent.antigravityQuota.timeout": "配额查询超时,请检查设备连接后重试。",+ "heteroAgent.antigravityQuota.title": "Antigravity 配额",+ "heteroAgent.antigravityQuota.tooltip": "查看 Antigravity 模型配额",+ "heteroAgent.antigravityQuota.unknown": "未知",+ "heteroAgent.antigravityQuota.unsupported": "请将 agy 更新至支持结构化配额查询的版本后刷新。","heteroAgent.apiMode.agentUnsupported": "{{name}} 不支持 LobeHub 服务商绑定。","heteroAgent.apiMode.configMissing": "服务商绑定需要选择服务商和模型,请前往 Agent 资料完成配置。","heteroAgent.apiMode.credentialUnsupported": "服务商「{{providerId}}」使用的认证方式不受此 Agent 支持。",@@ -1910,6 +1931,7 @@"modelSelector.model": "模型","newAgent": "创建助理","newAmpAgent": "添加 Amp",+ "newAntigravityAgent": "添加 Antigravity","newClaudeCodeAgent": "添加 Claude Code","newCodeBuddyAgent": "添加 CodeBuddy","newCodexAgent": "添加 Codex",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex c2e8fefd83c..e94b8a536e1 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1909,6 +1909,7 @@"settingSystemTools.tools.ag.desc": "The Silver Searcher - 快速代码搜索工具","settingSystemTools.tools.agentBrowser.desc": "Agent-browser - 面向AI代理的无头浏览器自动化命令行工具","settingSystemTools.tools.aider.desc": "Aider - 终端内的 AI 结对编程工具",+ "settingSystemTools.tools.antigravity.desc": "Antigravity CLI - Google 命令行编码智能体","settingSystemTools.tools.bun.desc": "Bun - 快速的 JavaScript 运行时和包管理器","settingSystemTools.tools.bunx.desc": "bunx - Bun 包执行器,用于运行 npm 包","settingSystemTools.tools.claude.desc": "Claude Code - Anthropic 官方命令行编码助理",diff --git a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts b/packages/agent-manager-runtime/src/heteroAgentDescriptor.tsindex 155fd604a1d..18fd43c2793 100644--- a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts+++ b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts@@ -41,6 +41,13 @@ const CODING_CAPABILITIES = [];const HETERO_PROFILES: Record<HeteroType, HeteroTypeProfile> = {+ 'antigravity': {+ capabilities: CODING_CAPABILITIES,+ description:+ "Antigravity — Google's native CLI coding agent (agy). It uses its own signed-in account, models and built-in tools to read and edit files and run permitted commands in a working directory. Command execution follows the user's Antigravity permission policy.",+ displayName: 'Antigravity',+ kind: 'cli',+ },'amp': {capabilities: CODING_CAPABILITIES,description:diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 759e6cb4aa6..6675e545d40 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -14,6 +14,7 @@ import path from 'node:path';import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { getAntigravityQuota } from '../antigravityQuota';import {APP_UPDATE_UNSUPPORTED_MESSAGE,CLI_UPDATE_UNSUPPORTED_MESSAGE,@@ -71,7 +72,21 @@ const makeDeps = (): DeviceControlDeps => ({})),});+vi.mock('../antigravityQuota', () => ({+ getAntigravityQuota: vi.fn(async () => ({ status: 'ok', groups: [] })),+}));+describe('executeDeviceRpc', () => {+ it('routes Antigravity quota RPCs through the shared host sampler', async () => {+ const params = { command: '/custom/agy', env: { AGY_PROFILE: 'fixture' }, force: true };+ expect(DEVICE_RPC_METHODS).toContain('getAntigravityQuota');+ await expect(executeDeviceRpc('getAntigravityQuota', params, makeDeps())).resolves.toEqual({+ status: 'ok',+ groups: [],+ });+ expect(getAntigravityQuota).toHaveBeenCalledWith(params);+ });+it.each(['getCliUpdateState', 'checkCliUpdate', 'restartCli'])('rejects missing CLI handler %s with a stable reason',async (method) => {diff --git a/packages/device-control/src/antigravityQuota.test.ts b/packages/device-control/src/antigravityQuota.test.tsnew file mode 100644index 00000000000..da541c20be6--- /dev/null+++ b/packages/device-control/src/antigravityQuota.test.ts@@ -0,0 +1,35 @@+import type * as QuotaSampler from '@lobechat/heterogeneous-agents/quota-sampler';+import { describe, expect, it, vi } from 'vitest';++import { getAntigravityQuota } from './antigravityQuota';++const fetchQuota = vi.hoisted(() => vi.fn());+vi.mock('@lobechat/heterogeneous-agents/quota-sampler', async (importOriginal) => ({+ ...(await importOriginal<typeof QuotaSampler>()),+ fetchAntigravityQuota: fetchQuota,+}));++describe('Antigravity host quota cache', () => {+ it('coalesces callers while isolating command/profile and honoring force refresh', async () => {+ const snapshot = {+ error: null,+ groups: [],+ provider: 'antigravity',+ status: 'ok',+ updatedAt: Date.now(),+ };+ fetchQuota.mockResolvedValue(snapshot);+ const params = { command: '/custom/agy', env: { HOME: '/profile/a' } };+ const [first, second] = await Promise.all([+ getAntigravityQuota(params),+ getAntigravityQuota(params),+ ]);+ expect(first).toBe(second);+ expect(fetchQuota).toHaveBeenCalledTimes(1);+ await getAntigravityQuota({ ...params, force: true });+ expect(fetchQuota).toHaveBeenCalledTimes(2);+ await getAntigravityQuota({ ...params, env: { HOME: '/profile/b' } });+ await getAntigravityQuota({ ...params, command: '/other/agy' });+ expect(fetchQuota).toHaveBeenCalledTimes(4);+ });+});diff --git a/packages/device-control/src/antigravityQuota.ts b/packages/device-control/src/antigravityQuota.tsnew file mode 100644index 00000000000..08af260979f--- /dev/null+++ b/packages/device-control/src/antigravityQuota.ts@@ -0,0 +1,19 @@+import type {+ AntigravityQuotaParams,+ AntigravityQuotaSnapshot,+} from '@lobechat/heterogeneous-agents/quota';+import {+ createQuotaCacheKey,+ fetchAntigravityQuota,+ QuotaSnapshotCache,+} from '@lobechat/heterogeneous-agents/quota-sampler';++const quotaCache = new QuotaSnapshotCache<AntigravityQuotaSnapshot>({ freshMs: 60_000 });++/** Shared by the CLI daemon, Desktop gateway and local Desktop IPC. */+export const getAntigravityQuota = (params: AntigravityQuotaParams = {}) =>+ quotaCache.get(+ createQuotaCacheKey('antigravity', params.command, params.env),+ () => fetchAntigravityQuota(params),+ { force: params.force },+ );diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 1063502ec66..9298a40e3ca 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -1,3 +1,4 @@+import type { AntigravityQuotaParams } from '@lobechat/heterogeneous-agents/quota';import {copyLocalFiles,createLocalDirectory,@@ -38,6 +39,7 @@ import type {} from '@lobechat/local-file-shell/types';import type { DeviceCliRestartParams } from '@lobechat/types';+import { getAntigravityQuota } from './antigravityQuota';import { listClaudeCodeMemory } from './claudeCodeMemory';import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';@@ -83,6 +85,7 @@ export const DEVICE_RPC_METHODS = ['unenrollWorkspace','initWorkspace','listHeterogeneousAgentModels',+ 'getAntigravityQuota','getClaudeCodeQuota','getCodexQuota','getKimiCodeQuota',@@ -231,6 +234,10 @@ export const executeDeviceRpc = async (return getClaudeCodeQuota(params as GetClaudeCodeQuotaParams);}+ case 'getAntigravityQuota': {+ return getAntigravityQuota(params as AntigravityQuotaParams);+ }+case 'getCodexQuota': {return getCodexQuota(params as GetCodexQuotaParams);}diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.tsindex 91a846f7844..bd050fa321f 100644--- a/packages/device-control/src/index.ts+++ b/packages/device-control/src/index.ts@@ -1,3 +1,4 @@+export { getAntigravityQuota } from './antigravityQuota';export {listClaudeCodeMemory,resolveClaudeCodeMemoryDir,diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex 5f8dd02f301..ccd5955a829 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -436,6 +436,7 @@ export interface ListHeterogeneousAgentModelsParams {cwd?: string;env?: Record<string, string>;type:+ | 'antigravity'| 'codebuddy'| 'codex'| 'copilot'diff --git a/packages/heterogeneous-agents/src/adapters/antigravity.test.ts b/packages/heterogeneous-agents/src/adapters/antigravity.test.tsnew file mode 100644index 00000000000..349224de55a--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/antigravity.test.ts@@ -0,0 +1,288 @@+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('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([]);+ }+ });+});diff --git a/packages/heterogeneous-agents/src/adapters/antigravity.ts b/packages/heterogeneous-agents/src/adapters/antigravity.tsnew file mode 100644index 00000000000..1f132f96b8b--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/antigravity.ts@@ -0,0 +1,329 @@+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);++/**+ * Native agy NDJSON protocol, not the Gemini/Claude stream-json protocol.+ * https://antigravity.google/docs/cli/headless/+ * LobeHub uses one process per turn and --conversation to resume. The native+ * protocol also supports multiple turns while stdin remains open.+ */+export class AntigravityAdapter implements AgentEventAdapter {+ sessionId?: string;++ private completedSteps = new Set<number>();+ private flushed = false;+ private hasResponseText = false;+ private model?: string;+ private pendingTools = new Map<number, PendingTool>();+ private resultReceived = false;+ private completionValidated = false;+ private responseStep?: number;+ private stepIndex = 0;+ private stepTools: ToolCallPayload[] = [];+ private streamOpen = false;+ private toolSinceResponse = false;+ private usageByStep = new Map<number, UsageData>();++ adapt(raw: unknown): HeterogeneousAgentEvent[] {+ if (this.flushed || this.resultReceived || !isRecord(raw)) return [];+ if (raw.event === 'init') {+ 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 [];++ const events: HeterogeneousAgentEvent[] = [];+ 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.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);+ if (!name && !subagents) return [];+ const events = this.openStream();+ this.toolSinceResponse = true;+ let pending = this.pendingTools.get(index);+ 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[] {+ this.resultReceived = 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());+ // 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/index.ts b/packages/heterogeneous-agents/src/adapters/index.tsindex df305f41284..2e01ce15f3a 100644--- a/packages/heterogeneous-agents/src/adapters/index.ts+++ b/packages/heterogeneous-agents/src/adapters/index.ts@@ -1,4 +1,5 @@export { AmpAdapter } from './amp';+export { AntigravityAdapter } from './antigravity';export { ClaudeCodeAdapter } from './claudeCode';export { ClaudeCodeSdkAdapter } from './claudeCodeSdk';export { CodeBuddyAdapter } from './codeBuddy';diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.tsindex 2c173cdd94b..48852511ee9 100644--- a/packages/heterogeneous-agents/src/client/index.ts+++ b/packages/heterogeneous-agents/src/client/index.ts@@ -1,6 +1,7 @@import type { IconType } from '@lobehub/icons';import {Amp,+ Antigravity,ClaudeCode,CodeBuddy,Codex,@@ -40,6 +41,7 @@ export type LocalRuntimeHeterogeneousAgentClientConfig =};const heterogeneousAgentIcons = {+ 'antigravity': Antigravity,'amp': Amp,'claude-code': ClaudeCode,'codebuddy': CodeBuddy,diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.tsindex c532f94d535..a4e8913bf52 100644--- a/packages/heterogeneous-agents/src/config.test.ts+++ b/packages/heterogeneous-agents/src/config.test.ts@@ -85,6 +85,7 @@ describe('heterogeneous agent config', () => {});it('resolves display labels with safe fallbacks', () => {+ expect(getHeterogeneousTypeLabel('antigravity')).toBe('Antigravity');expect(getHeterogeneousTypeLabel('codebuddy')).toBe('CodeBuddy');expect(getHeterogeneousTypeLabel('copilot')).toBe('GitHub Copilot');expect(getHeterogeneousTypeLabel('hermes')).toBe('Hermes');diff --git a/packages/heterogeneous-agents/src/errors/classifyCliMessageError.ts b/packages/heterogeneous-agents/src/errors/classifyCliMessageError.tsnew file mode 100644index 00000000000..750366d54eb--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/classifyCliMessageError.ts@@ -0,0 +1,48 @@+import type { LocalHeterogeneousAgentType } from '../config';+import {+ buildHeterogeneousAgentAuthRequiredError,+ isHeterogeneousAgentAuthRequired,+} from '../config';+import type { HeterogeneousTerminalErrorData } from '../types';+import { classifyCliQuotaMessage } from './cliQuota';++interface ClassifyCliMessageErrorParams {+ agentType: LocalHeterogeneousAgentType;+ command?: string;+ detail?: string;+}++/** Error text shared by stream adapters and process failure handling. */+export const classifyCliMessageError = ({+ agentType,+ command,+ detail: rawDetail,+}: ClassifyCliMessageErrorParams): HeterogeneousTerminalErrorData | undefined => {+ const detail = rawDetail?.trim();+ if (!detail) return;++ // A CLI can report a spent subscription through its auth layer. Signing in+ // again never fixes that, so explicit quota wording takes precedence.+ const quota = classifyCliQuotaMessage(detail);+ if (quota) {+ return {+ agentType,+ code: 'rate_limit',+ details: { kind: quota.kind },+ error: detail,+ message: detail,+ ...(quota.rateLimitType+ ? { rateLimitInfo: { rateLimitType: quota.rateLimitType, status: 'rejected' } }+ : {}),+ stderr: detail,+ };+ }++ if (isHeterogeneousAgentAuthRequired(agentType, detail)) {+ return buildHeterogeneousAgentAuthRequiredError({+ agentType,+ command,+ stderr: detail,+ });+ }+};diff --git a/packages/heterogeneous-agents/src/models/antigravity.test.ts b/packages/heterogeneous-agents/src/models/antigravity.test.tsnew file mode 100644index 00000000000..5f9b0e20b58--- /dev/null+++ b/packages/heterogeneous-agents/src/models/antigravity.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { parseAntigravityModelCatalog } from './antigravity';++describe('parseAntigravityModelCatalog', () => {+ it('preserves native model slugs and labels without inferring a provider', () => {+ expect(+ parseAntigravityModelCatalog(+ [+ 'Fetching available models...',+ 'MODEL NAME',+ '\u001B[32mgemini-4-argon-high\u001B[0m Gemini 4 Argon (High)',+ 'claude-sonnet-4-5 Claude Sonnet 4.5',+ 'gemini-4-argon-high Duplicate',+ '',+ 'some diagnostic message',+ ].join('\r\n'),+ ),+ ).toEqual([+ {+ id: 'gemini-4-argon-high',+ label: 'Gemini 4 Argon (High)',+ modelId: 'gemini-4-argon-high',+ providerId: 'antigravity',+ },+ {+ id: 'claude-sonnet-4-5',+ label: 'Claude Sonnet 4.5',+ modelId: 'claude-sonnet-4-5',+ providerId: 'antigravity',+ },+ ]);+ });++ it('ignores empty output, errors, headers and truncated ids', () => {+ expect(parseAntigravityModelCatalog('')).toEqual([]);+ expect(+ parseAntigravityModelCatalog(+ 'MODEL ID DISPLAY NAME\nError: authentication required\nmodel… Truncated',+ ),+ ).toEqual([]);+ });+});diff --git a/packages/heterogeneous-agents/src/models/antigravity.ts b/packages/heterogeneous-agents/src/models/antigravity.tsnew file mode 100644index 00000000000..7e709663f90--- /dev/null+++ b/packages/heterogeneous-agents/src/models/antigravity.ts@@ -0,0 +1,24 @@+import { stripVTControlCharacters } from 'node:util';++import type { HeterogeneousAgentModel } from '@lobechat/types';++/** Parse the slug and display-name columns emitted by `agy models`. */+export const parseAntigravityModelCatalog = (stdout: string): HeterogeneousAgentModel[] => {+ const seen = new Set<string>();+ const models: HeterogeneousAgentModel[] = [];++ for (const line of stripVTControlCharacters(stdout).split(/\r?\n/)) {+ const trimmed = line.trim();+ const separator = trimmed.search(/\s{2}|\t/);+ if (separator < 0) continue;+ const id = trimmed.slice(0, separator);+ const label = trimmed.slice(separator).trim();+ if (!/^\w[\w./:@+-]*$/.test(id) || id.endsWith(':') || !label) continue;+ if (['model', 'models', 'slug', 'id'].includes(id.toLowerCase()) || seen.has(id)) continue;++ seen.add(id);+ models.push({ id, label: label.trim(), modelId: id, providerId: 'antigravity' });+ }++ return models;+};diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.tsindex 1a3ee8ddc0d..a3e46cdad53 100644--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts@@ -128,6 +128,38 @@ describe('heterogeneous agent model discovery', () => {);});+ it('queries the configured Antigravity binary for its native model catalog', async () => {+ resolveExecFile('gemini-4-argon-high Gemini 4 Argon (High)');+ const { listHeterogeneousAgentModels } = await importModule();+ await expect(+ listHeterogeneousAgentModels({+ command: '/custom/agy',+ cwd: '/repo',+ env: { CUSTOM_ENV: 'value' },+ type: 'antigravity',+ }),+ ).resolves.toMatchObject({+ status: 'success',+ models: [+ { id: 'gemini-4-argon-high', label: 'Gemini 4 Argon (High)', providerId: 'antigravity' },+ ],+ });+ expect(execFileMock).toHaveBeenCalledWith(+ '/custom/agy',+ ['models'],+ expect.objectContaining({ cwd: '/repo', env: { CUSTOM_ENV: 'value' }, timeout: 15_000 }),+ expect.any(Function),+ );+ });++ it('reports a stalled Antigravity model query as a retryable catalog timeout', async () => {+ rejectExecFile(Object.assign(new Error('timed out'), { killed: true }));+ const { listHeterogeneousAgentModels } = await importModule();+ await expect(+ listHeterogeneousAgentModels({ command: '/custom/agy', type: 'antigravity' }),+ ).resolves.toMatchObject({ status: 'error', error: { code: 'timeout' } });+ });+it('loads Pi provider extensions with the same discovery policy as the configured run', async () => {resolveExecFile('custom fixture-model 4K 512 no no');const { listHeterogeneousAgentModels } = await importModule();diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.tsindex 4dd650b35ae..dc762462493 100644--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts@@ -20,6 +20,7 @@ import type { ResolvedHeteroCommand } from '../spawn/resolveCliCommand';import { resolveHeteroSpawnCommand } from '../spawn/resolveCliCommand';import { listTraeAcpModels } from '../spawn/traeAcpSession';import { resolveHeteroSpawnCwd } from '../spawn/workingDirectory';+import { parseAntigravityModelCatalog } from './antigravity';import { listCodexModels } from './codex';const execFilePromise = promisify(execFile);@@ -437,7 +438,9 @@ export const listHeterogeneousAgentModels = async (? ['--help']: params.type === 'devin'? ['models', 'list', '--format', 'json']- : params.type === 'grok-build' || params.type === 'opencode'+ : params.type === 'antigravity' ||+ params.type === 'grok-build' ||+ params.type === 'opencode'? ['models']: params.type === 'kimi-code'? ['provider', 'list', '--json']@@ -474,19 +477,21 @@ export const listHeterogeneousAgentModels = async (return {models:- params.type === 'cursor'- ? parseCursorModelCatalog(String(stdout))- : params.type === 'devin'- ? parseDevinModelCatalog(String(stdout))- : params.type === 'grok-build'- ? parseGrokBuildModelCatalog(String(stdout))- : params.type === 'kimi-code'- ? parseKimiCodeModelCatalog(String(stdout))- : params.type === 'pi'- ? parsePiModelCatalog(String(stdout))- : params.type === 'qoder'- ? parseQoderModelCatalog(String(stdout))- : parseOpenCodeModelCatalog(String(stdout)),+ params.type === 'antigravity'+ ? parseAntigravityModelCatalog(String(stdout))+ : params.type === 'cursor'+ ? parseCursorModelCatalog(String(stdout))+ : params.type === 'devin'+ ? parseDevinModelCatalog(String(stdout))+ : params.type === 'grok-build'+ ? parseGrokBuildModelCatalog(String(stdout))+ : params.type === 'kimi-code'+ ? parseKimiCodeModelCatalog(String(stdout))+ : params.type === 'pi'+ ? parsePiModelCatalog(String(stdout))+ : params.type === 'qoder'+ ? parseQoderModelCatalog(String(stdout))+ : parseOpenCodeModelCatalog(String(stdout)),status: 'success',updatedAt,};diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.tsindex 882b3128e91..a75ab6ccef8 100644--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.ts+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.ts@@ -1,4 +1,4 @@-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';@@ -20,7 +20,7 @@ describe('model discovery working directory', () => {).map(({ type }) => type) as ListHeterogeneousAgentModelsParams['type'][];beforeEach(async () => {- root = await mkdtemp(path.join(tmpdir(), 'hetero-model-cwd-'));+ root = await realpath(await mkdtemp(path.join(tmpdir(), 'hetero-model-cwd-')));project = path.join(root, 'project');await mkdir(project);await writeFile(path.join(root, 'file'), 'not a directory');@@ -43,6 +43,7 @@ if (['codex', 'copilot', 'droid', 'trae'].includes(engine)) {});} else {const outputs = {+ antigravity: model + ' Fixture',codebuddy: '--model <model> Currently supported: (' + model + ')',cursor: model + ' - Fixture',devin: JSON.stringify({ families: [{ variants: [{ model_uid: model }] }] }),diff --git a/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.test.tsnew file mode 100644index 00000000000..e7561363b48--- /dev/null+++ b/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.test.ts@@ -0,0 +1,132 @@+import * as childProcess from 'node:child_process';++import { beforeEach, describe, expect, it, vi } from 'vitest';++import { fetchAntigravityQuota, parseAntigravityQuota } from './antigravityQuota';++vi.mock('node:child_process', () => ({ execFile: vi.fn() }));+vi.mock('../spawn/resolveCliCommand', () => ({+ resolveHeteroSpawnCommand: vi.fn(async () => ({ command: '/bin/agy', pathEnv: '/resolved/bin' })),+}));+vi.mock('../spawn/cliSpawn', () => ({+ resolveCliSpawnPlan: vi.fn(async (command: string, args: string[]) => ({ command, args })),+}));++const envelope = (buckets: unknown[] = []) => ({+ status: 'SUCCESS',+ command: { name: 'usage', data: { groups: [{ name: 'Gemini', buckets }] } },+});+const bucket = {+ id: 'gemini-weekly',+ name: 'Weekly',+ remaining_fraction: 0.939,+ reset_time: '2026-11-06T02:52:08Z',+ window: 'weekly',+};+const respond = (stdout: string, error: Error | null = null) =>+ vi.mocked(childProcess.execFile).mockImplementationOnce(((...args: unknown[]) => {+ const callback = args.at(-1) as (+ error: Error | null,+ result: { stdout: string; stderr: string },+ ) => void;+ callback(error, { stdout, stderr: '' });+ return {} as childProcess.ChildProcess;+ }) as typeof childProcess.execFile);++describe('Antigravity quota sampler', () => {+ beforeEach(() => vi.clearAllMocks());++ it('preserves native groups and bucket ids without rolling expired readings to full', () => {+ expect(parseAntigravityQuota(envelope([bucket]))).toEqual([+ {+ name: 'Gemini',+ buckets: [+ {+ id: bucket.id,+ name: 'Weekly',+ remainingFraction: 0.939,+ remainingAmount: null,+ resetsAt: Date.parse(bucket.reset_time),+ window: 'weekly',+ disabled: false,+ },+ ],+ },+ ]);+ expect(+ parseAntigravityQuota(envelope([{ ...bucket, remaining_fraction: 0.5 }]))[0].buckets[0]+ .remainingFraction,+ ).toBe(0.5);+ expect(+ parseAntigravityQuota(envelope([{ ...bucket, remaining_fraction: 0.9 }]))[0].buckets[0]+ .remainingFraction,+ ).toBe(0.9);+ });++ it('keeps missing percentages unknown, zero distinct, disabled buckets and future window types', () => {+ const groups = parseAntigravityQuota(+ envelope([+ { id: 'unknown', remaining_fraction: 2, reset_time: 'invalid' },+ { id: 'empty', remaining_fraction: 0 },+ { id: 'amount', remaining_amount: 24, window: 'dynamic', disabled: true },+ { id: 'amount', remaining_fraction: 1 },+ null,+ ]),+ );+ expect(groups[0].buckets).toHaveLength(3);+ expect(groups[0].buckets[0]).toMatchObject({ remainingFraction: null, resetsAt: null });+ expect(groups[0].buckets[1].remainingFraction).toBe(0);+ expect(groups[0].buckets[2]).toMatchObject({+ disabled: true,+ remainingAmount: 24,+ remainingFraction: null,+ window: 'dynamic',+ });+ });++ it.each([+ {},+ { status: 'SUCCESS', response: '100%' },+ { status: 'ERROR' },+ { status: 'SUCCESS', command: { name: 'credits', data: { groups: [] } } },+ ])('rejects unsupported payloads instead of presenting zero usage: %j', (payload) => {+ expect(() => parseAntigravityQuota(payload)).toThrow();+ });++ it('queries only the native usage command with a bounded subprocess and caller environment', async () => {+ respond(JSON.stringify(envelope([bucket])));+ const result = await fetchAntigravityQuota({+ command: '/bin/agy',+ env: { AGY_TEST: 'profile', PATH: '/caller/bin' },+ });+ expect(result.status).toBe('ok');+ expect(result.groups[0].buckets[0].remainingFraction).toBe(0.939);+ expect(childProcess.execFile).toHaveBeenCalledWith(+ '/bin/agy',+ ['-p', '/usage', '--output-format', 'json', '--print-timeout', '15s'],+ expect.objectContaining({+ env: expect.objectContaining({ AGY_TEST: 'profile', PATH: '/caller/bin' }),+ timeout: 20_000,+ killSignal: 'SIGKILL',+ windowsHide: true,+ }),+ expect.any(Function),+ );+ });++ it.each([+ [Object.assign(new Error('missing'), { code: 'ENOENT' }), 'cli_not_found'],+ [Object.assign(new Error('timeout'), { killed: true }), 'timeout'],+ [Object.assign(new Error('failed'), { stderr: 'authentication required' }), 'auth_required'],+ ])('classifies process failures without exposing raw stderr', async (error, code) => {+ respond('', error);+ expect(await fetchAntigravityQuota()).toMatchObject({ errorCode: code, groups: [] });+ });++ it('reports old command formats and failed command envelopes', async () => {+ respond('Weekly\t100%');+ expect((await fetchAntigravityQuota()).errorCode).toBe('unsupported_client');+ respond(JSON.stringify({ status: 'ERROR', error: 'authentication required' }));+ expect((await fetchAntigravityQuota()).errorCode).toBe('auth_required');+ });+});diff --git a/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.tsnew file mode 100644index 00000000000..97c6f84cc98--- /dev/null+++ b/packages/heterogeneous-agents/src/quota-sampler/antigravityQuota.ts@@ -0,0 +1,137 @@+import { execFile } from 'node:child_process';+import { tmpdir } from 'node:os';+import { promisify } from 'node:util';++import { isRecord, pickString } from '@lobechat/utils/object';++import { isHeterogeneousAgentAuthRequired } from '../config';+import type {+ AntigravityQuotaErrorCode,+ AntigravityQuotaGroup,+ AntigravityQuotaParams,+ AntigravityQuotaSnapshot,+} from '../quota/antigravity';+import { resolveCliSpawnPlan } from '../spawn/cliSpawn';+import { resolveHeteroSpawnCommand } from '../spawn/resolveCliCommand';++const execFilePromise = promisify(execFile);++const nonnegative = (value: unknown): number | null =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;++/** The native command envelope is distinct from a model response. Fail closed on older CLIs. */+export const parseAntigravityQuota = (payload: unknown): AntigravityQuotaGroup[] => {+ if (+ !isRecord(payload) ||+ payload.status !== 'SUCCESS' ||+ !isRecord(payload.command) ||+ payload.command.name !== 'usage' ||+ !isRecord(payload.command.data) ||+ !Array.isArray(payload.command.data.groups)+ ) {+ throw new Error('Antigravity did not return a structured usage command result');+ }++ return payload.command.data.groups.flatMap((group) => {+ if (!isRecord(group) || !pickString(group.name) || !Array.isArray(group.buckets)) return [];+ const seen = new Set<string>();+ const buckets = group.buckets.flatMap((bucket) => {+ if (!isRecord(bucket)) return [];+ const id = pickString(bucket.id);+ if (!id || seen.has(id)) return [];+ seen.add(id);+ const fraction = nonnegative(bucket.remaining_fraction);+ const reset = typeof bucket.reset_time === 'string' ? Date.parse(bucket.reset_time) : NaN;+ return [+ {+ disabled: bucket.disabled === true,+ id,+ name: pickString(bucket.name) ?? id,+ remainingAmount: nonnegative(bucket.remaining_amount),+ remainingFraction: fraction !== null && fraction <= 1 ? fraction : null,+ resetsAt: Number.isFinite(reset) ? reset : null,+ window: pickString(bucket.window) ?? null,+ },+ ];+ });+ return [{ buckets, name: String(group.name) }];+ });+};++/** Query the installed CLI using its own login; never read or refresh credentials ourselves. */+export const fetchAntigravityQuota = async (+ params: AntigravityQuotaParams = {},+): Promise<AntigravityQuotaSnapshot> => {+ const failure = (errorCode: AntigravityQuotaErrorCode): AntigravityQuotaSnapshot => ({+ error: 'Antigravity quota query failed',+ errorCode,+ groups: [],+ provider: 'antigravity',+ status:+ errorCode === 'auth_required' ||+ errorCode === 'cli_not_found' ||+ errorCode === 'unsupported_client'+ ? 'unavailable'+ : 'error',+ updatedAt: Date.now(),+ });+ try {+ const resolved = await resolveHeteroSpawnCommand('antigravity', params.command);+ const env = {+ ...process.env,+ ...(resolved.pathEnv ? { PATH: resolved.pathEnv } : {}),+ ...params.env,+ };+ const plan = await resolveCliSpawnPlan(+ resolved.command,+ ['-p', '/usage', '--output-format', 'json', '--print-timeout', '15s'],+ env,+ );+ const { stdout } = await execFilePromise(plan.command, plan.args, {+ cwd: tmpdir(),+ encoding: 'utf8',+ env,+ killSignal: 'SIGKILL',+ maxBuffer: 1024 * 1024,+ timeout: 20_000,+ windowsHide: true,+ });+ let payload: unknown;+ try {+ payload = JSON.parse(stdout);+ } catch {+ return failure('unsupported_client');+ }+ if (isRecord(payload) && payload.status !== 'SUCCESS') {+ return failure(+ typeof payload.error === 'string' &&+ isHeterogeneousAgentAuthRequired('antigravity', payload.error)+ ? 'auth_required'+ : 'command_failed',+ );+ }+ try {+ return {+ error: null,+ groups: parseAntigravityQuota(payload),+ provider: 'antigravity',+ status: 'ok',+ updatedAt: Date.now(),+ };+ } catch {+ return failure('unsupported_client');+ }+ } catch (error) {+ const record = isRecord(error) ? error : {};+ const detail = `${record.stderr ?? ''} ${record.message ?? ''}`;+ return failure(+ record.code === 'ENOENT'+ ? 'cli_not_found'+ : record.killed || record.code === 'ETIMEDOUT'+ ? 'timeout'+ : isHeterogeneousAgentAuthRequired('antigravity', detail)+ ? 'auth_required'+ : 'command_failed',+ );+ }+};diff --git a/packages/heterogeneous-agents/src/quota-sampler/index.ts b/packages/heterogeneous-agents/src/quota-sampler/index.tsindex f28195878ef..a056a4fbcf8 100644--- a/packages/heterogeneous-agents/src/quota-sampler/index.ts+++ b/packages/heterogeneous-agents/src/quota-sampler/index.ts@@ -1,3 +1,4 @@+export * from './antigravityQuota';export * from './claudeCodeQuota';export * from './codexQuota';export * from './identity';diff --git a/packages/heterogeneous-agents/src/quota/antigravity.ts b/packages/heterogeneous-agents/src/quota/antigravity.tsnew file mode 100644index 00000000000..55477408870--- /dev/null+++ b/packages/heterogeneous-agents/src/quota/antigravity.ts@@ -0,0 +1,33 @@+/** Native agy quota buckets; no inferred windows, capacity or credit balance. */+export interface AntigravityQuotaBucket {+ disabled: boolean;+ id: string;+ name: string;+ remainingAmount: number | null;+ remainingFraction: number | null;+ resetsAt: number | null;+ window: string | null;+}++export interface AntigravityQuotaGroup {+ buckets: AntigravityQuotaBucket[];+ name: string;+}++export interface AntigravityQuotaParams {+ command?: string;+ env?: Record<string, string>;+ force?: boolean;+}++export type AntigravityQuotaErrorCode =+ 'auth_required' | 'cli_not_found' | 'command_failed' | 'timeout' | 'unsupported_client';++export interface AntigravityQuotaSnapshot {+ error: string | null;+ errorCode?: AntigravityQuotaErrorCode;+ groups: AntigravityQuotaGroup[];+ provider: 'antigravity';+ status: 'error' | 'ok' | 'unavailable';+ updatedAt: number;+}diff --git a/packages/heterogeneous-agents/src/quota/index.ts b/packages/heterogeneous-agents/src/quota/index.tsindex fd163707457..0e141952b27 100644--- a/packages/heterogeneous-agents/src/quota/index.ts+++ b/packages/heterogeneous-agents/src/quota/index.ts@@ -1,3 +1,4 @@+export * from './antigravity';export * from './calibration';export * from './claudeCodeRouting';export * from './codex';diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.tsindex ea268cfcb8f..29899de650b 100644--- a/packages/heterogeneous-agents/src/registry.ts+++ b/packages/heterogeneous-agents/src/registry.ts@@ -7,6 +7,7 @@import {AmpAdapter,+ AntigravityAdapter,ClaudeCodeAdapter,ClaudeCodeSdkAdapter,CodeBuddyAdapter,@@ -32,6 +33,9 @@ interface AgentRegistryEntry {}const localAgentRegistry = {+ 'antigravity': {+ createAdapter: () => new AntigravityAdapter(),+ },'amp': {createAdapter: () => new AmpAdapter(),},diff --git a/packages/heterogeneous-agents/src/spawn/antigravity.test.ts b/packages/heterogeneous-agents/src/spawn/antigravity.test.tsnew file mode 100644index 00000000000..b5137d0bda1--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/antigravity.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import { buildAntigravityArgs } from './antigravity';+import { buildAgentInput } from './input/buildAgentInput';++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 } });+ });++ 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',+ '--dangerously-skip-permissions',+ '--conversation',+ 'conv-1',+ '--model',+ 'custom-model',+ '--effort',+ 'high',+ ]);+ expect(buildAntigravityArgs({})).toContain('--dangerously-skip-permissions');+ });++ it.each([+ '--output-format=json',+ '--input-format',+ '--prompt-interactive=hello',+ '--remote-control',+ '-i',+ '-p',+ '--continue',+ '--conversation=other',+ '--',+ ])('rejects custom %s that breaks protocol or session ownership', (flag) => {+ expect(() => buildAntigravityArgs({ extraArgs: [flag] })).toThrow('LobeHub manages');+ });++ it('rejects image attachments instead of silently dropping them', async () => {+ await expect(+ buildAgentInput('antigravity', [+ { type: 'image', source: { type: 'path', path: '/tmp/image.png' } },+ ]),+ ).rejects.toThrow('does not support image attachments');+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/antigravity.ts b/packages/heterogeneous-agents/src/spawn/antigravity.tsnew file mode 100644index 00000000000..afeaed1ea0f--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/antigravity.ts@@ -0,0 +1,46 @@+/** 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;++interface AntigravitySpawnArgsOptions {+ extraArgs?: string[];+ resumeSessionId?: string;+}++const MANAGED_FLAGS = new Set([+ '--',+ '--input-format',+ '--output-format',+ '--print',+ '--prompt',+ '--prompt-interactive',+ '--remote-control',+ '-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}`,+ );+ }++ return [+ ...ANTIGRAVITY_BASE_ARGS,+ ...(resumeSessionId ? ['--conversation', resumeSessionId] : []),+ ...extraArgs,+ ];+};diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.tsindex 7299cd644ed..cd3e480bb6e 100644--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts@@ -1,11 +1,9 @@import {- buildHeterogeneousAgentAuthRequiredError,buildHeterogeneousAgentCliNotFoundError,HETEROGENEOUS_AGENT_CONFIGS,- isHeterogeneousAgentAuthRequired,isLocalHeterogeneousType,} from '../config';-import { classifyCliQuotaMessage } from '../errors/cliQuota';+import { classifyCliMessageError } from '../errors/classifyCliMessageError';import type { HeterogeneousTerminalErrorData } from '../types';/**@@ -120,30 +118,5 @@ export const classifyHeteroProcessFailure = (});}- // Before auth: a CLI can report a spent subscription through its auth layer- // (Kimi Code exits with `provider.auth_error: 403 You've reached your weekly- // (7-day) usage limit…`). Signing in again never fixes that, so the quota- // wording has to win over anything the auth patterns recognize.- const quota = classifyCliQuotaMessage(detail);- if (detail && quota) {- return {- agentType,- code: 'rate_limit',- details: { kind: quota.kind },- error: detail,- message: detail,- ...(quota.rateLimitType- ? { rateLimitInfo: { rateLimitType: quota.rateLimitType, status: 'rejected' } }- : {}),- stderr: detail,- };- }-- if (detail && isHeterogeneousAgentAuthRequired(agentType, detail)) {- return buildHeterogeneousAgentAuthRequiredError({- agentType,- command,- stderr: detail,- });- }+ return classifyCliMessageError({ agentType, command, detail });};diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 085dddd7ddb..670b69f8cf8 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -51,6 +51,7 @@ export {type AgentStreamPipelineOptions,type UploadHeterogeneousImage,} from './agentStreamPipeline';+export { ANTIGRAVITY_BASE_ARGS, buildAntigravityArgs } from './antigravity';export {classifyHeteroProcessFailure,type ClassifyHeteroProcessFailureParams,diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.tsindex 69b6af4621d..dd303f6087b 100644--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts@@ -200,6 +200,17 @@ export const buildAgentInput = async (const blocks = toBlocks(prompt);switch (agentType) {+ case 'antigravity': {+ // agy's stream input currently accepts text only. Never silently discard+ // attachments or send unsupported blocks that terminate its session.+ if (blocks.some(isImageBlock)) {+ throw new Error('Antigravity CLI stream input does not support image attachments.');+ }+ return {+ args: [],+ stdin: `${JSON.stringify({ event: 'user', message: { content: collectText(blocks) } })}\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.tsnew file mode 100644index 00000000000..b3410789c5f--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.antigravity.test.ts@@ -0,0 +1,137 @@+import * as childProcess from 'node:child_process';+import * as fsPromises from 'node:fs/promises';+import * as os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// The module captures `promisify(execFile)` at import time, so mock first.+vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => actual.platform()) };+});++vi.mock('node:child_process', () => ({+ exec: vi.fn(),+ execFile: vi.fn(),+}));++vi.mock('node:fs/promises', async () => {+ const actual = await vi.importActual<typeof fsPromises>('node:fs/promises');+ return { ...actual, access: vi.fn(), readFile: vi.fn() };+});++const platformMock = vi.mocked(os.platform);+const execFileMock = vi.mocked(childProcess.execFile);+const execMock = vi.mocked(childProcess.exec);+const accessMock = vi.mocked(fsPromises.access);++/** Declare which paths exist on the fake host. */+const existingFiles = (files: Record<string, true>) => {+ const entries = new Set(Object.keys(files).map((filePath) => filePath.toLowerCase()));+ accessMock.mockImplementation(async (filePath) => {+ if (!entries.has(String(filePath).toLowerCase())) throw new Error(`missing: ${filePath}`);+ });+};++const queueExecFile = (err: Error | null, stdout = '', stderr = '') => {+ execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {+ // promisify-wrapped: the callback is always the last positional arg.+ const callback = typeof opts === 'function' ? opts : cb;+ callback(err, { stderr, stdout });+ return {} as any;+ }) as any);+};+const callExecFile = (stdout: string, stderr = '') => queueExecFile(null, stdout, stderr);+const callExecFileError = (err: Error) => queueExecFile(err);++const importModule = () => import('./resolveCliCommand');++describe('resolveCliCommand — Antigravity', () => {+ beforeEach(async () => {+ (await importModule()).invalidateLoginShellPathCache();+ execFileMock.mockReset();+ execMock.mockReset();+ accessMock.mockReset();+ // Fail unqueued calls fast instead of hanging until the test timeout.+ execFileMock.mockImplementation(((file: string, args: any, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ callback(new Error(`unexpected execFile: ${file} ${JSON.stringify(args)}`), {+ stderr: '',+ stdout: '',+ });+ return {} as any;+ }) as any);+ existingFiles({});+ platformMock.mockReturnValue('darwin');+ });++ afterEach(() => {+ vi.resetModules();+ });++ it('detects Antigravity stream-json 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');+ const { detectHeterogeneousCliCommand } = await importModule();+ expect(await detectHeterogeneousCliCommand('antigravity', 'agy')).toMatchObject({+ available: true,+ path: '/Users/x/.local/bin/agy',+ version: '1.2.13-beta.1+build.5',+ });+ });++ it('rejects older agy versions that cannot stream input or resume', async () => {+ callExecFile('1.0.7');+ callExecFile('Usage: agy --print --output-format json');+ const { detectHeterogeneousCliCommand } = await importModule();+ expect(await detectHeterogeneousCliCommand('antigravity', '/tmp/old-agy')).toMatchObject({+ available: false,+ });+ });++ it('finds agy in the official Unix user install directory', async () => {+ const originalEnv = process.env;+ process.env = { ...process.env, PATH: '/usr/bin:/bin', SHELL: '' };+ try {+ callExecFileError(new Error('not found'));+ callExecFile('1.2.13');+ callExecFile('--input-format --output-format stream-json --conversation');+ const { detectHeterogeneousCliCommand } = await importModule();+ expect(await detectHeterogeneousCliCommand('antigravity', 'agy')).toMatchObject({+ available: true,+ path: path.join(os.homedir(), '.local', 'bin', 'agy'),+ });+ } finally {+ process.env = originalEnv;+ }+ });++ it('finds the native Windows agy executable outside inherited PATH', async () => {+ platformMock.mockReturnValue('win32');+ const originalLocal = process.env.LOCALAPPDATA;+ const originalPath = process.env.PATH;+ process.env.LOCALAPPDATA = 'C:\\Users\\Test User\\AppData\\Local';+ process.env.PATH = 'C:\\Windows';+ const binary = 'C:\\Users\\Test User\\AppData\\Local\\agy\\bin\\agy.exe';+ existingFiles({ [binary]: true });+ try {+ callExecFileError(new Error('not found'));+ callExecFileError(new Error('no registry PATH'));+ callExecFileError(new Error('no registry PATH'));+ callExecFile('1.2.13');+ callExecFile('--input-format --output-format stream-json --conversation');+ const { detectHeterogeneousCliCommand } = await importModule();+ expect(await detectHeterogeneousCliCommand('antigravity', 'agy')).toMatchObject({+ available: true,+ path: binary,+ });+ expect(execMock).not.toHaveBeenCalled();+ } finally {+ process.env.PATH = originalPath;+ if (originalLocal === undefined) delete process.env.LOCALAPPDATA;+ else process.env.LOCALAPPDATA = originalLocal;+ }+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex ca6c3738f65..500433586df 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -67,7 +67,7 @@ interface RecoveredProbeEnvironment {resolvedPathEnv: string;}-const VERSION_PATTERN = /v?(\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?)/;+const VERSION_PATTERN = /v?(\d+\.\d+\.\d+(?:-[\dA-Za-z.-]+)?(?:\+[\dA-Za-z.-]+)?)/;const extractVersion = (versionBanner: string): string | undefined =>versionBanner.match(VERSION_PATTERN)?.[1];@@ -665,6 +665,11 @@ export const detectValidatedCommand = async (): Promise<CliCommandStatus> => detectValidatedCommandCandidates([command], options, probeEnv);const HETEROGENEOUS_CLI_AGENT_OPTIONS = {+ 'antigravity': {+ validateHelpKeywords: ['--input-format', '--output-format', '--conversation', 'stream-json'],+ validatePattern:+ /^(?:(?:agy|antigravity(?: cli)?) (?:version )?)?v?\d+\.\d+\.\d+(?:-[\dA-Z.-]+)?(?:\+[\dA-Z.-]+)?$/i,+ },'amp': {validateFlag: '--help',validateKeywords: ['Amp CLI'],@@ -745,6 +750,14 @@ export const DEFAULT_HETERO_COMMAND = Object.fromEntries(// desktop app bundles a functional CLI inside its app bundle without symlinking it.const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[] => {switch (agentType) {+ case 'antigravity': {+ if (platform() === 'win32') {+ const localAppData = process.env.LOCALAPPDATA;+ return localAppData ? [path.win32.join(localAppData, 'agy', 'bin', 'agy.exe')] : [];+ }+ if (platform() !== 'darwin' && platform() !== 'linux') return [];+ return [path.join(homedir(), '.local', 'bin', 'agy')];+ }case 'amp': {if (platform() !== 'darwin' && platform() !== 'linux') return [];diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.antigravity.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.antigravity.test.tsnew file mode 100644index 00000000000..6480ddf4998--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.antigravity.test.ts@@ -0,0 +1,130 @@+import type * as childProcess from 'node:child_process';+import { EventEmitter } from 'node:events';+import type * as os from 'node:os';+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;+ }),+ };+});++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',+ });+ });++ 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');+ const handle = await spawnAgent({+ agentType: 'antigravity',+ operationId: 'op-agy',+ prompt: 'continue',+ resumeSessionId: 'agy-session',+ });+ 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',+ '--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);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 77df323fc9c..bbef4aec895 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -16,6 +16,7 @@ import {spawnTraeAcpAgent,} from './acpSpawnAgent';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';+import { buildAntigravityArgs } from './antigravity';import { ClaudeCodeLiveInput } from './claudeCodeLiveInput';import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';import { resolveCliSpawnPlan } from './cliSpawn';@@ -388,6 +389,9 @@ export const buildQoderArgs = ({const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {switch (params.agentType) {+ case 'antigravity': {+ return buildAntigravityArgs(params);+ }case 'amp': {return buildAmpArgs(params);}diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 27eba043917..4f3d9957d23 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -5,6 +5,25 @@ export default {'directMention.progress.usingTool': 'Using {{name}}…','directMention.progress.viewFullRecord': 'View full record','sharePage.app.linkCopied': 'Link copied',+ 'heteroAgent.antigravityQuota.title': 'Antigravity quota',+ 'heteroAgent.antigravityQuota.tooltip': 'View Antigravity model quotas',+ 'heteroAgent.antigravityQuota.fiveHour': '5 hours',+ 'heteroAgent.antigravityQuota.remainingAmount': '{{amount}} remaining',+ 'heteroAgent.antigravityQuota.unknown': 'Unknown',+ 'heteroAgent.antigravityQuota.disabled': 'Unavailable',+ 'heteroAgent.antigravityQuota.resetUnconfirmed':+ 'Reset time reached. Refresh to check the latest quota.',+ 'heteroAgent.antigravityQuota.stale': 'Showing the last query. Refresh to confirm current quota.',+ 'heteroAgent.antigravityQuota.authRequired': 'Run agy in a terminal to sign in, then refresh.',+ 'heteroAgent.antigravityQuota.cliNotFound':+ 'Antigravity CLI was not found on this device. Install agy, then refresh.',+ 'heteroAgent.antigravityQuota.unsupported':+ 'Update agy to a version that supports structured quota queries, then refresh.',+ 'heteroAgent.antigravityQuota.timeout':+ 'The quota query timed out. Check the device connection and try again.',+ 'heteroAgent.antigravityQuota.error':+ 'Could not query Antigravity quota. Check the device and try again.',+'sharePage.app.open': 'Open app','sharePage.app.help': 'Trouble opening the app?','sharePage.app.helpDescription':@@ -26,6 +45,7 @@ export default {'sharePage.app.fallback.download': 'Get the app','sharePage.app.fallback.title': 'App didn’t open?',+ 'newAntigravityAgent': 'Add Antigravity','backgroundActivity.alertDesc': '{{name}} is using {{memory}} of memory and {{cpu}} CPU.','backgroundActivity.cpu': 'CPU','backgroundActivity.details': 'View details',@@ -1261,6 +1281,16 @@ export default {"Skill wasn't added. Retry, or create an Agent anyway.",'createModal.skillSuggestion.title': 'A Skill may fit better','createModal.title': 'What should this Agent do?',+ 'antigravityInstallGuide.actions.openDocs': 'Open Install Guide',+ 'antigravityInstallGuide.actions.openSystemTools': 'Open System Tools',+ 'antigravityInstallGuide.afterInstall':+ 'After installing, run `agy` and sign in with your Google account, then retry your message or click Re-detect in System Tools.',+ 'antigravityInstallGuide.desc':+ 'Antigravity needs the native agy CLI with stream-json support. Follow the install guide for your operating system and make sure the `agy` command is available.',+ 'antigravityInstallGuide.menuNotification.title': 'Antigravity CLI not found',+ 'antigravityInstallGuide.reason': 'LobeHub could not start Antigravity: {{message}}',+ 'antigravityInstallGuide.title': 'Install Antigravity CLI',+ 'connectAgent.providerDesc.antigravity': 'Google coding agent CLI','ampInstallGuide.actions.openDocs': 'Open Install Guide','ampInstallGuide.actions.openSystemTools': 'Open System Tools','ampInstallGuide.afterInstall':diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 7fe224e1e58..f0e46a2e07b 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -27,6 +27,7 @@ export default {'devices.cliUpdate.retryCommand': 'Retry same request','devices.cliUpdate.ambiguous':'The request may have been accepted. Refresh status or retry the same request; do not start another operation.',+ 'settingSystemTools.tools.antigravity.desc': 'Antigravity CLI - Google agentic coding CLI','devices.keepAwake.desc':'Prevent automatic sleep while this computer is connected as a device, so it stays reachable. The display can still turn off; closing a laptop lid without an external display still puts it to sleep.','devices.keepAwake.title': 'Keep Awake While Connected',diff --git a/packages/types/src/agent/agencyConfig.antigravity.test.ts b/packages/types/src/agent/agencyConfig.antigravity.test.tsnew file mode 100644index 00000000000..bbadc49f929--- /dev/null+++ b/packages/types/src/agent/agencyConfig.antigravity.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import {+ applyTopicModelToHeterogeneousProvider,+ buildHeteroExecArgs,+ buildHeteroSpawnArgs,+} from './agencyConfig';+import { applyHeteroSelection, getHeteroSelectorCapability } from './heteroSelectorCapabilities';++describe('Antigravity model variant selection', () => {+ it('exposes the native model catalog without an independent effort selector', () => {+ const capability = getHeteroSelectorCapability('antigravity');+ expect(capability?.model?.source).toBe('catalog');+ expect(capability?.effort).toBeUndefined();+ expect(capability?.model?.resolve({ model: 'gemini-4-argon-high' })).toBe(+ 'gemini-4-argon-high',+ );+ });++ it('passes the complete model variant through native and CLI wrapper launches', () => {+ const provider = { type: 'antigravity' as const, model: 'gemini-4-argon-high' };+ expect(buildHeteroSpawnArgs(provider)).toEqual(['--model', 'gemini-4-argon-high']);+ expect(buildHeteroExecArgs(provider)).toEqual(['--model', 'gemini-4-argon-high']);+ expect(buildHeteroSpawnArgs({ ...provider, model: 'default' })).toBeUndefined();+ expect(buildHeteroExecArgs({ ...provider, model: 'default' })).toBeUndefined();+ });++ it('replaces the configured model argument when picking another variant', () => {+ const provider = {+ type: 'antigravity' as const,+ args: ['--model=gemini-4-argon-low', '--sandbox'],+ };+ const patch = applyHeteroSelection(provider, { model: 'gemini-4-argon-high' });+ expect(patch).toEqual({ args: ['--sandbox'], model: 'gemini-4-argon-high' });+ expect(buildHeteroSpawnArgs({ ...provider, ...patch })).toEqual([+ '--sandbox',+ '--model',+ 'gemini-4-argon-high',+ ]);+ expect(buildHeteroExecArgs({ ...provider, ...patch })).toEqual([+ '--agent-arg=--sandbox',+ '--model',+ 'gemini-4-argon-high',+ ]);+ });++ it('uses the topic variant without changing the Agent default', () => {+ const provider = { type: 'antigravity' as const, model: 'gemini-4-argon-low' };+ const effective = applyTopicModelToHeterogeneousProvider(provider, {+ model: 'gemini-4-argon-high',+ provider: 'antigravity',+ });+ expect(buildHeteroSpawnArgs(effective)).toEqual(['--model', 'gemini-4-argon-high']);+ expect(buildHeteroExecArgs(effective)).toEqual(['--model', 'gemini-4-argon-high']);+ expect(provider).toEqual({ type: 'antigravity', model: 'gemini-4-argon-low' });+ });+});diff --git a/packages/types/src/agent/heteroSelectorCapabilities.ts b/packages/types/src/agent/heteroSelectorCapabilities.tsindex 3500cc688e3..c86fce97902 100644--- a/packages/types/src/agent/heteroSelectorCapabilities.ts+++ b/packages/types/src/agent/heteroSelectorCapabilities.ts@@ -392,6 +392,13 @@ const MODEL_FLAGS_ENCODING = { flags: ['-m', '--model'], kind: 'flag' } as const* user-authored args already cover a dimension.*/export const HETERO_SELECTOR_CAPABILITIES = {+ 'antigravity': {+ model: {+ encodings: [{ flags: ['--model'], kind: 'flag' }],+ resolve: resolvePersistedModel,+ source: 'catalog',+ },+ },'amp': {mode: {encodings: [{ flags: ['--mode'], kind: 'flag' }],@@ -702,24 +709,7 @@ export const buildHeteroSpawnArgs = (provider: HeteroSpawnSelectionProvider | undefined | null,): string[] | undefined => {if (!provider) return undefined;- if (- provider.type !== 'amp' &&- provider.type !== 'claude-code' &&- provider.type !== 'codebuddy' &&- provider.type !== 'codex' &&- provider.type !== 'copilot' &&- provider.type !== 'cursor' &&- provider.type !== 'droid' &&- provider.type !== 'devin' &&- provider.type !== 'grok-build' &&- provider.type !== 'kimi-code' &&- provider.type !== 'opencode' &&- provider.type !== 'pi' &&- provider.type !== 'qoder' &&- provider.type !== 'trae'- ) {- return provider.args;- }+ if (!getHeteroSelectorCapability(provider.type)) return provider.args;const baseArgs = provider.args ?? [];const extraArgs: string[] = [];@@ -798,7 +788,7 @@ export const buildHeteroSpawnArgs = (}}- if (provider.type === 'cursor' || provider.type === 'devin') {+ if (provider.type === 'antigravity' || provider.type === 'cursor' || provider.type === 'devin') {const model = provider.model?.trim();if (model &&@@ -857,25 +847,7 @@ export const buildHeteroExecArgs = (provider: HeteroSpawnSelectionProvider | undefined | null,): string[] | undefined => {if (!provider) return undefined;- if (- provider.type !== 'amp' &&- provider.type !== 'claude-code' &&- provider.type !== 'codebuddy' &&- provider.type !== 'codex' &&- provider.type !== 'copilot' &&- provider.type !== 'cursor' &&- provider.type !== 'droid' &&- provider.type !== 'devin' &&- provider.type !== 'grok-build' &&- provider.type !== 'kimi-code' &&- provider.type !== 'opencode' &&- provider.type !== 'pi' &&- provider.type !== 'qoder' &&- provider.type !== 'trae' &&- provider.type !== 'deepseek-harness'- ) {- return provider.args;- }+ if (!getHeteroSelectorCapability(provider.type)) return provider.args;const baseArgs = provider.args ?? [];const wrapperArgs = baseArgs.map((arg) => `${HETERO_EXEC_AGENT_ARG_FLAG}=${arg}`);@@ -974,7 +946,7 @@ export const buildHeteroExecArgs = (}}- if (provider.type === 'cursor' || provider.type === 'devin') {+ if (provider.type === 'antigravity' || provider.type === 'cursor' || provider.type === 'devin') {const model = provider.model?.trim();if (model &&diff --git a/packages/types/src/agent/heterogeneousAgent.ts b/packages/types/src/agent/heterogeneousAgent.tsindex 24ae66ec54a..effb7d97b87 100644--- a/packages/types/src/agent/heterogeneousAgent.ts+++ b/packages/types/src/agent/heterogeneousAgent.ts@@ -52,6 +52,32 @@ const COMMON_AUTH_REQUIRED_PATTERNS = [] as const;export const HETEROGENEOUS_AGENT_CONFIGS = [+ {+ auth: {+ docsUrl: 'https://antigravity.google/docs/cli/install/',+ errorMessage: 'Antigravity could not authenticate. Run `agy` and sign in, then retry.',+ patterns: [+ ...COMMON_AUTH_REQUIRED_PATTERNS,+ 'authentication required',+ 'not logged in',+ 'please (?:log|sign) in',+ ],+ signInCommand: 'agy',+ },+ defaultCommand: 'agy',+ defaultTopicGroupMode: 'byProject',+ iconId: 'Antigravity',+ install: {+ commands: [],+ docsUrl: 'https://antigravity.google/docs/cli/install/',+ },+ kind: 'local-cli',+ menuKey: 'newAntigravityAgent',+ menuLabelKey: 'newAntigravityAgent',+ resume: { supported: true },+ title: 'Antigravity',+ type: 'antigravity',+ },{auth: {docsUrl: 'https://ampcode.com/manual',diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/AntigravityQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/AntigravityQuotaMenu.tsxnew file mode 100644index 00000000000..2c352cafe08--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/AntigravityQuotaMenu.tsx@@ -0,0 +1,156 @@+'use client';++import type {+ AntigravityQuotaParams,+ AntigravityQuotaSnapshot,+} from '@lobechat/heterogeneous-agents/quota';+import { Flexbox, Progress, Text } from '@lobehub/ui';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';+import { antigravityQuotaService } from '@/services/antigravityQuota';++import { antigravityQuotaCompact, isAntigravityQuotaStale } from './antigravityQuotaView';+import type { QuotaMenuHelpers } from './QuotaMenu';+import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';++const noWindows = () => [];+const hasBuckets = (quota: AntigravityQuotaSnapshot) =>+ quota.groups.some((group) => group.buckets.length > 0);+const createErrorSnapshot = (): AntigravityQuotaSnapshot => ({+ error: 'Antigravity quota is unavailable',+ errorCode: 'command_failed',+ groups: [],+ provider: 'antigravity',+ status: 'error',+ updatedAt: Date.now(),+});++const AntigravityQuotaGroups = ({+ quota,+ now,+ formatDuration,+}: {+ quota: AntigravityQuotaSnapshot;+} & Pick<QuotaMenuHelpers<AntigravityQuotaSnapshot>, 'formatDuration' | 'now'>) => {+ const { t } = useTranslation('chat');+ return (+ <Flexbox gap={16}>+ {quota.groups.map((group) => (+ <Flexbox gap={8} key={group.name}>+ <Text strong>{group.name}</Text>+ {group.buckets.map((bucket) => {+ const fraction = bucket.remainingFraction;+ const label =+ bucket.name === 'Weekly Limit Remaining'+ ? t('heteroAgent.quota.weekly')+ : bucket.name === 'Five Hour Limit Remaining'+ ? t('heteroAgent.antigravityQuota.fiveHour')+ : bucket.name;+ const duration =+ bucket.resetsAt === null ? undefined : formatDuration(bucket.resetsAt - now);+ const value = bucket.disabled+ ? t('heteroAgent.antigravityQuota.disabled')+ : fraction !== null+ ? `${fraction > 0 && fraction < 0.001 ? '<' : ''}${new Intl.NumberFormat(+ undefined,+ {+ style: 'percent',+ maximumFractionDigits: 1,+ },+ ).format(fraction > 0 && fraction < 0.001 ? 0.001 : fraction)}`+ : bucket.remainingAmount !== null+ ? t('heteroAgent.antigravityQuota.remainingAmount', {+ amount: bucket.remainingAmount,+ })+ : t('heteroAgent.antigravityQuota.unknown');+ return (+ <Flexbox gap={4} key={bucket.id}>+ <Flexbox horizontal gap={8} justify="space-between">+ <Text>{label}</Text>+ <Text>{value}</Text>+ </Flexbox>+ {!bucket.disabled && fraction !== null && (+ <Progress+ aria-label={`${group.name}: ${label}`}+ percent={fraction * 100}+ showInfo={false}+ size="small"+ />+ )}+ {bucket.resetsAt !== null && !bucket.disabled && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {bucket.resetsAt <= now+ ? t('heteroAgent.antigravityQuota.resetUnconfirmed')+ : duration+ ? t('heteroAgent.quota.resetsIn', { duration })+ : t('heteroAgent.quota.resetsSoon')}+ </Text>+ )}+ </Flexbox>+ );+ })}+ </Flexbox>+ ))}+ </Flexbox>+ );+};++/** Reuse quota-panel request ordering, scope isolation, persistence and refresh feedback. */+export const AntigravityQuotaMenu = ({+ command,+ deviceId,+ env,+}: AntigravityQuotaParams & { deviceId?: string }) => {+ const { t } = useTranslation('chat');+ const agentId = useAgentId();+ const sourceKey = createQuotaSourceKey('antigravity', agentId, deviceId, command, env);+ const fetchQuota = useMemo(+ () => (options?: { force?: boolean }) =>+ antigravityQuotaService.getQuota({ command, deviceId, env, force: options?.force }),+ [command, deviceId, env],+ );+ const errorText = (quota: AntigravityQuotaSnapshot) => {+ switch (quota.errorCode) {+ case 'auth_required': {+ return t('heteroAgent.antigravityQuota.authRequired');+ }+ case 'cli_not_found': {+ return t('heteroAgent.antigravityQuota.cliNotFound');+ }+ case 'unsupported_client': {+ return t('heteroAgent.antigravityQuota.unsupported');+ }+ case 'timeout': {+ return t('heteroAgent.antigravityQuota.timeout');+ }+ default: {+ return t('heteroAgent.antigravityQuota.error');+ }+ }+ };+ return (+ <QuotaMenu+ autoRefreshMs={120_000}+ contentWidth={320}+ createErrorSnapshot={createErrorSnapshot}+ fetchQuota={fetchQuota}+ getCompactItems={antigravityQuotaCompact}+ getErrorText={errorText}+ getRefreshErrorText={errorText}+ getUnavailableText={errorText}+ getWindows={noWindows}+ hasExtraData={hasBuckets}+ renderBody={(quota, helpers) => <AntigravityQuotaGroups quota={quota} {...helpers} />}+ sourceKey={sourceKey}+ title={t('heteroAgent.antigravityQuota.title')}+ tooltip={t('heteroAgent.antigravityQuota.tooltip')}+ getStaleNotice={(quota) =>+ isAntigravityQuotaStale(quota, Date.now())+ ? t('heteroAgent.antigravityQuota.stale')+ : undefined+ }+ />+ );+};diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsxindex 4e52f233457..a9d00201599 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx@@ -11,6 +11,7 @@ import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';import { cacheScope } from '@/libs/replica';import { hashQuotaSourceKey, quotaPanelResource } from '@/store/agentQuota/projection';+import { AntigravityQuotaMenu } from './AntigravityQuotaMenu';import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';import CodexQuotaMenu from './CodexQuotaMenu';import KimiCodeQuotaMenu from './KimiCodeQuotaMenu';@@ -18,6 +19,7 @@ import { createQuotaSourceKey } from './QuotaMenu';import { claudeSnapshot, codexSnapshot, isolateQuotaReplica, kimiCodeSnapshot } from './testUtils';const mockService = vi.hoisted(() => ({+ getAntigravityQuota: vi.fn(),consumeCodexRateLimitResetCredit: vi.fn(),getClaudeCodeQuota: vi.fn(),getCodexQuota: vi.fn(),@@ -106,15 +108,17 @@ vi.mock('@lobehub/ui', async (importOriginal) => {...(await importOriginal<object>()),ActionIcon: ({disabled,+ 'aria-label': ariaLabel,onClick,title,}: {- disabled?: boolean;- onClick?: () => void;- title?: string;+ 'aria-label'?: string;+ 'disabled'?: boolean;+ 'onClick'?: () => void;+ 'title'?: string;}) => (<button- aria-label={title}+ aria-label={ariaLabel ?? title}data-testid={title ? 'calendar' : 'refresh'}disabled={disabled}type="button"@@ -151,16 +155,18 @@ vi.mock('@lobehub/ui', async (importOriginal) => {async (importOriginal) => ({...((await importOriginal()) as Record<string, unknown>),ActionIcon: ({+ 'aria-label': ariaLabel,onClick,title,disabled,}: {- disabled?: boolean;- onClick?: (e: React.MouseEvent) => void;- title?: string;+ 'aria-label'?: string;+ 'disabled'?: boolean;+ 'onClick'?: (e: React.MouseEvent) => void;+ 'title'?: string;}) => (<button- aria-label={title}+ aria-label={ariaLabel ?? title}data-testid={title ? 'calendar' : 'refresh'}disabled={disabled}type="button"@@ -193,6 +199,7 @@ beforeEach(() => {confirmModalMock.mockReset();mockService.consumeCodexRateLimitResetCredit.mockReset();mockService.getClaudeCodeQuota.mockReset();+ mockService.getAntigravityQuota.mockReset();mockService.getCodexQuota.mockReset();mockService.getKimiCodeQuota.mockReset();mockLambdaClaudeQuota.mockReset();@@ -235,6 +242,56 @@ describe('quota panels sharing the account pool', () => {});describe('KimiCodeQuotaMenu', () => {+ it('renders native Antigravity groups, unknown buckets and a reset that needs confirmation', async () => {+ const sample = {+ error: null,+ provider: 'antigravity',+ status: 'ok',+ updatedAt: Date.now(),+ groups: [+ {+ name: 'Gemini Models',+ buckets: [+ {+ id: 'weekly',+ name: 'Weekly',+ remainingFraction: 0.939,+ remainingAmount: null,+ resetsAt: Date.now() - 1000,+ disabled: false,+ window: 'weekly',+ },+ {+ id: 'future',+ name: 'Dynamic limit',+ remainingFraction: null,+ remainingAmount: null,+ resetsAt: null,+ disabled: false,+ window: 'dynamic',+ },+ ],+ },+ ],+ };+ mockService.getAntigravityQuota.mockResolvedValue(sample);+ render(<AntigravityQuotaMenu command="/custom/agy" />);+ fireEvent.click(screen.getByRole('button', { name: 'heteroAgent.antigravityQuota.tooltip' }));+ expect(await screen.findByText('Gemini Models')).toBeTruthy();+ expect(screen.getByText('93.9%')).toBeTruthy();+ expect(screen.getByText('heteroAgent.antigravityQuota.unknown')).toBeTruthy();+ expect(screen.getByText('heteroAgent.antigravityQuota.resetUnconfirmed')).toBeTruthy();+ expect(mockService.getAntigravityQuota).toHaveBeenCalledWith({+ command: '/custom/agy',+ env: undefined,+ force: undefined,+ });+ mockService.getAntigravityQuota.mockRejectedValue(new Error('offline'));+ fireEvent.click(screen.getByRole('button', { name: 'heteroAgent.quota.refresh' }));+ expect(await screen.findByText('heteroAgent.antigravityQuota.error')).toBeTruthy();+ expect(screen.getByText('93.9%')).toBeTruthy();+ });+it('renders all four windows and the Extra Usage footer from the snapshot', async () => {mockService.getKimiCodeQuota.mockResolvedValue(kimiCodeSnapshot({diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsxindex 6e8fdae6e5c..8757f075590 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx@@ -140,7 +140,7 @@ export interface QuotaWindowItem {window: HeteroQuotaWindow | null;}-interface CompactQuotaItem {+export interface CompactQuotaItem {key: string;label?: string;leftPercent: number;@@ -183,6 +183,8 @@ interface QuotaMenuProps<S extends QuotaSnapshotBase> {contentWidth?: number;createErrorSnapshot: (error: unknown) => S;fetchQuota: (options?: FetchQuotaOptions<S>) => Promise<S>;+ /** Non-window providers keep their own native bucket semantics. */+ getCompactItems?: (quota: S) => CompactQuotaItem[];/** Localized explanation for `status: 'error'`; falls back to `error`. */getErrorText?: (quota: S) => string | undefined;/** Localized explanation for a manual refresh error when stale data is preserved. */@@ -197,6 +199,7 @@ interface QuotaMenuProps<S extends QuotaSnapshotBase> {getWindows: (quota: S) => QuotaWindowItem[];/** Extra agent-specific data (beyond windows) that makes the body worth rendering. */hasExtraData?: (quota: S) => boolean;+ renderBody?: (quota: S, helpers: QuotaMenuHelpers<S>) => ReactNode;renderFooter?: (quota: S, helpers: QuotaMenuHelpers<S>) => ReactNode;/** Agent-specific content rendered above the quota windows (e.g. account switcher). */renderHeader?: (quota: S, helpers: QuotaMenuHelpers<S>) => ReactNode;@@ -233,6 +236,8 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({getStaleNotice,getUnavailableText,getWindows,+ getCompactItems,+ renderBody,hasExtraData,renderFooter,renderHeader,@@ -521,7 +526,8 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({});}}- const compactItems = [...compactItemsByGroup.values()];+ const compactItems =+ quota && getCompactItems ? getCompactItems(quota) : [...compactItemsByGroup.values()];const hasQuotaData = hasQuotaDataForSnapshot(quota);const manualRefreshErrorText =refreshError && (getRefreshErrorText?.(refreshError) || t('heteroAgent.quota.refreshFailed'));@@ -631,6 +637,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({</Flexbox><Tooltip title={t('heteroAgent.quota.refresh')}><ActionIcon+ aria-label={t('heteroAgent.quota.refresh')}disabled={loading}icon={RefreshCwIcon}size={'small'}@@ -663,7 +670,11 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({) : hasQuotaData ? (<>{quota && renderHeader?.(quota, { applyQuota, formatDuration, now })}- <Flexbox gap={10}>{windows.map((item) => renderQuotaWindow(item))}</Flexbox>+ <Flexbox gap={10}>+ {quota && renderBody+ ? renderBody(quota, { applyQuota, formatDuration, now })+ : windows.map((item) => renderQuotaWindow(item))}+ </Flexbox>{quota && renderFooter?.(quota, { applyQuota, formatDuration, now })}{refreshErrorText && (// Stale windows stay the subject; the notice only annotates them.diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/antigravityQuotaView.test.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/antigravityQuotaView.test.tsnew file mode 100644index 00000000000..0930d6d61bd--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/antigravityQuotaView.test.ts@@ -0,0 +1,86 @@+import type { AntigravityQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';+import { describe, expect, it } from 'vitest';++import { antigravityQuotaCompact, isAntigravityQuotaStale } from './antigravityQuotaView';++const now = 1_800_000_000_000;+const snapshot: AntigravityQuotaSnapshot = {+ error: null,+ groups: [+ {+ name: 'Models',+ buckets: [+ {+ id: 'model',+ name: 'Quota',+ window: 'weekly',+ disabled: false,+ remainingAmount: null,+ remainingFraction: 0.939,+ resetsAt: now + 1000,+ },+ ],+ },+ ],+ provider: 'antigravity',+ status: 'ok',+ updatedAt: now,+};++describe('Antigravity quota display', () => {+ it('uses the native remaining fraction without substituting a window projection', () => {+ expect(antigravityQuotaCompact(snapshot, now)).toEqual([+ { key: 'antigravity', leftPercent: 93.9 },+ ]);+ });+ it('does not claim an expired snapshot is full or still current', () => {+ expect(isAntigravityQuotaStale(snapshot, now + 1001)).toBe(true);+ expect(antigravityQuotaCompact(snapshot, now + 1001)).toEqual([]);+ expect(snapshot.groups[0].buckets[0].remainingFraction).toBe(0.939);+ expect(antigravityQuotaCompact({ ...snapshot, updatedAt: now - 120_000 }, now)).toEqual([]);+ });+ it('does not round a small positive balance into an exhausted badge', () => {+ const tiny = {+ ...snapshot,+ groups: [+ {+ name: 'Models',+ buckets: [{ ...snapshot.groups[0].buckets[0], remainingFraction: 0.0001 }],+ },+ ],+ };+ expect(antigravityQuotaCompact(tiny, now)[0]).toMatchObject({ label: '<', leftPercent: 0.1 });+ });+ it('excludes disabled and unknown buckets, retaining a genuine zero', () => {+ const bucket = snapshot.groups[0].buckets[0];+ const data = {+ ...snapshot,+ groups: [+ {+ name: 'Models',+ buckets: [+ {+ ...bucket,+ id: 'disabled',+ disabled: true,+ remainingFraction: 0,+ resetsAt: now - 1000,+ },+ { ...bucket, id: 'unknown', remainingFraction: null },+ bucket,+ ],+ },+ ],+ };+ expect(antigravityQuotaCompact(data, now)[0].leftPercent).toBe(93.9);+ expect(+ antigravityQuotaCompact(+ {+ ...snapshot,+ groups: [{ name: 'Models', buckets: [{ ...bucket, remainingFraction: 0 }] }],+ },+ now,+ )[0].leftPercent,+ ).toBe(0);+ });+});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/antigravityQuotaView.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/antigravityQuotaView.tsnew file mode 100644index 00000000000..f18e8e21a3f--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/antigravityQuotaView.ts@@ -0,0 +1,28 @@+import type { AntigravityQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';++/** Old readings remain visible in the panel but never masquerade as a current badge. */+export const isAntigravityQuotaStale = (quota: AntigravityQuotaSnapshot, now: number) =>+ now - quota.updatedAt >= 120_000 ||+ quota.groups.some((group) =>+ group.buckets.some(+ (bucket) => !bucket.disabled && bucket.resetsAt !== null && bucket.resetsAt <= now,+ ),+ );++export const antigravityQuotaCompact = (quota: AntigravityQuotaSnapshot, now = Date.now()) => {+ if (quota.status !== 'ok' || isAntigravityQuotaStale(quota, now)) return [];+ const fractions = quota.groups.flatMap((group) =>+ group.buckets.flatMap((bucket) =>+ !bucket.disabled && bucket.remainingFraction !== null ? [bucket.remainingFraction] : [],+ ),+ );+ if (!fractions.length) return [];+ const remaining = Math.min(...fractions);+ return [+ {+ key: 'antigravity',+ ...(remaining > 0 && remaining < 0.001 ? { label: '<' } : {}),+ leftPercent: remaining === 0 ? 0 : Math.max(0.1, Math.round(remaining * 1000) / 10),+ },+ ];+};diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.tsindex e262976f9ab..2e5a29cd2ee 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.ts+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/index.ts@@ -1,3 +1,4 @@+export { AntigravityQuotaMenu } from './AntigravityQuotaMenu';export { default as ClaudeCodeQuotaMenu } from './ClaudeCodeQuotaMenu';export { default as CodexQuotaMenu } from './CodexQuotaMenu';export { default as KimiCodeQuotaMenu } from './KimiCodeQuotaMenu';diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsxindex a5ab62046b0..f953ed662a7 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx@@ -25,7 +25,12 @@ import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';-import { ClaudeCodeQuotaMenu, CodexQuotaMenu, KimiCodeQuotaMenu } from './QuotaMenu';+import {+ AntigravityQuotaMenu,+ ClaudeCodeQuotaMenu,+ CodexQuotaMenu,+ KimiCodeQuotaMenu,+} from './QuotaMenu';const styles = stylex.create({// Pinned to the same 28px row as the plain ControlBar so the composer footer@@ -195,6 +200,11 @@ const HeteroControlBar = memo(() => {heteroProvider?.type === 'kimi-code' &&(isLocalHeteroExecution || !!quotaDeviceId);+ const shouldShowAntigravityQuota =+ isSubscriptionAuth &&+ heteroProvider?.type === 'antigravity' &&+ (isLocalHeteroExecution || !!quotaDeviceId);+if (isAccessLoading) return <HeteroControlBarSkeleton />;// A can-use collaborator may choose only their execution device; working@@ -239,7 +249,8 @@ const HeteroControlBar = memo(() => {{(shouldShowApiCredits ||(shouldShowClaudeQuota && quotaDeviceId) ||(shouldShowCodexQuota && quotaDeviceId) ||- (shouldShowKimiCodeQuota && quotaDeviceId)) && (+ (shouldShowKimiCodeQuota && quotaDeviceId) ||+ (shouldShowAntigravityQuota && quotaDeviceId)) && (<Flexboxhorizontalalign={'center'}@@ -247,6 +258,13 @@ const HeteroControlBar = memo(() => {gap={4}>{shouldShowApiCredits && <ChatInputCredits />}+ {shouldShowAntigravityQuota && quotaDeviceId && (+ <AntigravityQuotaMenu+ command={heteroProvider?.command}+ deviceId={quotaDeviceId}+ env={heteroProvider?.env}+ />+ )}{shouldShowClaudeQuota && quotaDeviceId && (<ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />)}@@ -335,6 +353,13 @@ const HeteroControlBar = memo(() => {gap={4}>{shouldShowApiCredits && <ChatInputCredits />}+ {shouldShowAntigravityQuota && (+ <AntigravityQuotaMenu+ command={heteroProvider?.command}+ deviceId={quotaDeviceId}+ env={heteroProvider?.env}+ />+ )}{shouldShowCodexQuota && (<CodexQuotaMenucommand={heteroProvider?.command}diff --git a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.tsindex 4a7e1d4ec19..401fb0a2719 100644--- a/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts+++ b/src/features/ChatInput/ControlBar/HeteroModel/selectorView.test.ts@@ -57,6 +57,7 @@ describe('resolveSelectorShape', () => {});it('gives catalog-only providers the bare picker', () => {+ expect(resolveSelectorShape({ type: 'antigravity' }, true).kind).toBe('catalog');expect(resolveSelectorShape({ type: 'deepseek-harness' }, true).kind).toBe('catalog');expect(resolveSelectorShape({ type: 'kimi-code' }, true).kind).toBe('catalog');expect(resolveSelectorShape({ type: 'opencode' }, true).kind).toBe('catalog');@@ -76,6 +77,13 @@ describe('resolveSelectorShape', () => {});describe('dimensions per provider', () => {+ it('shows the Antigravity variant without a second effort dimension', () => {+ const view = viewOf({ type: 'antigravity', model: 'gemini-4-argon-high' });+ expect(view.isCatalogModel).toBe(true);+ expect(view.model).toBe('gemini-4-argon-high');+ expect(view.dimensions).toEqual([]);+ expect(view.triggerLabel.secondaryText).toBeUndefined();+ });it('uses the Codex catalog while preserving reasoning levels through max', () => {expect(viewOf({ type: 'codex' }).isCatalogModel).toBe(true);diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.tsindex 14d586e4f14..7d47073ebdd 100644--- a/src/features/ConnectAgent/providers.ts+++ b/src/features/ConnectAgent/providers.ts@@ -15,6 +15,7 @@ import {} from '@lobechat/heterogeneous-agents/client';import {Amp,+ Antigravity,ClaudeCode,CodeBuddy,Codex,@@ -43,6 +44,7 @@ export interface ConnectableProvider {/** Compound brand icon module — render via `icon.Avatar`. */brand:| typeof Amp+ | typeof Antigravity| typeof ClaudeCode| typeof CodeBuddy| typeof Codex@@ -80,6 +82,7 @@ interface BuildConnectAgentConfigOptions {}const CLI_BRANDS: Record<LocalHeterogeneousAgentType, ConnectableProvider['brand']> = {+ 'antigravity': Antigravity,'amp': Amp,'claude-code': ClaudeCode,'codebuddy': CodeBuddy,diff --git a/src/features/Conversation/Error/heterogeneous.ts b/src/features/Conversation/Error/heterogeneous.tsindex 925ee31b9c3..0cc05904a26 100644--- a/src/features/Conversation/Error/heterogeneous.ts+++ b/src/features/Conversation/Error/heterogeneous.ts@@ -28,7 +28,8 @@ export const isHeterogeneousAgentStatusGuideError = (const { agentType, code } = value as Partial<HeterogeneousAgentSessionError>;return (- (agentType === 'amp' ||+ (agentType === 'antigravity' ||+ agentType === 'amp' ||agentType === 'claude-code' ||agentType === 'codebuddy' ||agentType === 'codex' ||diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsxindex e6e6538d0ac..6ee29d394de 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx@@ -3,6 +3,7 @@ import { HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/heterogeneous-agents';import { DroidIcon } from '@lobechat/heterogeneous-agents/client';import {Amp,+ Antigravity,ClaudeCode,CodeBuddy,Codex,@@ -24,6 +25,10 @@ import {} from './types';const GUIDE_PRESENTATION_CONFIG = {+ 'antigravity': {+ icon: Antigravity,+ translationPrefix: 'antigravityInstallGuide',+ },'amp': {icon: Amp,translationPrefix: 'ampInstallGuide',diff --git a/src/features/Recommendations/actions/heteroAgent.ts b/src/features/Recommendations/actions/heteroAgent.tsindex e0f33efcc68..7f8675d8e57 100644--- a/src/features/Recommendations/actions/heteroAgent.ts+++ b/src/features/Recommendations/actions/heteroAgent.ts@@ -4,6 +4,7 @@ import {} from '@lobechat/heterogeneous-agents/client';import {Amp,+ Antigravity,ClaudeCode,CodeBuddy,Codex,@@ -22,6 +23,7 @@ import { createElement } from 'react';import type { RecommendedAction } from './types';const avatarIcons = {+ 'antigravity': Antigravity.Avatar,'amp': Amp.Avatar,'claude-code': ClaudeCode.Avatar,'codebuddy': CodeBuddy.Avatar,diff --git a/src/features/Settings/system-tools/features/ToolDetectorSection.tsx b/src/features/Settings/system-tools/features/ToolDetectorSection.tsxindex 2a22a8288da..226451ad7af 100644--- a/src/features/Settings/system-tools/features/ToolDetectorSection.tsx+++ b/src/features/Settings/system-tools/features/ToolDetectorSection.tsx@@ -37,6 +37,7 @@ const TOOL_CATEGORIES = {tools: [{ descKey: 'settingSystemTools.tools.claude.desc', name: 'claude' },{ descKey: 'settingSystemTools.tools.codex.desc', name: 'codex' },+ { descKey: 'settingSystemTools.tools.antigravity.desc', name: 'agy' },{ descKey: 'settingSystemTools.tools.gemini.desc', name: 'gemini' },{ descKey: 'settingSystemTools.tools.qwen.desc', name: 'qwen' },{ descKey: 'settingSystemTools.tools.kimi.desc', name: 'kimi' },diff --git a/src/services/antigravityQuota.test.ts b/src/services/antigravityQuota.test.tsnew file mode 100644index 00000000000..291b21e7e66--- /dev/null+++ b/src/services/antigravityQuota.test.ts@@ -0,0 +1,32 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { antigravityQuotaService } from './antigravityQuota';++const mocks = vi.hoisted(() => ({ local: vi.fn(), remote: vi.fn() }));+vi.mock('./electron/heterogeneousAgent', () => ({+ heterogeneousAgentService: { getAntigravityQuota: mocks.local },+}));+vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { device: { getAntigravityQuota: { query: mocks.remote } } },+}));++describe('Antigravity quota transport', () => {+ beforeEach(() => vi.clearAllMocks());+ it('queries the local Desktop with the configured command, environment and refresh flag', async () => {+ const snapshot = { status: 'ok', groups: [] };+ mocks.local.mockResolvedValue(snapshot);+ const params = { command: '/custom/agy', env: { HTTP_PROXY: 'proxy' }, force: true };+ expect(await antigravityQuotaService.getQuota(params)).toBe(snapshot);+ expect(mocks.local).toHaveBeenCalledWith(params);+ expect(mocks.remote).not.toHaveBeenCalled();+ });+ it('queries the bound device and treats an offline or outdated device as an error', async () => {+ const params = { deviceId: 'device-1', command: 'agy', force: true };+ mocks.remote.mockResolvedValue({ status: 'ok', groups: [] });+ await antigravityQuotaService.getQuota(params);+ expect(mocks.remote).toHaveBeenCalledWith(params);+ expect(mocks.local).not.toHaveBeenCalled();+ mocks.remote.mockResolvedValue(null);+ await expect(antigravityQuotaService.getQuota(params)).rejects.toThrow('unavailable');+ });+});diff --git a/src/services/antigravityQuota.ts b/src/services/antigravityQuota.tsnew file mode 100644index 00000000000..778ed7401c4--- /dev/null+++ b/src/services/antigravityQuota.ts@@ -0,0 +1,22 @@+import type {+ AntigravityQuotaParams,+ AntigravityQuotaSnapshot,+} from '@lobechat/heterogeneous-agents/quota';++import { lambdaClient } from '@/libs/trpc/client';++import { heterogeneousAgentService } from './electron/heterogeneousAgent';++class AntigravityQuotaService {+ async getQuota({+ deviceId,+ ...params+ }: AntigravityQuotaParams & { deviceId?: string }): Promise<AntigravityQuotaSnapshot> {+ if (!deviceId) return heterogeneousAgentService.getAntigravityQuota(params);+ const result = await lambdaClient.device.getAntigravityQuota.query({ deviceId, ...params });+ if (!result) throw new Error('Antigravity quota is unavailable on this device');+ return result;+ }+}++export const antigravityQuotaService = new AntigravityQuotaService();diff --git a/src/services/electron/heterogeneousAgent.test.ts b/src/services/electron/heterogeneousAgent.test.tsindex 7c73c871dfa..7f6b67a9a31 100644--- a/src/services/electron/heterogeneousAgent.test.ts+++ b/src/services/electron/heterogeneousAgent.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest';const mockHeterogeneousAgent = vi.hoisted(() => ({+ getAntigravityQuota: vi.fn(),cancelSession: vi.fn(),consumeCodexRateLimitResetCredit: vi.fn(),getClaudeCodeQuota: vi.fn(),@@ -20,6 +21,21 @@ vi.mock('@/utils/electron/ipc', () => ({}));describe('heterogeneousAgentService', () => {+ it('forwards the Antigravity quota query over IPC', async () => {+ const { heterogeneousAgentService } = await import('./heterogeneousAgent');+ const snapshot = {+ error: null,+ groups: [],+ provider: 'antigravity',+ status: 'ok',+ updatedAt: 1,+ };+ mockHeterogeneousAgent.getAntigravityQuota.mockResolvedValue(snapshot);+ const params = { command: '/custom/agy', env: { HOME: '/profile' }, force: true };+ await expect(heterogeneousAgentService.getAntigravityQuota(params)).resolves.toEqual(snapshot);+ expect(mockHeterogeneousAgent.getAntigravityQuota).toHaveBeenCalledWith(params);+ });+it('forwards model catalog params over IPC', async () => {const { heterogeneousAgentService } = await import('./heterogeneousAgent');const catalog = {diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex 7f186346de6..48c1a6271cc 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -10,6 +10,10 @@ import type {HeterogeneousAgentType,HeterogeneousProviderBindingReference,} from '@lobechat/heterogeneous-agents';+import type {+ AntigravityQuotaParams,+ AntigravityQuotaSnapshot,+} from '@lobechat/heterogeneous-agents/quota';import type {HeterogeneousAgentModelCatalog,HeteroSessionImportMessage,@@ -123,6 +127,10 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.listModels(params);}+ async getAntigravityQuota(params?: AntigravityQuotaParams): Promise<AntigravityQuotaSnapshot> {+ return this.ipc.heterogeneousAgent.getAntigravityQuota(params);+ }+async getCodexQuota(params?: {command?: string;env?: Record<string, string>;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.tsnew file mode 100644index 00000000000..472f16fcbf8--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.antigravity.test.ts@@ -0,0 +1,255 @@+/** Antigravity 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';++import type { HeterogeneousAgentExecutorParams } from '../transports/hetero/heterogeneousAgentExecutor';+import { executeHeterogeneousAgent } from '../transports/hetero/heterogeneousAgentExecutor';++const mockBatchMutate = vi.fn();+const mockCreateMessage = vi.fn();+const mockUpdateMessage = vi.fn();+const mockUpdateToolMessage = vi.fn();+vi.mock('@/services/message', () => ({+ messageService: {+ batchMutate: (...args: any[]) => mockBatchMutate(...args),+ createMessage: (...args: any[]) => mockCreateMessage(...args),+ getMessages: vi.fn(async () => []),+ updateMessage: (...args: any[]) => mockUpdateMessage(...args),+ updateMessageError: vi.fn(async () => ({ success: false })),+ updateToolMessage: (...args: any[]) => mockUpdateToolMessage(...args),+ },+}));++vi.mock('@/services/thread', () => ({+ threadService: {+ createThread: vi.fn(async (params: any) => params.id),+ getThreads: vi.fn(async () => []),+ updateThread: vi.fn(),+ },+}));++const mockStartSession = vi.fn();+const mockSendPrompt = vi.fn();+const mockGetSessionInfo = vi.fn();+vi.mock('@/services/electron/heterogeneousAgent', () => ({+ heterogeneousAgentService: {+ cancelSession: vi.fn(async () => undefined),+ getClaudeCodeIdentity: vi.fn(async () => null),+ getCodexQuota: vi.fn(async () => null),+ getSessionInfo: (...args: any[]) => mockGetSessionInfo(...args),+ sendPrompt: (...args: any[]) => mockSendPrompt(...args),+ startSession: (...args: any[]) => mockStartSession(...args),+ stopSession: vi.fn(async () => undefined),+ },+}));++// Unmocked, account routing and the usage ledger fire real trpc fetches.+vi.mock('@/services/agentQuota', () => ({+ agentQuotaService: {+ recordUsage: vi.fn(async () => undefined),+ selectAccountForAgent: vi.fn(async () => null),+ },+}));++vi.mock('../transports/gateway/gatewayEventHandler', () => ({+ createGatewayEventHandler: vi.fn(() => vi.fn()),+}));++const IPC_SESSION = 'ipc-sess-1';++const defaultParams: HeterogeneousAgentExecutorParams = {+ assistantMessageId: 'ast-initial',+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ heterogeneousProvider: { command: 'agy', type: 'antigravity' },+ message: 'test prompt',+ operationId: 'op-1',+};++const flush = async () => {+ for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 10));+};++const createMockStore = () => {+ const store = {+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ dbMessagesMap: {},+ drainQueuedMessages: vi.fn(() => []),+ internal_dispatchMessage: vi.fn(),+ internal_toggleToolCallingStreaming: vi.fn(),+ markTopicUnread: vi.fn(),+ messagesMap: {},+ operations: {+ 'op-1': { context: defaultParams.context, metadata: { startTime: 0 } },+ } as Record<string, any>,+ refreshMessages: vi.fn(async () => {}),+ refreshThreads: vi.fn(async () => {}),+ replaceMessages: vi.fn(),+ sendMessage: vi.fn(async () => {}),+ startOperation: vi.fn(() => ({ abortController: new AbortController(), operationId: 'sub' })),+ topicDataMap: {},+ updateOperationMetadata: vi.fn((operationId: string, metadata: Record<string, any>) => {+ const operation = store.operations[operationId];+ if (operation) operation.metadata = { ...operation.metadata, ...metadata };+ }),+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),+ };+ return store as any;+};++/** Mirror main's raw stdout line → adapter → `heteroAgentEvent` broadcast. */+const setupIpc = () => {+ const listeners = new Map<string, (...args: any[]) => void>();+ (globalThis as any).window = {+ electron: {+ ipcRenderer: {+ on: vi.fn((channel: string, handler: (...args: any[]) => void) => {+ listeners.set(channel, handler);+ return () => listeners.delete(channel);+ }),+ removeListener: vi.fn(),+ },+ },+ };+ let adapter: AgentEventAdapter | undefined;+ return {+ emitComplete: () =>+ listeners.get('heteroAgentSessionComplete')?.(null, { sessionId: IPC_SESSION }),+ emitRawLine: (raw: unknown) => {+ adapter ??= createAdapter('antigravity');+ for (const event of adapter.adapt(raw)) {+ listeners.get('heteroAgentEvent')?.(null, {+ event: { ...event, operationId: defaultParams.operationId },+ sessionId: IPC_SESSION,+ });+ }+ },+ sessionId: () => adapter?.sessionId,+ };+};++describe('heterogeneousAgentExecutor — Antigravity', () => {+ let ipc: ReturnType<typeof setupIpc>;++ beforeEach(() => {+ vi.clearAllMocks();+ ipc = setupIpc();+ mockStartSession.mockResolvedValue({ sessionId: IPC_SESSION });+ mockGetSessionInfo.mockImplementation(async () => ({ agentSessionId: ipc.sessionId() }));+ // Honor caller-provided ids: coordinators pre-allocate them to chain parentIds.+ mockCreateMessage.mockImplementation(async (params: any) => ({+ id: params.id ?? `created-${params.role}-${Math.random().toString(36).slice(2, 8)}`,+ }));+ mockUpdateMessage.mockResolvedValue(undefined);+ mockUpdateToolMessage.mockResolvedValue(undefined);+ mockBatchMutate.mockImplementation(async (operations: any[]) => {+ const results = [];+ for (const [index, operation] of operations.entries()) {+ let id = operation.id;+ if (operation.type === 'createMessage')+ id = (await mockCreateMessage(operation.message)).id;+ else if (operation.type === 'updateToolMessage')+ await mockUpdateToolMessage(operation.id, operation.value, operation.ctx);+ else await mockUpdateMessage(operation.id, operation.value, operation.ctx);+ results.push({ id, index, success: true, type: operation.type });+ }+ return { results, success: true };+ });+ });++ afterEach(() => {+ delete (globalThis as any).window;+ });++ const runWithEvents = async (+ rawEvents: unknown[],+ opts?: { params?: Partial<HeterogeneousAgentExecutorParams> },+ ) => {+ const store = createMockStore();+ let resolveSendPrompt!: () => void;+ mockSendPrompt.mockReturnValue(new Promise<void>((r) => (resolveSendPrompt = r)));++ const executorPromise = executeHeterogeneousAgent(+ vi.fn(() => store),+ { ...defaultParams, ...opts?.params },+ );+ await flush();+ for (const raw of rawEvents) ipc.emitRawLine(raw);+ ipc.emitComplete();+ await flush();+ resolveSendPrompt();+ await executorPromise;+ await flush();+ return { store };+ };++ it('persists native Antigravity tools, final reply and resumable conversation identity', async () => {+ const { store } = await runWithEvents(+ [+ { event: 'init', conversation_id: 'agy-conversation', init: { cwd: '/project' } },+ {+ 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' },+ },+ },+ {+ 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 },+ },+ },+ {+ event: 'result',+ result: {+ conversation_id: 'agy-conversation',+ status: 'SUCCESS',+ response: 'The file says hello.',+ usage: { input_tokens: 100, output_tokens: 50 },+ },+ },+ ],+ { params: { heterogeneousProvider: { command: 'agy', type: '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',+ });+ expect(mockUpdateToolMessage).toHaveBeenCalledWith(+ tool.id,+ { content: 'hello', pluginError: undefined },+ { agentId: 'agent-1', topicId: 'topic-1' },+ );+ const finalAssistant = mockCreateMessage.mock.calls.find(([p]) => p.role === 'assistant')?.[0];+ expect(finalAssistant).toMatchObject({ parentId: 'ast-initial' });+ expect(mockUpdateMessage).toHaveBeenCalledWith(+ finalAssistant.id,+ expect.objectContaining({+ content: 'The file says hello.',+ }),+ expect.anything(),+ );+ expect(mockUpdateMessage).toHaveBeenCalledWith(+ finalAssistant.id,+ expect.objectContaining({ usage: expect.objectContaining({ totalTokens: 15 }) }),+ expect.anything(),+ );+ expect(store.updateTopicMetadata).toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({ heteroSessionId: 'agy-conversation' }),+ );+ });+});diff --git a/src/store/tool/slices/builtin/executors/__tests__/antigravityGitEffects.test.ts b/src/store/tool/slices/builtin/executors/__tests__/antigravityGitEffects.test.tsnew file mode 100644index 00000000000..3f3b008d356--- /dev/null+++ b/src/store/tool/slices/builtin/executors/__tests__/antigravityGitEffects.test.ts@@ -0,0 +1,83 @@+import type { ToolAfterCallContext } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { antigravityExecutor } from '../heteroCli';++const mocks = vi.hoisted(() => ({+ revalidateGitStatus: vi.fn(),+ updateTopicMetadata: vi.fn(),+}));++vi.mock('@/store/chat/store', () => ({+ getChatStoreState: () => ({ updateTopicMetadata: mocks.updateTopicMetadata }),+}));++vi.mock('@/store/chat/selectors', () => ({+ topicSelectors: {+ getTopicById: () => () => ({+ metadata: {+ boundDeviceId: 'remote-device',+ workingDirectoryConfig: { git: { branch: 'canary' }, path: '/repo' },+ },+ }),+ },+}));++vi.mock('@/store/device/gitStatus/store', () => ({+ getGitStatusStoreState: () => ({ revalidateGitStatus: mocks.revalidateGitStatus }),+}));++vi.mock('@/store/electron', () => ({+ getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: 'local-device' } }),+}));++vi.mock('@/services/git', () => ({ gitService: { listGitWorktrees: vi.fn() } }));++const call = (overrides: Partial<ToolAfterCallContext> = {}): ToolAfterCallContext => ({+ apiName: 'run_command',+ identifier: 'antigravity',+ params: { CommandLine: 'git worktree add -b fix/agy ../agy-worktree' },+ result: { content: '', success: true },+ topicId: 'run-topic',+ ...overrides,+});++beforeEach(() => vi.clearAllMocks());++describe('Antigravity Git completion effects', () => {+ it('records the native CommandLine worktree on the run topic', async () => {+ await antigravityExecutor.onAfterCall(call());++ expect(mocks.updateTopicMetadata).toHaveBeenCalledWith('run-topic', {+ workingDirectoryConfig: {+ git: { activeWorktree: '/agy-worktree', branch: 'fix/agy', isWorktree: true },+ path: '/repo',+ },+ });+ });++ it('refreshes the remote topic branch after a successful native git switch', async () => {+ await antigravityExecutor.onAfterCall(call({ params: { CommandLine: 'git switch fix/agy' } }));++ expect(mocks.updateTopicMetadata).toHaveBeenCalledWith('run-topic', {+ workingDirectoryConfig: { git: { branch: 'fix/agy' }, path: '/repo' },+ });+ expect(mocks.revalidateGitStatus).toHaveBeenCalledWith('remote-device', '/repo', ['branch']);+ });++ it.each([+ { result: { content: 'command failed', success: false } },+ { topicId: undefined },+ { apiName: 'write_to_file' },+ { params: { CommandLine: 42 } },+ { params: { content: 'git worktree add -b fix/agy ../agy-worktree' } },+ ])(+ 'does not mutate topic metadata for an unrelated or unsuccessful call: %j',+ async (override) => {+ await antigravityExecutor.onAfterCall(call(override));++ expect(mocks.updateTopicMetadata).not.toHaveBeenCalled();+ expect(mocks.revalidateGitStatus).not.toHaveBeenCalled();+ },+ );+});diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.tsindex fce564913ca..975c587c681 100644--- a/src/store/tool/slices/builtin/executors/catalog.ts+++ b/src/store/tool/slices/builtin/executors/catalog.ts@@ -19,6 +19,7 @@ import { videoGenerationExecutor } from '@lobechat/builtin-tool-video-generationimport type { IBuiltinToolExecutor } from '../types';import {ampExecutor,+ antigravityExecutor,claudeCodeExecutor,codeBuddyExecutor,codexExecutor,@@ -51,6 +52,7 @@ export const builtinToolExecutors = [// Hook-only executors for heterogeneous CLI agents —// observe their shell tool results via `onAfterCall` (never invoked).ampExecutor,+ antigravityExecutor,claudeCodeExecutor,codeBuddyExecutor,codexExecutor,diff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.tsindex bb77b5bc7e2..90d140e8c77 100644--- a/src/store/tool/slices/builtin/executors/heteroCli.ts+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts@@ -1,5 +1,6 @@import type { ToolAfterCallContext } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';import {recordGitCommandEffects,@@ -9,7 +10,7 @@ import {/*** Hook-only executor for a heterogeneous CLI agent's tool identifier- * (`amp` / `claude-code` / `codebuddy` / `codex` / `cursor` / `droid` / `grok-build` /+ * (`amp` / `antigravity` / `claude-code` / `codebuddy` / `codex` / `cursor` / `droid` / `grok-build` /* `kimi-code` / `opencode` / `pi` / `qoder` / `trae` — set by the adapters in* `packages/heterogeneous-agents/src/adapters/*`). These agents run their OWN* tools, so this executor is NEVER invoked: `apiEnum` is empty → `hasApi()` is@@ -25,14 +26,14 @@ import {const EMPTY_API_ENUM = {} as Record<string, string>;/**- * Pull the command out of a shell tool's parsed params. Only reads `command`/`cmd`- * — never `content` — so a file-write tool can't be mistaken for a shell command.+ * Pull the command out of a shell tool's parsed params. Only reads `command`, `cmd`,+ * or Antigravity's `CommandLine` — never `content` — so file writes aren't commands.* Returns the raw value (string OR the argv-array form) so the detector can keep* argument boundaries.*/const readShellCommand = (params: unknown): string | string[] | undefined => {- if (!params || typeof params !== 'object') return undefined;- const raw = (params as { cmd?: unknown; command?: unknown }).command ?? (params as any).cmd;+ if (!isRecord(params)) return undefined;+ const raw = params.command ?? params.cmd ?? params.CommandLine;if (typeof raw === 'string') return raw;if (Array.isArray(raw) && raw.every((t) => typeof t === 'string')) return raw as string[];return undefined;@@ -100,6 +101,7 @@ class HeteroCliExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {// `command_execution`; Cursor's is `shellToolCall`; Grok Build uses ACP's stable `execute`// kind; Kimi Code uses `Shell`; OpenCode and Pi both use `bash`.export const ampExecutor = new HeteroCliExecutor('amp', new Set(['shell_command']));+export const antigravityExecutor = new HeteroCliExecutor('antigravity', new Set(['run_command']));export const claudeCodeExecutor = new HeteroCliExecutor('claude-code', new Set(['Bash']), {enter: 'EnterWorktree',exit: 'ExitWorktree',diff --git a/src/store/tool/slices/builtin/executors/index.test.ts b/src/store/tool/slices/builtin/executors/index.test.tsindex 6312e69d00a..c0206cea865 100644--- a/src/store/tool/slices/builtin/executors/index.test.ts+++ b/src/store/tool/slices/builtin/executors/index.test.ts@@ -77,13 +77,20 @@ describe('builtin executor registry', () => {);}, 30_000);- it('registers the hook-only Grok Build executor without exposing invokable APIs', async () => {- await registerBuiltinToolExecutors();+ it.each([+ ['antigravity', 'run_command'],+ ['grok-build', 'execute'],+ ])(+ 'registers the hook-only %s executor without exposing invokable APIs',+ async (identifier, apiName) => {+ await registerBuiltinToolExecutors();- expect(getRegisteredIdentifiers()).toContain('grok-build');- await expect(hasExecutor('grok-build', 'execute')).resolves.toBe(false);- expect(getApiNamesForIdentifier('grok-build')).toEqual([]);- }, 30_000);+ expect(getRegisteredIdentifiers()).toContain(identifier);+ await expect(hasExecutor(identifier, apiName)).resolves.toBe(false);+ expect(getApiNamesForIdentifier(identifier)).toEqual([]);+ },+ 30_000,+ );it('rejects nested sub-agent execution', async () => {const subAgentRun = vi.fn();