🤯 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(cursor): migrate heterogeneous agent to ACP (#18475)
AmAzing-dcfa6e161816
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 54ef321477c..3b603684378 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -537,6 +537,7 @@ describe('hetero exec command', () => {expect(mockSpawnAgent).toHaveBeenCalledWith(expect.objectContaining({agentType: 'cursor',+ askUserBridge: undefined,command: 'agent',extraArgs: ['--mode', 'plan', '--model', 'sonnet-4-thinking'],resumeSessionId: 'cursor-session',@@ -544,6 +545,32 @@ describe('hetero exec command', () => {);});+ it('passes an intervention bridge to server-ingest Cursor runs', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'cursor',+ '--prompt',+ 'do thing',+ '--topic',+ 'topic-1',+ '--operation-id',+ 'op-cursor-server',+ '--render',+ 'none',+ ]);++ expect(mockSpawnAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'cursor',+ askUserBridge: expect.objectContaining({ pending: expect.any(Function) }),+ }),+ );+ });+it('runs OpenCode with model, resume, and native args while ignoring effort and speed', async () => {mockSpawnAgent.mockReturnValue(createFakeHandle());diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 27e47ca928d..e38017a5d4e 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -10,7 +10,7 @@ import {isLocalHeterogeneousType,LOCAL_HETEROGENEOUS_AGENT_TYPES,} from '@lobechat/heterogeneous-agents';-import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';+import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';import { LobeBuiltinMcpServer } from '@lobechat/heterogeneous-agents/builtinMcp';import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';import type {@@ -475,24 +475,32 @@ const exec = async (options: ExecOptions): Promise<void> => {let askBridge: AskUserBridge | undefined;let askMcpConfigPath: string | undefined;const askPollAbort = new AbortController();- if (serverIngest && (agentType === 'claude-code' || agentType === 'qoder') && serverIngester) {- askServer = new LobeBuiltinMcpServer();- await askServer.start();- askBridge = askServer.registerOperation(operationId);- askMcpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);- await writeFile(- askMcpConfigPath,- JSON.stringify({- mcpServers: {- lobe_cc: {- alwaysLoad: true,- type: 'http',- url: askServer.urlForOperation(operationId),+ if (+ serverIngest &&+ (agentType === 'claude-code' || agentType === 'cursor' || agentType === 'qoder') &&+ serverIngester+ ) {+ if (agentType === 'cursor') {+ askBridge = new AskUserBridge(operationId);+ } else {+ askServer = new LobeBuiltinMcpServer();+ await askServer.start();+ askBridge = askServer.registerOperation(operationId);+ askMcpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);+ await writeFile(+ askMcpConfigPath,+ JSON.stringify({+ mcpServers: {+ lobe_cc: {+ alwaysLoad: true,+ type: 'http',+ url: askServer.urlForOperation(operationId),+ },},- },- }),- 'utf8',- );+ }),+ 'utf8',+ );+ }// (i) Forward bridge events into the same ordered ingest path as CC's. The// request always goes out. For responses, only forward the ones the browser@@ -813,6 +821,7 @@ const exec = async (options: ExecOptions): Promise<void> => {const first = await runOneAgent({agentType: options.type,+ askUserBridge: askBridge,command: resolvedCommand.command,cwd: options.cwd || process.cwd(),env: commandEnv,@@ -851,6 +860,7 @@ const exec = async (options: ExecOptions): Promise<void> => {result = await runOneAgent({agentType: options.type,+ askUserBridge: askBridge,command: resolvedCommand.command,cwd: options.cwd || process.cwd(),env: commandEnv,@@ -935,7 +945,7 @@ const exec = async (options: ExecOptions): Promise<void> => {if (askServer) {askServer.unregisterOperation(operationId);await askServer.stop().catch(() => {});- }+ } else askBridge?.cancelAll('session_ended');if (askMcpConfigPath) await unlink(askMcpConfigPath).catch(() => {});if (code !== null) {diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 1243eb83b1f..89ca41f2c68 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -23,7 +23,7 @@ import {isHeterogeneousAgentAuthRequired,resolveHeterogeneousAgentCommand,} from '@lobechat/heterogeneous-agents';-import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';+import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';import type {LobeBuiltinMcpServer,McpToolResult,@@ -49,6 +49,8 @@ import {buildCodexAppServerArgs,buildCodexAppServerInput,buildCodexAppServerThreadParams,+ buildCursorAcpArgs,+ buildCursorAcpPrompt,buildGrokAcpArgs,buildGrokAcpPrompt,buildTraeAcpArgs,@@ -57,10 +59,12 @@ import {CodexAppServerClient,CodexThreadSession,createFileStoreImageUploader,+ CursorAcpSession,ensureClaudeCodeResumeTranscript,getCodexAppServerUnsupportedArgs,GrokAcpSession,isCodexAppServerCompatibilityError,+ isCursorAcpSessionNotFoundError,readCodexSessionModel,resolveCliSpawnPlan,resolveCodexInitialModel,@@ -310,6 +314,7 @@ interface AgentSession {cancelledByUs?: boolean;codexAppServerFallback?: boolean;command: string;+ cursorAcpSession?: CursorAcpSession;cwd?: string;env?: Record<string, string>;grokAcpSession?: GrokAcpSession;@@ -368,7 +373,7 @@ interface InterventionSlot {/** Resolves once bridge.events() iterator ends (after `cancelAll`). */pumpDone?: Promise<void>;/** Path to the per-op temp `mcp.json` we wrote for `--mcp-config`. */- tmpConfigPath: string;+ tmpConfigPath?: string;}export default class HeterogeneousAgentCtr {@@ -569,6 +574,34 @@ export default class HeterogeneousAgentCtr {};}+ private getCursorResumeError(+ error: unknown,+ session: AgentSession,+ ): HeterogeneousAgentSessionError | undefined {+ if (+ session.agentType !== 'cursor' ||+ !session.resumeSessionId ||+ !isCursorAcpSessionNotFoundError(error)+ ) {+ return;+ }++ return {+ agentType: 'cursor',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ command: session.command,+ details: {+ code: error.rpcError.code,+ message: error.rpcError.message,+ },+ message:+ 'The saved Cursor session cannot be loaded through ACP, so a new conversation will start.',+ resumeSessionId: session.resumeSessionId,+ stderr: error.message,+ workingDirectory: session.cwd,+ };+ }+private getCliAuthRequiredError(error: unknown,session: AgentSession,@@ -593,7 +626,9 @@ export default class HeterogeneousAgentCtr {}const resumeError =- this.getCodexResumeError(error, session) ?? this.getGrokResumeError(error, session);+ this.getCodexResumeError(error, session) ??+ this.getGrokResumeError(error, session) ??+ this.getCursorResumeError(error, session);if (resumeError) return resumeError;const authRequiredError = this.getCliAuthRequiredError(error, session);@@ -919,6 +954,35 @@ export default class HeterogeneousAgentCtr {// ─── AskUserQuestion MCP server () ───+ /** Register and broadcast a native ACP intervention without starting an MCP server. */+ private setupAcpInterventionForOp(+ operationId: string,+ sessionId: string,+ ): {+ bridge: AskUserBridge;+ cleanup: () => Promise<void>;+ } {+ const bridge = new AskUserBridge(operationId);+ const pumpDone = (async () => {+ for await (const event of bridge.events()) {+ this.broadcast('heteroAgentEvent', { event, sessionId });+ }+ })().catch((error) => {+ logger.warn('ACP AskUserQuestion bridge pump error:', error);+ });+ const slot: InterventionSlot = { bridge, pumpDone };+ this.opIdToIntervention.set(operationId, slot);++ return {+ bridge,+ cleanup: async () => {+ bridge.cancelAll('session_ended');+ await pumpDone;+ this.opIdToIntervention.delete(operationId);+ },+ };+ }+/*** Lazy single-instance MCP server for CC's AskUserQuestion replacement.* First claude-code prompt triggers `start()`; subsequent prompts reuse@@ -1187,6 +1251,10 @@ export default class HeterogeneousAgentCtr {return this.sendPromptWithGrokAcp(params, session);}+ if (session.agentType === 'cursor') {+ return this.sendPromptWithCursorAcp(params, session);+ }+if (session.agentType === 'trae') {return this.sendPromptWithTraeAcp(params, session);}@@ -1716,6 +1784,98 @@ export default class HeterogeneousAgentCtr {}}+ private async sendPromptWithCursorAcp(+ params: SendPromptParams,+ session: AgentSession,+ ): Promise<void> {+ const cwd = this.resolveSessionWorkingDirectory(session);+ const spawnEnv = this.buildSessionSpawnEnv(session);+ const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);+ const promptInput = buildHeterogeneousPrompt({+ imageList: params.imageList,+ prompt: params.prompt,+ systemContext: params.systemContext,+ });+ const prompt = buildCursorAcpPrompt(promptInput);+ const tracePayload = `${JSON.stringify(prompt)}\n`;+ const traceSession = await this.createCliTraceSession({+ cliArgs: buildCursorAcpArgs(session.args),+ cwd,+ imageList: params.imageList ?? [],+ session,+ stdinPayload: tracePayload,+ });+ void this.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);+ const stderrChunks: string[] = [];+ const intervention = this.setupAcpInterventionForOp(params.operationId, session.sessionId);+ const cursorAcpSession = new CursorAcpSession({+ args: session.args,+ askUserBridge: intervention.bridge,+ clientVersion: electronApp.getVersion(),+ commandPath,+ cwd,+ env: spawnEnv,+ onEvents: async (events) => {+ for (const event of events) {+ this.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });+ }+ },+ onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),+ onRuntimeStatus: (status) => this.broadcast('heteroAgentRuntimeStatus', status),+ onSessionId: (agentSessionId) => {+ session.agentSessionId = agentSessionId;+ },+ onStderr: (data) => {+ stderrChunks.push(data);+ return this.appendCliTraceFile(traceSession, 'stderr.log', data);+ },+ operationId: params.operationId,+ prompt,+ resumeSessionId: session.agentSessionId,+ sessionId: session.sessionId,+ });+ session.cursorAcpSession = cursorAcpSession;++ try {+ await cursorAcpSession.run();+ void this.writeCliTraceJson(traceSession, 'exit.json', {+ finishedAt: new Date().toISOString(),+ transport: 'cursor-acp',+ });+ await this.flushCliTrace(traceSession);+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });+ } catch (error) {+ void this.writeCliTraceJson(traceSession, 'process-error.json', {+ message: this.getErrorMessage(error),+ transport: 'cursor-acp',+ });+ await this.flushCliTrace(traceSession);+ if (session.cancelledByUs) {+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });+ return;+ }+ const stderr = stderrChunks.join('').trim();+ const errorForClassification = isCursorAcpSessionNotFoundError(error)+ ? error+ : stderr+ ? new Error([this.getErrorMessage(error), stderr].filter(Boolean).join('\n'), {+ cause: error,+ })+ : error;+ const sessionError = this.getSessionErrorPayload(errorForClassification, session);+ this.broadcast('heteroAgentSessionError', {+ error: sessionError,+ sessionId: session.sessionId,+ });+ throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {+ cause: error,+ });+ } finally {+ await intervention.cleanup();+ if (session.cursorAcpSession === cursorAcpSession) session.cursorAcpSession = undefined;+ }+ }+private async sendPromptWithTraeAcp(params: SendPromptParams,session: AgentSession,@@ -2241,6 +2401,10 @@ export default class HeterogeneousAgentCtr {session.grokAcpSession.interrupt();return;}+ if (session.cursorAcpSession) {+ session.cursorAcpSession.interrupt();+ return;+ }if (session.appServerSession) {const appServerSession = session.appServerSession;try {@@ -2285,6 +2449,11 @@ export default class HeterogeneousAgentCtr {session.grokAcpSession.close();}+ if (session.cursorAcpSession) {+ session.cancelledByUs = true;+ session.cursorAcpSession.close();+ }+if (session.appServerSession) {session.cancelledByUs = true;try {@@ -2355,6 +2524,7 @@ export default class HeterogeneousAgentCtr {*/private unlinkPendingInterventionConfigsSync = (): void => {for (const [, intervention] of this.opIdToIntervention) {+ if (!intervention.tmpConfigPath) continue;try {unlinkSync(intervention.tmpConfigPath);} catch {@@ -2376,6 +2546,10 @@ export default class HeterogeneousAgentCtr {session.cancelledByUs = true;session.grokAcpSession.close();}+ if (session.cursorAcpSession) {+ session.cancelledByUs = true;+ session.cursorAcpSession.close();+ }if (session.appServerSession) {session.cancelledByUs = true;session.appServerSession.close();diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 418d257bf89..a9801dfce39 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -111,6 +111,10 @@ const {codexAppServerShouldFailAfterThread,codexAppServerShouldFailResume,codexAppServerShouldFallback,+ cursorAcpSessionCloseMock,+ cursorAcpSessionConstructMock,+ cursorAcpSessionInterruptMock,+ cursorAcpSessionRunMock,grokAcpSessionCloseMock,grokAcpSessionConstructMock,grokAcpSessionInterruptMock,@@ -133,6 +137,10 @@ const {codexAppServerShouldFailAfterThread: { value: false },codexAppServerShouldFailResume: { value: false },codexAppServerShouldFallback: { value: false },+ cursorAcpSessionCloseMock: vi.fn(),+ cursorAcpSessionConstructMock: vi.fn(),+ cursorAcpSessionInterruptMock: vi.fn(),+ cursorAcpSessionRunMock: vi.fn(),grokAcpSessionCloseMock: vi.fn(),grokAcpSessionConstructMock: vi.fn(),grokAcpSessionInterruptMock: vi.fn(),@@ -297,6 +305,53 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {}}+ class MockCursorAcpSession {+ constructor(private readonly options: any) {+ cursorAcpSessionConstructMock(options);+ }++ close() {+ cursorAcpSessionCloseMock();+ }++ interrupt() {+ cursorAcpSessionInterruptMock();+ }++ async run() {+ if (cursorAcpSessionRunMock.getMockImplementation()) {+ return cursorAcpSessionRunMock(this.options);+ }+ const now = Date.now();+ this.options.onRuntimeStatus({+ activeTasks: [],+ lastEventAt: now,+ operationId: this.options.operationId,+ sessionId: this.options.sessionId,+ state: 'running',+ transport: 'cursor-acp',+ });+ this.options.onSessionId('cursor-session-1');+ await this.options.onEvents([+ {+ data: { stopReason: 'end_turn' },+ operationId: this.options.operationId,+ stepIndex: 0,+ timestamp: now,+ type: 'agent_runtime_end',+ },+ ]);+ this.options.onRuntimeStatus({+ activeTasks: [],+ lastEventAt: now,+ operationId: this.options.operationId,+ sessionId: this.options.sessionId,+ state: 'closed',+ transport: 'cursor-acp',+ });+ }+ }+class MockTraeAcpSession {constructor(private readonly options: any) {traeAcpSessionConstructMock(options);@@ -349,6 +404,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {ClaudeAgentSdkSession: MockClaudeAgentSdkSession,CodexAppServerClient: MockCodexAppServerClient,CodexThreadSession: MockCodexThreadSession,+ CursorAcpSession: MockCursorAcpSession,isCodexAppServerCompatibilityError: (error: Error) =>error.name === 'CodexAppServerConnectionError',GrokAcpSession: MockGrokAcpSession,@@ -462,6 +518,10 @@ describe('HeterogeneousAgentCtr', () => {codexAppServerShouldFailAfterThread.value = false;codexAppServerShouldFailResume.value = false;codexAppServerShouldFallback.value = false;+ cursorAcpSessionCloseMock.mockReset();+ cursorAcpSessionConstructMock.mockReset();+ cursorAcpSessionInterruptMock.mockReset();+ cursorAcpSessionRunMock.mockReset();grokAcpSessionCloseMock.mockReset();grokAcpSessionConstructMock.mockReset();grokAcpSessionInterruptMock.mockReset();@@ -1107,53 +1167,189 @@ describe('HeterogeneousAgentCtr', () => {execFileMock.mockReset();});- it('spawns with the positional prompt without writing it to argv logs or trace metadata', async () => {- const originalNodeEnv = process.env.NODE_ENV;- process.env.NODE_ENV = 'development';+ it('routes Cursor through ACP and persists its native session id', async () => {+ const send = vi.fn();+ mockGetAllWindows.mockReturnValue([+ {+ isDestroyed: () => false,+ webContents: { send },+ },+ ]);+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'cursor',+ args: ['--model', 'composer-1.5'],+ command: 'agent',+ resumeSessionId: 'cursor-session-old',+ });- try {- const prompt = 'private user request';- const systemContext = 'private selected workspace context';- const payload = `${systemContext}\n\n${prompt}`;- const { proc, writes } = createFakeProc();- nextFakeProc = proc;- const ctr = new HeterogeneousAgentCtr({- appStoragePath,- storeManager: { get: vi.fn() },- } as any);- const { sessionId } = await ctr.startSession({- agentType: 'cursor',- command: 'agent',- cwd: appStoragePath,- });+ await ctr.sendPrompt({+ operationId: 'op-cursor',+ prompt: 'private user request',+ sessionId,+ systemContext: 'private selected workspace context',+ });- await ctr.sendPrompt({- operationId: 'op-cursor-private',- prompt,+ expect(spawnCalls).toHaveLength(0);+ expect(cursorAcpSessionConstructMock).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--model', 'composer-1.5'],+ askUserBridge: expect.any(Object),+ clientVersion: '1.0.0-test',+ commandPath: 'agent',+ cwd: FAKE_DESKTOP_PATH,+ operationId: 'op-cursor',+ prompt: [+ { text: 'private selected workspace context', type: 'text' },+ { text: 'private user request', type: 'text' },+ ],+ resumeSessionId: 'cursor-session-old',sessionId,- systemContext,+ }),+ );+ await expect(ctr.getSessionInfo({ sessionId })).resolves.toEqual({+ agentSessionId: 'cursor-session-1',+ });+ expect(send).toHaveBeenCalledWith(+ 'heteroAgentRuntimeStatus',+ expect.objectContaining({ state: 'running', transport: 'cursor-acp' }),+ );+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });+ });++ it('forwards Cursor questions through the existing intervention bridge and returns the answer', async () => {+ const send = vi.fn();+ mockGetAllWindows.mockReturnValue([+ {+ isDestroyed: () => false,+ webContents: { send },+ },+ ]);+ let receivedAnswer: unknown;+ cursorAcpSessionRunMock.mockImplementation(async (options) => {+ receivedAnswer = await options.askUserBridge.pending({+ arguments: {+ questions: [+ {+ header: 'Scope',+ multiSelect: false,+ options: [{ label: 'Narrow' }, { label: 'Full' }],+ question: 'How broad?',+ },+ ],+ },+ toolCallId: 'cursor-question-1',});+ });+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({ agentType: 'cursor', command: 'agent' });+ const run = ctr.sendPrompt({ operationId: 'op-cursor-question', prompt: 'work', sessionId });++ await vi.waitFor(() =>+ expect(send).toHaveBeenCalledWith(+ 'heteroAgentEvent',+ expect.objectContaining({+ event: expect.objectContaining({+ data: expect.objectContaining({ toolCallId: 'cursor-question-1' }),+ type: 'agent_intervention_request',+ }),+ sessionId,+ }),+ ),+ );+ await ctr.submitIntervention({+ operationId: 'op-cursor-question',+ result: { 'How broad?': 'Full' },+ toolCallId: 'cursor-question-1',+ });+ await run;- const { args: cliArgs } = spawnCalls[0];- expect(cliArgs.at(-2)).toBe('--');- expect(cliArgs.at(-1)).toBe(payload);- expect(writes).toEqual([]);-- const logged = JSON.stringify(loggerInfoMock.mock.calls);- expect(logged).toContain('<argv payload redacted>');- expect(logged).not.toContain(prompt);- expect(logged).not.toContain(systemContext);-- const traceRoot = path.join(appStoragePath, '.heerogeneous-tracing', 'cursor');- const traceDirs = await readdir(traceRoot);- const metaText = await readFile(path.join(traceRoot, traceDirs[0], 'meta.json'), 'utf8');- const meta = JSON.parse(metaText);- expect(meta.args).toEqual(cliArgs.slice(0, -1));- expect(metaText).not.toContain(prompt);- expect(metaText).not.toContain(systemContext);- } finally {- process.env.NODE_ENV = originalNodeEnv;- }+ expect(receivedAnswer).toEqual({ result: { 'How broad?': 'Full' } });+ });++ it('classifies an exact Cursor ACP session/load not-found error for resume fallback', async () => {+ const send = vi.fn();+ mockGetAllWindows.mockReturnValue([+ {+ isDestroyed: () => false,+ webContents: { send },+ },+ ]);+ const missingSessionError = new AcpRpcResponseError('session/load', {+ code: -32_602,+ message: 'Session "legacy-cursor-session" not found',+ });+ cursorAcpSessionRunMock.mockImplementation(async (options) => {+ await options.onStderr('Cursor ACP diagnostic\n');+ throw missingSessionError;+ });+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'cursor',+ command: 'agent',+ cwd: '/Users/fake/projects/repo',+ resumeSessionId: 'legacy-cursor-session',+ });++ await expect(+ ctr.sendPrompt({ operationId: 'op-cursor-resume', prompt: 'continue', sessionId }),+ ).rejects.toThrow(+ 'The saved Cursor session cannot be loaded through ACP, so a new conversation will start.',+ );++ expect(send).toHaveBeenCalledWith('heteroAgentSessionError', {+ error: {+ agentType: 'cursor',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ command: 'agent',+ details: {+ code: -32_602,+ message: 'Session "legacy-cursor-session" not found',+ },+ message:+ 'The saved Cursor session cannot be loaded through ACP, so a new conversation will start.',+ resumeSessionId: 'legacy-cursor-session',+ stderr: missingSessionError.message,+ workingDirectory: '/Users/fake/projects/repo',+ },+ sessionId,+ });+ expect(send).not.toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });+ });++ it.each([+ ['cancelSession', cursorAcpSessionInterruptMock],+ ['stopSession', cursorAcpSessionCloseMock],+ ] as const)('%s delegates to the active Cursor ACP session', async (action, expectedMock) => {+ let resolveRun: (() => void) | undefined;+ cursorAcpSessionRunMock.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ resolveRun = resolve;+ }),+ );+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({ agentType: 'cursor', command: 'agent' });+ const run = ctr.sendPrompt({ operationId: 'op-cursor', prompt: 'work', sessionId });+ await vi.waitFor(() => expect(cursorAcpSessionConstructMock).toHaveBeenCalledOnce());++ await ctr[action]({ sessionId });++ expect(expectedMock).toHaveBeenCalledOnce();+ resolveRun?.();+ await run;});});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.test.tsindex 2feac76f88a..4fb2880f1dd 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.test.ts@@ -1,48 +1,11 @@-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import { getHeterogeneousAgentDriver } from '../index';-import type {- HeterogeneousAgentBuildPlanHelpers,- HeterogeneousAgentBuildPlanParams,-} from '../types';import { cursorDriver } from './cursor';-const buildAgentInput = vi.fn(async () => ({ args: [], stdin: '-inspect this repository' }));-const helpers: HeterogeneousAgentBuildPlanHelpers = { buildAgentInput };--const buildParams = (- overrides: Partial<HeterogeneousAgentBuildPlanParams> = {},-): HeterogeneousAgentBuildPlanParams => ({- args: [],- helpers,- promptInput: '-inspect this repository',- ...overrides,-});-describe('cursorDriver', () => {- it('is registered and composes headless, resume, model, and positional prompt args', async () => {+ it('is registered but rejects the obsolete one-shot spawn path', async () => {expect(getHeterogeneousAgentDriver('cursor')).toBe(cursorDriver);-- const plan = await cursorDriver.buildSpawnPlan(- buildParams({ args: ['--model', 'sonnet-4-thinking'], resumeSessionId: 'cursor-session' }),- );-- expect(buildAgentInput).toHaveBeenCalledWith('cursor', '-inspect this repository');- expect(plan).toEqual({- args: [- '-p',- '--force',- '--trust',- '--output-format',- 'stream-json',- '--stream-partial-output',- '--resume',- 'cursor-session',- '--model',- 'sonnet-4-thinking',- '--',- ],- argvPayload: '-inspect this repository',- });+ await expect(cursorDriver.buildSpawnPlan({} as never)).rejects.toThrow('native ACP session');});});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.tsindex 7f097820207..acdda4120fd 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/cursor.ts@@ -1,24 +1,8 @@-import { CURSOR_BASE_ARGS } from '@lobechat/heterogeneous-agents/spawn';--import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';+import type { HeterogeneousAgentDriver } from '../types';+/** Cursor prompts are owned by CursorAcpSession in the controller, never by one-shot spawn. */export const cursorDriver: HeterogeneousAgentDriver = {- async buildSpawnPlan({- args,- helpers,- promptInput,- resumeSessionId,- }: HeterogeneousAgentBuildPlanParams) {- const input = await helpers.buildAgentInput('cursor', promptInput);- return {- args: [- ...CURSOR_BASE_ARGS,- ...(resumeSessionId ? ['--resume', resumeSessionId] : []),- ...args,- ...input.args,- '--',- ],- argvPayload: input.stdin,- };+ async buildSpawnPlan() {+ throw new Error('Cursor prompts must run through the native ACP session');},};diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 9677ab78b63..4bbee45f119 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -727,6 +727,7 @@"heteroAgent.quota.updatedAgo": "Updated {{duration}} ago","heteroAgent.quota.updatedJustNow": "Updated just now","heteroAgent.quota.weekly": "Weekly",+ "heteroAgent.resumeReset.cursorAcpIncompatible": "The previous Cursor session could not be restored through ACP, so a new conversation has started with fresh context.","heteroAgent.resumeReset.cwdChanged": "Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.","heteroAgent.resumeReset.resumeFailed": "The saved Codex thread could not be resumed safely, so a new conversation has started for this topic.","heteroAgent.switchCwd.cancel": "Cancel",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 6b796aafd0d..37063c01745 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -727,6 +727,7 @@"heteroAgent.quota.updatedAgo": "{{duration}}前更新","heteroAgent.quota.updatedJustNow": "刚刚更新","heteroAgent.quota.weekly": "每周",+ "heteroAgent.resumeReset.cursorAcpIncompatible": "之前的 Cursor 会话无法通过 ACP 恢复,已使用全新上下文开始新对话。","heteroAgent.resumeReset.cwdChanged": "工作目录已切换,之前的 Claude Code 会话只能在原目录下继续,已开始新对话。","heteroAgent.resumeReset.resumeFailed": "已保存的 Codex 线程无法安全恢复,当前话题已自动开启新会话。","heteroAgent.switchCwd.cancel": "取消",diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.tsindex f0e344ac9ad..fd1846f0d1b 100644--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts@@ -143,5 +143,6 @@ export interface HeterogeneousAgentRuntimeStatus {sessionId: string;staleDeadlineAt?: number;state: HeterogeneousAgentRuntimeState;- transport: 'acp-stdio' | 'claude-sdk' | 'cli-spawn' | 'codex-app-server' | 'trae-acp';+ transport:+ 'acp-stdio' | 'claude-sdk' | 'cli-spawn' | 'codex-app-server' | 'cursor-acp' | 'trae-acp';}diff --git a/packages/heterogeneous-agents/src/adapters/cursorAcp.ts b/packages/heterogeneous-agents/src/adapters/cursorAcp.tsnew file mode 100644index 00000000000..bfc7db1532e--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/cursorAcp.ts@@ -0,0 +1,8 @@+import { TraeAcpAdapter } from './traeAcp';++/** Maps Cursor's standard ACP session updates into the shared event protocol. */+export class CursorAcpAdapter extends TraeAcpAdapter {+ constructor() {+ super({ eventPrefix: 'cursor', provider: 'cursor' });+ }+}diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.tsindex a40d86d0d34..9e2a89c3e6d 100644--- a/packages/heterogeneous-agents/src/adapters/index.ts+++ b/packages/heterogeneous-agents/src/adapters/index.ts@@ -4,6 +4,7 @@ export { CodeBuddyAdapter } from './codeBuddy';export { CodexAdapter } from './codex';export { CodexAppServerAdapter } from './codexAppServer';export { CursorAdapter } from './cursor';+export { CursorAcpAdapter } from './cursorAcp';export { GrokBuildAdapter } from './grokBuild';export { KimiCodeAdapter } from './kimiCode';export { OpenCodeAdapter } from './opencode';diff --git a/packages/heterogeneous-agents/src/registry.test.ts b/packages/heterogeneous-agents/src/registry.test.tsindex ae6945a3c0f..6f2fcd71517 100644--- a/packages/heterogeneous-agents/src/registry.test.ts+++ b/packages/heterogeneous-agents/src/registry.test.ts@@ -5,6 +5,7 @@ import {ClaudeCodeAdapter,CodeBuddyAdapter,CodexAdapter,+ CursorAcpAdapter,CursorAdapter,GrokBuildAdapter,KimiCodeAdapter,@@ -45,6 +46,10 @@ describe('registry', () => {expect(createAdapter('cursor')).toBeInstanceOf(CursorAdapter);});+ it('creates a CursorAcpAdapter for the native ACP runtime', () => {+ expect(createAdapter('cursor-acp')).toBeInstanceOf(CursorAcpAdapter);+ });+it('creates a GrokBuildAdapter for "grok-build"', () => {expect(createAdapter('grok-build')).toBeInstanceOf(GrokBuildAdapter);});@@ -76,6 +81,7 @@ describe('registry', () => {HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type).toSorted(),);expect(listAgentTypes()).toContain('claude-code-sdk');+ expect(listAgentTypes()).toContain('cursor-acp');});});});diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.tsindex 783c316f045..40e13103ae1 100644--- a/packages/heterogeneous-agents/src/registry.ts+++ b/packages/heterogeneous-agents/src/registry.ts@@ -11,6 +11,7 @@ import {ClaudeCodeSdkAdapter,CodeBuddyAdapter,CodexAdapter,+ CursorAcpAdapter,CursorAdapter,GrokBuildAdapter,KimiCodeAdapter,@@ -67,6 +68,9 @@ const runtimeAdapterRegistry = {'claude-code-sdk': {createAdapter: () => new ClaudeCodeSdkAdapter(),},+ 'cursor-acp': {+ createAdapter: () => new CursorAcpAdapter(),+ },} satisfies Record<string, AgentRegistryEntry>;const registry: Record<string, AgentRegistryEntry> = {diff --git a/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.ts b/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.tsindex 581e341e1a2..2eb94ac8ce1 100644--- a/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.ts+++ b/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.ts@@ -114,6 +114,67 @@ describe('AcpStdioClient', () => {client.close();});+ it('delivers later notifications while a server request is still waiting on the host', async () => {+ const { child, stdout, writes } = createProcess();+ spawnMock.mockReturnValue(child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ let releaseServerRequest: ((result: unknown) => void) | undefined;+ const messages: unknown[] = [];+ const client = new AcpStdioClient({+ args: ['agent', 'stdio'],+ commandPath: 'agent',+ cwd: '/workspace',+ env: { ...process.env },+ onMessage: (message) => {+ messages.push(message);+ },+ onRawMessage: vi.fn(),+ onServerRequest: () =>+ new Promise((resolve) => {+ releaseServerRequest = resolve;+ }),+ onStderr: vi.fn(),+ });+ await client.start();++ stdout.write(+ `${JSON.stringify({+ id: 'ask-1',+ jsonrpc: '2.0',+ method: 'cursor/ask_question',+ params: { toolCallId: 'q1' },+ })}\n`,+ );+ await vi.waitFor(() => expect(releaseServerRequest).toBeTypeOf('function'));++ stdout.write(+ `${JSON.stringify({+ jsonrpc: '2.0',+ method: 'session/update',+ params: {+ update: {+ content: { text: 'still streaming', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ },+ },+ })}\n`,+ );+ await vi.waitFor(() =>+ expect(messages).toContainEqual(expect.objectContaining({ method: 'session/update' })),+ );++ releaseServerRequest!({ outcome: { outcome: 'cancelled' } });+ await vi.waitFor(() =>+ expect(writes).toContainEqual(+ expect.objectContaining({+ id: 'ask-1',+ result: { outcome: { outcome: 'cancelled' } },+ }),+ ),+ );+ client.close();+ });+it('does not dispatch queued or subsequent stdout messages after host close', async () => {const { child, stdout } = createProcess();spawnMock.mockReturnValue(child);diff --git a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts b/packages/heterogeneous-agents/src/spawn/acpStdioClient.tsindex f3e9d66ecac..1840a6f2690 100644--- a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts+++ b/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts@@ -240,7 +240,12 @@ export class AcpStdioClient {if (this.closed) return;if (message.method) {- if (message.id !== undefined) await this.handleServerRequest(message);+ if (message.id !== undefined) {+ // Server requests (permissions, questions, plan approval) can block on+ // a host UI. Keep that wait off the serial queue so later+ // `session/update` notifications still reach the adapter.+ void this.handleServerRequest(message).catch((error) => this.fail(this.toError(error)));+ }return;}diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex 6d1003ae009..1af138bef97 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -117,7 +117,8 @@ export interface HeterogeneousAgentRuntimeStatus {sessionId: string;staleDeadlineAt?: number;state: HeterogeneousAgentRuntimeState;- transport: 'acp-stdio' | 'claude-sdk' | 'cli-spawn' | 'codex-app-server' | 'trae-acp';+ transport:+ 'acp-stdio' | 'claude-sdk' | 'cli-spawn' | 'codex-app-server' | 'cursor-acp' | 'trae-acp';}export interface ClaudeAgentSdkSessionOptions {diff --git a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.tsnew file mode 100644index 00000000000..4030da3bf40--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts@@ -0,0 +1,654 @@+import type { ChildProcess } from 'node:child_process';+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';++import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { AskUserBridge } from '../askUser/AskUserBridge';+import { DEFAULT_ASK_USER_TIMEOUT_MS } from '../askUser/constants';+import { AcpRpcResponseError } from './acpStdioClient';+import {+ buildCursorAcpArgs,+ buildCursorAcpPrompt,+ CursorAcpSession,+ type CursorAcpSessionOptions,+ isCursorAcpSessionNotFoundError,+} from './cursorAcpSession';++const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));++vi.mock('node:child_process', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return { ...actual, spawn: spawnMock };+});++interface RpcMessage {+ error?: { code: number; message: string };+ id?: number | string;+ method?: string;+ params?: Record<string, unknown>;+ result?: unknown;+}++const createAcpProcess = ({+ askQuestion = false,+ loadError,+ serverRequest,+}: {+ askQuestion?: boolean;+ loadError?: { code: number; message: string };+ serverRequest?: RpcMessage;+} = {}) => {+ const child = new EventEmitter() as ChildProcess;+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const requests: RpcMessage[] = [];+ let promptRequest: RpcMessage | undefined;+ const blockingRequest: RpcMessage | undefined =+ serverRequest ??+ (askQuestion+ ? {+ id: 'ask-1',+ method: 'cursor/ask_question',+ params: {+ questions: [+ {+ allowMultiple: false,+ id: 'scope',+ options: [+ { id: 'narrow', label: 'Narrow' },+ { id: 'full', label: 'Full' },+ ],+ prompt: 'How broad should the fix be?',+ },+ ],+ title: 'Scope',+ toolCallId: 'cursor-question-1',+ },+ }+ : undefined);+ const send = (message: Record<string, unknown>) =>+ stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);++ Object.assign(child, {+ kill: vi.fn(() => true),+ killed: false,+ pid: 987_654,+ stderr,+ stdin: {+ once: vi.fn(),+ write: vi.fn((chunk: string) => {+ const message = JSON.parse(chunk.trim()) as RpcMessage;+ requests.push(message);+ queueMicrotask(() => {+ switch (message.method) {+ case 'initialize': {+ send({+ id: message.id,+ result: {+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: 'cursor_login', name: 'Cursor Login' }],+ protocolVersion: 1,+ },+ });+ return;+ }+ case 'authenticate': {+ send({ id: message.id, result: {} });+ return;+ }+ case 'session/new': {+ send({ id: message.id, result: { sessionId: 'cursor-session-1' } });+ return;+ }+ case 'session/load': {+ send(+ loadError ? { error: loadError, id: message.id } : { id: message.id, result: {} },+ );+ return;+ }+ case 'session/prompt': {+ promptRequest = message;+ send({+ method: 'session/update',+ params: {+ sessionId: 'cursor-session-1',+ update: {+ content: { text: 'Working', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ },+ },+ });+ if (askQuestion) {+ send({+ method: 'session/update',+ params: {+ sessionId: 'cursor-session-1',+ update: {+ kind: 'other',+ rawInput: {+ questions: [+ {+ allowMultiple: false,+ id: 'scope',+ options: [+ { id: 'narrow', label: 'Narrow' },+ { id: 'full', label: 'Full' },+ ],+ prompt: 'How broad should the fix be?',+ },+ ],+ title: 'Scope',+ },+ sessionUpdate: 'tool_call',+ status: 'in_progress',+ title: 'AskQuestion',+ toolCallId: 'cursor-question-1',+ },+ },+ });+ }+ if (blockingRequest) {+ send(blockingRequest as Record<string, unknown>);+ } else {+ send({ id: message.id, result: { stopReason: 'end_turn' } });+ }+ return;+ }+ }++ if (message.id === blockingRequest?.id && message.result && promptRequest) {+ send({ id: promptRequest.id, result: { stopReason: 'end_turn' } });+ }+ });+ return true;+ }),+ },+ stdout,+ });++ return { child, requests, send };+};++const createSessionOptions = (+ overrides: Partial<CursorAcpSessionOptions> = {},+): CursorAcpSessionOptions => ({+ args: ['--model', 'composer-1.5'],+ clientVersion: '1.2.3',+ commandPath: 'agent',+ cwd: '/workspace',+ env: process.env,+ onEvents: vi.fn(),+ onRawMessage: vi.fn(),+ onRuntimeStatus: vi.fn(),+ onSessionId: vi.fn(),+ onStderr: vi.fn(),+ operationId: 'operation-1',+ prompt: [{ text: 'hello', type: 'text' }],+ sessionId: 'session-1',+ ...overrides,+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ spawnMock.mockReset();+});++describe('Cursor ACP helpers', () => {+ it('places root arguments before the ACP subcommand and builds text prompt blocks', () => {+ expect(buildCursorAcpArgs(['--model', 'composer-1.5'])).toEqual([+ '--model',+ 'composer-1.5',+ 'acp',+ ]);+ expect(buildCursorAcpPrompt('hello')).toEqual([{ text: 'hello', type: 'text' }]);+ });++ it('rejects image prompts instead of silently dropping them', () => {+ expect(() =>+ buildCursorAcpPrompt([+ { source: { path: '/workspace/image.png', type: 'path' }, type: 'image' },+ ]),+ ).toThrow('Cursor CLI does not support image input');+ });+});++describe('CursorAcpSession', () => {+ it('initializes, authenticates, starts a session, streams updates, and completes', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions();+ const events: AgentStreamEvent[] = [];+ options.onEvents = (batch) => {+ events.push(...batch);+ };++ await new CursorAcpSession(options).run();++ expect(spawnMock).toHaveBeenCalledWith(+ 'agent',+ ['--model', 'composer-1.5', 'acp'],+ expect.objectContaining({ cwd: '/workspace', stdio: ['pipe', 'pipe', 'pipe'] }),+ );+ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'authenticate',+ 'session/new',+ 'session/prompt',+ ]);+ expect(options.onSessionId).toHaveBeenCalledWith('cursor-session-1');+ expect(events).toContainEqual(+ expect.objectContaining({+ data: { chunkType: 'text', content: 'Working' },+ type: 'stream_chunk',+ }),+ );+ expect(events).toContainEqual(expect.objectContaining({ type: 'agent_runtime_end' }));+ expect(options.onRuntimeStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ state: 'closed', transport: 'cursor-acp' }),+ );+ });++ it('loads a native ACP session when resuming', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({ resumeSessionId: 'cursor-session-old' });++ await new CursorAcpSession(options).run();++ expect(fake.requests.find(({ method }) => method === 'session/load')?.params).toEqual({+ cwd: '/workspace',+ mcpServers: [],+ sessionId: 'cursor-session-old',+ });+ expect(options.onSessionId).toHaveBeenCalledWith('cursor-session-old');+ });++ it('recognizes only Cursor session/load invalid-params errors with the exact not-found message', () => {+ expect(+ isCursorAcpSessionNotFoundError(+ new AcpRpcResponseError('session/load', {+ code: -32_602,+ message: 'Session "legacy-session" not found',+ }),+ ),+ ).toBe(true);++ for (const error of [+ new AcpRpcResponseError('session/prompt', {+ code: -32_602,+ message: 'Session "legacy-session" not found',+ }),+ new AcpRpcResponseError('session/load', {+ code: -32_603,+ message: 'Session "legacy-session" not found',+ }),+ new AcpRpcResponseError('session/load', {+ code: -32_602,+ message: 'Session legacy-session not found',+ }),+ ]) {+ expect(isCursorAcpSessionNotFoundError(error)).toBe(false);+ }+ });++ it('preserves the structured RPC error when a legacy Cursor session cannot be loaded', async () => {+ const fake = createAcpProcess({+ loadError: { code: -32_602, message: 'Session "legacy-session" not found' },+ });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);++ const run = new CursorAcpSession(+ createSessionOptions({ resumeSessionId: 'legacy-session' }),+ ).run();++ await expect(run).rejects.toSatisfy(isCursorAcpSessionNotFoundError);+ expect(fake.requests.some(({ method }) => method === 'session/prompt')).toBe(false);+ });++ it('returns an explicit cancellation instead of fabricating a skipped answer without a UI', async () => {+ const fake = createAcpProcess({ askQuestion: true });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);++ await new CursorAcpSession(createSessionOptions()).run();++ expect(fake.requests.find(({ id }) => id === 'ask-1')?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+ });++ it('keeps streaming session updates while AskUserBridge is waiting', async () => {+ const fake = createAcpProcess({ askQuestion: true });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const options = createSessionOptions({ askUserBridge: bridge });+ const events: AgentStreamEvent[] = [];+ options.onEvents = (batch) => {+ events.push(...batch);+ };+ const eventIterator = bridge.events()[Symbol.asyncIterator]();+ const run = new CursorAcpSession(options).run();++ await eventIterator.next();+ fake.send({+ method: 'session/update',+ params: {+ sessionId: 'cursor-session-1',+ update: {+ content: { text: ' still streaming', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ },+ },+ });+ await vi.waitFor(() =>+ expect(events).toContainEqual(+ expect.objectContaining({+ data: { chunkType: 'text', content: ' still streaming' },+ type: 'stream_chunk',+ }),+ ),+ );++ bridge.resolve('cursor-question-1', {+ result: { 'How broad should the fix be?': 'Full' },+ });+ await run;+ });++ it('blocks cursor/ask_question until the bridge returns selected option labels', async () => {+ const fake = createAcpProcess({ askQuestion: true });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const options = createSessionOptions({ askUserBridge: bridge });+ const events: AgentStreamEvent[] = [];+ options.onEvents = (batch) => {+ events.push(...batch);+ };+ const eventIterator = bridge.events()[Symbol.asyncIterator]();+ const run = new CursorAcpSession(options).run();++ const intervention = await eventIterator.next();+ expect(intervention.value).toMatchObject({+ data: {+ apiName: 'askUserQuestion',+ toolCallId: 'cursor-question-1',+ },+ type: 'agent_intervention_request',+ });+ expect(JSON.parse(intervention.value!.data.arguments)).toEqual({+ questions: [+ {+ header: 'Scope',+ multiSelect: false,+ options: [{ label: 'Narrow' }, { label: 'Full' }],+ question: 'How broad should the fix be?',+ },+ ],+ });+ expect(events).toContainEqual(+ expect.objectContaining({+ data: expect.objectContaining({+ toolCalling: expect.objectContaining({+ apiName: 'askUserQuestion',+ id: 'cursor-question-1',+ identifier: 'claude-code',+ }),+ toolCallId: 'cursor-question-1',+ }),+ type: 'tool_start',+ }),+ );+ expect(events.filter(({ type }) => type === 'tool_start')).toHaveLength(1);++ bridge.resolve('cursor-question-1', {+ result: { 'How broad should the fix be?': 'Full' },+ });+ await run;++ expect(fake.requests.find(({ id }) => id === 'ask-1')?.result).toEqual({+ outcome: {+ answers: [{ questionId: 'scope', selectedOptionIds: ['full'] }],+ outcome: 'answered',+ },+ });+ });++ it('preserves a custom answer and maps cancellation to Cursor outcomes', async () => {+ for (const [bridgeAnswer, expectedOutcome] of [+ [+ { result: { 'How broad should the fix be?': 'Only the crash path' } },+ {+ answers: [{ questionId: 'scope', selectedOptionIds: ['Only the crash path'] }],+ outcome: 'answered',+ },+ ],+ [{ cancelReason: 'user_cancelled', cancelled: true }, { outcome: 'cancelled' }],+ ] as const) {+ const fake = createAcpProcess({ askQuestion: true });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const options = createSessionOptions({ askUserBridge: bridge });+ const eventIterator = bridge.events()[Symbol.asyncIterator]();+ const run = new CursorAcpSession(options).run();+ await eventIterator.next();++ bridge.resolve('cursor-question-1', bridgeAnswer);+ await run;++ expect(fake.requests.find(({ id }) => id === 'ask-1')?.result).toEqual({+ outcome: expectedOutcome,+ });+ }+ });++ it('returns only the permission option explicitly selected by the user', async () => {+ const fake = createAcpProcess({+ serverRequest: {+ id: 'permission-1',+ method: 'session/request_permission',+ params: {+ options: [+ { kind: 'allow_once', name: 'Allow once', optionId: 'allow-once' },+ { kind: 'allow_always', name: 'Always allow', optionId: 'allow-always' },+ { kind: 'reject_once', name: 'Reject', optionId: 'reject-once' },+ ],+ sessionId: 'cursor-session-1',+ toolCall: { title: 'Run the test suite', toolCallId: 'tool-1' },+ },+ },+ });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const events: AgentStreamEvent[] = [];+ const sessionOptions = createSessionOptions({ askUserBridge: bridge });+ sessionOptions.onEvents = (batch) => {+ events.push(...batch);+ };+ const eventIterator = bridge.events()[Symbol.asyncIterator]();+ const run = new CursorAcpSession(sessionOptions).run();++ const intervention = await eventIterator.next();+ expect(intervention.value!.data.toolCallId).toBe('cursor-permission-permission-1-tool-1');+ expect(JSON.parse(intervention.value!.data.arguments)).toEqual({+ questions: [+ {+ header: 'Permission required',+ multiSelect: false,+ options: [{ label: 'Allow once' }, { label: 'Always allow' }, { label: 'Reject' }],+ question: 'Run the test suite',+ },+ ],+ });+ expect(events).toContainEqual(+ expect.objectContaining({+ data: expect.objectContaining({+ toolCalling: expect.objectContaining({+ apiName: 'askUserQuestion',+ id: 'cursor-permission-permission-1-tool-1',+ identifier: 'claude-code',+ }),+ }),+ type: 'tool_start',+ }),+ );+ bridge.resolve(intervention.value!.data.toolCallId, {+ result: { 'Run the test suite': 'Allow once' },+ });+ await run;++ expect(fake.requests.find(({ id }) => id === 'permission-1')?.result).toEqual({+ outcome: { optionId: 'allow-once', outcome: 'selected' },+ });+ expect(events).toContainEqual(+ expect.objectContaining({+ data: expect.objectContaining({+ toolCallId: 'cursor-permission-permission-1-tool-1',+ }),+ type: 'tool_end',+ }),+ );+ });++ it('never grants a permission without a matching explicit user choice', async () => {+ for (const bridgeAnswer of [+ undefined,+ { cancelReason: 'user_cancelled', cancelled: true } as const,+ { result: { 'Run the test suite': 'Allow everything' } },+ ]) {+ const fake = createAcpProcess({+ serverRequest: {+ id: 'permission-1',+ method: 'session/request_permission',+ params: {+ options: [+ { kind: 'allow_always', name: 'Always allow', optionId: 'allow-always' },+ { kind: 'allow_once', name: 'Allow once', optionId: 'allow-once' },+ ],+ sessionId: 'cursor-session-1',+ toolCall: { title: 'Run the test suite', toolCallId: 'tool-1' },+ },+ },+ });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = bridgeAnswer ? new AskUserBridge('operation-1') : undefined;+ const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();++ if (bridge) {+ const intervention = await bridge.events()[Symbol.asyncIterator]().next();+ bridge.resolve(intervention.value!.data.toolCallId, bridgeAnswer!);+ }+ await run;++ expect(fake.requests.find(({ id }) => id === 'permission-1')?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+ }+ });++ it.each([+ ['Accept', 'accepted'],+ ['Reject', 'rejected'],+ ] as const)('maps an explicit %s plan decision to %s', async (selection, outcome) => {+ const fake = createAcpProcess({+ serverRequest: {+ id: 'plan-request-1',+ method: 'cursor/create_plan',+ params: {+ name: 'Fix approvals',+ overview: 'Require an explicit decision.',+ plan: '1. Show the plan.\n2. Wait for the user.',+ todos: [],+ toolCallId: 'plan-1',+ },+ },+ });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const eventIterator = bridge.events()[Symbol.asyncIterator]();+ const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();++ const intervention = await eventIterator.next();+ expect(JSON.parse(intervention.value!.data.arguments)).toEqual({+ questions: [+ {+ header: 'Fix approvals',+ multiSelect: false,+ options: [{ label: 'Accept' }, { label: 'Reject' }],+ question: 'Require an explicit decision.\n\n1. Show the plan.\n2. Wait for the user.',+ },+ ],+ });+ bridge.resolve(intervention.value!.data.toolCallId, {+ result: {+ 'Require an explicit decision.\n\n1. Show the plan.\n2. Wait for the user.': selection,+ },+ });+ await run;++ expect(fake.requests.find(({ id }) => id === 'plan-request-1')?.result).toEqual({+ outcome: { outcome },+ });+ });++ it('cancels plan approval when there is no UI or the user cancels', async () => {+ for (const withBridge of [false, true]) {+ const fake = createAcpProcess({+ serverRequest: {+ id: 'plan-request-1',+ method: 'cursor/create_plan',+ params: { plan: 'Do the work.', todos: [], toolCallId: 'plan-1' },+ },+ });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = withBridge ? new AskUserBridge('operation-1') : undefined;+ const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();++ if (bridge) {+ const intervention = await bridge.events()[Symbol.asyncIterator]().next();+ bridge.cancel(intervention.value!.data.toolCallId);+ }+ await run;++ expect(fake.requests.find(({ id }) => id === 'plan-request-1')?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+ }+ });++ it('cancels plan approval when the intervention times out', async () => {+ vi.useFakeTimers();+ const fake = createAcpProcess({+ serverRequest: {+ id: 'plan-request-1',+ method: 'cursor/create_plan',+ params: { plan: 'Do the work.', todos: [], toolCallId: 'plan-1' },+ },+ });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const eventIterator = bridge.events()[Symbol.asyncIterator]();+ const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();++ await eventIterator.next();+ await vi.advanceTimersByTimeAsync(DEFAULT_ASK_USER_TIMEOUT_MS);+ await run;++ expect(fake.requests.find(({ id }) => id === 'plan-request-1')?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.ts b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.tsnew file mode 100644index 00000000000..06e3dcf37cf--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.ts@@ -0,0 +1,508 @@+import { isRecord } from '@lobechat/utils/object';++import type { AskUserBridge, InterventionAnswer } from '../askUser/AskUserBridge';+import type { AgentPromptInput } from '../protocol';+import type { AcpAgentSessionOptions } from './acpAgentSession';+import { ACP_PROTOCOL_VERSION, AcpAgentSession } from './acpAgentSession';+import type { AcpRpcMessage } from './acpStdioClient';+import { AcpRpcResponseError, AcpServerRequestError } from './acpStdioClient';++const AUTH_METHOD = 'cursor_login';+const TRANSPORT = 'cursor-acp' as const;++export interface CursorAcpTextPromptBlock {+ text: string;+ type: 'text';+}++interface CursorAcpInitializeResult {+ agentCapabilities?: { loadSession?: boolean };+ authMethods?: Array<{ id?: string }>;+ protocolVersion?: number | string;+}++interface CursorAcpSessionResult {+ sessionId?: string;+}++interface CursorAcpPromptResult {+ stopReason?: string;+}++interface CursorAcpPermissionOption {+ kind: string;+ name: string;+ optionId: string;+}++interface CursorAcpPermissionRequest {+ options: CursorAcpPermissionOption[];+ toolCall: {+ title: string;+ toolCallId: string;+ };+}++interface CursorQuestionOption {+ id: string;+ label: string;+}++interface CursorQuestion {+ allowMultiple?: boolean;+ id: string;+ options: CursorQuestionOption[];+ prompt: string;+}++interface CursorAskQuestionRequest {+ questions: CursorQuestion[];+ title?: string;+ toolCallId: string;+}++interface CursorCreatePlanRequest {+ name?: string;+ overview?: string;+ plan: string;+ toolCallId: string;+}++interface CursorBridgeOption {+ id: string;+ label: string;+}++interface CanonicalAskQuestionArgs {+ questions: Array<{+ header: string;+ multiSelect: boolean;+ options: Array<{ label: string }>;+ question: string;+ }>;+}++export interface CursorAcpSessionOptions extends AcpAgentSessionOptions {+ askUserBridge?: AskUserBridge;+ prompt: CursorAcpTextPromptBlock[];+}++export const buildCursorAcpArgs = (extraArgs: string[] = []): string[] => [...extraArgs, 'acp'];++/** Cursor ACP currently accepts the same text-only prompt surface as its former print mode. */+export const buildCursorAcpPrompt = (prompt: AgentPromptInput): CursorAcpTextPromptBlock[] => {+ if (typeof prompt === 'string') return prompt ? [{ text: prompt, type: 'text' }] : [];++ return prompt.map((block) => {+ if (block.type === 'image') throw new Error('Cursor CLI does not support image input.');+ return { text: block.text, type: 'text' };+ });+};++export const normalizeCursorQuestion = (+ request: CursorAskQuestionRequest,+): CanonicalAskQuestionArgs => ({+ questions: request.questions.map((question) => ({+ header: request.title ?? '',+ multiSelect: question.allowMultiple === true,+ options: question.options.map(({ label }) => ({ label })),+ question: question.prompt,+ })),+});++export const isCursorAcpSessionNotFoundError = (error: unknown): error is AcpRpcResponseError =>+ error instanceof AcpRpcResponseError &&+ error.method === 'session/load' &&+ error.rpcError.code === -32_602 &&+ typeof error.rpcError.message === 'string' &&+ /^Session "[^"]+" not found$/.test(error.rpcError.message);++/** Cursor's ACP v1 lifecycle (auth + AskUserBridge reverse requests) on the shared session base. */+export class CursorAcpSession extends AcpAgentSession<+ CursorAcpInitializeResult,+ CursorAcpSessionOptions+> {+ private acceptUpdates = false;++ constructor(options: CursorAcpSessionOptions) {+ super(options, {+ args: buildCursorAcpArgs(options.args),+ pipeline: { agentType: 'cursor-acp', cwd: options.cwd },+ processLabel: 'Cursor ACP',+ transport: TRANSPORT,+ });+ }++ get sessionId(): string | undefined {+ return this.acpSessionId;+ }++ protected buildInitializeParams(): unknown {+ return {+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ clientInfo: {+ name: 'lobehub',+ title: 'LobeHub',+ version: this.options.clientVersion,+ },+ protocolVersion: ACP_PROTOCOL_VERSION,+ };+ }++ protected validateInitialized(initialized: CursorAcpInitializeResult): void {+ if (+ initialized.protocolVersion !== ACP_PROTOCOL_VERSION &&+ initialized.protocolVersion !== String(ACP_PROTOCOL_VERSION)+ ) {+ throw new Error(+ `Cursor ACP returned unsupported protocol version: ${String(initialized.protocolVersion)}`,+ );+ }+ }++ protected async establishSession(initialized: CursorAcpInitializeResult): Promise<string> {+ const advertisedAuthMethods = initialized.authMethods?.flatMap(({ id }) =>+ typeof id === 'string' ? [id] : [],+ );+ if (advertisedAuthMethods?.length && !advertisedAuthMethods.includes(AUTH_METHOD)) {+ throw new Error('Cursor could not authenticate. Run `agent login`, then retry.');+ }+ if (advertisedAuthMethods?.includes(AUTH_METHOD)) {+ await this.client.request('authenticate', { methodId: AUTH_METHOD });+ }+ if (this.options.resumeSessionId && initialized.agentCapabilities?.loadSession !== true) {+ throw new Error('Cursor ACP does not support loading this saved session');+ }++ const sessionResult = await this.client.request<CursorAcpSessionResult>(+ this.options.resumeSessionId ? 'session/load' : 'session/new',+ {+ cwd: this.options.cwd,+ mcpServers: [],+ ...(this.options.resumeSessionId ? { sessionId: this.options.resumeSessionId } : {}),+ },+ );+ const sessionId = sessionResult.sessionId ?? this.options.resumeSessionId;+ if (!sessionId) throw new Error('Cursor ACP returned no session id');+ this.options.onSessionId(sessionId);+ await this.pushToPipeline({ sessionId, type: 'cursor_session' });+ return sessionId;+ }++ protected onBeforePrompt(): void {+ // session/load may replay historical updates before returning. Keep setup+ // notifications gated until the new prompt is about to start.+ this.acceptUpdates = true;+ }++ protected buildPromptParams(sessionId: string): unknown {+ return { prompt: this.options.prompt, sessionId };+ }++ protected override async settlePrompt(result: unknown): Promise<void> {+ await this.client.drain();+ await this.pushToPipeline({+ stopReason: (result as CursorAcpPromptResult | undefined)?.stopReason,+ type: 'cursor_prompt_completed',+ });+ }++ protected async onRunFailure(error: Error): Promise<void> {+ await this.pushToPipeline({ message: error.message, type: 'cursor_error' });+ await this.emitEvents(await this.pipeline.flush());+ }++ protected async handleAgentMessage(message: AcpRpcMessage): Promise<void> {+ if (!this.acceptUpdates || message.method !== 'session/update') return;+ const params = isRecord(message.params) ? message.params : undefined;+ if (!isRecord(params?.update)) return;+ await this.pushToPipeline(this.normalizeSessionUpdate(params.update));+ }++ protected async handleServerRequest(message: AcpRpcMessage): Promise<unknown> {+ if (message.method === 'session/request_permission') {+ const request = this.parsePermissionRequest(message.params);+ const selected = await this.selectBridgeOption({+ header: 'Permission required',+ options: request.options.map(({ name, optionId }) => ({ id: optionId, label: name })),+ question: request.toolCall.title,+ toolCallId: this.buildInterventionToolCallId(+ message,+ 'permission',+ request.toolCall.toolCallId,+ ),+ });+ return {+ outcome: selected+ ? { optionId: selected.id, outcome: 'selected' }+ : { outcome: 'cancelled' },+ };+ }++ if (message.method === 'cursor/ask_question') {+ const request = this.parseAskQuestionRequest(message.params);+ const args = normalizeCursorQuestion(request);+ // Cursor normally emits a matching tool_call update, but synthesize the+ // canonical call as well so the intervention never races a missing or+ // delayed update. The adapter deduplicates by toolCallId.+ await this.pushToPipeline({+ identifier: 'claude-code',+ rawInput: args,+ sessionUpdate: 'tool_call',+ title: 'askUserQuestion',+ toolCallId: request.toolCallId,+ });++ if (!this.options.askUserBridge) return { outcome: { outcome: 'cancelled' } };+ const answer = await this.options.askUserBridge.pending({+ arguments: args,+ toolCallId: request.toolCallId,+ });+ return this.buildQuestionResponse(request, answer);+ }++ if (message.method === 'cursor/create_plan') {+ const request = this.parseCreatePlanRequest(message.params);+ const question = [request.overview, request.plan].filter(Boolean).join('\n\n');+ const selected = await this.selectBridgeOption({+ header: request.name ?? 'Plan approval',+ options: [+ { id: 'accepted', label: 'Accept' },+ { id: 'rejected', label: 'Reject' },+ ],+ question,+ toolCallId: this.buildInterventionToolCallId(message, 'plan', request.toolCallId),+ });+ return {+ outcome: {+ outcome:+ selected?.id === 'accepted'+ ? 'accepted'+ : selected?.id === 'rejected'+ ? 'rejected'+ : 'cancelled',+ },+ };+ }++ throw new AcpServerRequestError(-32_601, `Unsupported ACP client request: ${message.method}`);+ }++ private normalizeSessionUpdate(update: Record<string, unknown>): Record<string, unknown> {+ if (+ update.sessionUpdate !== 'tool_call' ||+ typeof update.toolCallId !== 'string' ||+ !isRecord(update.rawInput)+ ) {+ return update;+ }++ try {+ const request = this.parseAskQuestionRequest({+ ...update.rawInput,+ toolCallId: update.toolCallId,+ });+ return {+ ...update,+ identifier: 'claude-code',+ rawInput: normalizeCursorQuestion(request),+ title: 'askUserQuestion',+ };+ } catch {+ return update;+ }+ }++ private parsePermissionRequest(value: unknown): CursorAcpPermissionRequest {+ if (!isRecord(value) || !Array.isArray(value.options) || !isRecord(value.toolCall)) {+ throw new AcpServerRequestError(-32_602, 'Invalid session/request_permission request');+ }++ const options = value.options.flatMap((option) => {+ if (+ !isRecord(option) ||+ typeof option.kind !== 'string' ||+ typeof option.name !== 'string' ||+ typeof option.optionId !== 'string'+ ) {+ return [];+ }+ return [{ kind: option.kind, name: option.name, optionId: option.optionId }];+ });+ if (+ options.length !== value.options.length ||+ options.length === 0 ||+ typeof value.toolCall.toolCallId !== 'string' ||+ typeof value.toolCall.title !== 'string'+ ) {+ throw new AcpServerRequestError(-32_602, 'Invalid session/request_permission options');+ }++ return {+ options,+ toolCall: {+ title: value.toolCall.title,+ toolCallId: value.toolCall.toolCallId,+ },+ };+ }++ private parseCreatePlanRequest(value: unknown): CursorCreatePlanRequest {+ if (+ !isRecord(value) ||+ typeof value.toolCallId !== 'string' ||+ typeof value.plan !== 'string'+ ) {+ throw new AcpServerRequestError(-32_602, 'Invalid cursor/create_plan request');+ }++ return {+ name: typeof value.name === 'string' ? value.name : undefined,+ overview: typeof value.overview === 'string' ? value.overview : undefined,+ plan: value.plan,+ toolCallId: value.toolCallId,+ };+ }++ private async selectBridgeOption({+ header,+ options,+ question,+ toolCallId,+ }: {+ header: string;+ options: CursorBridgeOption[];+ question: string;+ toolCallId: string;+ }): Promise<CursorBridgeOption | undefined> {+ if (!this.options.askUserBridge) return;++ const arguments_ = {+ questions: [+ {+ header,+ multiSelect: false,+ options: options.map(({ label }) => ({ label })),+ question,+ },+ ],+ } satisfies CanonicalAskQuestionArgs;+ await this.pushToPipeline({+ identifier: 'claude-code',+ rawInput: arguments_,+ sessionUpdate: 'tool_call',+ title: 'askUserQuestion',+ toolCallId,+ });+ const answer = await this.options.askUserBridge.pending({+ arguments: arguments_,+ toolCallId,+ });+ await this.pushToPipeline({+ rawOutput: answer,+ sessionUpdate: 'tool_call_update',+ status: 'completed',+ toolCallId,+ });+ const selections = this.getAnswerSelections(answer, question);+ return options.find(({ id, label }) => selections.includes(id) || selections.includes(label));+ }++ private buildInterventionToolCallId(+ message: AcpRpcMessage,+ kind: 'permission' | 'plan',+ sourceToolCallId: string,+ ): string {+ return `cursor-${kind}-${String(message.id)}-${sourceToolCallId}`;+ }++ private getAnswerSelections(answer: InterventionAnswer, question: string): string[] {+ if (answer.cancelled || !isRecord(answer.result)) return [];+ const rawSelection = answer.result[question];+ return (Array.isArray(rawSelection) ? rawSelection : [rawSelection]).flatMap((selection) =>+ typeof selection === 'string' ? [selection] : [],+ );+ }++ private parseAskQuestionRequest(value: unknown): CursorAskQuestionRequest {+ if (+ !isRecord(value) ||+ typeof value.toolCallId !== 'string' ||+ !Array.isArray(value.questions)+ ) {+ throw new AcpServerRequestError(-32_602, 'Invalid cursor/ask_question request');+ }++ const questions = value.questions.flatMap((questionValue) => {+ if (!isRecord(questionValue)) return [];+ if (+ typeof questionValue.id !== 'string' ||+ typeof questionValue.prompt !== 'string' ||+ !Array.isArray(questionValue.options)+ ) {+ return [];+ }+ const options = questionValue.options.flatMap((optionValue) =>+ isRecord(optionValue) &&+ typeof optionValue.id === 'string' &&+ typeof optionValue.label === 'string'+ ? [{ id: optionValue.id, label: optionValue.label }]+ : [],+ );+ if (options.length === 0) return [];+ return [+ {+ allowMultiple: questionValue.allowMultiple === true,+ id: questionValue.id,+ options,+ prompt: questionValue.prompt,+ },+ ];+ });+ if (questions.length !== value.questions.length || questions.length === 0) {+ throw new AcpServerRequestError(-32_602, 'Invalid cursor/ask_question questions');+ }++ return {+ questions,+ title: typeof value.title === 'string' ? value.title : undefined,+ toolCallId: value.toolCallId,+ };+ }++ private buildQuestionResponse(+ request: CursorAskQuestionRequest,+ answer: InterventionAnswer,+ ): unknown {+ if (answer.cancelled) return { outcome: { outcome: 'cancelled' } };+ if (!isRecord(answer.result)) return { outcome: { outcome: 'cancelled' } };++ const freeform = answer.result.__freeform__;+ if (typeof freeform === 'string' && freeform.trim()) {+ return {+ outcome: {+ answers: request.questions.map(({ id }) => ({+ questionId: id,+ selectedOptionIds: [freeform.trim()],+ })),+ outcome: 'answered',+ },+ };+ }++ const answers = [];+ for (const question of request.questions) {+ const selectedOptionIds = this.getAnswerSelections(answer, question.prompt).flatMap(+ (selection) => {+ const option = question.options.find(+ ({ id, label }) => id === selection || label === selection,+ );+ return [option?.id ?? selection];+ },+ );+ answers.push({ questionId: question.id, selectedOptionIds });+ }++ return { outcome: { answers, outcome: 'answered' } };+ }+}diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 8b23d1c41bd..611ca98660e 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -74,6 +74,15 @@ export {readCodexSessionModel,resolveCodexInitialModel,} from './codexModel';+export {+ buildCursorAcpArgs,+ buildCursorAcpPrompt,+ CursorAcpSession,+ type CursorAcpSessionOptions,+ type CursorAcpTextPromptBlock,+ isCursorAcpSessionNotFoundError,+ normalizeCursorQuestion,+} from './cursorAcpSession';export {createFileStoreImageUploader,type FileStoreCreateFileInput,@@ -124,7 +133,6 @@ export {CODEX_DEFAULT_EXECUTION_ARGS,CODEX_EXECUTION_MODE_FLAGS,CODEX_REQUIRED_ARGS,- CURSOR_BASE_ARGS,KIMI_CODE_BASE_ARGS,OPENCODE_BASE_ARGS,PI_BASE_ARGS,diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.tsindex e8ab278ffe6..434ec49656e 100644--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts@@ -253,23 +253,6 @@ describe('buildAgentInput', () => {});});- describe('cursor', () => {- it('passes v1 text input through and explicitly rejects images', async () => {- await expect(buildAgentInput('cursor', 'hello')).resolves.toEqual({- args: [],- stdin: 'hello',- });- await expect(- buildAgentInput('cursor', [- {- source: { data: PNG_BYTES.toString('base64'), mediaType: 'image/png', type: 'base64' },- type: 'image',- },- ]),- ).rejects.toThrow('Cursor CLI does not support image input.');- });- });-describe('opencode', () => {it('uses raw text stdin and repeatable --file flags', async () => {const filePath = path.join(tmp, 'opencode.png');diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.tsindex f44bde11fae..843bd3d2f77 100644--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts@@ -46,13 +46,6 @@ const collectText = (blocks: AgentContentBlock[]): string =>.filter((t) => t.length > 0).join('\n\n');-const buildCursorInput = (blocks: AgentContentBlock[]): AgentInputPlan => {- if (blocks.some(isImageBlock)) {- throw new Error('Cursor CLI does not support image input.');- }- return { args: [], stdin: collectText(blocks) };-};-const buildClaudeCompatibleStdin = async (blocks: AgentContentBlock[],options: BuildAgentInputOptions,@@ -184,7 +177,6 @@ const buildQoderInput = async (** - `amp` / `claude-code` / `codebuddy`: stream-json on stdin with text + base64 image content blocks* - `codex`: raw text on stdin + repeatable `--image <path>` flags- * - `cursor`: raw text passed as a positional argument; images are unsupported* - `opencode`: raw text on stdin + repeatable `--file <path>` flags* - `pi`: raw text on stdin + repeatable `@<path>` arguments* - `qoder`: stream-json text on stdin + repeatable `--attachment <path>` flags@@ -208,9 +200,6 @@ export const buildAgentInput = async (case 'codex': {return buildCodexInput(blocks, options);}- case 'cursor': {- return buildCursorInput(blocks);- }case 'kimi-code': {return buildKimiCodeInput(blocks);}diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex c6f2da1592b..a71abfd1761 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -253,6 +253,62 @@ const createFakeAcpProc = ({return { proc, requests };};+const createCursorAcpProc = () => {+ const proc = new EventEmitter() as any;+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const requests: Array<{+ id?: number;+ method?: string;+ params?: Record<string, unknown>;+ }> = [];+ const send = (message: Record<string, unknown>) =>+ stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);+ Object.assign(proc, {+ kill: vi.fn(() => true),+ killed: false,+ pid: 67_890,+ stderr,+ stdin: {+ once: vi.fn(),+ write: vi.fn((chunk: string) => {+ const message = JSON.parse(chunk.trim());+ requests.push(message);+ queueMicrotask(() => {+ switch (message.method) {+ case 'initialize': {+ send({+ id: message.id,+ result: {+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: 'cursor_login' }],+ protocolVersion: 1,+ },+ });+ return;+ }+ case 'authenticate': {+ send({ id: message.id, result: {} });+ return;+ }+ case 'session/load': {+ send({ id: message.id, result: {} });+ return;+ }+ case 'session/prompt': {+ send({ id: message.id, result: { stopReason: 'end_turn' } });+ }+ }+ });+ return true;+ }),+ },+ stdout,+ });++ return { proc, requests };+};+const ccInit = `${JSON.stringify({model: 'claude-sonnet-4-6',session_id: 'cc-1',@@ -473,39 +529,39 @@ describe('spawnAgent', () => {expect(spawnCalls).toHaveLength(0);});- it('spawns Cursor with positional prompt, resume, native args, and no stdin payload', async () => {- const fake = createFakeProc();+ it('runs Cursor through ACP with native args and an ACP-native resume id', async () => {+ const fake = createCursorAcpProc();nextFakeProc = fake.proc;+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);const { spawnAgent } = await import('./spawnAgent');- await spawnAgent({+ const handle = await spawnAgent({agentType: 'cursor',extraArgs: ['--model', 'sonnet', '--mode', 'plan'],operationId: 'op-cursor',prompt: 'do a thing',resumeSessionId: 'cursor-session',});+ const events = [];+ for await (const event of handle.events) events.push(event);+ await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });expect(spawnCalls[0]).toMatchObject({- args: [- '-p',- '--force',- '--trust',- '--output-format',- 'stream-json',- '--stream-partial-output',- '--resume',- 'cursor-session',- '--model',- 'sonnet',- '--mode',- 'plan',- '--',- 'do a thing',- ],+ args: ['--model', 'sonnet', '--mode', 'plan', 'acp'],command: 'agent',});- expect(fake.stdinWrites).toEqual([]);- expect(fake.proc.stdin.end).toHaveBeenCalledOnce();+ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'authenticate',+ 'session/load',+ 'session/prompt',+ ]);+ expect(fake.requests.find(({ method }) => method === 'session/prompt')?.params).toEqual({+ prompt: [{ text: 'do a thing', type: 'text' }],+ sessionId: 'cursor-session',+ });+ expect(handle.sessionId).toBe('cursor-session');+ expect(events).toContainEqual(expect.objectContaining({ type: 'agent_runtime_end' }));+ killSpy.mockRestore();});it('runs TRAE through ACP behind the standard handle contract', async () => {diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 3c0f103ea8e..9e640d13049 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -6,11 +6,13 @@ import { PassThrough } from 'node:stream';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { AskUserBridge } from '../askUser/AskUserBridge';import { resolveHeterogeneousAgentCommand } from '../config';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';import { HETERO_WORKING_DIRECTORY_NOT_FOUND } from './classifyProcessFailure';import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';+import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';import type { AgentPromptInput, BuildAgentInputOptions } from './input';import { buildAgentInput } from './input';@@ -19,6 +21,8 @@ import { buildTraeAcpPrompt, TraeAcpSession } from './traeAcpSession';export interface SpawnAgentOptions {/** Registered local heterogeneous-agent type key. */agentType: string;+ /** Bridge for bidirectional question requests emitted by ACP agents. */+ askUserBridge?: AskUserBridge;/*** Override the CLI binary name. Defaults to the agent's standard executable.* Use this when the binary lives at a non-default@@ -203,15 +207,6 @@ export const AMP_BASE_ARGS = ['--no-archive-after-execute',] as const;-export const CURSOR_BASE_ARGS = [- '-p',- '--force',- '--trust',- '--output-format',- 'stream-json',- '--stream-partial-output',-] as const;-export const OPENCODE_BASE_ARGS = ['run', '--format', 'json', '--thinking', '--auto'] as const;export const PI_BASE_ARGS = ['--mode', 'json'] as const;export const KIMI_CODE_BASE_ARGS = ['--output-format', 'stream-json'] as const;@@ -237,8 +232,6 @@ interface BuildSpawnArgsParams {includePartialMessages: boolean;/** Per-agent input args produced by `buildAgentInput` (e.g. Codex `--image`). */inputArgs: string[];- /** Text payload produced by `buildAgentInput`; Cursor passes it positionally. */- inputText: string;/** Native session id for resume; undefined for fresh runs. */resumeSessionId: string | undefined;}@@ -291,20 +284,6 @@ const buildAmpArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsP: executionArgs;};-const buildCursorArgs = ({- extraArgs,- inputArgs,- inputText,- resumeSessionId,-}: BuildSpawnArgsParams) => [- ...CURSOR_BASE_ARGS,- ...(resumeSessionId ? ['--resume', resumeSessionId] : []),- ...extraArgs,- ...inputArgs,- '--',- inputText,-];-const buildOpenCodeArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsParams) => [...OPENCODE_BASE_ARGS,...(resumeSessionId ? ['--session', resumeSessionId] : []),@@ -357,9 +336,6 @@ const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {case 'codex': {return buildCodexArgs(params);}- case 'cursor': {- return buildCursorArgs(params);- }case 'kimi-code': {return buildKimiCodeArgs(params);}@@ -546,6 +522,46 @@ const spawnGrokAcpAgent = async (};};+const spawnCursorAcpAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+): Promise<SpawnAgentHandle> => {+ const prompt = buildCursorAcpPrompt(options.prompt);+ const bridge = createAcpSpawnBridge();+ const session = new CursorAcpSession({+ args: options.extraArgs ?? [],+ askUserBridge: options.askUserBridge,+ clientVersion: 'lobehub-cli',+ commandPath: command,+ cwd,+ env: { ...process.env, ...options.env },+ onEvents: bridge.onEvents,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ const { exit, kill } = bridge.attach(session);++ return {+ events: bridge.events,+ exit,+ kill,+ get pid() {+ return session.pid;+ },+ get sessionId() {+ return session.sessionId;+ },+ stderr: bridge.stderr,+ };+};+/*** Spawn an external agent CLI (Amp, Claude Code, CodeBuddy, Codex, Cursor,* Kimi Code, OpenCode, Pi, Qoder, or TRAE) and yield its stream as unified@@ -575,6 +591,9 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentif (options.agentType === 'grok-build') {return spawnGrokAcpAgent(options, command, cwd);}+ if (options.agentType === 'cursor') {+ return spawnCursorAcpAgent(options, command, cwd);+ }const inputPlan = await buildAgentInput(options.agentType, options.prompt, options.inputOptions);const args = buildSpawnArgs({@@ -582,7 +601,6 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentextraArgs: options.extraArgs ?? [],includePartialMessages: options.includePartialMessages ?? false,inputArgs: inputPlan.args,- inputText: inputPlan.stdin,resumeSessionId: options.resumeSessionId,});const childEnv = {@@ -654,12 +672,9 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent);if (proc.stdin) {- if (options.agentType === 'cursor') proc.stdin.end();- else {- proc.stdin.write(inputPlan.stdin, () => {- proc.stdin?.end();- });- }+ proc.stdin.write(inputPlan.stdin, () => {+ proc.stdin?.end();+ });}// ALL pipeline work — push / flush — runs through this single chain so:diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex a8b924ad5bd..2d35331c4c1 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -508,6 +508,8 @@ export default {'Update the target device client to discover CLI models.','heteroAgent.resumeReset.cwdChanged':'Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.',+ 'heteroAgent.resumeReset.cursorAcpIncompatible':+ 'The previous Cursor session could not be restored through ACP, so a new conversation has started with fresh context.','heteroAgent.resumeReset.resumeFailed':'The saved Codex thread could not be resumed safely, so a new conversation has started for this topic.','heteroAgent.switchCwd.cancel': 'Cancel',diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 8580454a660..f1bb04e0cb4 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -39,6 +39,11 @@ const mockUpdateMessageError = vi.fn();const mockUpdateToolMessage = vi.fn();const mockGetMessages = vi.fn();+const mockToastInfo = vi.fn();+vi.mock('@lobehub/ui/base-ui', () => ({+ toast: { info: (...args: unknown[]) => mockToastInfo(...args) },+}));+vi.mock('@/services/message', () => ({messageService: {batchMutate: (...args: any[]) => mockBatchMutate(...args),@@ -2031,6 +2036,74 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockStopSession.mock.calls).toEqual([['ipc-sess-1'], ['ipc-sess-2']]);});+ it('starts a fresh Cursor ACP context after an old session cannot be loaded', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);+ const sendPromptControllers = new Map<+ string,+ { reject: (reason?: unknown) => void; resolve: () => void }+ >();+ let startCount = 0;+ mockStartSession.mockImplementation(async (params: any) => {+ startCount += 1;+ const sessionId = startCount === 1 ? 'ipc-sess-1' : 'ipc-sess-2';+ ipc.setAgentType(sessionId, params.agentType);+ return { sessionId };+ });+ mockSendPrompt.mockImplementation(+ ({ sessionId }: { sessionId: string }) =>+ new Promise<void>((resolve, reject) => {+ sendPromptControllers.set(sessionId, { reject, resolve });+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: { command: 'agent', type: 'cursor' as const },+ resumeSessionId: 'legacy-cursor-session',+ workingDirectory: '/Users/me/repo',+ });+ await flush();++ ipc.emitError('ipc-sess-1', {+ agentType: 'cursor',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ message:+ 'The saved Cursor session cannot be loaded through ACP, so a new conversation will start.',+ });+ await flush();+ sendPromptControllers.get('ipc-sess-1')?.reject(new Error('resume failed'));+ await flush();++ expect(mockStartSession).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ agentType: 'cursor',+ resumeSessionId: 'legacy-cursor-session',+ }),+ );+ expect(mockStartSession).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ agentType: 'cursor', resumeSessionId: undefined }),+ );+ expect(store.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ heteroSessionId: undefined,+ heteroSessionIdByWorkingDirectory: {},+ workingDirectory: '/Users/me/repo',+ workingDirectoryConfig: { path: '/Users/me/repo' },+ });+ expect(mockToastInfo).toHaveBeenCalledWith(+ expect.stringMatching(/Cursor|cursorAcpIncompatible/),+ );++ ipc.emitComplete('ipc-sess-2');+ await flush();+ sendPromptControllers.get('ipc-sess-2')?.resolve();+ await executorPromise;++ expect(mockStopSession.mock.calls).toEqual([['ipc-sess-1'], ['ipc-sess-2']]);+ });+it('retries Grok without resume when a recoverable session error follows a terminal event', async () => {const store = createMockStore();const get = vi.fn(() => store);diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 565e5b41e25..0c4ee564a5f 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -1014,7 +1014,14 @@ export const executeHeterogeneousAgent = async (completed = true;fallbackPromise = (async () => {await clearStaleResumeMetadata().catch(console.error);- toast?.info?.(t('heteroAgent.resumeReset.resumeFailed', { ns: 'chat' }));+ toast?.info?.(+ t(+ adapterType === 'cursor'+ ? 'heteroAgent.resumeReset.cursorAcpIncompatible'+ : 'heteroAgent.resumeReset.resumeFailed',+ { ns: 'chat' },+ ),+ );await executeHeterogeneousAgent(get, { ...params, resumeSessionId: undefined });})();