Skip to content

🤯 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.

✨ feat(heterogeneous-agents): 接入 GitHub Copilot CLI 异构 Agent (#22195)

Mocha03e777a8c345
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index bcef6e9dff5..fac0c22abc5 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -10,6 +10,7 @@ import {
isLocalHeterogeneousType,
LOCAL_HETEROGENEOUS_AGENT_TYPES,
type LocalHeterogeneousAgentType,
+ usesHeterogeneousSessionInitialModel,
} from '@lobechat/heterogeneous-agents';
import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
import { LobeBuiltinMcpServer } from '@lobechat/heterogeneous-agents/builtinMcp';
@@ -247,14 +248,17 @@ const collectAgentArg = (value: string, previous: string[] = []): string[] => [.
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.mode
+ ? ['--mode', options.mode]
+ : []
: options.type === 'droid' || options.type === 'trae'
? []
: options.type === 'codex'
? [
- ...(options.model ? ['--model', options.model] : []),
+ ...modelArg,
...(options.effort
? ['-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${options.effort}"`]
: []),
@@ -265,21 +269,15 @@ const buildExtraArgs = (
: options.type === 'claude-code' ||
options.type === 'codebuddy' ||
options.type === 'grok-build'
- ? [
- ...(options.model ? ['--model', options.model] : []),
- ...(options.effort ? ['--effort', options.effort] : []),
- ]
+ ? [...modelArg, ...(options.effort ? ['--effort', options.effort] : [])]
: options.type === 'cursor' ||
options.type === 'devin' ||
options.type === 'kimi-code' ||
options.type === 'opencode' ||
options.type === 'pi'
- ? [...(options.model ? ['--model', options.model] : [])]
- : options.type === 'qoder'
- ? [
- ...(options.model ? ['--model', options.model] : []),
- ...(options.effort ? ['--reasoning-effort', options.effort] : []),
- ]
+ ? modelArg
+ : options.type === 'copilot' || options.type === 'qoder'
+ ? [...modelArg, ...(options.effort ? ['--reasoning-effort', options.effort] : [])]
: [];
const extraArgs = [...(options.agentArg ?? []), ...selectorArgs];
@@ -762,22 +760,23 @@ const exec = async (options: ExecOptions): Promise<void> => {
if (
serverIngest &&
(agentType === 'claude-code' ||
+ agentType === 'copilot' ||
agentType === 'cursor' ||
agentType === 'droid' ||
agentType === 'devin' ||
agentType === 'qoder') &&
serverIngester
) {
- if (agentType === 'cursor' || agentType === 'droid') {
+ if (
+ agentType === 'copilot' ||
+ agentType === 'cursor' ||
+ agentType === 'devin' ||
+ agentType === 'droid'
+ ) {
askBridge = new AskUserBridge(operationId, {
identifier: agentType === 'cursor' ? 'claude-code' : agentType,
provider: agentType,
});
- } else if (agentType === 'devin') {
- askBridge = new AskUserBridge(operationId, {
- identifier: 'devin',
- provider: 'devin',
- });
} else {
askServer = new LobeBuiltinMcpServer();
await askServer.start();
@@ -1269,10 +1268,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
// server agents. Ask Claude Code for content-block deltas so the current conversation
// receives text while the process is running, not only the terminal assistant snapshot.
includePartialMessages: options.type === 'claude-code',
- initialModel:
- options.type === 'droid' || options.type === 'devin' || options.type === 'trae'
- ? options.model
- : undefined,
+ initialModel: usesHeterogeneousSessionInitialModel(options.type) ? options.model : undefined,
// Keep Claude Code's stdin open while it can still use input: closing it
// early makes print mode kill background tasks after 10 minutes.
liveInput: options.type === 'claude-code',
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 2c57dcecbff..4bd2100e845 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -69,41 +69,22 @@ import type {
UsageData,
} from '@lobechat/heterogeneous-agents/spawn';
import {
- AcpRpcResponseError,
AgentStreamPipeline,
buildAgentInput,
- buildCursorAcpArgs,
- buildCursorAcpPrompt,
- buildDevinAcpArgs,
- buildDevinAcpPrompt,
- buildDroidAcpArgs,
- buildDroidAcpPrompt,
- buildGrokAcpArgs,
- buildGrokAcpPrompt,
- buildTraeAcpArgs,
- buildTraeAcpPrompt,
ClaudeAgentSdkSession,
createFileStoreImageUploader,
- CursorAcpSession,
detectDshCommand,
- DevinAcpSession,
- DroidAcpSession,
DSH_COMMAND,
ensureClaudeCodeResumeTranscript,
findClaudeCodeTranscriptPath,
getCodexAppServerUnsupportedArgs,
getHeterogeneousAgentPresetEnv,
- GrokAcpSession,
- isCursorAcpSessionNotFoundError,
- isDevinAcpSessionNotFoundError,
- isDroidAcpSessionNotFoundError,
prepareClaudeCodeLobeHubCli,
readClaudeCodeSessionCost,
readCodexSessionModel,
resolveCliSpawnPlan,
resolveCodexInitialModel,
spawnDshAcpSession,
- TraeAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
import {
buildClaudeCodeReplayTurn,
@@ -125,7 +106,6 @@ import {
} from '@lobechat/utils/managedProcess';
import { sleep } from '@lobechat/utils/sleep';
import { app as electronApp, BrowserWindow } from 'electron';
-import { isPlainObject } from 'es-toolkit';
import semver from 'semver';
import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';
@@ -182,7 +162,13 @@ import { createLogger } from '@/utils/logger';
import BrowserControlCtr from './BrowserControlCtr';
import { sendPromptWithCodexAppServer } from './codexAppServer';
import type { AgentSession, CliTraceSession, SendPromptParams } from './heterogeneousAgentSession';
-import { claudeProfileDirOf } from './heterogeneousAgentSession';
+import {
+ claudeProfileDirOf,
+ closeActiveAcpSessions,
+ getAcpResumeError,
+ interruptActiveAcpSession,
+ sendPromptWithAcpSession,
+} from './heterogeneousAgentSession';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
const logger = createLogger('controllers:HeterogeneousAgentCtr');
@@ -215,15 +201,15 @@ export const buildInheritedSpawnEnv = (
};
const appendLoopbackNoProxy = (env: NodeJS.ProcessEnv): void => {
- const entries = new Set(
- [env.NO_PROXY, env.no_proxy]
+ const entries = new Set([
+ ...[env.NO_PROXY, env.no_proxy]
.filter((value): value is string => !!value)
.flatMap((value) => value.split(','))
.map((value) => value.trim())
.filter(Boolean),
- );
- entries.add('127.0.0.1');
- entries.add('localhost');
+ '127.0.0.1',
+ 'localhost',
+ ]);
const noProxy = [...entries].join(',');
env.NO_PROXY = noProxy;
env.no_proxy = noProxy;
@@ -415,10 +401,6 @@ interface LhHeteroExecTask {
process: ChildProcess;
}
-interface InteractiveAcpSession {
- run: () => Promise<void>;
-}
-
/**
* External Agent Controller — manages external agent CLI processes via Electron IPC.
*
@@ -582,16 +564,20 @@ export default class HeterogeneousAgentCtr {
});
return false;
},
+ 'copilot': async (params, session) => {
+ await this.sendPromptWithAcp(params, session);
+ return true;
+ },
'cursor': async (params, session) => {
- await this.sendPromptWithCursorAcp(params, session);
+ await this.sendPromptWithAcp(params, session);
return true;
},
'devin': async (params, session) => {
- await this.sendPromptWithDevinAcp(params, session);
+ await this.sendPromptWithAcp(params, session);
return true;
},
'droid': async (params, session) => {
- await this.sendPromptWithDroidAcp(params, session);
+ await this.sendPromptWithAcp(params, session);
return true;
},
'deepseek-harness': async (params, session) => {
@@ -599,11 +585,11 @@ export default class HeterogeneousAgentCtr {
return true;
},
'grok-build': async (params, session) => {
- await this.sendPromptWithGrokAcp(params, session);
+ await this.sendPromptWithAcp(params, session);
return true;
},
'trae': async (params, session) => {
- await this.sendPromptWithTraeAcp(params, session);
+ await this.sendPromptWithAcp(params, session);
return true;
},
// Pi runs exclusively over the RPC transport — there is no json fallback.
@@ -770,119 +756,6 @@ export default class HeterogeneousAgentCtr {
}
}
- private getDroidResumeError(
- error: unknown,
- session: AgentSession,
- ): HeterogeneousAgentSessionError | undefined {
- if (
- session.agentType !== 'droid' ||
- !session.resumeSessionId ||
- !isDroidAcpSessionNotFoundError(error)
- ) {
- return;
- }
-
- return {
- agentType: 'droid',
- code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
- command: session.command,
- details: {
- code: error.rpcError.code,
- data: error.rpcError.data,
- },
- message:
- 'The saved Factory Droid session could not be found, so a new conversation will start.',
- resumeSessionId: session.resumeSessionId,
- stderr: error.message,
- workingDirectory: session.cwd,
- };
- }
-
- private getGrokResumeError(
- error: unknown,
- session: AgentSession,
- ): HeterogeneousAgentSessionError | undefined {
- if (
- session.agentType !== 'grok-build' ||
- !session.resumeSessionId ||
- !(error instanceof AcpRpcResponseError) ||
- error.method !== 'session/load' ||
- !isPlainObject(error.rpcError.data) ||
- error.rpcError.data.code !== 'FS_NOT_FOUND'
- ) {
- return;
- }
-
- return {
- agentType: 'grok-build',
- code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
- command: session.command,
- details: {
- code: error.rpcError.code,
- data: error.rpcError.data,
- },
- message: 'The saved Grok Build session could not be found, so it can no longer be resumed.',
- resumeSessionId: session.resumeSessionId,
- stderr: error.message,
- workingDirectory: session.cwd,
- };
- }
-
- 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 getDevinResumeError(
- error: unknown,
- session: AgentSession,
- ): HeterogeneousAgentSessionError | undefined {
- if (
- session.agentType !== 'devin' ||
- !session.resumeSessionId ||
- !isDevinAcpSessionNotFoundError(error)
- ) {
- return;
- }
-
- return {
- agentType: 'devin',
- code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
- command: session.command,
- details: {
- code: error.rpcError.code,
- data: error.rpcError.data,
- },
- message: 'The saved Devin session could not be found, so a new conversation will start.',
- resumeSessionId: session.resumeSessionId,
- stderr: error.message,
- workingDirectory: session.cwd,
- };
- }
-
private getCliAuthRequiredError(
error: unknown,
session: AgentSession,
@@ -907,11 +780,7 @@ export default class HeterogeneousAgentCtr {
}
const resumeError =
- this.getCodexResumeError(error, session) ??
- this.getDroidResumeError(error, session) ??
- this.getGrokResumeError(error, session) ??
- this.getCursorResumeError(error, session) ??
- this.getDevinResumeError(error, session);
+ this.getCodexResumeError(error, session) ?? getAcpResumeError(error, session);
if (resumeError) return resumeError;
const authRequiredError = this.getCliAuthRequiredError(error, session);
@@ -2199,518 +2068,28 @@ export default class HeterogeneousAgentCtr {
);
}
- private async sendPromptWithGrokAcp(
- params: SendPromptParams,
- session: AgentSession,
- ): Promise<void> {
- const cwd = session.cwd || electronApp.getPath('desktop');
- const spawnEnv = this.buildSessionSpawnEnv(session);
- const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);
- const promptInput = buildHeterogeneousPrompt({
- imageList: params.imageList,
- isNewSession: this.needsSessionIntroduction(session),
- prompt: params.prompt,
- systemContext: params.systemContext,
- });
- let prompt;
- try {
- prompt = await buildGrokAcpPrompt(promptInput, { cacheDir: this.fileCacheDir });
- } catch (error) {
- logger.error('Failed to prepare Grok Build ACP input:', error);
- throw new Error(
- `Failed to attach image(s) to Grok Build: ${this.getErrorMessage(error) || 'Unknown error'}`,
- { cause: error },
- );
- }
-
- const traceInput = `${JSON.stringify(prompt)}\n`;
- const traceSession = await this.createCliTraceSession({
- cliArgs: buildGrokAcpArgs(session.args),
- cwd,
- imageList: params.imageList ?? [],
- session,
- stdinPayload: traceInput,
- });
- void this.writeCliTraceFile(traceSession, 'stdin.txt', traceInput);
-
- if (session.cancelledByUs) {
- await this.completeCancelledSessionBeforeLaunch(session);
- return;
- }
-
- const acpSession = new GrokAcpSession({
- args: session.args,
- 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) => {
- if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;
- },
- onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),
- operationId: params.operationId,
- prompt,
- resumeSessionId: session.agentSessionId,
- sessionId: session.sessionId,
- });
- session.grokAcpSession = acpSession;
-
- logger.info('Starting Grok Build ACP session:', {
- commandPath,
- cwd,
- sessionId: session.sessionId,
- });
-
- try {
- await acpSession.run();
- void this.writeCliTraceJson(traceSession, 'exit.json', {
- finishedAt: new Date().toISOString(),
- transport: 'acp-stdio',
- });
- await this.flushCliTrace(traceSession);
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- } catch (error) {
- logger.error('Grok Build ACP session error:', error);
- void this.writeCliTraceJson(traceSession, 'process-error.json', {
- message: error instanceof Error ? error.message : String(error),
- name: error instanceof Error ? error.name : 'Error',
- transport: 'acp-stdio',
- });
- await this.flushCliTrace(traceSession);
-
- if (session.cancelledByUs) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- return;
- }
-
- const sessionError = this.getSessionErrorPayload(error, session);
- this.broadcast('heteroAgentSessionError', {
- error: sessionError,
- sessionId: session.sessionId,
- });
- throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {
- cause: error,
- });
- } finally {
- await session.hostedProviderBinding?.cleanup();
- if (session.grokAcpSession === acpSession) session.grokAcpSession = undefined;
- }
- }
-
- 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,
- isNewSession: this.needsSessionIntroduction(session),
- 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);
-
- if (session.cancelledByUs) {
- await this.completeCancelledSessionBeforeLaunch(session);
- return;
- }
-
- const stderrChunks: string[] = [];
- const intervention = this.setupAcpInterventionForOp(
- params.operationId,
- session.sessionId,
- 'cursor',
- );
- 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;
-
- await this.runInteractiveAcpSession({
- acpSession: cursorAcpSession,
- activeSessionKey: 'cursorAcpSession',
- cleanup: intervention.cleanup,
- isResumeError: isCursorAcpSessionNotFoundError,
- session,
- stderrChunks,
- traceSession,
- transport: 'cursor-acp',
- });
- }
-
- private async sendPromptWithDroidAcp(
- 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,
- isNewSession: this.needsSessionIntroduction(session),
- prompt: params.prompt,
- systemContext: params.systemContext,
- });
- const prompt = await buildDroidAcpPrompt(promptInput, { cacheDir: this.fileCacheDir });
- const tracePayload = `${JSON.stringify(prompt)}\n`;
- const traceSession = await this.createCliTraceSession({
- cliArgs: buildDroidAcpArgs(session.args),
- cwd,
- imageList: params.imageList ?? [],
- session,
- stdinPayload: tracePayload,
- });
- void this.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
-
- if (session.cancelledByUs) {
- await this.completeCancelledSessionBeforeLaunch(session);
- return;
- }
-
- const stderrChunks: string[] = [];
- const intervention = this.setupAcpInterventionForOp(
- params.operationId,
- session.sessionId,
- 'droid',
- );
- const droidAcpSession = new DroidAcpSession({
- args: session.args,
- askUserBridge: intervention.bridge,
- clientVersion: electronApp.getVersion(),
- commandPath,
- cwd,
- env: spawnEnv,
- initialModel: session.model,
- onEvents: async (events) => {
- for (const event of events) {
- this.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });
- }
- },
- onModel: (model) => {
- session.model = model;
- session.modelSource = 'droid-acp';
- },
- 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);
+ private sendPromptWithAcp(params: SendPromptParams, session: AgentSession): Promise<void> {
+ return sendPromptWithAcpSession(
+ {
+ appendCliTraceFile: this.appendCliTraceFile.bind(this),
+ broadcast: this.broadcast.bind(this),
+ buildSessionSpawnEnv: this.buildSessionSpawnEnv.bind(this),
+ completeCancelledSessionBeforeLaunch: this.completeCancelledSessionBeforeLaunch.bind(this),
+ createCliTraceSession: this.createCliTraceSession.bind(this),
+ fileCacheDir: this.fileCacheDir,
+ flushCliTrace: this.flushCliTrace.bind(this),
+ getErrorMessage: this.getErrorMessage.bind(this),
+ getSessionErrorPayload: this.getSessionErrorPayload.bind(this),
+ needsSessionIntroduction: this.needsSessionIntroduction.bind(this),
+ resolveSessionCommand: this.resolveSessionCommand.bind(this),
+ resolveSessionWorkingDirectory: this.resolveSessionWorkingDirectory.bind(this),
+ setupAcpInterventionForOp: this.setupAcpInterventionForOp.bind(this),
+ writeCliTraceFile: this.writeCliTraceFile.bind(this),
+ writeCliTraceJson: this.writeCliTraceJson.bind(this),
},
- operationId: params.operationId,
- prompt,
- resumeSessionId: session.agentSessionId,
- sessionId: session.sessionId,
- });
- session.droidAcpSession = droidAcpSession;
-
- try {
- await droidAcpSession.run();
- void this.writeCliTraceJson(traceSession, 'exit.json', {
- finishedAt: new Date().toISOString(),
- transport: 'droid-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: 'droid-acp',
- });
- await this.flushCliTrace(traceSession);
- if (session.cancelledByUs) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- return;
- }
- const stderr = stderrChunks.join('').trim();
- const errorForClassification = isDroidAcpSessionNotFoundError(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.droidAcpSession === droidAcpSession) session.droidAcpSession = undefined;
- }
- }
-
- private async sendPromptWithDevinAcp(
- 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,
- isNewSession: this.needsSessionIntroduction(session),
- prompt: params.prompt,
- systemContext: params.systemContext,
- });
- const prompt = await buildDevinAcpPrompt(promptInput, { cacheDir: this.fileCacheDir });
- const tracePayload = `${JSON.stringify(prompt)}\n`;
- const traceSession = await this.createCliTraceSession({
- cliArgs: buildDevinAcpArgs(session.args),
- cwd,
- imageList: params.imageList ?? [],
+ params,
session,
- stdinPayload: tracePayload,
- });
- void this.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
-
- if (session.cancelledByUs) {
- await this.completeCancelledSessionBeforeLaunch(session);
- return;
- }
-
- const stderrChunks: string[] = [];
- const intervention = this.setupAcpInterventionForOp(
- params.operationId,
- session.sessionId,
- 'devin',
);
- const devinAcpSession = new DevinAcpSession({
- args: session.args,
- askUserBridge: intervention.bridge,
- clientVersion: electronApp.getVersion(),
- commandPath,
- cwd,
- env: spawnEnv,
- initialModel: session.model,
- onEvents: async (events) => {
- for (const event of events) {
- this.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });
- }
- },
- onModel: (model) => {
- session.model = model;
- session.modelSource = 'devin-acp';
- },
- 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.devinAcpSession = devinAcpSession;
-
- await this.runInteractiveAcpSession({
- acpSession: devinAcpSession,
- activeSessionKey: 'devinAcpSession',
- cleanup: intervention.cleanup,
- isResumeError: isDevinAcpSessionNotFoundError,
- session,
- stderrChunks,
- traceSession,
- transport: 'devin-acp',
- });
- }
-
- private async runInteractiveAcpSession({
- acpSession,
- activeSessionKey,
- cleanup,
- isResumeError,
- session,
- stderrChunks,
- traceSession,
- transport,
- }: {
- acpSession: InteractiveAcpSession;
- activeSessionKey: 'cursorAcpSession' | 'devinAcpSession' | 'traeAcpSession';
- cleanup?: () => Promise<void>;
- isResumeError?: (error: unknown) => boolean;
- session: AgentSession;
- stderrChunks: string[];
- traceSession: CliTraceSession | undefined;
- transport: 'cursor-acp' | 'devin-acp' | 'trae-acp';
- }): Promise<void> {
- try {
- await acpSession.run();
- void this.writeCliTraceJson(traceSession, 'exit.json', {
- finishedAt: new Date().toISOString(),
- transport,
- });
- await this.flushCliTrace(traceSession);
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- } catch (error) {
- void this.writeCliTraceJson(traceSession, 'process-error.json', {
- message: this.getErrorMessage(error),
- transport,
- });
- await this.flushCliTrace(traceSession);
- if (session.cancelledByUs) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- return;
- }
- const stderr = stderrChunks.join('').trim();
- const errorForClassification = isResumeError?.(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 cleanup?.();
- if (activeSessionKey === 'cursorAcpSession' && session.cursorAcpSession === acpSession) {
- session.cursorAcpSession = undefined;
- } else if (activeSessionKey === 'devinAcpSession' && session.devinAcpSession === acpSession) {
- session.devinAcpSession = undefined;
- } else if (activeSessionKey === 'traeAcpSession' && session.traeAcpSession === acpSession) {
- session.traeAcpSession = undefined;
- }
- }
- }
-
- private async sendPromptWithTraeAcp(
- 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,
- isNewSession: this.needsSessionIntroduction(session),
- prompt: params.prompt,
- systemContext: params.systemContext,
- });
- const prompt = await buildTraeAcpPrompt(promptInput, { cacheDir: this.fileCacheDir });
- const tracePayload = `${JSON.stringify(prompt)}\n`;
- const traceSession = await this.createCliTraceSession({
- cliArgs: buildTraeAcpArgs(session.args),
- cwd,
- imageList: params.imageList ?? [],
- session,
- stdinPayload: tracePayload,
- });
- void this.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
-
- if (session.cancelledByUs) {
- await this.completeCancelledSessionBeforeLaunch(session);
- return;
- }
-
- const stderrChunks: string[] = [];
-
- const traeAcpSession = new TraeAcpSession({
- args: session.args,
- clientVersion: electronApp.getVersion(),
- commandPath,
- cwd,
- env: spawnEnv,
- initialModel: session.model,
- onEvents: async (events) => {
- for (const event of events) {
- this.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });
- }
- },
- onModel: (model) => {
- session.model = model;
- session.modelSource = 'trae-acp';
- },
- 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.traeAcpSession = traeAcpSession;
-
- await this.runInteractiveAcpSession({
- acpSession: traeAcpSession,
- activeSessionKey: 'traeAcpSession',
- cleanup: async () => {
- await session.hostedProviderBinding?.cleanup();
- },
- session,
- stderrChunks,
- traceSession,
- transport: 'trae-acp',
- });
}
/**
@@ -3750,20 +3129,7 @@ export default class HeterogeneousAgentCtr {
await session.dshSession.dispose();
return;
}
- if (session.devinAcpSession) {
- session.devinAcpSession.interrupt();
- return;
- }
- if (session.grokAcpSession) {
- session.grokAcpSession.interrupt();
- return;
- }
- if (session.cursorAcpSession) {
- session.cursorAcpSession.interrupt();
- return;
- }
- if (session.droidAcpSession) {
- session.droidAcpSession.interrupt();
+ if (await interruptActiveAcpSession(session)) {
return;
}
if (session.appServerSession) {
@@ -3777,10 +3143,6 @@ export default class HeterogeneousAgentCtr {
}
return;
}
- if (session.traeAcpSession) {
- await session.traeAcpSession.interrupt();
- return;
- }
if (session.piRpcSession) {
// Resolves only after settlement or confirmed shutdown. Propagate a
// failed shutdown so "Send now" cannot start another native writer.
@@ -3829,25 +3191,7 @@ export default class HeterogeneousAgentCtr {
await session.dshSession.dispose();
session.dshSession = undefined;
}
- if (session.devinAcpSession) {
- session.cancelledByUs = true;
- session.devinAcpSession.close();
- }
-
- if (session.grokAcpSession) {
- session.cancelledByUs = true;
- session.grokAcpSession.close();
- }
-
- if (session.cursorAcpSession) {
- session.cancelledByUs = true;
- session.cursorAcpSession.close();
- }
-
- if (session.droidAcpSession) {
- session.cancelledByUs = true;
- session.droidAcpSession.close();
- }
+ closeActiveAcpSessions(session);
if (session.appServerSession) {
session.cancelledByUs = true;
@@ -3859,11 +3203,6 @@ export default class HeterogeneousAgentCtr {
session.appServerSession.close();
}
- if (session.traeAcpSession) {
- session.cancelledByUs = true;
- session.traeAcpSession.close();
- }
-
if (session.piRpcSession) {
session.cancelledByUs = true;
// Healthy settled processes remain pooled; failed cancellation closes them.
@@ -3956,30 +3295,11 @@ export default class HeterogeneousAgentCtr {
session.cancelledByUs = true;
piClosing.push(session.piRpcSession.close());
}
- if (session.devinAcpSession) {
- session.cancelledByUs = true;
- session.devinAcpSession.close();
- }
- if (session.grokAcpSession) {
- session.cancelledByUs = true;
- session.grokAcpSession.close();
- }
- if (session.cursorAcpSession) {
- session.cancelledByUs = true;
- session.cursorAcpSession.close();
- }
- if (session.droidAcpSession) {
- session.cancelledByUs = true;
- session.droidAcpSession.close();
- }
+ closeActiveAcpSessions(session);
if (session.appServerSession) {
session.cancelledByUs = true;
session.appServerSession.close();
}
- if (session.traeAcpSession) {
- session.cancelledByUs = true;
- session.traeAcpSession.close();
- }
if (session.sdkSession) {
session.cancelledByUs = true;
session.sdkSession.close();
diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts
index 07c8f377827..9805346ac40 100644
--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts
+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts
@@ -1,24 +1,53 @@
import type { ChildProcess } from 'node:child_process';
+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';
+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
+import type { AskUserBridge, AskUserBridgeOptions } from '@lobechat/heterogeneous-agents/askUser';
+import { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocol';
import type { PiRpcSession } from '@lobechat/heterogeneous-agents/rpc';
import type {
ClaudeAgentSdkSession,
CodexThreadSession,
+ DshAcpSessionHandle,
+} from '@lobechat/heterogeneous-agents/spawn';
+import {
+ AcpRpcResponseError,
+ buildCopilotAcpArgs,
+ buildCopilotAcpPrompt,
+ buildCursorAcpArgs,
+ buildCursorAcpPrompt,
+ buildDevinAcpArgs,
+ buildDevinAcpPrompt,
+ buildDroidAcpArgs,
+ buildDroidAcpPrompt,
+ buildGrokAcpArgs,
+ buildGrokAcpPrompt,
+ buildTraeAcpArgs,
+ buildTraeAcpPrompt,
+ CopilotAcpSession,
CursorAcpSession,
DevinAcpSession,
DroidAcpSession,
- DshAcpSessionHandle,
GrokAcpSession,
+ isCopilotAcpSessionNotFoundError,
+ isCursorAcpSessionNotFoundError,
+ isDevinAcpSessionNotFoundError,
+ isDroidAcpSessionNotFoundError,
TraeAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
import type {
HeterogeneousServerDefaultApiConfig,
HeteroSessionImportMessage,
} from '@lobechat/types';
+import { app as electronApp } from 'electron';
+import { isPlainObject } from 'es-toolkit';
import type { HostedProviderBinding } from '@/modules/heterogeneousAgent/providerBindingHost';
import type { HeterogeneousAgentImageAttachment } from '@/modules/heterogeneousAgent/types';
+import { createLogger } from '@/utils/logger';
+
+const logger = createLogger('controllers:HeterogeneousAgentCtr');
/** Prompt and ownership context shared by desktop transports. */
export interface SendPromptParams {
@@ -104,6 +133,7 @@ export interface AgentSession {
cliVersion?: string;
codexAppServerFallback?: boolean;
command: string;
+ copilotAcpSession?: CopilotAcpSession;
cursorAcpSession?: CursorAcpSession;
cwd?: string;
devinAcpSession?: DevinAcpSession;
@@ -174,3 +204,616 @@ export const claudeProfileDirOf = (
session: Pick<AgentSession, 'env' | 'hostedProviderBinding'>,
): string | undefined =>
session.env?.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir;
+
+export const getAcpResumeError = (
+ error: unknown,
+ session: AgentSession,
+): HeterogeneousAgentSessionError | undefined => {
+ if (!session.resumeSessionId) return;
+
+ if (session.agentType === 'copilot' && isCopilotAcpSessionNotFoundError(error)) {
+ return {
+ agentType: 'copilot',
+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
+ command: session.command,
+ details: {
+ code: error.rpcError.code,
+ data: error.rpcError.data,
+ },
+ message:
+ 'The saved GitHub Copilot session could not be found, so a new conversation will start.',
+ resumeSessionId: session.resumeSessionId,
+ stderr: error.message,
+ workingDirectory: session.cwd,
+ };
+ }
+
+ if (session.agentType === 'cursor' && isCursorAcpSessionNotFoundError(error)) {
+ 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,
+ };
+ }
+
+ if (session.agentType === 'devin' && isDevinAcpSessionNotFoundError(error)) {
+ return {
+ agentType: 'devin',
+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
+ command: session.command,
+ details: {
+ code: error.rpcError.code,
+ data: error.rpcError.data,
+ },
+ message: 'The saved Devin session could not be found, so a new conversation will start.',
+ resumeSessionId: session.resumeSessionId,
+ stderr: error.message,
+ workingDirectory: session.cwd,
+ };
+ }
+
+ if (session.agentType === 'droid' && isDroidAcpSessionNotFoundError(error)) {
+ return {
+ agentType: 'droid',
+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
+ command: session.command,
+ details: {
+ code: error.rpcError.code,
+ data: error.rpcError.data,
+ },
+ message:
+ 'The saved Factory Droid session could not be found, so a new conversation will start.',
+ resumeSessionId: session.resumeSessionId,
+ stderr: error.message,
+ workingDirectory: session.cwd,
+ };
+ }
+
+ if (
+ session.agentType === 'grok-build' &&
+ error instanceof AcpRpcResponseError &&
+ error.method === 'session/load' &&
+ isPlainObject(error.rpcError.data) &&
+ error.rpcError.data.code === 'FS_NOT_FOUND'
+ ) {
+ return {
+ agentType: 'grok-build',
+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
+ command: session.command,
+ details: {
+ code: error.rpcError.code,
+ data: error.rpcError.data,
+ },
+ message: 'The saved Grok Build session could not be found, so it can no longer be resumed.',
+ resumeSessionId: session.resumeSessionId,
+ stderr: error.message,
+ workingDirectory: session.cwd,
+ };
+ }
+};
+
+export const interruptActiveAcpSession = async (session: AgentSession): Promise<boolean> => {
+ if (session.copilotAcpSession) {
+ session.copilotAcpSession.interrupt();
+ return true;
+ }
+ if (session.devinAcpSession) {
+ session.devinAcpSession.interrupt();
+ return true;
+ }
+ if (session.grokAcpSession) {
+ session.grokAcpSession.interrupt();
+ return true;
+ }
+ if (session.cursorAcpSession) {
+ session.cursorAcpSession.interrupt();
+ return true;
+ }
+ if (session.droidAcpSession) {
+ session.droidAcpSession.interrupt();
+ return true;
+ }
+ if (session.traeAcpSession) {
+ await session.traeAcpSession.interrupt();
+ return true;
+ }
+ return false;
+};
+
+export const closeActiveAcpSessions = (session: AgentSession): void => {
+ for (const active of [
+ session.copilotAcpSession,
+ session.devinAcpSession,
+ session.grokAcpSession,
+ session.cursorAcpSession,
+ session.droidAcpSession,
+ session.traeAcpSession,
+ ]) {
+ if (active) {
+ session.cancelledByUs = true;
+ active.close();
+ }
+ }
+};
+
+export interface AcpSessionHost {
+ appendCliTraceFile: (
+ trace: CliTraceSession | undefined,
+ name: string,
+ data: string,
+ ) => Promise<void> | undefined;
+ broadcast: <T>(channel: string, data: T) => void;
+ buildSessionSpawnEnv: (session: AgentSession) => NodeJS.ProcessEnv;
+ completeCancelledSessionBeforeLaunch: (session: AgentSession) => Promise<void>;
+ createCliTraceSession: (args: {
+ cliArgs: string[];
+ cwd: string;
+ imageList: NonNullable<SendPromptParams['imageList']>;
+ session: AgentSession;
+ stdinPayload: string;
+ }) => Promise<CliTraceSession | undefined>;
+ fileCacheDir: string;
+ flushCliTrace: (trace: CliTraceSession | undefined) => Promise<void>;
+ getErrorMessage: (error: unknown) => string | undefined;
+ getSessionErrorPayload: (
+ error: unknown,
+ session: AgentSession,
+ ) => HeterogeneousAgentSessionError | string;
+ needsSessionIntroduction: (session: AgentSession) => boolean;
+ resolveSessionCommand: (session: AgentSession) => string;
+ resolveSessionWorkingDirectory: (session: AgentSession) => string;
+ setupAcpInterventionForOp: (
+ operationId: string,
+ sessionId: string,
+ provider: NonNullable<AskUserBridgeOptions['provider']>,
+ ) => {
+ bridge: AskUserBridge;
+ cleanup: () => Promise<void>;
+ };
+ writeCliTraceFile: (
+ trace: CliTraceSession | undefined,
+ name: string,
+ data: string,
+ ) => Promise<void> | undefined;
+ writeCliTraceJson: (
+ trace: CliTraceSession | undefined,
+ name: string,
+ payload: unknown,
+ ) => Promise<void> | undefined;
+}
+
+interface InteractiveAcpSession {
+ run: () => Promise<void>;
+}
+
+const runInteractiveAcpSession = async (
+ host: AcpSessionHost,
+ {
+ acpSession,
+ activeSessionKey,
+ cleanup,
+ isResumeError,
+ session,
+ stderrChunks,
+ traceSession,
+ transport,
+ }: {
+ acpSession: InteractiveAcpSession;
+ activeSessionKey:
+ | 'copilotAcpSession'
+ | 'cursorAcpSession'
+ | 'devinAcpSession'
+ | 'droidAcpSession'
+ | 'traeAcpSession';
+ cleanup?: () => Promise<void>;
+ isResumeError?: (error: unknown) => boolean;
+ session: AgentSession;
+ stderrChunks: string[];
+ traceSession: CliTraceSession | undefined;
+ transport: 'copilot-acp' | 'cursor-acp' | 'devin-acp' | 'droid-acp' | 'trae-acp';
+ },
+): Promise<void> => {
+ try {
+ await acpSession.run();
+ void host.writeCliTraceJson(traceSession, 'exit.json', {
+ finishedAt: new Date().toISOString(),
+ transport,
+ });
+ await host.flushCliTrace(traceSession);
+ host.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ } catch (error) {
+ void host.writeCliTraceJson(traceSession, 'process-error.json', {
+ message: host.getErrorMessage(error),
+ transport,
+ });
+ await host.flushCliTrace(traceSession);
+ if (session.cancelledByUs) {
+ host.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return;
+ }
+ const stderr = stderrChunks.join('').trim();
+ const errorForClassification = isResumeError?.(error)
+ ? error
+ : stderr
+ ? new Error([host.getErrorMessage(error), stderr].filter(Boolean).join('\n'), {
+ cause: error,
+ })
+ : error;
+ const sessionError = host.getSessionErrorPayload(errorForClassification, session);
+ host.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {
+ cause: error,
+ });
+ } finally {
+ await cleanup?.();
+ if (activeSessionKey === 'copilotAcpSession' && session.copilotAcpSession === acpSession) {
+ session.copilotAcpSession = undefined;
+ } else if (activeSessionKey === 'cursorAcpSession' && session.cursorAcpSession === acpSession) {
+ session.cursorAcpSession = undefined;
+ } else if (activeSessionKey === 'devinAcpSession' && session.devinAcpSession === acpSession) {
+ session.devinAcpSession = undefined;
+ } else if (activeSessionKey === 'droidAcpSession' && session.droidAcpSession === acpSession) {
+ session.droidAcpSession = undefined;
+ } else if (activeSessionKey === 'traeAcpSession' && session.traeAcpSession === acpSession) {
+ session.traeAcpSession = undefined;
+ }
+ }
+};
+
+export const sendPromptWithAcpSession = async (
+ host: AcpSessionHost,
+ params: SendPromptParams,
+ session: AgentSession,
+): Promise<void> => {
+ const spawnEnv = host.buildSessionSpawnEnv(session);
+ const commandPath = session.resolvedCommandPath ?? host.resolveSessionCommand(session);
+ const promptInput = buildHeterogeneousPrompt({
+ imageList: params.imageList,
+ isNewSession: host.needsSessionIntroduction(session),
+ prompt: params.prompt,
+ systemContext: params.systemContext,
+ });
+
+ if (session.agentType === 'grok-build') {
+ const cwd = session.cwd || electronApp.getPath('desktop');
+ let prompt;
+ try {
+ prompt = await buildGrokAcpPrompt(promptInput, { cacheDir: host.fileCacheDir });
+ } catch (error) {
+ logger.error('Failed to prepare Grok Build ACP input:', error);
+ throw new Error(
+ `Failed to attach image(s) to Grok Build: ${host.getErrorMessage(error) || 'Unknown error'}`,
+ { cause: error },
+ );
+ }
+
+ const traceInput = `${JSON.stringify(prompt)}\n`;
+ const traceSession = await host.createCliTraceSession({
+ cliArgs: buildGrokAcpArgs(session.args),
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: traceInput,
+ });
+ void host.writeCliTraceFile(traceSession, 'stdin.txt', traceInput);
+
+ if (session.cancelledByUs) {
+ await host.completeCancelledSessionBeforeLaunch(session);
+ return;
+ }
+
+ const acpSession = new GrokAcpSession({
+ args: session.args,
+ clientVersion: electronApp.getVersion(),
+ commandPath,
+ cwd,
+ env: spawnEnv,
+ onEvents: async (events) => {
+ for (const event of events) {
+ host.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });
+ }
+ },
+ onRawMessage: (line) => host.appendCliTraceFile(traceSession, 'stdout.jsonl', line),
+ onRuntimeStatus: (status) => host.broadcast('heteroAgentRuntimeStatus', status),
+ onSessionId: (agentSessionId) => {
+ if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;
+ },
+ onStderr: (data) => host.appendCliTraceFile(traceSession, 'stderr.log', data),
+ operationId: params.operationId,
+ prompt,
+ resumeSessionId: session.agentSessionId,
+ sessionId: session.sessionId,
+ });
+ session.grokAcpSession = acpSession;
+
+ logger.info('Starting Grok Build ACP session:', {
+ commandPath,
+ cwd,
+ sessionId: session.sessionId,
+ });
+
+ try {
+ await acpSession.run();
+ void host.writeCliTraceJson(traceSession, 'exit.json', {
+ finishedAt: new Date().toISOString(),
+ transport: 'acp-stdio',
+ });
+ await host.flushCliTrace(traceSession);
+ host.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ } catch (error) {
+ logger.error('Grok Build ACP session error:', error);
+ void host.writeCliTraceJson(traceSession, 'process-error.json', {
+ message: error instanceof Error ? error.message : String(error),
+ name: error instanceof Error ? error.name : 'Error',
+ transport: 'acp-stdio',
+ });
+ await host.flushCliTrace(traceSession);
+
+ if (session.cancelledByUs) {
+ host.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return;
+ }
+
+ const sessionError = host.getSessionErrorPayload(error, session);
+ host.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {
+ cause: error,
+ });
+ } finally {
+ await session.hostedProviderBinding?.cleanup();
+ if (session.grokAcpSession === acpSession) session.grokAcpSession = undefined;
+ }
+ return;
+ }
+
+ const cwd = host.resolveSessionWorkingDirectory(session);
+ const stderrChunks: string[] = [];
+ const createCommonOptions = (traceSession: CliTraceSession | undefined) => ({
+ args: session.args,
+ clientVersion: electronApp.getVersion(),
+ commandPath,
+ cwd,
+ env: spawnEnv,
+ onEvents: async (events: unknown[]) => {
+ for (const event of events) {
+ host.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });
+ }
+ },
+ onRawMessage: (line: string) => host.appendCliTraceFile(traceSession, 'stdout.jsonl', line),
+ onRuntimeStatus: (status: unknown) => host.broadcast('heteroAgentRuntimeStatus', status),
+ onSessionId: (agentSessionId: string) => {
+ session.agentSessionId = agentSessionId;
+ },
+ onStderr: (data: string) => {
+ stderrChunks.push(data);
+ return host.appendCliTraceFile(traceSession, 'stderr.log', data);
+ },
+ operationId: params.operationId,
+ resumeSessionId: session.agentSessionId,
+ sessionId: session.sessionId,
+ });
+
+ if (session.agentType === 'cursor') {
+ const prompt = buildCursorAcpPrompt(promptInput);
+ const tracePayload = `${JSON.stringify(prompt)}\n`;
+ const traceSession = await host.createCliTraceSession({
+ cliArgs: buildCursorAcpArgs(session.args),
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: tracePayload,
+ });
+ void host.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
+ if (session.cancelledByUs) {
+ await host.completeCancelledSessionBeforeLaunch(session);
+ return;
+ }
+ const intervention = host.setupAcpInterventionForOp(
+ params.operationId,
+ session.sessionId,
+ 'cursor',
+ );
+ const cursorAcpSession = new CursorAcpSession({
+ ...createCommonOptions(traceSession),
+ askUserBridge: intervention.bridge,
+ prompt,
+ });
+ session.cursorAcpSession = cursorAcpSession;
+ await runInteractiveAcpSession(host, {
+ acpSession: cursorAcpSession,
+ activeSessionKey: 'cursorAcpSession',
+ cleanup: intervention.cleanup,
+ isResumeError: isCursorAcpSessionNotFoundError,
+ session,
+ stderrChunks,
+ traceSession,
+ transport: 'cursor-acp',
+ });
+ return;
+ }
+
+ if (session.agentType === 'droid') {
+ const prompt = await buildDroidAcpPrompt(promptInput, { cacheDir: host.fileCacheDir });
+ const tracePayload = `${JSON.stringify(prompt)}\n`;
+ const traceSession = await host.createCliTraceSession({
+ cliArgs: buildDroidAcpArgs(session.args),
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: tracePayload,
+ });
+ void host.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
+ if (session.cancelledByUs) {
+ await host.completeCancelledSessionBeforeLaunch(session);
+ return;
+ }
+ const intervention = host.setupAcpInterventionForOp(
+ params.operationId,
+ session.sessionId,
+ 'droid',
+ );
+ const droidAcpSession = new DroidAcpSession({
+ ...createCommonOptions(traceSession),
+ askUserBridge: intervention.bridge,
+ initialModel: session.model,
+ onModel: (model) => {
+ session.model = model;
+ session.modelSource = 'droid-acp';
+ },
+ prompt,
+ });
+ session.droidAcpSession = droidAcpSession;
+ await runInteractiveAcpSession(host, {
+ acpSession: droidAcpSession,
+ activeSessionKey: 'droidAcpSession',
+ cleanup: intervention.cleanup,
+ isResumeError: isDroidAcpSessionNotFoundError,
+ session,
+ stderrChunks,
+ traceSession,
+ transport: 'droid-acp',
+ });
+ return;
+ }
+
+ if (session.agentType === 'devin') {
+ const prompt = await buildDevinAcpPrompt(promptInput, { cacheDir: host.fileCacheDir });
+ const tracePayload = `${JSON.stringify(prompt)}\n`;
+ const traceSession = await host.createCliTraceSession({
+ cliArgs: buildDevinAcpArgs(session.args),
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: tracePayload,
+ });
+ void host.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
+ if (session.cancelledByUs) {
+ await host.completeCancelledSessionBeforeLaunch(session);
+ return;
+ }
+ const intervention = host.setupAcpInterventionForOp(
+ params.operationId,
+ session.sessionId,
+ 'devin',
+ );
+ const devinAcpSession = new DevinAcpSession({
+ ...createCommonOptions(traceSession),
+ askUserBridge: intervention.bridge,
+ initialModel: session.model,
+ onModel: (model) => {
+ session.model = model;
+ session.modelSource = 'devin-acp';
+ },
+ prompt,
+ });
+ session.devinAcpSession = devinAcpSession;
+ await runInteractiveAcpSession(host, {
+ acpSession: devinAcpSession,
+ activeSessionKey: 'devinAcpSession',
+ cleanup: intervention.cleanup,
+ isResumeError: isDevinAcpSessionNotFoundError,
+ session,
+ stderrChunks,
+ traceSession,
+ transport: 'devin-acp',
+ });
+ return;
+ }
+
+ if (session.agentType === 'copilot') {
+ const prompt = await buildCopilotAcpPrompt(promptInput, { cacheDir: host.fileCacheDir });
+ const tracePayload = `${JSON.stringify(prompt)}\n`;
+ const traceSession = await host.createCliTraceSession({
+ cliArgs: buildCopilotAcpArgs(session.args),
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: tracePayload,
+ });
+ void host.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
+ if (session.cancelledByUs) {
+ await host.completeCancelledSessionBeforeLaunch(session);
+ return;
+ }
+ const intervention = host.setupAcpInterventionForOp(
+ params.operationId,
+ session.sessionId,
+ 'copilot',
+ );
+ const copilotAcpSession = new CopilotAcpSession({
+ ...createCommonOptions(traceSession),
+ askUserBridge: intervention.bridge,
+ initialModel: session.model,
+ onModel: (model) => {
+ session.model = model;
+ session.modelSource = 'copilot-acp';
+ },
+ prompt,
+ });
+ session.copilotAcpSession = copilotAcpSession;
+ await runInteractiveAcpSession(host, {
+ acpSession: copilotAcpSession,
+ activeSessionKey: 'copilotAcpSession',
+ cleanup: intervention.cleanup,
+ isResumeError: isCopilotAcpSessionNotFoundError,
+ session,
+ stderrChunks,
+ traceSession,
+ transport: 'copilot-acp',
+ });
+ return;
+ }
+
+ if (session.agentType === 'trae') {
+ const prompt = await buildTraeAcpPrompt(promptInput, { cacheDir: host.fileCacheDir });
+ const tracePayload = `${JSON.stringify(prompt)}\n`;
+ const traceSession = await host.createCliTraceSession({
+ cliArgs: buildTraeAcpArgs(session.args),
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: tracePayload,
+ });
+ void host.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);
+ if (session.cancelledByUs) {
+ await host.completeCancelledSessionBeforeLaunch(session);
+ return;
+ }
+ const traeAcpSession = new TraeAcpSession({
+ ...createCommonOptions(traceSession),
+ initialModel: session.model,
+ onModel: (model) => {
+ session.model = model;
+ session.modelSource = 'trae-acp';
+ },
+ prompt,
+ });
+ session.traeAcpSession = traeAcpSession;
+ await runInteractiveAcpSession(host, {
+ acpSession: traeAcpSession,
+ activeSessionKey: 'traeAcpSession',
+ cleanup: async () => {
+ await session.hostedProviderBinding?.cleanup();
+ },
+ session,
+ stderrChunks,
+ traceSession,
+ transport: 'trae-acp',
+ });
+ }
+};
diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
index 4a6d871b41a..5e370e88ed1 100644
--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts
@@ -88,6 +88,14 @@ export const codexBinary: BinarySpec = {
priority: 2,
};
+/** GitHub Copilot CLI @see https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli */
+export const copilotBinary: BinarySpec = {
+ description: 'GitHub Copilot - GitHub official agentic coding CLI',
+ detect: () => detectHeterogeneousCliCommand('copilot', 'copilot'),
+ name: 'copilot',
+ priority: 3,
+};
+
/** Cursor Agent CLI @see https://cursor.com/docs/cli/installation */
export const cursorBinary: BinarySpec = {
description: 'Cursor - Cursor agentic coding CLI',
@@ -221,6 +229,7 @@ export const heterogeneousCliAgentBinaries = {
'claude-code': claudeCodeBinary,
'codebuddy': codeBuddyBinary,
'codex': codexBinary,
+ 'copilot': copilotBinary,
'cursor': cursorBinary,
'droid': droidBinary,
'devin': devinBinary,
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/copilot.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/copilot.ts
new file mode 100644
index 00000000000..bf9ee82419b
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/copilot.ts
@@ -0,0 +1,7 @@
+import type { HeterogeneousAgentDriver } from '../types';
+
+export const copilotDriver: HeterogeneousAgentDriver = {
+ async buildSpawnPlan() {
+ throw new Error('GitHub Copilot prompts must run through the native ACP session');
+ },
+};
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
index d94fbbdfb1c..4d80a79d3ca 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts
@@ -4,6 +4,7 @@ import { ampDriver } from './drivers/amp';
import { claudeCodeDriver } from './drivers/claudeCode';
import { codeBuddyDriver } from './drivers/codeBuddy';
import { codexDriver } from './drivers/codex';
+import { copilotDriver } from './drivers/copilot';
import { cursorDriver } from './drivers/cursor';
import { devinDriver } from './drivers/devin';
import { droidDriver } from './drivers/droid';
@@ -20,6 +21,7 @@ const heterogeneousAgentDrivers = {
'claude-code': claudeCodeDriver,
'codebuddy': codeBuddyDriver,
'codex': codexDriver,
+ 'copilot': copilotDriver,
'cursor': cursorDriver,
'droid': droidDriver,
'devin': devinDriver,
diff --git a/apps/server/src/routers/lambda/device/agents.ts b/apps/server/src/routers/lambda/device/agents.ts
index 3eb697b07a6..64922ac7a5e 100644
--- a/apps/server/src/routers/lambda/device/agents.ts
+++ b/apps/server/src/routers/lambda/device/agents.ts
@@ -138,6 +138,7 @@ export const agentsRouter = router({
type: z.enum([
'codebuddy',
'codex',
+ 'copilot',
'cursor',
'droid',
'devin',
diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.ts
index 7ed739eefd3..fe1fde70f85 100644
--- a/apps/server/src/services/deviceGateway/agents.ts
+++ b/apps/server/src/services/deviceGateway/agents.ts
@@ -98,6 +98,7 @@ export async function listHeterogeneousAgentModels(
type:
| 'codebuddy'
| 'codex'
+ | 'copilot'
| 'cursor'
| 'devin'
| 'droid'
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
index 24ae3f07927..9e308a30dda 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts
@@ -142,6 +142,7 @@ export const INTERVENTION_KINDS = new Set<AgentInterventionInteractionKind>([
export const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>([
'claude-code',
+ 'copilot',
'cursor',
'devin',
'droid',
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 9f5c5dc7e89..c9be2433ba9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -279,6 +279,7 @@
"connectAgent.providerDesc.claude-code": "Anthropic coding agent CLI",
"connectAgent.providerDesc.codebuddy": "Tencent coding agent CLI",
"connectAgent.providerDesc.codex": "OpenAI coding agent CLI",
+ "connectAgent.providerDesc.copilot": "GitHub Copilot coding agent CLI",
"connectAgent.providerDesc.cursor": "Cursor coding agent CLI",
"connectAgent.providerDesc.deepseek-harness": "DeepSeek Harness agent (dsh CLI) with tools and subagents",
"connectAgent.providerDesc.devin": "Cognition coding agent CLI",
@@ -291,6 +292,15 @@
"connectAgent.providerDesc.pi": "Minimal coding agent CLI",
"connectAgent.providerDesc.qoder": "Qoder coding agent CLI",
"connectAgent.providerDesc.trae": "TRAE Enterprise coding agent CLI",
+ "copilotInstallGuide.actions.openDocs": "Open Install Guide",
+ "copilotInstallGuide.actions.openSystemTools": "Open System Tools",
+ "copilotInstallGuide.afterInstall": "After installing, run `copilot login`, then retry your message or click Re-detect in System Tools.",
+ "copilotInstallGuide.desc": "GitHub Copilot needs the GitHub Copilot CLI to run locally. Install it and make sure the `copilot` command is available in your PATH.",
+ "copilotInstallGuide.installWithBrew": "Homebrew (macOS / Linux)",
+ "copilotInstallGuide.installWithNpm": "Recommended install",
+ "copilotInstallGuide.menuNotification.title": "GitHub Copilot CLI not found",
+ "copilotInstallGuide.reason": "LobeHub could not start GitHub Copilot: {{message}}",
+ "copilotInstallGuide.title": "Install GitHub Copilot CLI",
"createGoal.addCriterion": "Add criterion",
"createGoal.agentsHint": "The main agent plans and supervises the goal; tasks go to the executor, or to the main agent when none is chosen.",
"createGoal.agentsTitle": "Agents",
@@ -1859,6 +1869,7 @@
"newClaudeCodeAgent": "Add Claude Code",
"newCodeBuddyAgent": "Add CodeBuddy",
"newCodexAgent": "Add Codex",
+ "newCopilotAgent": "Add GitHub Copilot",
"newCursorAgent": "Add Cursor",
"newDevinAgent": "Add Devin",
"newDroidAgent": "Add Factory Droid",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 773553c7e2c..18874643a3e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -279,6 +279,7 @@
"connectAgent.providerDesc.claude-code": "Anthropic 编码助理 CLI",
"connectAgent.providerDesc.codebuddy": "腾讯编码助理 CLI",
"connectAgent.providerDesc.codex": "OpenAI 编码助理 CLI",
+ "connectAgent.providerDesc.copilot": "GitHub Copilot 编码助理 CLI",
"connectAgent.providerDesc.cursor": "Cursor 编码助理 CLI",
"connectAgent.providerDesc.deepseek-harness": "DeepSeek Harness Agent(dsh CLI),支持工具调用和子 Agent",
"connectAgent.providerDesc.devin": "Cognition 编码助理 CLI",
@@ -291,6 +292,15 @@
"connectAgent.providerDesc.pi": "轻量编码助理 CLI",
"connectAgent.providerDesc.qoder": "Qoder 编码助理 CLI",
"connectAgent.providerDesc.trae": "TRAE 企业版编码助理 CLI",
+ "copilotInstallGuide.actions.openDocs": "打开安装指南",
+ "copilotInstallGuide.actions.openSystemTools": "打开系统工具",
+ "copilotInstallGuide.afterInstall": "安装完成后,请运行 `copilot login` 登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",
+ "copilotInstallGuide.desc": "GitHub Copilot 需要在本地运行 GitHub Copilot CLI。请安装它,并确保 `copilot` 命令在您的 PATH 中可用。",
+ "copilotInstallGuide.installWithBrew": "Homebrew (macOS / Linux)",
+ "copilotInstallGuide.installWithNpm": "推荐安装方式",
+ "copilotInstallGuide.menuNotification.title": "未找到 GitHub Copilot CLI",
+ "copilotInstallGuide.reason": "LobeHub 无法启动 GitHub Copilot:{{message}}",
+ "copilotInstallGuide.title": "安装 GitHub Copilot CLI",
"createGoal.addCriterion": "添加验收标准",
"createGoal.agentsHint": "主 Agent 负责规划和监督目标;任务交给执行 Agent,不选则由主 Agent 自己完成。",
"createGoal.agentsTitle": "负责的 Agent",
@@ -1859,6 +1869,7 @@
"newClaudeCodeAgent": "添加 Claude Code",
"newCodeBuddyAgent": "添加 CodeBuddy",
"newCodexAgent": "添加 Codex",
+ "newCopilotAgent": "添加 GitHub Copilot",
"newCursorAgent": "添加 Cursor",
"newDevinAgent": "添加 Devin",
"newDroidAgent": "添加 Factory Droid",
diff --git a/packages/agent-gateway-client/src/intervention.ts b/packages/agent-gateway-client/src/intervention.ts
index bca9cd0c8ab..2a9c87bebb4 100644
--- a/packages/agent-gateway-client/src/intervention.ts
+++ b/packages/agent-gateway-client/src/intervention.ts
@@ -13,6 +13,7 @@ const INTERACTION_KINDS = new Set<AgentInterventionInteractionKind>([
]);
const PROVIDERS = new Set<AgentInterventionProvider>([
'claude-code',
+ 'copilot',
'cursor',
'devin',
'droid',
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 95ef93950d1..62192983926 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -278,7 +278,7 @@ export type AgentInterventionInteractionKind = 'permission' | 'plan' | 'question
/** Producer that owns the blocked interaction. */
export type AgentInterventionProvider =
- 'claude-code' | 'cursor' | 'devin' | 'droid' | 'opencode' | 'qoder';
+ 'claude-code' | 'copilot' | 'cursor' | 'devin' | 'droid' | 'opencode' | 'qoder';
/** Whitelisted option surface that may be persisted for cold-start review. */
export interface AgentInterventionRenderOption {
diff --git a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
index 06a1dd0f541..155fd604a1d 100644
--- a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
+++ b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts
@@ -69,6 +69,13 @@ const HETERO_PROFILES: Record<HeteroType, HeteroTypeProfile> = {
displayName: 'Codex',
kind: 'cli',
},
+ 'copilot': {
+ capabilities: CODING_CAPABILITIES,
+ description:
+ "GitHub Copilot — GitHub's autonomous CLI coding agent. It can inspect and edit a working directory, run shell commands and tests, search code, and complete multi-step software-engineering tasks through its built-in tools.",
+ displayName: 'GitHub Copilot',
+ kind: 'cli',
+ },
'cursor': {
capabilities: CODING_CAPABILITIES,
description:
diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.ts b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.ts
index adfa076f788..7ee86ac18d5 100644
--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.ts
+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.ts
@@ -36,7 +36,10 @@ export const buildReadFileState = ({
if (!filePath) return;
const canUseContentFallback =
- identifier === 'opencode' || identifier === 'pi' || identifier === 'devin';
+ identifier === 'copilot' ||
+ identifier === 'opencode' ||
+ identifier === 'pi' ||
+ identifier === 'devin';
// ACP agents (Devin) park the raw session update in pluginState, whose
// `content` is a content-block array — never the read text — so only a
// string value counts as reported content.
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
index 089e9ecbcbc..923d94b2a08 100644
--- a/packages/builtin-tools/src/register.ts
+++ b/packages/builtin-tools/src/register.ts
@@ -210,6 +210,7 @@ import { registerBuiltinRenders } from './renders';
import { registerBuiltinStreamings } from './streamings';
import { TwitterIdentifier, TwitterInspectors } from './twitter';
+const COPILOT_IDENTIFIER = 'copilot';
const DROID_IDENTIFIER = 'droid';
const DEVIN_IDENTIFIER = 'devin';
const QODER_IDENTIFIER = 'qoder';
@@ -274,6 +275,10 @@ export const registerBuiltinToolSurfaces = (): void => {
[AgentDocumentsManifest.identifier]: AgentDocumentsRenders as Record<string, BuiltinRender>,
[AgentManagementManifest.identifier]: AgentManagementRenders as Record<string, BuiltinRender>,
[ClaudeCodeIdentifier]: ClaudeCodeRenders as Record<string, BuiltinRender>,
+ [COPILOT_IDENTIFIER]: {
+ execute: RunCommandRender as BuiltinRender,
+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeRenders[ClaudeCodeApiName.AskUserQuestion],
+ },
[DROID_IDENTIFIER]: {
[ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeRenders[ClaudeCodeApiName.AskUserQuestion],
},
@@ -342,6 +347,12 @@ export const registerBuiltinToolSurfaces = (): void => {
BuiltinInspector
>,
[ClaudeCodeIdentifier]: ClaudeCodeInspectors as Record<string, BuiltinInspector>,
+ [COPILOT_IDENTIFIER]: {
+ execute: createRunCommandInspector(
+ 'builtins.lobe-local-system.apiName.runCommand',
+ ) as BuiltinInspector,
+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeInspectors[ClaudeCodeApiName.AskUserQuestion],
+ },
[DROID_IDENTIFIER]: {
[ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeInspectors[ClaudeCodeApiName.AskUserQuestion],
},
@@ -447,6 +458,10 @@ export const registerBuiltinToolSurfaces = (): void => {
BuiltinIntervention
>,
[ClaudeCodeIdentifier]: ClaudeCodeInterventions as Record<string, BuiltinIntervention>,
+ [COPILOT_IDENTIFIER]: {
+ [ClaudeCodeApiName.AskUserQuestion]:
+ ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],
+ },
[DROID_IDENTIFIER]: {
[ClaudeCodeApiName.AskUserQuestion]:
ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 0798696dad1..f88d3832b5f 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -436,6 +436,7 @@ export interface ListHeterogeneousAgentModelsParams {
type:
| 'codebuddy'
| 'codex'
+ | 'copilot'
| 'cursor'
| 'devin'
| 'droid'
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index 8710efbc58b..c0f9804a236 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -13,6 +13,8 @@ export {
CODEBUDDY_CLI_INSTALL_DOCS_URL,
CODEX_CLI_INSTALL_COMMANDS,
CODEX_CLI_INSTALL_DOCS_URL,
+ COPILOT_CLI_INSTALL_COMMANDS,
+ COPILOT_CLI_INSTALL_DOCS_URL,
CURSOR_CLI_INSTALL_COMMANDS,
CURSOR_CLI_INSTALL_DOCS_URL,
DROID_CLI_INSTALL_COMMANDS,
@@ -128,6 +130,7 @@ export interface HeterogeneousAgentRuntimeStatus {
| 'claude-sdk'
| 'cli-spawn'
| 'codex-app-server'
+ | 'copilot-acp'
| 'cursor-acp'
| 'droid-acp'
| 'dsh-jsonrpc'
diff --git a/packages/heterogeneous-agents/src/adapters/copilotAcp.test.ts b/packages/heterogeneous-agents/src/adapters/copilotAcp.test.ts
new file mode 100644
index 00000000000..b3f3a5f0f2e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/copilotAcp.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+
+import type { HeterogeneousAgentEvent } from '../types';
+import { CopilotAcpAdapter } from './copilotAcp';
+
+const dataFor = (events: HeterogeneousAgentEvent[], type: HeterogeneousAgentEvent['type']) =>
+ events.filter((event) => event.type === type).map((event) => event.data);
+
+describe('CopilotAcpAdapter', () => {
+ it('normalizes shell tool calls with kind "execute" and no name to apiName "execute"', () => {
+ const adapter = new CopilotAcpAdapter();
+
+ const startEvents = adapter.adapt({
+ kind: 'execute',
+ rawInput: { command: 'pwd', description: 'Print working directory' },
+ sessionUpdate: 'tool_call',
+ title: 'Print working directory',
+ toolCallId: 'bash-call-1',
+ });
+
+ expect(dataFor(startEvents, 'tool_start')).toEqual([
+ expect.objectContaining({
+ toolCallId: 'bash-call-1',
+ toolCalling: expect.objectContaining({
+ apiName: 'execute',
+ id: 'bash-call-1',
+ identifier: 'copilot',
+ }),
+ }),
+ ]);
+
+ const endEvents = adapter.adapt({
+ content: [{ content: { text: '/repo\n', type: 'text' }, type: 'content' }],
+ sessionUpdate: 'tool_call_update',
+ status: 'completed',
+ toolCallId: 'bash-call-1',
+ });
+
+ expect(dataFor(endEvents, 'tool_end')).toEqual([
+ {
+ isSuccess: true,
+ toolCallId: 'bash-call-1',
+ },
+ ]);
+ });
+
+ it('emits stream_start and step_complete with provider "copilot"', () => {
+ const adapter = new CopilotAcpAdapter();
+
+ const events = [
+ ...adapter.adapt({
+ model: 'claude-sonnet-4.6',
+ sessionId: 'copilot-session-1',
+ type: 'copilot_session',
+ }),
+ ...adapter.adapt({
+ content: { text: 'Hello from Copilot', type: 'text' },
+ sessionUpdate: 'agent_message_chunk',
+ }),
+ ...adapter.adapt({
+ stopReason: 'end_turn',
+ type: 'copilot_prompt_completed',
+ usage: { inputTokens: 100, outputTokens: 20, totalTokens: 120 },
+ }),
+ ];
+
+ expect(dataFor(events, 'stream_start')).toEqual([
+ expect.objectContaining({
+ model: 'claude-sonnet-4.6',
+ provider: 'copilot',
+ sessionId: 'copilot-session-1',
+ }),
+ ]);
+ expect(dataFor(events, 'step_complete')).toEqual([
+ {
+ model: 'claude-sonnet-4.6',
+ phase: 'turn_metadata',
+ provider: 'copilot',
+ usage: {
+ inputCacheMissTokens: 100,
+ outputTextTokens: 20,
+ totalInputTokens: 100,
+ totalOutputTokens: 20,
+ totalTokens: 120,
+ },
+ },
+ ]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/adapters/copilotAcp.ts b/packages/heterogeneous-agents/src/adapters/copilotAcp.ts
new file mode 100644
index 00000000000..d418227590f
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/copilotAcp.ts
@@ -0,0 +1,38 @@
+import type { HeterogeneousAgentEvent } from '../types';
+import { TraeAcpAdapter } from './traeAcp';
+
+/**
+ * GitHub Copilot CLI (`copilot --acp --stdio`) emits standard ACP `session/update`
+ * notifications (`agent_message_chunk`, `agent_thought_chunk`, `tool_call`,
+ * `tool_call_update`, `usage_update`, `plan`), plus synthetic lifecycle events
+ * (`copilot_session`, `copilot_prompt_completed`, `copilot_error`) injected by
+ * `CopilotAcpSession`.
+ *
+ * When Copilot CLI runs a shell command (`kind: 'execute'`), `title` holds the
+ * human-readable command description while `name` is omitted; normalizing
+ * `name: 'execute'` routes shell tool calls to the built-in command renderer
+ * and git side-effect tracker.
+ */
+export class CopilotAcpAdapter extends TraeAcpAdapter {
+ constructor() {
+ super({ eventPrefix: 'copilot', provider: 'copilot' });
+ }
+
+ override adapt(value: unknown): HeterogeneousAgentEvent[] {
+ if (
+ value &&
+ typeof value === 'object' &&
+ ((value as Record<string, unknown>).sessionUpdate === 'tool_call' ||
+ (value as Record<string, unknown>).sessionUpdate === 'tool_call_update') &&
+ (value as Record<string, unknown>).kind === 'execute' &&
+ typeof (value as Record<string, unknown>).name !== 'string'
+ ) {
+ return super.adapt({
+ ...(value as Record<string, unknown>),
+ name: 'execute',
+ });
+ }
+
+ return super.adapt(value);
+ }
+}
diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.ts
index a2e48236fc8..df305f41284 100644
--- a/packages/heterogeneous-agents/src/adapters/index.ts
+++ b/packages/heterogeneous-agents/src/adapters/index.ts
@@ -4,6 +4,7 @@ export { ClaudeCodeSdkAdapter } from './claudeCodeSdk';
export { CodeBuddyAdapter } from './codeBuddy';
export { CodexAdapter } from './codex';
export { CodexAppServerAdapter } from './codexAppServer';
+export { CopilotAcpAdapter } from './copilotAcp';
export { CursorAdapter } from './cursor';
export { CursorAcpAdapter } from './cursorAcp';
export { DevinAcpAdapter } from './devinAcp';
diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.ts
index e8d53b7882f..2c173cdd94b 100644
--- a/packages/heterogeneous-agents/src/client/index.ts
+++ b/packages/heterogeneous-agents/src/client/index.ts
@@ -8,6 +8,7 @@ import {
DeepSeek,
Devin,
getLobeIconCDN,
+ GithubCopilot,
Grok,
Kimi,
OpenCode,
@@ -43,6 +44,7 @@ const heterogeneousAgentIcons = {
'claude-code': ClaudeCode,
'codebuddy': CodeBuddy,
'codex': Codex,
+ 'copilot': GithubCopilot,
'cursor': Cursor,
'droid': DroidIcon,
'devin': Devin,
diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.ts
index a34e7ee4eb0..b80d4b0b6ba 100644
--- a/packages/heterogeneous-agents/src/config.test.ts
+++ b/packages/heterogeneous-agents/src/config.test.ts
@@ -18,6 +18,7 @@ describe('heterogeneous agent config', () => {
'claude-code',
'codebuddy',
'codex',
+ 'copilot',
'cursor',
'droid',
'devin',
@@ -45,6 +46,19 @@ describe('heterogeneous agent config', () => {
title: 'Codex',
type: 'codex',
});
+ expect(getHeterogeneousAgentConfig('copilot')).toMatchObject({
+ auth: { signInCommand: 'copilot login' },
+ defaultCommand: 'copilot',
+ install: {
+ commands: [
+ 'curl -fsSL https://gh.io/copilot-install | bash',
+ 'npm install -g @github/copilot',
+ ],
+ docsUrl: 'https://docs.github.com/en/copilot/how-tos/copilot-cli',
+ },
+ title: 'GitHub Copilot',
+ type: 'copilot',
+ });
expect(getHeterogeneousAgentConfig('codebuddy')).toMatchObject({
defaultCommand: 'codebuddy',
title: 'CodeBuddy',
@@ -182,6 +196,7 @@ describe('heterogeneous agent config', () => {
'claude-code': 'Claude Code',
'codebuddy': 'CodeBuddy',
'codex': 'Codex',
+ 'copilot': 'GitHub Copilot',
'cursor': 'Cursor',
'droid': 'Factory Droid',
'devin': 'Devin',
diff --git a/packages/heterogeneous-agents/src/config.ts b/packages/heterogeneous-agents/src/config.ts
index 8152d190467..390a797f773 100644
--- a/packages/heterogeneous-agents/src/config.ts
+++ b/packages/heterogeneous-agents/src/config.ts
@@ -68,6 +68,17 @@ export const getHeterogeneousAgentConfigOrThrow = (
return config;
};
+const SESSION_INITIAL_MODEL_TYPES = new Set<string>([
+ 'copilot',
+ 'deepseek-harness',
+ 'devin',
+ 'droid',
+ 'trae',
+]);
+
+export const usesHeterogeneousSessionInitialModel = (type: string): boolean =>
+ SESSION_INITIAL_MODEL_TYPES.has(type);
+
export const resolveHeterogeneousAgentCommand = (type: string, command?: string): string => {
const configuredCommand = command?.trim();
return configuredCommand || getHeterogeneousAgentConfigOrThrow(type).defaultCommand;
@@ -147,6 +158,7 @@ const ampDescriptor = getHeterogeneousAgentConfigOrThrow('amp');
const claudeCodeDescriptor = getHeterogeneousAgentConfigOrThrow('claude-code');
const codeBuddyDescriptor = getHeterogeneousAgentConfigOrThrow('codebuddy');
const codexDescriptor = getHeterogeneousAgentConfigOrThrow('codex');
+const copilotDescriptor = getHeterogeneousAgentConfigOrThrow('copilot');
const cursorDescriptor = getHeterogeneousAgentConfigOrThrow('cursor');
const droidDescriptor = getHeterogeneousAgentConfigOrThrow('droid');
const grokBuildDescriptor = getHeterogeneousAgentConfigOrThrow('grok-build');
@@ -162,6 +174,8 @@ export const CODEBUDDY_CLI_INSTALL_COMMANDS = codeBuddyDescriptor.install.comman
export const CODEBUDDY_CLI_INSTALL_DOCS_URL = codeBuddyDescriptor.install.docsUrl;
export const CODEX_CLI_INSTALL_COMMANDS = codexDescriptor.install.commands;
export const CODEX_CLI_INSTALL_DOCS_URL = codexDescriptor.install.docsUrl;
+export const COPILOT_CLI_INSTALL_COMMANDS = copilotDescriptor.install.commands;
+export const COPILOT_CLI_INSTALL_DOCS_URL = copilotDescriptor.install.docsUrl;
export const CURSOR_CLI_INSTALL_COMMANDS = cursorDescriptor.install.commands;
export const CURSOR_CLI_INSTALL_DOCS_URL = cursorDescriptor.install.docsUrl;
export const DROID_CLI_INSTALL_COMMANDS = droidDescriptor.install.commands;
diff --git a/packages/heterogeneous-agents/src/imageInput.test.ts b/packages/heterogeneous-agents/src/imageInput.test.ts
index 51a1c24c8b6..6fc27699298 100644
--- a/packages/heterogeneous-agents/src/imageInput.test.ts
+++ b/packages/heterogeneous-agents/src/imageInput.test.ts
@@ -3,9 +3,12 @@ import { describe, expect, it } from 'vitest';
import { heteroAgentSupportsImageInput } from './imageInput';
describe('heteroAgentSupportsImageInput', () => {
- it.each(['claude-code', 'codex', 'grok-build', 'opencode'])('accepts images for %s', (type) => {
- expect(heteroAgentSupportsImageInput(type)).toBe(true);
- });
+ it.each(['claude-code', 'codex', 'copilot', 'grok-build', 'opencode'])(
+ 'accepts images for %s',
+ (type) => {
+ expect(heteroAgentSupportsImageInput(type)).toBe(true);
+ },
+ );
it.each(['cursor', 'droid', 'devin', 'trae', 'deepseek-harness', 'openclaw', 'hermes'])(
'rejects images for text-only %s',
diff --git a/packages/heterogeneous-agents/src/imageInput.ts b/packages/heterogeneous-agents/src/imageInput.ts
index b4d2cad0c9f..9772f603670 100644
--- a/packages/heterogeneous-agents/src/imageInput.ts
+++ b/packages/heterogeneous-agents/src/imageInput.ts
@@ -13,6 +13,7 @@ const IMAGE_INPUT_AGENT_TYPES = new Set<string>([
'claude-code',
'codebuddy',
'codex',
+ 'copilot',
'grok-build',
'kimi-code',
'opencode',
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index 1a561e1162d..47d411035e0 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -2,6 +2,7 @@ export {
AmpAdapter,
ClaudeCodeAdapter,
CodeBuddyAdapter,
+ CopilotAcpAdapter,
GrokBuildAdapter,
QoderAdapter,
} from './adapters';
@@ -34,6 +35,8 @@ export {
CODEBUDDY_CLI_INSTALL_DOCS_URL,
CODEX_CLI_INSTALL_COMMANDS,
CODEX_CLI_INSTALL_DOCS_URL,
+ COPILOT_CLI_INSTALL_COMMANDS,
+ COPILOT_CLI_INSTALL_DOCS_URL,
CURSOR_CLI_INSTALL_COMMANDS,
CURSOR_CLI_INSTALL_DOCS_URL,
DROID_CLI_INSTALL_COMMANDS,
@@ -58,6 +61,7 @@ export {
QODER_CLI_INSTALL_DOCS_URL,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
resolveHeterogeneousAgentCommand,
+ usesHeterogeneousSessionInitialModel,
} from './config';
export type {
HeteroErrorAttribution,
diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
index 77801748726..34107b768ac 100644
--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
@@ -13,6 +13,7 @@ import { isRecord } from '@lobechat/utils/object';
import { getHeterogeneousTypeLabel } from '../labels';
import { AcpRpcResponseError } from '../spawn/acpStdioClient';
import { resolveCliSpawnPlan } from '../spawn/cliSpawn';
+import { listCopilotAcpModels } from '../spawn/copilotAcpSession';
import { listDroidAcpModels } from '../spawn/droidAcpSession';
import { resolveHeteroSpawnCommand } from '../spawn/resolveCliCommand';
import { listTraeAcpModels } from '../spawn/traeAcpSession';
@@ -358,6 +359,17 @@ export const listHeterogeneousAgentModels = async (
// Keep valid project directories so project-specific provider configuration still applies.
const cwd = resolveHeteroSpawnCwd(params.cwd ?? process.cwd());
+ if (params.type === 'copilot') {
+ const models = await listCopilotAcpModels({
+ args: params.args,
+ commandPath: resolved.command,
+ cwd: cwd ?? process.cwd(),
+ env: env as NodeJS.ProcessEnv,
+ timeoutMs: MODEL_CATALOG_TIMEOUT_MS,
+ });
+ return { models, status: 'success', updatedAt };
+ }
+
if (params.type === 'droid') {
const models = await listDroidAcpModels({
args: params.args,
diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.ts
index bf59092a751..882b3128e91 100644
--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.ts
+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.workingDirectory.test.ts
@@ -29,7 +29,7 @@ describe('model discovery working directory', () => {
fixture,
String.raw`const engine = process.argv[2];
const model = process.cwd() === ${JSON.stringify(project)} ? 'project-model' : 'host-model';
-if (['codex', 'droid', 'trae'].includes(engine)) {
+if (['codex', 'copilot', 'droid', 'trae'].includes(engine)) {
require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {
const message = JSON.parse(line);
if (message.id === undefined) return;
diff --git a/packages/heterogeneous-agents/src/registry.test.ts b/packages/heterogeneous-agents/src/registry.test.ts
index 6a9668c8d74..b3e3b9e9472 100644
--- a/packages/heterogeneous-agents/src/registry.test.ts
+++ b/packages/heterogeneous-agents/src/registry.test.ts
@@ -5,10 +5,11 @@ import {
ClaudeCodeAdapter,
CodeBuddyAdapter,
CodexAdapter,
+ CopilotAcpAdapter,
CursorAcpAdapter,
CursorAdapter,
- DroidAcpAdapter,
DevinAcpAdapter,
+ DroidAcpAdapter,
GrokBuildAdapter,
KimiCodeAdapter,
OpenCodeAdapter,
@@ -40,6 +41,10 @@ describe('registry', () => {
expect(adapter).toBeInstanceOf(CodexAdapter);
});
+ it('creates a CopilotAcpAdapter for "copilot"', () => {
+ expect(createAdapter('copilot')).toBeInstanceOf(CopilotAcpAdapter);
+ });
+
it('creates a KimiCodeAdapter for "kimi-code"', () => {
expect(createAdapter('kimi-code')).toBeInstanceOf(KimiCodeAdapter);
});
diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.ts
index 86e910997f8..ea268cfcb8f 100644
--- a/packages/heterogeneous-agents/src/registry.ts
+++ b/packages/heterogeneous-agents/src/registry.ts
@@ -11,6 +11,7 @@ import {
ClaudeCodeSdkAdapter,
CodeBuddyAdapter,
CodexAdapter,
+ CopilotAcpAdapter,
CursorAcpAdapter,
CursorAdapter,
DevinAcpAdapter,
@@ -43,6 +44,9 @@ const localAgentRegistry = {
'codex': {
createAdapter: () => new CodexAdapter(),
},
+ 'copilot': {
+ createAdapter: () => new CopilotAcpAdapter(),
+ },
'cursor': {
createAdapter: () => new CursorAdapter(),
},
diff --git a/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts b/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts
index cdf3a289dad..a555d1985bd 100644
--- a/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/acpSpawnAgent.ts
@@ -5,6 +5,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { resolveHeterogeneousAgentCommand } from '../config';
import { isPathLikeCommand } from './cliSpawn';
+import { buildCopilotAcpPrompt, CopilotAcpSession } from './copilotAcpSession';
import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';
import { buildDevinAcpPrompt, DevinAcpSession } from './devinAcpSession';
import { buildDroidAcpPrompt, DroidAcpSession } from './droidAcpSession';
@@ -284,6 +285,35 @@ export const spawnDevinAcpAgent = async (
return createAcpSpawnHandle(bridge, session);
};
+export const spawnCopilotAcpAgent = async (
+ options: SpawnAgentOptions,
+ command: string,
+ cwd: string,
+): Promise<SpawnAgentHandle> => {
+ const prompt = await buildCopilotAcpPrompt(options.prompt, options.inputOptions);
+ const bridge = createAcpSpawnBridge();
+ const session = new CopilotAcpSession({
+ args: options.extraArgs ?? [],
+ askUserBridge: options.askUserBridge,
+ clientVersion: 'lobehub-cli',
+ commandPath: command,
+ cwd,
+ detached: options.detached,
+ env: { ...process.env, ...options.env },
+ initialModel: options.initialModel,
+ onEvents: bridge.onEvents,
+ onRawMessage: teeAcpRawStdout(options.onRawStdout),
+ onRuntimeStatus: () => {},
+ onSessionId: () => {},
+ onStderr: bridge.onStderr,
+ operationId: options.operationId,
+ prompt,
+ resumeSessionId: options.resumeSessionId,
+ sessionId: options.operationId,
+ });
+ return createAcpSpawnHandle(bridge, session);
+};
+
/** Spawn TRAE's bidirectional ACP runtime behind the ordinary SpawnAgentHandle contract. */
export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentHandle> => {
const requestedCommand = resolveHeterogeneousAgentCommand('trae', options.command);
diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
index 58fb1bfff32..f58d1353e51 100644
--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
@@ -156,6 +156,7 @@ export interface HeterogeneousAgentRuntimeStatus {
| 'claude-sdk'
| 'cli-spawn'
| 'codex-app-server'
+ | 'copilot-acp'
| 'cursor-acp'
| 'droid-acp'
| 'devin-acp'
diff --git a/packages/heterogeneous-agents/src/spawn/copilotAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/copilotAcpSession.test.ts
new file mode 100644
index 00000000000..6ca14826587
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/copilotAcpSession.test.ts
@@ -0,0 +1,372 @@
+import type { ChildProcess } from 'node:child_process';
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { AcpRpcResponseError } from './acpStdioClient';
+import {
+ buildCopilotAcpArgs,
+ CopilotAcpSession,
+ isCopilotAcpSessionNotFoundError,
+ parseCopilotAcpModelCatalog,
+} from './copilotAcpSession';
+
+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 };
+});
+
+describe('Copilot ACP helpers', () => {
+ afterEach(() => {
+ spawnMock.mockReset();
+ });
+
+ it('prepends --acp --stdio while stripping session-level model/effort flags and duplicated ACP flags', () => {
+ expect(
+ buildCopilotAcpArgs([
+ '--acp',
+ '--stdio',
+ '--model',
+ 'gpt-5.4',
+ '--reasoning-effort',
+ 'high',
+ '--allow-all-tools',
+ ]),
+ ).toEqual(['--acp', '--stdio', '--allow-all-tools']);
+ });
+
+ it('parses models from ACP session/new response', () => {
+ expect(
+ parseCopilotAcpModelCatalog({
+ configOptions: [
+ {
+ category: 'model',
+ currentValue: 'claude-sonnet-4.6',
+ id: 'model',
+ options: [
+ {
+ description: 'Claude Sonnet 4.6 (1x)',
+ name: 'Claude Sonnet 4.6',
+ value: 'claude-sonnet-4.6',
+ },
+ {
+ description: 'GPT-5.4 (1x)',
+ name: 'GPT-5.4',
+ value: 'gpt-5.4',
+ },
+ ],
+ },
+ ],
+ models: {
+ availableModels: [
+ {
+ description: 'Claude Sonnet 4.6 (1x)',
+ modelId: 'claude-sonnet-4.6',
+ name: 'Claude Sonnet 4.6',
+ },
+ {
+ description: 'GPT-5.4 (1x)',
+ modelId: 'gpt-5.4',
+ name: 'GPT-5.4',
+ },
+ ],
+ currentModelId: 'claude-sonnet-4.6',
+ },
+ sessionId: 'copilot-session-1',
+ }),
+ ).toEqual({
+ configId: 'model',
+ currentModelId: 'claude-sonnet-4.6',
+ models: [
+ {
+ id: 'claude-sonnet-4.6',
+ label: 'Claude Sonnet 4.6',
+ modelId: 'claude-sonnet-4.6',
+ providerId: 'copilot',
+ },
+ {
+ id: 'gpt-5.4',
+ label: 'GPT-5.4',
+ modelId: 'gpt-5.4',
+ providerId: 'copilot',
+ },
+ ],
+ });
+ });
+
+ it('recognizes Copilot session-not-found RPC errors', () => {
+ expect(
+ isCopilotAcpSessionNotFoundError(
+ new AcpRpcResponseError('session/load', {
+ code: -32_603,
+ data: { details: 'Session missing-id not found' },
+ message: 'Internal error',
+ }),
+ ),
+ ).toBe(true);
+
+ expect(
+ isCopilotAcpSessionNotFoundError(
+ new AcpRpcResponseError('session/load', {
+ code: -32_603,
+ data: { details: 'Authentication required' },
+ message: 'Internal error',
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it('applies initialModel on resume even when discovery session defaults to the same model', async () => {
+ const requests: Array<{
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown>;
+ }> = [];
+ spawnMock.mockImplementation(() => {
+ const child = new EventEmitter() as ChildProcess;
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ 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: 123_456,
+ stderr,
+ stdin: {
+ once: vi.fn(),
+ write: vi.fn((chunk: string) => {
+ const msg = JSON.parse(chunk.trim()) as {
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown>;
+ };
+ requests.push(msg);
+ queueMicrotask(() => {
+ switch (msg.method) {
+ case 'initialize': {
+ send({
+ id: msg.id,
+ result: { agentCapabilities: { loadSession: true }, protocolVersion: 1 },
+ });
+ return;
+ }
+ case 'session/load': {
+ send({ id: msg.id, result: {} });
+ return;
+ }
+ case 'session/new': {
+ send({
+ id: msg.id,
+ result: {
+ configOptions: [
+ {
+ category: 'model',
+ currentValue: 'auto',
+ id: 'model',
+ options: [
+ { name: 'Auto', value: 'auto' },
+ { name: 'GPT-5.4', value: 'gpt-5.4' },
+ ],
+ },
+ ],
+ sessionId: 'discovery-session',
+ },
+ });
+ return;
+ }
+ case 'session/set_config_option': {
+ send({
+ id: msg.id,
+ result: {
+ configOptions: [
+ {
+ category: 'model',
+ currentValue: msg.params?.value,
+ id: 'model',
+ },
+ ],
+ },
+ });
+ return;
+ }
+ case 'session/prompt': {
+ send({ id: msg.id, result: { stopReason: 'end_turn' } });
+ return;
+ }
+ }
+ });
+ return true;
+ }),
+ },
+ stdout,
+ });
+ return child;
+ });
+
+ const models: string[] = [];
+ const session = new CopilotAcpSession({
+ commandPath: 'copilot',
+ cwd: '/tmp',
+ initialModel: 'auto',
+ onEvents: async () => {},
+ onModel: (model) => models.push(model),
+ onRawMessage: () => {},
+ onRuntimeStatus: () => {},
+ onSessionId: () => {},
+ onStderr: () => {},
+ operationId: 'op-1',
+ prompt: 'hello',
+ resumeSessionId: 'resumed-session-1',
+ sessionId: 'session-1',
+ });
+
+ await session.run();
+
+ const setModelCall = requests.find(
+ (req) =>
+ req.method === 'session/set_config_option' &&
+ req.params?.configId === 'model' &&
+ req.params?.sessionId === 'resumed-session-1',
+ );
+ expect(setModelCall?.params).toEqual({
+ configId: 'model',
+ sessionId: 'resumed-session-1',
+ value: 'auto',
+ });
+ expect(models).toEqual(['auto']);
+ });
+
+ it('applies reasoningEffort on resume without initialModel when session/load omits configOptions', async () => {
+ const requests: Array<{
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown>;
+ }> = [];
+ spawnMock.mockImplementation(() => {
+ const child = new EventEmitter() as ChildProcess;
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ 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: 123_456,
+ stderr,
+ stdin: {
+ once: vi.fn(),
+ write: vi.fn((chunk: string) => {
+ const msg = JSON.parse(chunk.trim()) as {
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown>;
+ };
+ requests.push(msg);
+ queueMicrotask(() => {
+ switch (msg.method) {
+ case 'initialize': {
+ send({
+ id: msg.id,
+ result: { agentCapabilities: { loadSession: true }, protocolVersion: 1 },
+ });
+ return;
+ }
+ case 'session/load': {
+ send({ id: msg.id, result: {} });
+ return;
+ }
+ case 'session/new': {
+ send({
+ id: msg.id,
+ result: {
+ configOptions: [
+ {
+ category: 'model',
+ currentValue: 'gpt-5.4',
+ id: 'model',
+ options: [
+ { name: 'Auto', value: 'auto' },
+ { name: 'GPT-5.4', value: 'gpt-5.4' },
+ ],
+ },
+ {
+ category: 'thought_level',
+ currentValue: 'high',
+ id: 'reasoning_effort',
+ options: [
+ { name: 'Low', value: 'low' },
+ { name: 'Medium', value: 'medium' },
+ { name: 'High', value: 'high' },
+ ],
+ },
+ ],
+ sessionId: 'discovery-session',
+ },
+ });
+ return;
+ }
+ case 'session/set_config_option': {
+ send({
+ id: msg.id,
+ result: {
+ configOptions: [
+ {
+ category: 'thought_level',
+ currentValue: msg.params?.value,
+ id: 'reasoning_effort',
+ },
+ ],
+ },
+ });
+ return;
+ }
+ case 'session/prompt': {
+ send({ id: msg.id, result: { stopReason: 'end_turn' } });
+ return;
+ }
+ }
+ });
+ return true;
+ }),
+ },
+ stdout,
+ });
+ return child;
+ });
+
+ const session = new CopilotAcpSession({
+ commandPath: 'copilot',
+ cwd: '/tmp',
+ onEvents: async () => {},
+ onRawMessage: () => {},
+ onRuntimeStatus: () => {},
+ onSessionId: () => {},
+ onStderr: () => {},
+ operationId: 'op-2',
+ prompt: 'hello',
+ reasoningEffort: 'high',
+ resumeSessionId: 'resumed-session-2',
+ sessionId: 'session-2',
+ });
+
+ await session.run();
+
+ const setEffortCall = requests.find(
+ (req) =>
+ req.method === 'session/set_config_option' &&
+ req.params?.configId === 'reasoning_effort' &&
+ req.params?.sessionId === 'resumed-session-2',
+ );
+ expect(setEffortCall?.params).toEqual({
+ configId: 'reasoning_effort',
+ sessionId: 'resumed-session-2',
+ value: 'high',
+ });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/copilotAcpSession.ts b/packages/heterogeneous-agents/src/spawn/copilotAcpSession.ts
new file mode 100644
index 00000000000..1502701080d
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/copilotAcpSession.ts
@@ -0,0 +1,816 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { HeterogeneousAgentModel } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+
+import type { AskUserBridge, InterventionAnswer } from '../askUser/AskUserBridge';
+import type { AcpAgentSessionOptions } from './acpAgentSession';
+import { ACP_PROTOCOL_VERSION, AcpAgentSession } from './acpAgentSession';
+import type { AcpRpcMessage } from './acpStdioClient';
+import { AcpRpcResponseError, AcpServerRequestError } from './acpStdioClient';
+import type { AgentPromptInput, BuildAgentInputOptions } from './input';
+import type {
+ TraeAcpImagePromptBlock,
+ TraeAcpPromptBlock,
+ TraeAcpTextPromptBlock,
+} from './traeAcpSession';
+import { buildTraeAcpPrompt } from './traeAcpSession';
+
+const NOTIFICATION_DRAIN_QUIET_MS = 250;
+const NOTIFICATION_DRAIN_TIMEOUT_MS = 2000;
+const TRANSPORT = 'copilot-acp' as const;
+const UUID_RE = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
+
+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+export type CopilotAcpTextPromptBlock = TraeAcpTextPromptBlock;
+export type CopilotAcpImagePromptBlock = TraeAcpImagePromptBlock;
+export type CopilotAcpPromptBlock = TraeAcpPromptBlock;
+
+interface ExtractedCopilotSessionFlags {
+ args: string[];
+ model?: string;
+ reasoningEffort?: string;
+}
+
+const extractCopilotSessionFlags = (extraArgs: string[] = []): ExtractedCopilotSessionFlags => {
+ const args: string[] = [];
+ let model: string | undefined;
+ let reasoningEffort: string | undefined;
+
+ for (let index = 0; index < extraArgs.length; index += 1) {
+ const arg = extraArgs[index]!;
+ if (arg === '--acp' || arg === '--stdio') {
+ continue;
+ }
+ if (arg === '--model' || arg === '-m') {
+ const value = extraArgs[index + 1];
+ if (value && !value.startsWith('-')) {
+ model = value;
+ index += 1;
+ }
+ continue;
+ }
+ if (arg.startsWith('--model=')) {
+ model = arg.slice('--model='.length);
+ continue;
+ }
+ if (arg.startsWith('-m=')) {
+ model = arg.slice('-m='.length);
+ continue;
+ }
+ if (arg === '--reasoning-effort') {
+ const value = extraArgs[index + 1];
+ if (value && !value.startsWith('-')) {
+ reasoningEffort = value;
+ index += 1;
+ }
+ continue;
+ }
+ if (arg.startsWith('--reasoning-effort=')) {
+ reasoningEffort = arg.slice('--reasoning-effort='.length);
+ continue;
+ }
+ args.push(arg);
+ }
+
+ return { args, model, reasoningEffort };
+};
+
+export const buildCopilotAcpArgs = (extraArgs: string[] = []): string[] => {
+ const { args } = extractCopilotSessionFlags(extraArgs);
+ return ['--acp', '--stdio', ...args];
+};
+
+export const buildCopilotAcpPrompt = (
+ prompt: AgentPromptInput,
+ options: BuildAgentInputOptions = {},
+): Promise<CopilotAcpPromptBlock[]> => buildTraeAcpPrompt(prompt, options);
+
+export const isCopilotAcpSessionNotFoundError = (error: unknown): error is AcpRpcResponseError => {
+ if (!(error instanceof AcpRpcResponseError) || error.method !== 'session/load') return false;
+
+ const data = isRecord(error.rpcError.data) ? error.rpcError.data : undefined;
+ const details = typeof data?.details === 'string' ? data.details : '';
+ const combined = `${error.rpcError.message} ${details}`;
+ return /session\b[\s\S]*?\bnot found/i.test(combined);
+};
+
+interface CopilotAcpInitializeResult {
+ agentCapabilities?: {
+ loadSession?: boolean;
+ promptCapabilities?: { image?: boolean };
+ sessionCapabilities?: { close?: unknown };
+ };
+ protocolVersion?: number | string;
+}
+
+interface CopilotAcpSessionResult {
+ configOptions?: unknown;
+ models?: {
+ availableModels?: unknown;
+ currentModelId?: unknown;
+ };
+ sessionId?: string;
+}
+
+interface CopilotAcpPromptResult {
+ stopReason?: string;
+ usage?: unknown;
+}
+
+interface CopilotAcpConfigOption {
+ category?: unknown;
+ currentValue?: unknown;
+ id?: unknown;
+ name?: unknown;
+ options?: unknown;
+ type?: unknown;
+ value?: unknown;
+}
+
+interface CopilotAcpModelOption {
+ modelId?: unknown;
+ name?: unknown;
+}
+
+interface CopilotAcpSetConfigOptionResult {
+ configOptions?: unknown;
+}
+
+interface CopilotAcpPermissionOption {
+ kind: string;
+ name: string;
+ optionId: string;
+}
+
+interface CopilotAcpPermissionRequest {
+ options: CopilotAcpPermissionOption[];
+ toolCall: {
+ title: string;
+ toolCallId: string;
+ };
+}
+
+export interface CopilotAcpModelCatalog {
+ configId: string;
+ currentModelId?: string;
+ models: HeterogeneousAgentModel[];
+}
+
+interface CopilotAcpDiscoveredCatalog extends CopilotAcpModelCatalog {
+ configOptions?: unknown;
+}
+
+export interface ListCopilotAcpModelsOptions {
+ args?: string[];
+ clientVersion?: string;
+ commandPath: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ timeoutMs?: number;
+}
+
+const toCopilotModel = (id: string, name: unknown): HeterogeneousAgentModel => ({
+ id,
+ ...(typeof name === 'string' && name && name !== id ? { label: name } : {}),
+ modelId: id,
+ providerId: 'copilot',
+});
+
+const parseConfigOptionModels = (options: unknown): HeterogeneousAgentModel[] => {
+ if (!Array.isArray(options)) return [];
+
+ const values = options.flatMap((value) => {
+ const option = value as CopilotAcpConfigOption | null;
+ return Array.isArray(option?.options) ? option.options : [value];
+ });
+ const seen = new Set<string>();
+ const models: HeterogeneousAgentModel[] = [];
+ for (const value of values) {
+ const option = value as CopilotAcpConfigOption | null;
+ if (typeof option?.value !== 'string' || !option.value || seen.has(option.value)) continue;
+ seen.add(option.value);
+ models.push(toCopilotModel(option.value, option.name));
+ }
+ return models;
+};
+
+const getReasoningEffortConfig = (configOptions: unknown): CopilotAcpConfigOption | undefined => {
+ if (!Array.isArray(configOptions)) return undefined;
+ return configOptions
+ .map((value) => value as CopilotAcpConfigOption | null)
+ .find(
+ (option) =>
+ option &&
+ (option.id === 'reasoning_effort' || option.category === 'thought_level') &&
+ (option.type === undefined || option.type === 'select'),
+ ) as CopilotAcpConfigOption | undefined;
+};
+
+export const parseCopilotAcpModelCatalog = (
+ result: Pick<CopilotAcpSessionResult, 'configOptions' | 'models'> | null | undefined,
+): CopilotAcpModelCatalog | undefined => {
+ const configOptions = Array.isArray(result?.configOptions)
+ ? result.configOptions.map((value) => value as CopilotAcpConfigOption | null)
+ : [];
+ const selectableOptions = configOptions.filter(
+ (option) => option?.type === undefined || option.type === 'select',
+ );
+ const modelConfig =
+ selectableOptions.find((option) => option?.category === 'model') ??
+ selectableOptions.find((option) => option?.id === 'model') ??
+ selectableOptions.find(
+ (option) => typeof option?.name === 'string' && option.name.toLowerCase() === 'model',
+ );
+ if (modelConfig && typeof modelConfig.id === 'string' && modelConfig.id) {
+ return {
+ configId: modelConfig.id,
+ currentModelId:
+ typeof modelConfig.currentValue === 'string' ? modelConfig.currentValue : undefined,
+ models: parseConfigOptionModels(modelConfig.options),
+ };
+ }
+
+ if (!Array.isArray(result?.models?.availableModels)) return undefined;
+ const seen = new Set<string>();
+ const models: HeterogeneousAgentModel[] = [];
+ for (const value of result.models.availableModels) {
+ const option = value as CopilotAcpModelOption | null;
+ if (typeof option?.modelId !== 'string' || !option.modelId || seen.has(option.modelId))
+ continue;
+ seen.add(option.modelId);
+ models.push(toCopilotModel(option.modelId, option.name));
+ }
+ return {
+ configId: 'model',
+ currentModelId:
+ typeof result.models.currentModelId === 'string' ? result.models.currentModelId : undefined,
+ models,
+ };
+};
+
+const cleanupEmptyCopilotSessionDir = async (sessionId: string): Promise<void> => {
+ if (!UUID_RE.test(sessionId)) return;
+ const sessionDir = path.join(os.homedir(), '.copilot', 'session-state', sessionId);
+ try {
+ await fs.access(path.join(sessionDir, 'events.jsonl'));
+ } catch {
+ await fs.rm(sessionDir, { force: true, recursive: true }).catch(() => {});
+ }
+};
+
+export interface CopilotAcpSessionOptions extends AcpAgentSessionOptions {
+ askUserBridge?: AskUserBridge;
+ initialModel?: string;
+ inputOptions?: BuildAgentInputOptions;
+ onModel?: (model: string) => void;
+ prompt: AgentPromptInput | CopilotAcpPromptBlock[];
+ reasoningEffort?: string;
+}
+
+export class CopilotAcpSession extends AcpAgentSession<
+ CopilotAcpInitializeResult,
+ CopilotAcpSessionOptions
+> {
+ private acceptUpdates = false;
+ private lastSessionUpdateAt = 0;
+ private modelDiscovery?: CopilotAcpSession;
+ private readonly modelFromArgs?: string;
+ private readonly reasoningEffort?: string;
+ private resolvedPrompt: CopilotAcpPromptBlock[] = [];
+
+ constructor(options: CopilotAcpSessionOptions) {
+ const extracted = extractCopilotSessionFlags(options.args);
+ super(options, {
+ args: ['--acp', '--stdio', ...extracted.args],
+ pipeline: { agentType: 'copilot', cwd: options.cwd },
+ processLabel: 'GitHub Copilot ACP',
+ transport: TRANSPORT,
+ });
+ this.modelFromArgs = extracted.model;
+ this.reasoningEffort = options.reasoningEffort ?? extracted.reasoningEffort;
+ }
+
+ get sessionId(): string | undefined {
+ return this.acpSessionId;
+ }
+
+ async discoverModels(): Promise<HeterogeneousAgentModel[]> {
+ return (await this.discoverModelCatalog()).models;
+ }
+
+ protected async prepareRun(): Promise<void> {
+ this.resolvedPrompt = await this.resolvePrompt();
+ }
+
+ 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: CopilotAcpInitializeResult): void {
+ if (
+ initialized?.protocolVersion !== undefined &&
+ initialized.protocolVersion !== ACP_PROTOCOL_VERSION &&
+ initialized.protocolVersion !== String(ACP_PROTOCOL_VERSION)
+ ) {
+ throw new Error(
+ `GitHub Copilot ACP returned unsupported protocol version: ${String(initialized?.protocolVersion)}`,
+ );
+ }
+ }
+
+ protected async establishSession(initialized: CopilotAcpInitializeResult): Promise<string> {
+ if (
+ this.resolvedPrompt.some((block) => block.type === 'image') &&
+ initialized?.agentCapabilities?.promptCapabilities?.image !== true
+ ) {
+ throw new Error('GitHub Copilot ACP does not support image prompt blocks');
+ }
+ if (this.options.resumeSessionId && initialized?.agentCapabilities?.loadSession !== true) {
+ throw new Error('GitHub Copilot ACP does not support loading sessions');
+ }
+
+ const sessionResult = await this.client.request<CopilotAcpSessionResult>(
+ 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('GitHub Copilot ACP returned no session id');
+ this.acpSessionId = sessionId;
+ this.options.onSessionId(sessionId);
+
+ const { configOptions, hasSessionConfigOptions, model } = await this.applyInitialModel(
+ sessionId,
+ sessionResult,
+ );
+ await this.applyReasoningEffort(sessionId, configOptions, hasSessionConfigOptions);
+
+ if (model) {
+ this.pipeline.configureSession({ model });
+ this.options.onModel?.(model);
+ }
+ await this.pushToPipeline({ model, sessionId, type: 'copilot_session' });
+ return sessionId;
+ }
+
+ protected onBeforePrompt(): void {
+ this.acceptUpdates = true;
+ }
+
+ protected buildPromptParams(sessionId: string): unknown {
+ return { prompt: this.resolvedPrompt, sessionId };
+ }
+
+ protected override async settlePrompt(result: unknown): Promise<void> {
+ await this.drainNotifications();
+ await this.client.drain();
+ const promptResult = isRecord(result) ? (result as CopilotAcpPromptResult) : undefined;
+ await this.pushToPipeline({
+ stopReason: promptResult?.stopReason,
+ type: 'copilot_prompt_completed',
+ usage: promptResult?.usage,
+ });
+ }
+
+ protected async onRunFailure(error: Error): Promise<void> {
+ this.options.askUserBridge?.cancelAll('session_ended');
+ const detail =
+ error instanceof AcpRpcResponseError &&
+ isRecord(error.rpcError.data) &&
+ typeof error.rpcError.data.details === 'string' &&
+ error.rpcError.data.details
+ ? `${error.message}: ${error.rpcError.data.details}`
+ : error.message;
+ await this.pushToPipeline({ message: detail, type: 'copilot_error' });
+ await this.emitEvents(await this.pipeline.flush());
+ }
+
+ protected async onRunCancelled(): Promise<void> {
+ this.options.askUserBridge?.cancelAll('session_ended');
+ await this.pushToPipeline({ stopReason: 'cancelled', type: 'copilot_prompt_completed' });
+ }
+
+ protected onHostClose(): void {
+ this.options.askUserBridge?.cancelAll('session_ended');
+ this.modelDiscovery?.close();
+ }
+
+ protected async handleAgentMessage(message: AcpRpcMessage): Promise<void> {
+ if (message.method !== 'session/update' || !this.acceptUpdates) return;
+
+ this.lastSessionUpdateAt = Date.now();
+ const update = (message.params as { update?: unknown } | undefined)?.update;
+ if (!isRecord(update)) return;
+
+ if (update.sessionUpdate === 'config_option_update') {
+ const catalog = parseCopilotAcpModelCatalog({ configOptions: update.configOptions });
+ if (catalog?.currentModelId) {
+ this.pipeline.configureSession({ model: catalog.currentModelId });
+ this.options.onModel?.(catalog.currentModelId);
+ }
+ }
+ await this.pushToPipeline(update);
+ }
+
+ protected async handleServerRequest(message: AcpRpcMessage): Promise<unknown> {
+ if (message.method === 'session/request_permission') {
+ const request = this.parsePermissionRequest(message.params);
+ return this.requestPermission(
+ request,
+ this.buildInterventionToolCallId(message, request.toolCall.toolCallId),
+ );
+ }
+ throw new AcpServerRequestError(-32_601, `Unsupported ACP client request: ${message.method}`);
+ }
+
+ private async discoverModelCatalog(): Promise<CopilotAcpDiscoveredCatalog> {
+ let discoverySessionId: string | undefined;
+ try {
+ const initialized = await this.initializeConnection();
+ const sessionResult = await this.client.request<CopilotAcpSessionResult>('session/new', {
+ cwd: this.options.cwd,
+ mcpServers: [],
+ });
+ if (!sessionResult?.sessionId) throw new Error('GitHub Copilot ACP returned no session id');
+ discoverySessionId = sessionResult.sessionId;
+ const catalog = parseCopilotAcpModelCatalog(sessionResult);
+ if (!catalog) {
+ throw new Error('GitHub Copilot ACP did not expose a model configuration option');
+ }
+ if (initialized?.agentCapabilities?.sessionCapabilities?.close) {
+ await this.client.request('session/close', { sessionId: sessionResult.sessionId });
+ }
+ return { ...catalog, configOptions: sessionResult.configOptions };
+ } finally {
+ this.client.close();
+ if (discoverySessionId) {
+ await cleanupEmptyCopilotSessionDir(discoverySessionId);
+ }
+ }
+ }
+
+ private async resolvePrompt(): Promise<CopilotAcpPromptBlock[]> {
+ const prompt = this.options.prompt;
+ if (
+ Array.isArray(prompt) &&
+ prompt.every(
+ (block) =>
+ 'type' in block && (block.type === 'text' || ('data' in block && block.type === 'image')),
+ )
+ ) {
+ return prompt as CopilotAcpPromptBlock[];
+ }
+ return buildCopilotAcpPrompt(prompt as AgentPromptInput, this.options.inputOptions);
+ }
+
+ private hasRequestedReasoningEffort(): boolean {
+ const requestedEffort = this.reasoningEffort?.trim();
+ return Boolean(requestedEffort && requestedEffort !== 'default');
+ }
+
+ private async applyInitialModel(
+ sessionId: string,
+ sessionResult: CopilotAcpSessionResult,
+ ): Promise<{ configOptions: unknown; hasSessionConfigOptions: boolean; model?: string }> {
+ const hasLoadedConfigOptions = Array.isArray(sessionResult?.configOptions);
+ const sessionCatalog = parseCopilotAcpModelCatalog(sessionResult);
+ let catalog: CopilotAcpDiscoveredCatalog | undefined = sessionCatalog;
+ const requestedModel = (this.options.initialModel?.trim() || this.modelFromArgs?.trim()) ?? '';
+ if (!requestedModel || requestedModel === 'default') {
+ const currentModelId = sessionCatalog?.currentModelId;
+ if (
+ this.options.resumeSessionId &&
+ sessionCatalog &&
+ currentModelId &&
+ currentModelId !== 'auto' &&
+ !getReasoningEffortConfig(sessionResult.configOptions)
+ ) {
+ const response = await this.resetLoadedModelWithoutReasoningEffort(
+ sessionId,
+ sessionCatalog.configId,
+ currentModelId,
+ );
+ const nextConfigOptions = response?.configOptions ?? sessionResult.configOptions;
+ return {
+ configOptions: nextConfigOptions,
+ hasSessionConfigOptions: Array.isArray(nextConfigOptions),
+ model: currentModelId,
+ };
+ }
+ if (!sessionCatalog && this.options.resumeSessionId && this.hasRequestedReasoningEffort()) {
+ catalog = await this.discoverResumeModelCatalog();
+ return {
+ configOptions: catalog.configOptions,
+ hasSessionConfigOptions: false,
+ model: currentModelId,
+ };
+ }
+ return {
+ configOptions: sessionResult.configOptions,
+ hasSessionConfigOptions: hasLoadedConfigOptions,
+ model: currentModelId,
+ };
+ }
+ if (!catalog && this.options.resumeSessionId) {
+ catalog = await this.discoverResumeModelCatalog();
+ }
+ if (!catalog) {
+ throw new Error('GitHub Copilot ACP did not expose a model configuration option');
+ }
+
+ const selected = catalog.models.find(
+ (model) => model.id === requestedModel || model.label === requestedModel,
+ );
+ if (!selected) throw new Error(`GitHub Copilot ACP model is unavailable: ${requestedModel}`);
+
+ if (sessionCatalog?.currentModelId === selected.id) {
+ if (
+ this.options.resumeSessionId &&
+ selected.id !== 'auto' &&
+ !getReasoningEffortConfig(sessionResult.configOptions)
+ ) {
+ const response = await this.resetLoadedModelWithoutReasoningEffort(
+ sessionId,
+ sessionCatalog.configId,
+ selected.id,
+ );
+ const nextConfigOptions = response?.configOptions ?? sessionResult.configOptions;
+ return {
+ configOptions: nextConfigOptions,
+ hasSessionConfigOptions: Array.isArray(nextConfigOptions),
+ model: selected.id,
+ };
+ }
+ return {
+ configOptions: sessionResult.configOptions,
+ hasSessionConfigOptions: hasLoadedConfigOptions,
+ model: selected.id,
+ };
+ }
+
+ const response = await this.client.request<CopilotAcpSetConfigOptionResult>(
+ 'session/set_config_option',
+ {
+ configId: catalog.configId,
+ sessionId,
+ value: selected.id,
+ },
+ );
+ const nextConfigOptions =
+ response?.configOptions ?? sessionResult.configOptions ?? catalog.configOptions;
+ return {
+ configOptions: nextConfigOptions,
+ hasSessionConfigOptions: Array.isArray(response?.configOptions) || hasLoadedConfigOptions,
+ model:
+ parseCopilotAcpModelCatalog({ configOptions: response?.configOptions })?.currentModelId ??
+ selected.id,
+ };
+ }
+
+ /**
+ * Copilot CLI `session/load` replays `session.start`'s `reasoningEffort` from
+ * `events.jsonl` but ignores `reasoningEffort: null` in `session.model_change`.
+ * Re-selecting the same model is a no-op, so bounce through `auto` and back to
+ * clear stale reasoning effort on models that do not support it.
+ */
+ private async resetLoadedModelWithoutReasoningEffort(
+ sessionId: string,
+ configId: string,
+ modelId: string,
+ ): Promise<CopilotAcpSetConfigOptionResult | undefined> {
+ await this.client.request<CopilotAcpSetConfigOptionResult>('session/set_config_option', {
+ configId,
+ sessionId,
+ value: 'auto',
+ });
+ return this.client.request<CopilotAcpSetConfigOptionResult>('session/set_config_option', {
+ configId,
+ sessionId,
+ value: modelId,
+ });
+ }
+
+ private async applyReasoningEffort(
+ sessionId: string,
+ configOptions: unknown,
+ hasSessionConfigOptions = true,
+ ): Promise<void> {
+ const requestedEffort = this.reasoningEffort?.trim();
+ if (!requestedEffort || requestedEffort === 'default') return;
+
+ const reasoningConfig =
+ getReasoningEffortConfig(configOptions) ??
+ (!hasSessionConfigOptions && this.options.resumeSessionId
+ ? { id: 'reasoning_effort' }
+ : undefined);
+ if (!reasoningConfig || typeof reasoningConfig.id !== 'string' || !reasoningConfig.id) {
+ return;
+ }
+
+ const availableValues = Array.isArray(reasoningConfig.options)
+ ? reasoningConfig.options.flatMap((option) =>
+ isRecord(option) && typeof option.value === 'string' && option.value
+ ? [option.value]
+ : [],
+ )
+ : [];
+ const targetValue =
+ availableValues.length === 0 || availableValues.includes(requestedEffort)
+ ? requestedEffort
+ : undefined;
+ if (!targetValue || (hasSessionConfigOptions && reasoningConfig.currentValue === targetValue)) {
+ return;
+ }
+
+ await this.client.request<CopilotAcpSetConfigOptionResult>('session/set_config_option', {
+ configId: reasoningConfig.id,
+ sessionId,
+ value: targetValue,
+ });
+ }
+
+ private async discoverResumeModelCatalog(): Promise<CopilotAcpDiscoveredCatalog> {
+ const discovery = new CopilotAcpSession({
+ ...this.options,
+ askUserBridge: undefined,
+ initialModel: undefined,
+ onEvents: () => {},
+ onModel: undefined,
+ onRuntimeStatus: () => {},
+ onSessionId: () => {},
+ operationId: `${this.options.operationId}-model-discovery`,
+ prompt: '',
+ reasoningEffort: undefined,
+ resumeSessionId: undefined,
+ sessionId: `${this.options.sessionId}-model-discovery`,
+ });
+ this.modelDiscovery = discovery;
+ try {
+ return await discovery.discoverModelCatalog();
+ } finally {
+ discovery.close();
+ if (this.modelDiscovery === discovery) this.modelDiscovery = undefined;
+ }
+ }
+
+ private parsePermissionRequest(value: unknown): CopilotAcpPermissionRequest {
+ 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.name !== 'string' ||
+ option.name.length === 0 ||
+ option.name.length > 200 ||
+ typeof option.optionId !== 'string' ||
+ option.optionId.length === 0 ||
+ option.optionId.length > 200
+ ) {
+ return [];
+ }
+ const kind =
+ typeof option.kind === 'string' && option.kind.length > 0 && option.kind.length <= 1000
+ ? option.kind
+ : option.optionId;
+ return [{ kind, name: option.name, optionId: option.optionId }];
+ });
+ const optionIds = new Set(options.map(({ optionId }) => optionId));
+ if (
+ options.length !== value.options.length ||
+ options.length === 0 ||
+ optionIds.size !== options.length ||
+ typeof value.toolCall.toolCallId !== 'string' ||
+ value.toolCall.toolCallId.length === 0
+ ) {
+ throw new AcpServerRequestError(-32_602, 'Invalid session/request_permission options');
+ }
+
+ const rawTitle = typeof value.toolCall.title === 'string' ? value.toolCall.title.trim() : '';
+ const rawInput = isRecord(value.toolCall.rawInput) ? value.toolCall.rawInput : undefined;
+ const command = typeof rawInput?.command === 'string' ? rawInput.command.trim() : '';
+ const combinedTitle =
+ rawTitle && command && !rawTitle.includes(command)
+ ? `${rawTitle} (\`${command}\`)`
+ : rawTitle || command || 'GitHub Copilot requests permission';
+
+ return {
+ options,
+ toolCall: {
+ title: combinedTitle.slice(0, 4000),
+ toolCallId: value.toolCall.toolCallId,
+ },
+ };
+ }
+
+ private async requestPermission(
+ request: CopilotAcpPermissionRequest,
+ interventionToolCallId: string,
+ ): Promise<unknown> {
+ const bridge = this.options.askUserBridge;
+ if (!bridge) return { outcome: { outcome: 'cancelled' } };
+
+ const question = request.toolCall.title;
+ const arguments_ = {
+ questions: [
+ {
+ header: 'GitHub Copilot permission',
+ multiSelect: false,
+ options: request.options.map(({ kind, name, optionId }) => ({
+ description: kind,
+ id: optionId,
+ label: name,
+ })),
+ question,
+ },
+ ],
+ };
+ await this.pushToPipeline({
+ identifier: 'copilot',
+ rawInput: arguments_,
+ sessionUpdate: 'tool_call',
+ title: 'askUserQuestion',
+ toolCallId: interventionToolCallId,
+ });
+ const answer = await bridge.pending({
+ arguments: arguments_,
+ interactionKind: 'permission',
+ toolCallId: interventionToolCallId,
+ });
+ await this.pushToPipeline({
+ rawOutput: answer,
+ sessionUpdate: 'tool_call_update',
+ status: 'completed',
+ toolCallId: interventionToolCallId,
+ });
+
+ const selections = this.getAnswerSelections(answer, question);
+ const selected = request.options.find(({ optionId }) => selections.includes(optionId));
+ return selected
+ ? { outcome: { optionId: selected.optionId, outcome: 'selected' } }
+ : { outcome: { outcome: 'cancelled' } };
+ }
+
+ private buildInterventionToolCallId(message: AcpRpcMessage, sourceToolCallId: string): string {
+ return `copilot-permission-${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 async drainNotifications(): Promise<void> {
+ const deadline = Date.now() + NOTIFICATION_DRAIN_TIMEOUT_MS;
+ let quietSince = Date.now();
+
+ while (Date.now() < deadline) {
+ await sleep(Math.min(NOTIFICATION_DRAIN_QUIET_MS, deadline - Date.now()));
+ await this.client.drain();
+ if (this.lastSessionUpdateAt > quietSince) {
+ quietSince = this.lastSessionUpdateAt;
+ continue;
+ }
+ if (Date.now() - quietSince >= NOTIFICATION_DRAIN_QUIET_MS) return;
+ }
+ }
+}
+
+export const listCopilotAcpModels = async (
+ options: ListCopilotAcpModelsOptions,
+): Promise<HeterogeneousAgentModel[]> =>
+ new CopilotAcpSession({
+ args: options.args ?? [],
+ clientVersion: options.clientVersion ?? '1.0.0',
+ commandPath: options.commandPath,
+ cwd: options.cwd,
+ env: options.env,
+ onEvents: () => {},
+ onRawMessage: () => {},
+ onRuntimeStatus: () => {},
+ onSessionId: () => {},
+ onStderr: () => {},
+ operationId: 'copilot-model-discovery',
+ prompt: '',
+ requestTimeoutMs: options.timeoutMs,
+ sessionId: 'copilot-model-discovery',
+ }).discoverModels();
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index ee90b45d7e7..8742520b066 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -87,6 +87,20 @@ export {
refreshCodexJwtFiles,
toTomlBasicString,
} from './codexShellEnv';
+export {
+ buildCopilotAcpArgs,
+ buildCopilotAcpPrompt,
+ type CopilotAcpImagePromptBlock,
+ type CopilotAcpModelCatalog,
+ type CopilotAcpPromptBlock,
+ CopilotAcpSession,
+ type CopilotAcpSessionOptions,
+ type CopilotAcpTextPromptBlock,
+ isCopilotAcpSessionNotFoundError,
+ listCopilotAcpModels,
+ type ListCopilotAcpModelsOptions,
+ parseCopilotAcpModelCatalog,
+} from './copilotAcpSession';
export {
buildCursorAcpArgs,
buildCursorAcpPrompt,
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
index d6f4852f557..eae0050b39c 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
@@ -680,6 +680,11 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {
'codex': {
validateKeywords: ['codex'],
},
+ 'copilot': {
+ validateHelpKeywords: ['--acp'],
+ validateKeywords: ['github copilot cli', 'copilot'],
+ validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,
+ },
'cursor': {
validateFlag: '--help',
validatePattern: /^Usage: agent[\s\S]*Cursor Agent/im,
@@ -807,6 +812,19 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[
path.join(homedir(), 'Applications', bundledCli),
]);
}
+ case 'copilot': {
+ if (platform() === 'win32') {
+ return [path.join(homedir(), 'AppData', 'Roaming', 'npm', 'copilot.cmd')];
+ }
+ if (platform() !== 'darwin' && platform() !== 'linux') return [];
+
+ return [
+ path.join(homedir(), '.local', 'bin', 'copilot'),
+ path.join(homedir(), '.bun', 'bin', 'copilot'),
+ path.join(homedir(), '.npm-global', 'bin', 'copilot'),
+ path.join(homedir(), 'Library', 'pnpm', 'copilot'),
+ ];
+ }
case 'cursor': {
if (platform() !== 'darwin' && platform() !== 'linux') return [];
return [
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index 953705daef7..9418353bfe4 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -8,6 +8,7 @@ import { ClaudeCodeAdapter } from '../adapters/claudeCode';
import type { AskUserBridge } from '../askUser/AskUserBridge';
import { resolveHeterogeneousAgentCommand } from '../config';
import {
+ spawnCopilotAcpAgent,
spawnCursorAcpAgent,
spawnDevinAcpAgent,
spawnDroidAcpAgent,
@@ -472,6 +473,9 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
const command = resolveHeterogeneousAgentCommand(options.agentType, options.command);
const cwd = options.cwd || process.cwd();
assertSpawnableWorkingDirectory(cwd);
+ if (options.agentType === 'copilot') {
+ return spawnCopilotAcpAgent(options, command, cwd);
+ }
if (options.agentType === 'devin') {
return spawnDevinAcpAgent(options, command, cwd);
}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 9ca55f48bea..e5ae6e5386a 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1335,6 +1335,17 @@ export default {
'codexInstallGuide.menuNotification.title': 'Codex CLI not found',
'codexInstallGuide.reason': 'LobeHub could not start Codex: {{message}}',
'codexInstallGuide.title': 'Install Codex CLI',
+ 'copilotInstallGuide.actions.openDocs': 'Open Install Guide',
+ 'copilotInstallGuide.actions.openSystemTools': 'Open System Tools',
+ 'copilotInstallGuide.afterInstall':
+ 'After installing, run `copilot login`, then retry your message or click Re-detect in System Tools.',
+ 'copilotInstallGuide.desc':
+ 'GitHub Copilot needs the GitHub Copilot CLI to run locally. Install it and make sure the `copilot` command is available in your PATH.',
+ 'copilotInstallGuide.installWithBrew': 'Homebrew (macOS / Linux)',
+ 'copilotInstallGuide.installWithNpm': 'Recommended install',
+ 'copilotInstallGuide.menuNotification.title': 'GitHub Copilot CLI not found',
+ 'copilotInstallGuide.reason': 'LobeHub could not start GitHub Copilot: {{message}}',
+ 'copilotInstallGuide.title': 'Install GitHub Copilot CLI',
'cursorInstallGuide.actions.openDocs': 'Open Install Guide',
'cursorInstallGuide.actions.openSystemTools': 'Open System Tools',
'cursorInstallGuide.afterInstall':
@@ -1451,6 +1462,7 @@ export default {
'newClaudeCodeAgent': 'Add Claude Code',
'newCodeBuddyAgent': 'Add CodeBuddy',
'newCodexAgent': 'Add Codex',
+ 'newCopilotAgent': 'Add GitHub Copilot',
'newCursorAgent': 'Add Cursor',
'newDroidAgent': 'Add Factory Droid',
'newDevinAgent': 'Add Devin',
@@ -1548,6 +1560,7 @@ export default {
'DeepSeek Harness agent (dsh CLI) with tools and subagents',
'connectAgent.providerDesc.codebuddy': 'Tencent coding agent CLI',
'connectAgent.providerDesc.codex': 'OpenAI coding agent CLI',
+ 'connectAgent.providerDesc.copilot': 'GitHub Copilot coding agent CLI',
'connectAgent.providerDesc.cursor': 'Cursor coding agent CLI',
'connectAgent.providerDesc.droid': 'Factory coding agent CLI',
'connectAgent.providerDesc.devin': 'Cognition coding agent CLI',
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 130737cd33a..16f2a5d249b 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -1,7 +1,7 @@
import type { WorkingDirConfigValue } from '../device';
import type { LobeAgentChatConfig } from './chatConfig';
import type { AgentGraph } from './graph';
-import { hasAnyCliFlag, hasCliConfigKey, hasCliFlag } from './heteroCliArgs';
+import { hasAnyCliFlag, hasCliConfigKey } from './heteroCliArgs';
import type { HeterogeneousAgentType, LocalHeterogeneousAgentType } from './heterogeneousAgent';
import {
HETEROGENEOUS_AGENT_CONFIGS,
@@ -9,34 +9,21 @@ import {
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
} from './heterogeneousAgent';
import type {
- AmpAgentMode,
- ClaudeCodeReasoningEffort,
- CodexReasoningEffort,
- CodexSpeedMode,
- GrokBuildReasoningEffort,
- HeteroCliEncoding,
HeterogeneousAgentMode,
+ HeterogeneousCatalogAgentType,
HeterogeneousReasoningEffort,
HeterogeneousSpeedMode,
- QoderReasoningEffort,
} from './heteroSelectorCapabilities';
import {
applyHeteroSelection,
- CODEX_REASONING_EFFORT_CONFIG_KEY,
- CODEX_SERVICE_TIER_CONFIG_KEY,
+ buildHeteroExecArgs,
+ buildHeteroSpawnArgs,
getHeteroSelectorCapability,
- GROK_BUILD_REASONING_EFFORT_FLAGS,
- HETERO_SELECTOR_CAPABILITIES,
HETEROGENEOUS_AGENT_DEFAULT_SELECTION,
- isAmpAgentMode,
- isClaudeCodeReasoningEffort,
- isCodexFastServiceTier,
- isCodexReasoningEffort,
- isGrokBuildReasoningEffort,
- isQoderReasoningEffort,
- QODER_REASONING_EFFORT_FLAG,
} from './heteroSelectorCapabilities';
+export { buildHeteroExecArgs, buildHeteroSpawnArgs };
+
export type HeterogeneousAgentModelCatalogErrorCode =
| 'cli_not_found'
| 'command_failed'
@@ -62,18 +49,7 @@ export interface ListHeterogeneousAgentModelsParams {
command?: string;
cwd?: string;
env?: Record<string, string>;
- type:
- | 'codebuddy'
- | 'codex'
- | 'cursor'
- | 'devin'
- | 'droid'
- | 'grok-build'
- | 'kimi-code'
- | 'opencode'
- | 'pi'
- | 'qoder'
- | 'trae';
+ type: HeterogeneousCatalogAgentType;
}
export interface HeterogeneousAgentModelCatalogSuccess {
@@ -464,437 +440,6 @@ const normalizeAgencyConfigHeterogeneousProvider = (
: { ...base, heterogeneousProvider };
};
-interface ClaudeCodeSelectionSource {
- args?: string[];
- effort?: string | null;
- model?: string | null;
-}
-
-interface AmpSelectionSource {
- args?: string[];
- mode?: string | null;
-}
-
-interface CodexSelectionSource {
- args?: string[];
- effort?: string | null;
- model?: string | null;
- speed?: string | null;
-}
-
-interface GrokBuildSelectionSource {
- args?: string[];
- effort?: string | null;
- model?: string | null;
-}
-
-interface QoderSelectionSource {
- args?: string[];
- effort?: string | null;
- model?: string | null;
-}
-
-const HETERO_EXEC_AGENT_ARG_FLAG = '--agent-arg';
-
-const modelFlagsOf = (
- type: 'codex' | 'grok-build' | 'kimi-code' | 'opencode' | 'pi' | 'qoder',
-): readonly string[] =>
- HETERO_SELECTOR_CAPABILITIES[type].model.encodings.flatMap((encoding: HeteroCliEncoding) =>
- encoding.kind === 'flag' ? encoding.flags : [],
- );
-
-const CODEX_MODEL_FLAGS = modelFlagsOf('codex');
-const CURSOR_MODEL_FLAGS = ['--model'] as const;
-const GROK_BUILD_MODEL_FLAGS = modelFlagsOf('grok-build');
-const KIMI_CODE_MODEL_FLAGS = modelFlagsOf('kimi-code');
-const OPENCODE_MODEL_FLAGS = modelFlagsOf('opencode');
-const PI_MODEL_FLAGS = modelFlagsOf('pi');
-const QODER_MODEL_FLAGS = modelFlagsOf('qoder');
-
-const getExplicitAmpAgentMode = (
- source: AmpSelectionSource | null | undefined,
-): AmpAgentMode | undefined => {
- const mode = source?.mode?.trim();
- return isAmpAgentMode(mode) ? mode : undefined;
-};
-
-const getExplicitClaudeCodeModel = (
- source: ClaudeCodeSelectionSource | null | undefined,
-): string | undefined => {
- const model = source?.model?.trim();
- return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION ? model : undefined;
-};
-
-const getExplicitClaudeCodeReasoningEffort = (
- source: ClaudeCodeSelectionSource | null | undefined,
-): ClaudeCodeReasoningEffort | undefined => {
- const effort = source?.effort?.trim();
- return isClaudeCodeReasoningEffort(effort) ? effort : undefined;
-};
-
-const getExplicitCodexModel = (
- source: CodexSelectionSource | null | undefined,
-): string | undefined => {
- const model = source?.model?.trim();
- return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION ? model : undefined;
-};
-
-const getExplicitCodexReasoningEffort = (
- source: CodexSelectionSource | null | undefined,
-): CodexReasoningEffort | undefined => {
- const effort = source?.effort?.trim();
- return isCodexReasoningEffort(effort) ? effort : undefined;
-};
-
-const getExplicitGrokBuildReasoningEffort = (
- source: GrokBuildSelectionSource | null | undefined,
-): GrokBuildReasoningEffort | undefined => {
- const effort = source?.effort?.trim();
- return isGrokBuildReasoningEffort(effort) ? effort : undefined;
-};
-
-const getExplicitQoderReasoningEffort = (
- source: QoderSelectionSource | null | undefined,
-): QoderReasoningEffort | undefined => {
- const effort = source?.effort?.trim();
- return isQoderReasoningEffort(effort) ? effort : undefined;
-};
-
-const getExplicitCodexSpeedMode = (
- source: CodexSelectionSource | null | undefined,
-): CodexSpeedMode | undefined => {
- const speed = source?.speed?.trim();
- return isCodexFastServiceTier(speed) ? 'fast' : undefined;
-};
-
-/**
- * Resolve the effective native CLI args for a heterogeneous spawn.
- *
- * For Amp, Claude Code, CodeBuddy, and Codex, explicit mode/model/effort
- * selections are persisted on the provider config; this is the single place
- * that maps those stored settings onto provider-specific argv for direct local
- * desktop spawns. OpenCode, Pi, and Qoder use their device-local model catalogs
- * and forward the selected model using the native `--model` flag.
- * Missing/default settings are resolved by the UI helpers for display only.
- * They are not appended here because CLI overrides must not mask each CLI's
- * own settings/env/account defaults. User-authored `args` win, so there is
- * never a duplicate flag/config override.
- *
- * Returns `provider.args` unchanged (possibly `undefined`) when there is
- * nothing to inject, preserving the prior `args: provider.args` behavior for
- * every other provider type.
- */
-export const buildHeteroSpawnArgs = (
- provider: HeterogeneousProviderConfig | undefined | null,
-): string[] | undefined => {
- if (!provider) return undefined;
- if (
- provider.type !== 'amp' &&
- provider.type !== 'claude-code' &&
- provider.type !== 'codebuddy' &&
- provider.type !== 'codex' &&
- 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;
- }
-
- const baseArgs = provider.args ?? [];
- const extraArgs: string[] = [];
-
- if (provider.type === 'amp') {
- const mode = getExplicitAmpAgentMode(provider);
- if (mode && !hasCliFlag(baseArgs, '--mode')) extraArgs.push('--mode', mode);
- }
-
- if (provider.type === 'claude-code' || provider.type === 'codebuddy') {
- const model = getExplicitClaudeCodeModel(provider);
- if (model && !hasCliFlag(baseArgs, '--model')) extraArgs.push('--model', model);
- const effort = getExplicitClaudeCodeReasoningEffort(provider);
- if (effort && !hasCliFlag(baseArgs, '--effort')) extraArgs.push('--effort', effort);
- }
-
- if (provider.type === 'codex') {
- const model = getExplicitCodexModel(provider);
- if (
- model &&
- !hasAnyCliFlag(baseArgs, CODEX_MODEL_FLAGS) &&
- !hasCliConfigKey(baseArgs, 'model')
- ) {
- extraArgs.push('--model', model);
- }
-
- const effort = getExplicitCodexReasoningEffort(provider);
- if (effort && !hasCliConfigKey(baseArgs, CODEX_REASONING_EFFORT_CONFIG_KEY)) {
- extraArgs.push('-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${effort}"`);
- }
-
- const speed = getExplicitCodexSpeedMode(provider);
- if (speed && !hasCliConfigKey(baseArgs, CODEX_SERVICE_TIER_CONFIG_KEY)) {
- extraArgs.push('-c', `${CODEX_SERVICE_TIER_CONFIG_KEY}="${speed}"`);
- }
- }
-
- if (provider.type === 'grok-build') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, GROK_BUILD_MODEL_FLAGS)
- ) {
- extraArgs.push('--model', model);
- }
- const effort = getExplicitGrokBuildReasoningEffort(provider);
- if (effort && !hasAnyCliFlag(baseArgs, GROK_BUILD_REASONING_EFFORT_FLAGS)) {
- extraArgs.push('--effort', effort);
- }
- }
-
- if (provider.type === 'opencode') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, OPENCODE_MODEL_FLAGS)
- ) {
- extraArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'cursor' || provider.type === 'devin') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, CURSOR_MODEL_FLAGS)
- ) {
- extraArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'kimi-code') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, KIMI_CODE_MODEL_FLAGS)
- ) {
- extraArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'pi') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, PI_MODEL_FLAGS)
- ) {
- extraArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'qoder') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, QODER_MODEL_FLAGS)
- ) {
- extraArgs.push('--model', model);
- }
- const effort = getExplicitQoderReasoningEffort(provider);
- if (effort && !hasCliFlag(baseArgs, QODER_REASONING_EFFORT_FLAG)) {
- extraArgs.push(QODER_REASONING_EFFORT_FLAG, effort);
- }
- }
-
- if (extraArgs.length === 0) return provider.args;
- return [...baseArgs, ...extraArgs];
-};
-
-/**
- * Resolve args for the `lh hetero exec` wrapper.
- *
- * Unlike `buildHeteroSpawnArgs`, these args are consumed by the LobeHub CLI
- * wrapper first, not by the native agent binary. Native provider args are
- * encoded with `--agent-arg=<arg>` so wrapper flags such as `-c, --command`
- * never collide with provider flags. Keep selector overrides in the wrapper's
- * structured `--model` / `--effort` form; `lh hetero exec` translates them
- * into native provider arguments immediately before `spawnAgent`. Amp mode is
- * encoded as a native argument because older device CLIs predate the wrapper's
- * structured `--mode` option but already support `--agent-arg`.
- */
-export const buildHeteroExecArgs = (
- provider: HeterogeneousProviderConfig | undefined | null,
-): string[] | undefined => {
- if (!provider) return undefined;
- if (
- provider.type !== 'amp' &&
- provider.type !== 'claude-code' &&
- provider.type !== 'codebuddy' &&
- provider.type !== 'codex' &&
- 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;
- }
-
- const baseArgs = provider.args ?? [];
- const wrapperArgs = baseArgs.map((arg) => `${HETERO_EXEC_AGENT_ARG_FLAG}=${arg}`);
- const selectorArgs: string[] = [];
-
- if (provider.type === 'amp') {
- const mode = getExplicitAmpAgentMode(provider);
- if (mode && !hasCliFlag(baseArgs, '--mode')) {
- wrapperArgs.push(
- `${HETERO_EXEC_AGENT_ARG_FLAG}=--mode`,
- `${HETERO_EXEC_AGENT_ARG_FLAG}=${mode}`,
- );
- }
- }
-
- if (provider.type === 'claude-code' || provider.type === 'codebuddy') {
- const model = getExplicitClaudeCodeModel(provider);
- if (model && !hasCliFlag(baseArgs, '--model')) selectorArgs.push('--model', model);
- const effort = getExplicitClaudeCodeReasoningEffort(provider);
- if (effort && !hasCliFlag(baseArgs, '--effort')) selectorArgs.push('--effort', effort);
- }
-
- if (provider.type === 'codex') {
- const model = getExplicitCodexModel(provider);
- if (
- model &&
- !hasAnyCliFlag(baseArgs, CODEX_MODEL_FLAGS) &&
- !hasCliConfigKey(baseArgs, 'model')
- ) {
- selectorArgs.push('--model', model);
- }
-
- const effort = getExplicitCodexReasoningEffort(provider);
- if (
- effort &&
- !hasCliFlag(baseArgs, '--effort') &&
- !hasCliConfigKey(baseArgs, CODEX_REASONING_EFFORT_CONFIG_KEY)
- ) {
- selectorArgs.push('--effort', effort);
- }
-
- const speed = getExplicitCodexSpeedMode(provider);
- if (
- speed &&
- !hasCliFlag(baseArgs, '--speed') &&
- !hasCliConfigKey(baseArgs, CODEX_SERVICE_TIER_CONFIG_KEY)
- ) {
- selectorArgs.push('--speed', speed);
- }
- }
-
- if (provider.type === 'grok-build') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, GROK_BUILD_MODEL_FLAGS)
- ) {
- wrapperArgs.push(
- `${HETERO_EXEC_AGENT_ARG_FLAG}=--model`,
- `${HETERO_EXEC_AGENT_ARG_FLAG}=${model}`,
- );
- }
- const effort = getExplicitGrokBuildReasoningEffort(provider);
- if (effort && !hasAnyCliFlag(baseArgs, GROK_BUILD_REASONING_EFFORT_FLAGS)) {
- wrapperArgs.push(
- `${HETERO_EXEC_AGENT_ARG_FLAG}=--effort`,
- `${HETERO_EXEC_AGENT_ARG_FLAG}=${effort}`,
- );
- }
- }
-
- if (provider.type === 'opencode') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, OPENCODE_MODEL_FLAGS)
- ) {
- selectorArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'cursor' || provider.type === 'devin') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, CURSOR_MODEL_FLAGS)
- ) {
- selectorArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'kimi-code') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, KIMI_CODE_MODEL_FLAGS)
- ) {
- selectorArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'pi') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, PI_MODEL_FLAGS)
- ) {
- selectorArgs.push('--model', model);
- }
- }
-
- if (provider.type === 'qoder') {
- const model = provider.model?.trim();
- if (
- model &&
- model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
- !hasAnyCliFlag(baseArgs, QODER_MODEL_FLAGS)
- ) {
- selectorArgs.push('--model', model);
- }
- const effort = getExplicitQoderReasoningEffort(provider);
- if (effort && !hasCliFlag(baseArgs, QODER_REASONING_EFFORT_FLAG)) {
- selectorArgs.push('--effort', effort);
- }
- }
-
- if (provider.type === 'droid' || provider.type === 'trae') {
- const model = provider.model?.trim();
- if (model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION) {
- selectorArgs.push('--model', model);
- }
- }
-
- const args = [...wrapperArgs, ...selectorArgs];
- return args.length > 0 ? args : undefined;
-};
-
/**
* Where an agent runs.
* - `none` : no execution environment — plain chat, no built-in run tools
diff --git a/packages/types/src/agent/heteroSelectorCapabilities.test.ts b/packages/types/src/agent/heteroSelectorCapabilities.test.ts
index 799ad755982..9217aca4f13 100644
--- a/packages/types/src/agent/heteroSelectorCapabilities.test.ts
+++ b/packages/types/src/agent/heteroSelectorCapabilities.test.ts
@@ -17,6 +17,7 @@ describe('selector availability', () => {
expect(isHeteroSelectorAvailable('claude-code')).toBe(true);
expect(isHeteroSelectorAvailable('codebuddy')).toBe(true);
expect(isHeteroSelectorAvailable('codex')).toBe(true);
+ expect(isHeteroSelectorAvailable('copilot')).toBe(true);
expect(isHeteroSelectorAvailable('cursor')).toBe(true);
expect(isHeteroSelectorAvailable('droid')).toBe(true);
expect(isHeteroSelectorAvailable('devin')).toBe(true);
@@ -41,6 +42,14 @@ describe('selector availability', () => {
expect(getHeteroSelectorCapability('amp')?.model).toBeUndefined();
expect(getHeteroSelectorCapability('claude-code')?.speed).toBeUndefined();
expect(getHeteroSelectorCapability('codex')?.speed).toBeDefined();
+ expect(getHeteroSelectorCapability('copilot')?.model?.source).toBe('catalog');
+ expect(getHeteroSelectorCapability('copilot')?.effort?.levels()).toEqual([
+ 'low',
+ 'medium',
+ 'high',
+ 'xhigh',
+ 'max',
+ ]);
expect(getHeteroSelectorCapability('cursor')?.model?.source).toBe('catalog');
expect(getHeteroSelectorCapability('droid')?.model?.source).toBe('catalog');
expect(getHeteroSelectorCapability('devin')?.model?.source).toBe('catalog');
diff --git a/packages/types/src/agent/heteroSelectorCapabilities.ts b/packages/types/src/agent/heteroSelectorCapabilities.ts
index e9d44eef485..9ba317ecc39 100644
--- a/packages/types/src/agent/heteroSelectorCapabilities.ts
+++ b/packages/types/src/agent/heteroSelectorCapabilities.ts
@@ -2,10 +2,13 @@ import {
getAnyCliFlagValue,
getCliConfigValue,
getCliFlagValue,
+ hasAnyCliFlag,
+ hasCliConfigKey,
+ hasCliFlag,
stripCliConfigKey,
stripCliFlags,
} from './heteroCliArgs';
-import type { LocalHeterogeneousAgentType } from './heterogeneousAgent';
+import type { HeterogeneousAgentType, LocalHeterogeneousAgentType } from './heterogeneousAgent';
/**
* Selector value that means "do not override the underlying CLI".
@@ -90,9 +93,20 @@ export type QoderReasoningEffort = (typeof QODER_REASONING_EFFORT_LEVELS)[number
export const QODER_REASONING_EFFORT_FLAG = '--reasoning-effort';
+/**
+ * GitHub Copilot CLI reasoning-effort levels, mirrored 1:1 with the CLI's
+ * `--reasoning-effort <level>` flag and ACP `reasoning_effort` config option.
+ */
+const COPILOT_REASONING_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const;
+
+export type CopilotReasoningEffort = (typeof COPILOT_REASONING_EFFORT_LEVELS)[number];
+
+export const COPILOT_REASONING_EFFORT_FLAG = '--reasoning-effort';
+
export type HeterogeneousReasoningEffortLevel =
| ClaudeCodeReasoningEffort
| CodexReasoningEffort
+ | CopilotReasoningEffort
| GrokBuildReasoningEffort
| QoderReasoningEffort;
@@ -156,6 +170,11 @@ export const isGrokBuildReasoningEffort = (
export const isQoderReasoningEffort = (value: string | undefined): value is QoderReasoningEffort =>
!!value && QODER_REASONING_EFFORT_LEVELS.includes(value as QoderReasoningEffort);
+export const isCopilotReasoningEffort = (
+ value: string | undefined,
+): value is CopilotReasoningEffort =>
+ !!value && COPILOT_REASONING_EFFORT_LEVELS.includes(value as CopilotReasoningEffort);
+
export const isCodexFastServiceTier = (value: string | undefined): boolean =>
!!value &&
CODEX_FAST_SERVICE_TIER_VALUES.includes(value as (typeof CODEX_FAST_SERVICE_TIER_VALUES)[number]);
@@ -277,6 +296,15 @@ const resolveQoderReasoningEffort = (
return isQoderReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
};
+const resolveCopilotReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): CopilotReasoningEffort | HeterogeneousAgentDefaultSelection => {
+ const effort = (
+ getCliFlagValue(source?.args, COPILOT_REASONING_EFFORT_FLAG) ?? source?.effort
+ )?.trim();
+ return isCopilotReasoningEffort(effort) ? effort : HETEROGENEOUS_AGENT_DEFAULT_SELECTION;
+};
+
/**
* Catalog providers persist the picked model id verbatim and never read it back
* out of `args`. Widening them to the arg-first order that `buildHeteroSpawnArgs`
@@ -400,6 +428,18 @@ export const HETERO_SELECTOR_CAPABILITIES = {
supported: codexModelSupportsFastSpeed,
},
},
+ 'copilot': {
+ effort: {
+ encodings: [{ flags: [COPILOT_REASONING_EFFORT_FLAG], kind: 'flag' }],
+ levels: () => COPILOT_REASONING_EFFORT_LEVELS,
+ resolve: resolveCopilotReasoningEffort,
+ },
+ model: {
+ encodings: [{ flags: ['--model'], kind: 'flag' }],
+ resolve: resolvePersistedModel,
+ source: 'catalog',
+ },
+ },
'cursor': {
model: {
encodings: [{ flags: ['--model'], kind: 'flag' }],
@@ -540,3 +580,434 @@ export const applyHeteroSelection = (
return patch;
};
+
+export type HeterogeneousCatalogAgentType = {
+ [
+ K in keyof typeof HETERO_SELECTOR_CAPABILITIES
+ ]: (typeof HETERO_SELECTOR_CAPABILITIES)[K] extends {
+ model: { source: 'catalog' };
+ }
+ ? K
+ : never;
+}[keyof typeof HETERO_SELECTOR_CAPABILITIES];
+
+export interface HeteroSpawnSelectionProvider extends HeteroSelectionSource {
+ type: HeterogeneousAgentType;
+}
+
+const HETERO_EXEC_AGENT_ARG_FLAG = '--agent-arg';
+
+const modelFlagsOf = (
+ type: 'codex' | 'copilot' | 'grok-build' | 'kimi-code' | 'opencode' | 'pi' | 'qoder',
+): readonly string[] =>
+ HETERO_SELECTOR_CAPABILITIES[type].model.encodings.flatMap((encoding: HeteroCliEncoding) =>
+ encoding.kind === 'flag' ? encoding.flags : [],
+ );
+
+const COPILOT_MODEL_FLAGS = modelFlagsOf('copilot');
+const CURSOR_MODEL_FLAGS = ['--model'] as const;
+const GROK_BUILD_MODEL_FLAGS = modelFlagsOf('grok-build');
+const KIMI_CODE_MODEL_FLAGS = modelFlagsOf('kimi-code');
+const OPENCODE_MODEL_FLAGS = modelFlagsOf('opencode');
+const PI_MODEL_FLAGS = modelFlagsOf('pi');
+const QODER_MODEL_FLAGS = modelFlagsOf('qoder');
+
+const getExplicitAmpAgentMode = (
+ source: HeteroSelectionSource | null | undefined,
+): AmpAgentMode | undefined => {
+ const mode = source?.mode?.trim();
+ return isAmpAgentMode(mode) ? mode : undefined;
+};
+
+const getExplicitClaudeCodeModel = (
+ source: HeteroSelectionSource | null | undefined,
+): string | undefined => {
+ const model = source?.model?.trim();
+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION ? model : undefined;
+};
+
+const getExplicitClaudeCodeReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): ClaudeCodeReasoningEffort | undefined => {
+ const effort = source?.effort?.trim();
+ return isClaudeCodeReasoningEffort(effort) ? effort : undefined;
+};
+
+const getExplicitCodexModel = (
+ source: HeteroSelectionSource | null | undefined,
+): string | undefined => {
+ const model = source?.model?.trim();
+ return model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION ? model : undefined;
+};
+
+const getExplicitCodexReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): CodexReasoningEffort | undefined => {
+ const effort = source?.effort?.trim();
+ return isCodexReasoningEffort(effort) ? effort : undefined;
+};
+
+const getExplicitCopilotReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): CopilotReasoningEffort | undefined => {
+ const effort = source?.effort?.trim();
+ return isCopilotReasoningEffort(effort) ? effort : undefined;
+};
+
+const getExplicitGrokBuildReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): GrokBuildReasoningEffort | undefined => {
+ const effort = source?.effort?.trim();
+ return isGrokBuildReasoningEffort(effort) ? effort : undefined;
+};
+
+const getExplicitQoderReasoningEffort = (
+ source: HeteroSelectionSource | null | undefined,
+): QoderReasoningEffort | undefined => {
+ const effort = source?.effort?.trim();
+ return isQoderReasoningEffort(effort) ? effort : undefined;
+};
+
+const getExplicitCodexSpeedMode = (
+ source: HeteroSelectionSource | null | undefined,
+): CodexSpeedMode | undefined => {
+ const speed = source?.speed?.trim();
+ return isCodexFastServiceTier(speed) ? 'fast' : undefined;
+};
+
+/**
+ * Resolve the effective native CLI args for a heterogeneous spawn.
+ */
+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;
+ }
+
+ const baseArgs = provider.args ?? [];
+ const extraArgs: string[] = [];
+
+ if (provider.type === 'amp') {
+ const mode = getExplicitAmpAgentMode(provider);
+ if (mode && !hasCliFlag(baseArgs, '--mode')) extraArgs.push('--mode', mode);
+ }
+
+ if (provider.type === 'claude-code' || provider.type === 'codebuddy') {
+ const model = getExplicitClaudeCodeModel(provider);
+ if (model && !hasCliFlag(baseArgs, '--model')) extraArgs.push('--model', model);
+ const effort = getExplicitClaudeCodeReasoningEffort(provider);
+ if (effort && !hasCliFlag(baseArgs, '--effort')) extraArgs.push('--effort', effort);
+ }
+
+ if (provider.type === 'codex') {
+ const model = getExplicitCodexModel(provider);
+ if (
+ model &&
+ !hasAnyCliFlag(baseArgs, CODEX_MODEL_FLAGS) &&
+ !hasCliConfigKey(baseArgs, 'model')
+ ) {
+ extraArgs.push('--model', model);
+ }
+
+ const effort = getExplicitCodexReasoningEffort(provider);
+ if (effort && !hasCliConfigKey(baseArgs, CODEX_REASONING_EFFORT_CONFIG_KEY)) {
+ extraArgs.push('-c', `${CODEX_REASONING_EFFORT_CONFIG_KEY}="${effort}"`);
+ }
+
+ const speed = getExplicitCodexSpeedMode(provider);
+ if (speed && !hasCliConfigKey(baseArgs, CODEX_SERVICE_TIER_CONFIG_KEY)) {
+ extraArgs.push('-c', `${CODEX_SERVICE_TIER_CONFIG_KEY}="${speed}"`);
+ }
+ }
+
+ if (provider.type === 'copilot') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, COPILOT_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ const effort = getExplicitCopilotReasoningEffort(provider);
+ if (effort && !hasCliFlag(baseArgs, COPILOT_REASONING_EFFORT_FLAG)) {
+ extraArgs.push(COPILOT_REASONING_EFFORT_FLAG, effort);
+ }
+ }
+
+ if (provider.type === 'grok-build') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, GROK_BUILD_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ const effort = getExplicitGrokBuildReasoningEffort(provider);
+ if (effort && !hasAnyCliFlag(baseArgs, GROK_BUILD_REASONING_EFFORT_FLAGS)) {
+ extraArgs.push('--effort', effort);
+ }
+ }
+
+ if (provider.type === 'opencode') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, OPENCODE_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'cursor' || provider.type === 'devin') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, CURSOR_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'kimi-code') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, KIMI_CODE_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'pi') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, PI_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'qoder') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, QODER_MODEL_FLAGS)
+ ) {
+ extraArgs.push('--model', model);
+ }
+ const effort = getExplicitQoderReasoningEffort(provider);
+ if (effort && !hasCliFlag(baseArgs, QODER_REASONING_EFFORT_FLAG)) {
+ extraArgs.push(QODER_REASONING_EFFORT_FLAG, effort);
+ }
+ }
+
+ if (extraArgs.length === 0) return provider.args;
+ return [...baseArgs, ...extraArgs];
+};
+
+/**
+ * Resolve args for the `lh hetero exec` wrapper.
+ */
+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'
+ ) {
+ return provider.args;
+ }
+
+ const baseArgs = provider.args ?? [];
+ const wrapperArgs = baseArgs.map((arg) => `${HETERO_EXEC_AGENT_ARG_FLAG}=${arg}`);
+ const selectorArgs: string[] = [];
+
+ if (provider.type === 'amp') {
+ const mode = getExplicitAmpAgentMode(provider);
+ if (mode && !hasCliFlag(baseArgs, '--mode')) {
+ wrapperArgs.push(
+ `${HETERO_EXEC_AGENT_ARG_FLAG}=--mode`,
+ `${HETERO_EXEC_AGENT_ARG_FLAG}=${mode}`,
+ );
+ }
+ }
+
+ if (provider.type === 'claude-code' || provider.type === 'codebuddy') {
+ const model = getExplicitClaudeCodeModel(provider);
+ if (model && !hasCliFlag(baseArgs, '--model')) selectorArgs.push('--model', model);
+ const effort = getExplicitClaudeCodeReasoningEffort(provider);
+ if (effort && !hasCliFlag(baseArgs, '--effort')) selectorArgs.push('--effort', effort);
+ }
+
+ if (provider.type === 'codex') {
+ const model = getExplicitCodexModel(provider);
+ if (
+ model &&
+ !hasAnyCliFlag(baseArgs, CODEX_MODEL_FLAGS) &&
+ !hasCliConfigKey(baseArgs, 'model')
+ ) {
+ selectorArgs.push('--model', model);
+ }
+
+ const effort = getExplicitCodexReasoningEffort(provider);
+ if (
+ effort &&
+ !hasCliFlag(baseArgs, '--effort') &&
+ !hasCliConfigKey(baseArgs, CODEX_REASONING_EFFORT_CONFIG_KEY)
+ ) {
+ selectorArgs.push('--effort', effort);
+ }
+
+ const speed = getExplicitCodexSpeedMode(provider);
+ if (
+ speed &&
+ !hasCliFlag(baseArgs, '--speed') &&
+ !hasCliConfigKey(baseArgs, CODEX_SERVICE_TIER_CONFIG_KEY)
+ ) {
+ selectorArgs.push('--speed', speed);
+ }
+ }
+
+ if (provider.type === 'copilot') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, COPILOT_MODEL_FLAGS)
+ ) {
+ selectorArgs.push('--model', model);
+ }
+ const effort = getExplicitCopilotReasoningEffort(provider);
+ if (effort && !hasCliFlag(baseArgs, COPILOT_REASONING_EFFORT_FLAG)) {
+ selectorArgs.push('--effort', effort);
+ }
+ }
+
+ if (provider.type === 'grok-build') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, GROK_BUILD_MODEL_FLAGS)
+ ) {
+ wrapperArgs.push(
+ `${HETERO_EXEC_AGENT_ARG_FLAG}=--model`,
+ `${HETERO_EXEC_AGENT_ARG_FLAG}=${model}`,
+ );
+ }
+ const effort = getExplicitGrokBuildReasoningEffort(provider);
+ if (effort && !hasAnyCliFlag(baseArgs, GROK_BUILD_REASONING_EFFORT_FLAGS)) {
+ wrapperArgs.push(
+ `${HETERO_EXEC_AGENT_ARG_FLAG}=--effort`,
+ `${HETERO_EXEC_AGENT_ARG_FLAG}=${effort}`,
+ );
+ }
+ }
+
+ if (provider.type === 'opencode') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, OPENCODE_MODEL_FLAGS)
+ ) {
+ selectorArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'cursor' || provider.type === 'devin') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, CURSOR_MODEL_FLAGS)
+ ) {
+ selectorArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'kimi-code') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, KIMI_CODE_MODEL_FLAGS)
+ ) {
+ selectorArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'pi') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, PI_MODEL_FLAGS)
+ ) {
+ selectorArgs.push('--model', model);
+ }
+ }
+
+ if (provider.type === 'qoder') {
+ const model = provider.model?.trim();
+ if (
+ model &&
+ model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION &&
+ !hasAnyCliFlag(baseArgs, QODER_MODEL_FLAGS)
+ ) {
+ selectorArgs.push('--model', model);
+ }
+ const effort = getExplicitQoderReasoningEffort(provider);
+ if (effort && !hasCliFlag(baseArgs, QODER_REASONING_EFFORT_FLAG)) {
+ selectorArgs.push('--effort', effort);
+ }
+ }
+
+ if (provider.type === 'droid' || provider.type === 'trae') {
+ const model = provider.model?.trim();
+ if (model && model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION) {
+ selectorArgs.push('--model', model);
+ }
+ }
+
+ const args = [...wrapperArgs, ...selectorArgs];
+ return args.length > 0 ? args : undefined;
+};
diff --git a/packages/types/src/agent/heterogeneousAgent.ts b/packages/types/src/agent/heterogeneousAgent.ts
index ed4f4e40272..24ae66ec54a 100644
--- a/packages/types/src/agent/heterogeneousAgent.ts
+++ b/packages/types/src/agent/heterogeneousAgent.ts
@@ -157,6 +157,38 @@ export const HETEROGENEOUS_AGENT_CONFIGS = [
title: 'Codex',
type: 'codex',
},
+ {
+ auth: {
+ docsUrl: 'https://docs.github.com/en/copilot/how-tos/copilot-cli',
+ errorMessage:
+ 'GitHub Copilot CLI could not authenticate. Run `copilot login` in your terminal, then retry.',
+ patterns: [
+ ...COMMON_AUTH_REQUIRED_PATTERNS,
+ 'authentication required',
+ 'not authenticated',
+ 'not logged in',
+ 'copilot login',
+ 'gh auth login',
+ ],
+ signInCommand: 'copilot login',
+ },
+ defaultCommand: 'copilot',
+ defaultTopicGroupMode: 'byProject',
+ iconId: 'GithubCopilot',
+ install: {
+ commands: [
+ 'curl -fsSL https://gh.io/copilot-install | bash',
+ 'npm install -g @github/copilot',
+ ],
+ docsUrl: 'https://docs.github.com/en/copilot/how-tos/copilot-cli',
+ },
+ kind: 'local-cli',
+ menuKey: 'newCopilotAgent',
+ menuLabelKey: 'newCopilotAgent',
+ resume: { supported: true },
+ title: 'GitHub Copilot',
+ type: 'copilot',
+ },
{
auth: {
docsUrl: 'https://cursor.com/docs/cli/installation',
diff --git a/packages/types/src/agent/heterogeneousIntervention.ts b/packages/types/src/agent/heterogeneousIntervention.ts
index 75b090c7946..5fa5ba111e6 100644
--- a/packages/types/src/agent/heterogeneousIntervention.ts
+++ b/packages/types/src/agent/heterogeneousIntervention.ts
@@ -5,6 +5,7 @@ export type HeterogeneousAgentInterventionKind =
export const HETEROGENEOUS_AGENT_INTERVENTION_PROVIDERS = [
'claude-code',
+ 'copilot',
'cursor',
'devin',
'droid',
diff --git a/packages/types/src/tool/intervention.test.ts b/packages/types/src/tool/intervention.test.ts
index b4008452c77..97948a0b4a3 100644
--- a/packages/types/src/tool/intervention.test.ts
+++ b/packages/types/src/tool/intervention.test.ts
@@ -4,6 +4,10 @@ import { classifyToolInterventionPresentation } from './intervention';
describe('classifyToolInterventionPresentation', () => {
it('renders Devin questions and provider-specific interactions as forms', () => {
+ expect(classifyToolInterventionPresentation('copilot', 'askUserQuestion')).toEqual({
+ interactionKind: 'question',
+ surface: 'form',
+ });
expect(classifyToolInterventionPresentation('devin', 'askUserQuestion')).toEqual({
interactionKind: 'question',
surface: 'form',
diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.ts
index 5f7c84f249b..fac1123c397 100644
--- a/packages/types/src/tool/intervention.ts
+++ b/packages/types/src/tool/intervention.ts
@@ -164,6 +164,7 @@ export type ToolInterventionPresentation = {
const ASK_USER_QUESTION_IDENTIFIERS = new Set([
'claude-code',
+ 'copilot',
'cursor',
'devin',
'droid',
@@ -174,6 +175,7 @@ const ASK_USER_QUESTION_IDENTIFIERS = new Set([
const HETEROGENEOUS_CUSTOM_INTERACTION_IDENTIFIERS = new Set([
'claude-code',
+ 'copilot',
'cursor',
'devin',
'droid',
diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.ts
index 6aa36b54f8c..14d586e4f14 100644
--- a/src/features/ConnectAgent/providers.ts
+++ b/src/features/ConnectAgent/providers.ts
@@ -21,6 +21,7 @@ import {
Cursor,
DeepSeek,
Devin,
+ GithubCopilot,
Grok,
HermesAgent,
Kimi,
@@ -49,6 +50,7 @@ export interface ConnectableProvider {
| typeof DeepSeek
| typeof DroidIcon
| typeof Devin
+ | typeof GithubCopilot
| typeof Grok
| typeof HermesAgent
| typeof Kimi
@@ -82,6 +84,7 @@ const CLI_BRANDS: Record<LocalHeterogeneousAgentType, ConnectableProvider['brand
'claude-code': ClaudeCode,
'codebuddy': CodeBuddy,
'codex': Codex,
+ 'copilot': GithubCopilot,
'cursor': Cursor,
'droid': DroidIcon,
'devin': Devin,
diff --git a/src/features/Conversation/Error/heterogeneous.ts b/src/features/Conversation/Error/heterogeneous.ts
index bafbd1660db..925ee31b9c3 100644
--- a/src/features/Conversation/Error/heterogeneous.ts
+++ b/src/features/Conversation/Error/heterogeneous.ts
@@ -32,6 +32,7 @@ export const isHeterogeneousAgentStatusGuideError = (
agentType === 'claude-code' ||
agentType === 'codebuddy' ||
agentType === 'codex' ||
+ agentType === 'copilot' ||
agentType === 'cursor' ||
agentType === 'droid' ||
agentType === 'devin' ||
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
index 947fa1c84a8..b100ed7c1fa 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts
@@ -16,6 +16,7 @@ import { pickString } from '@lobechat/utils';
import { installMarketplaceAgents } from '@/services/installMarketplaceAgents';
import { topicService } from '@/services/topic';
+const COPILOT_IDENTIFIER = 'copilot';
const CURSOR_IDENTIFIER = 'cursor';
const DEVIN_IDENTIFIER = 'devin';
const DROID_IDENTIFIER = 'droid';
@@ -170,6 +171,7 @@ const findCustomInteractionSubmitHandler = (identifier: string, apiName?: string
*/
const HETERO_CUSTOM_INTERACTION_IDENTIFIERS = new Set<string>([
ClaudeCodeIdentifier,
+ COPILOT_IDENTIFIER,
CURSOR_IDENTIFIER,
DEVIN_IDENTIFIER,
DROID_IDENTIFIER,
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx
index 51e3c0613a5..e6e6538d0ac 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx
@@ -8,6 +8,7 @@ import {
Codex,
Cursor,
Devin,
+ GithubCopilot,
Grok,
Kimi,
OpenCode,
@@ -39,6 +40,10 @@ const GUIDE_PRESENTATION_CONFIG = {
icon: Codex,
translationPrefix: 'codexInstallGuide',
},
+ 'copilot': {
+ icon: GithubCopilot,
+ translationPrefix: 'copilotInstallGuide',
+ },
'cursor': {
icon: Cursor,
translationPrefix: 'cursorInstallGuide',
diff --git a/src/features/Recommendations/actions/heteroAgent.ts b/src/features/Recommendations/actions/heteroAgent.ts
index 71b6935d3b3..e0f33efcc68 100644
--- a/src/features/Recommendations/actions/heteroAgent.ts
+++ b/src/features/Recommendations/actions/heteroAgent.ts
@@ -9,6 +9,7 @@ import {
Codex,
Cursor,
Devin,
+ GithubCopilot,
Grok,
Kimi,
OpenCode,
@@ -25,6 +26,7 @@ const avatarIcons = {
'claude-code': ClaudeCode.Avatar,
'codebuddy': CodeBuddy.Avatar,
'codex': Codex.Avatar,
+ 'copilot': GithubCopilot.Avatar,
'cursor': Cursor.Avatar,
'droid': DroidIcon.Avatar,
'devin': Devin.Avatar,
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
index b3e8ddbf4bb..ecf6c21fbdc 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
@@ -46,17 +46,23 @@ vi.mock('@lobechat/heterogeneous-agents/client', () => ({
icon: () => <span>OpenCode Icon</span>,
title: 'OpenCode',
}
- : type === 'pi'
+ : type === 'copilot'
? {
- defaultCommand: 'pi',
- icon: () => <span>Pi Icon</span>,
- title: 'Pi',
+ defaultCommand: 'copilot',
+ icon: () => <span>GitHub Copilot Icon</span>,
+ title: 'GitHub Copilot',
}
- : {
- defaultCommand: 'codex',
- icon: () => <span>Codex Icon</span>,
- title: 'Codex',
- },
+ : type === 'pi'
+ ? {
+ defaultCommand: 'pi',
+ icon: () => <span>Pi Icon</span>,
+ title: 'Pi',
+ }
+ : {
+ defaultCommand: 'codex',
+ icon: () => <span>Codex Icon</span>,
+ title: 'Codex',
+ },
isRemoteHeterogeneousType: (type: string) => ['openclaw', 'hermes'].includes(type),
isLocalRuntimeHeterogeneousType: (type: string) => type === 'deepseek-harness',
}));
@@ -413,6 +419,32 @@ describe('HeterogeneousAgentStatusCard', () => {
expect(screen.getByText('pi Install Guide')).toBeInTheDocument();
});
+ it('detects GitHub Copilot and shows its install guide when unavailable', async () => {
+ detectHeterogeneousAgentCommand.mockResolvedValue({ available: false });
+
+ const provider = {
+ command: 'copilot',
+ type: 'copilot',
+ } satisfies HeterogeneousProviderConfig;
+
+ render(
+ <MemoryRouter>
+ <HeterogeneousAgentStatusCard provider={provider} />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({
+ agentType: 'copilot',
+ command: 'copilot',
+ });
+ });
+
+ expect(screen.getByText('GitHub Copilot CLI')).toBeInTheDocument();
+ expect(screen.getByText('GitHub Copilot CLI is unavailable')).toBeInTheDocument();
+ expect(screen.getByText('copilot Install Guide')).toBeInTheDocument();
+ });
+
it('shows the embedded Claude Code install guide when the CLI is unavailable', async () => {
detectHeterogeneousAgentCommand.mockResolvedValue({ available: false });
getClaudeAuthStatus.mockResolvedValue(null);
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
index f4894b24dc8..685ebab5d6f 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx
@@ -369,6 +369,7 @@ const CliHeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(
provider.type === 'claude-code' ||
provider.type === 'codebuddy' ||
provider.type === 'codex' ||
+ provider.type === 'copilot' ||
provider.type === 'cursor' ||
provider.type === 'droid' ||
provider.type === 'devin' ||
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index e3585aea60f..940e070ad88 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -20,6 +20,7 @@ import {
resolveHeterogeneousAgentCommand,
type SubagentIntent,
type SubagentRunSnapshot,
+ usesHeterogeneousSessionInitialModel,
} from '@lobechat/heterogeneous-agents';
import {
isEchoedErrorText,
@@ -1950,10 +1951,7 @@ export const executeHeterogeneousAgent = async (
cwd: workingDirectory,
env: sessionEnv,
initialModel:
- (adapterType === 'devin' ||
- adapterType === 'droid' ||
- adapterType === 'trae' ||
- adapterType === 'deepseek-harness') &&
+ usesHeterogeneousSessionInitialModel(adapterType) &&
!providerBindingActive &&
heterogeneousProvider.model &&
heterogeneousProvider.model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTION
diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.ts
index 03f5fe86664..fce564913ca 100644
--- a/src/store/tool/slices/builtin/executors/catalog.ts
+++ b/src/store/tool/slices/builtin/executors/catalog.ts
@@ -22,6 +22,7 @@ import {
claudeCodeExecutor,
codeBuddyExecutor,
codexExecutor,
+ copilotExecutor,
cursorExecutor,
devinExecutor,
droidExecutor,
@@ -53,6 +54,7 @@ export const builtinToolExecutors = [
claudeCodeExecutor,
codeBuddyExecutor,
codexExecutor,
+ copilotExecutor,
cursorExecutor,
droidExecutor,
devinExecutor,
diff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.ts
index 7c0eabfaa43..bb77b5bc7e2 100644
--- a/src/store/tool/slices/builtin/executors/heteroCli.ts
+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts
@@ -106,6 +106,7 @@ export const claudeCodeExecutor = new HeteroCliExecutor('claude-code', new Set([
});
export const codeBuddyExecutor = new HeteroCliExecutor('codebuddy', new Set(['Bash']));
export const codexExecutor = new HeteroCliExecutor('codex', new Set(['command_execution']));
+export const copilotExecutor = new HeteroCliExecutor('copilot', new Set(['execute']));
export const cursorExecutor = new HeteroCliExecutor('cursor', new Set(['shellToolCall']));
// Droid's ACP shell tool name is not a documented protocol guarantee. Keep this
// hook inert rather than guessing and recording unrelated tool calls.