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(hetero-agent): add Codex app-server runtime lab (#17907)

AmAzing-6e2c5b055fcf
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index c2764cf5240..63da6e71bf7 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -50,9 +50,13 @@ import type { AgentStreamEvent, UsageData } from '@lobechat/heterogeneous-agents
import {
AgentStreamPipeline,
buildAgentInput,
+ buildCodexAppServerArgs,
+ buildCodexAppServerInput,
ClaudeAgentSdkSession,
+ CodexAppServerSession,
createFileStoreImageUploader,
ensureClaudeCodeResumeTranscript,
+ getCodexAppServerUnsupportedArgs,
readCodexSessionModel,
resolveCliSpawnPlan,
resolveCodexInitialModel,
@@ -147,7 +151,7 @@ const CODEX_WARN_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+WARN\s+/;
const CODEX_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+(?:DEBUG|ERROR|INFO|TRACE|WARN)\s+/;
const CLI_ERROR_LINE_PATTERN = /^(?:error:|Error:|Usage:)/;
const HETERO_SESSION_COMPLETE_GRACE_MS = 1_000;
-const CLAUDE_CODE_SDK_LAB_ENABLED_VALUES = new Set(['1', 'true', 'yes', 'on']);
+const HETERO_RUNTIME_LAB_ENABLED_VALUES = new Set(['1', 'true', 'yes', 'on']);
const waitForHeteroSessionCompleteGrace = () =>
new Promise<void>((resolve) => setTimeout(resolve, HETERO_SESSION_COMPLETE_GRACE_MS));
@@ -169,6 +173,8 @@ interface StartSessionParams {
resumeSessionId?: string;
/** Run claude-code prompts through the Claude Agent SDK instead of CLI spawn (lab preference) */
useClaudeCodeSdk?: boolean;
+ /** Run Codex prompts through codex app-server instead of one-shot codex exec (lab preference) */
+ useCodexAppServer?: boolean;
}
export interface StartSessionResult {
@@ -269,6 +275,7 @@ export interface SessionInfo {
interface AgentSession {
agentSessionId?: string;
agentType: HeterogeneousCliAgentType;
+ appServerSession?: CodexAppServerSession;
args: string[];
/**
* True when *we* initiated the kill (cancelSession / stopSession / before-quit).
@@ -305,6 +312,7 @@ interface AgentSession {
sdkSession?: ClaudeAgentSdkSession;
sessionId: string;
useClaudeCodeSdk?: boolean;
+ useCodexAppServer?: boolean;
verifiedModel?: string;
verifiedModelContextWindow?: number;
verifiedModelProvider?: string;
@@ -759,11 +767,18 @@ export default class HeterogeneousAgentCtr {
* per-user Labs toggle arrives per session as `session.useClaudeCodeSdk`.
*/
private get isClaudeCodeSdkLabEnabled(): boolean {
- return CLAUDE_CODE_SDK_LAB_ENABLED_VALUES.has(
+ return HETERO_RUNTIME_LAB_ENABLED_VALUES.has(
String(process.env.LOBE_CLAUDE_CODE_SDK ?? '').toLowerCase(),
);
}
+ /** Environment override for development and automated app-server verification. */
+ private get isCodexAppServerLabEnabled(): boolean {
+ return HETERO_RUNTIME_LAB_ENABLED_VALUES.has(
+ String(process.env.LOBE_CODEX_APP_SERVER ?? '').toLowerCase(),
+ );
+ }
+
private buildSessionSpawnEnv(session: AgentSession): NodeJS.ProcessEnv {
// Forward the user's proxy settings to the CLI/SDK subprocess. The
// main-process undici dispatcher doesn't reach child processes — they need
@@ -1158,6 +1173,7 @@ export default class HeterogeneousAgentCtr {
sessionId,
resumeSessionId: params.resumeSessionId,
useClaudeCodeSdk: params.useClaudeCodeSdk,
+ useCodexAppServer: params.useCodexAppServer,
});
logger.info('Session created:', { agentType, sessionId });
@@ -1174,6 +1190,7 @@ export default class HeterogeneousAgentCtr {
async sendPrompt(params: SendPromptParams): Promise<void> {
const session = this.sessions.get(params.sessionId);
if (!session) throw new Error(`Session not found: ${params.sessionId}`);
+ session.cancelledByUs = false;
const preflightError = await this.getSpawnPreflightError(session);
if (preflightError) {
@@ -1221,6 +1238,22 @@ export default class HeterogeneousAgentCtr {
return this.sendPromptWithClaudeSdk(params, session);
}
+ if (
+ session.agentType === 'codex' &&
+ (session.useCodexAppServer || this.isCodexAppServerLabEnabled)
+ ) {
+ const unsupportedArgs = getCodexAppServerUnsupportedArgs(session.args, {
+ resume: !!session.agentSessionId,
+ });
+ if (unsupportedArgs.length === 0) {
+ return this.sendPromptWithCodexAppServer(params, session);
+ }
+ logger.warn('Falling back to codex exec because app-server cannot preserve CLI args:', {
+ sessionId: session.sessionId,
+ unsupportedArgs,
+ });
+ }
+
// Stand up the AskUserQuestion MCP bridge for claude-code prompts BEFORE
// building the spawn plan so the driver can wire the temp config path
// into `--mcp-config`. Codex / future agents skip this entirely.
@@ -1449,6 +1482,125 @@ export default class HeterogeneousAgentCtr {
}
}
+ private async sendPromptWithCodexAppServer(
+ 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,
+ prompt: params.prompt,
+ systemContext: params.systemContext,
+ });
+ let inputPlan;
+ try {
+ inputPlan = await buildAgentInput('codex', promptInput, { cacheDir: this.fileCacheDir });
+ } catch (error) {
+ logger.error('Failed to prepare Codex app-server input:', error);
+ throw new Error(
+ `Failed to attach image(s) to Codex app-server: ${this.getErrorMessage(error) || 'Unknown error'}`,
+ { cause: error },
+ );
+ }
+
+ const input = buildCodexAppServerInput(inputPlan);
+ const appServerArgs = buildCodexAppServerArgs(session.args);
+ const initialModel = await resolveCodexInitialModel({ args: session.args, env: spawnEnv });
+ if (initialModel?.model) {
+ session.model = initialModel.model;
+ session.modelSource = initialModel.source;
+ }
+ const initialCumulativeUsage = session.agentSessionId
+ ? (await readCodexSessionModel(session.agentSessionId, { env: spawnEnv }))?.cumulativeUsage
+ : undefined;
+ const inputPayload = `${JSON.stringify(input)}\n`;
+ const traceSession = await this.createCliTraceSession({
+ cliArgs: appServerArgs,
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: inputPayload,
+ });
+ void this.writeCliTraceFile(traceSession, 'stdin.txt', inputPayload);
+
+ const appServerSession = new CodexAppServerSession({
+ args: session.args,
+ clientVersion: electronApp.getVersion(),
+ commandPath,
+ cwd,
+ env: spawnEnv,
+ initialCumulativeUsage,
+ initialModel: session.model,
+ input,
+ onEvents: async (events) => {
+ for (const event of events) {
+ this.broadcast('heteroAgentEvent', {
+ event,
+ sessionId: session.sessionId,
+ });
+ }
+ },
+ onModel: (model) => {
+ session.model = model;
+ session.modelSource = 'codex-app-server';
+ },
+ 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,
+ resumeSessionId: session.agentSessionId,
+ sessionId: session.sessionId,
+ });
+ session.appServerSession = appServerSession;
+
+ logger.info('Starting Codex app-server session:', {
+ commandPath,
+ cwd,
+ sessionId: session.sessionId,
+ });
+
+ try {
+ await appServerSession.run();
+ void this.writeCliTraceJson(traceSession, 'exit.json', {
+ finishedAt: new Date().toISOString(),
+ transport: 'codex-app-server',
+ });
+ await this.flushCliTrace(traceSession);
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ } catch (error) {
+ logger.error('Codex app-server 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: 'codex-app-server',
+ });
+ 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 {
+ if (session.appServerSession === appServerSession) session.appServerSession = undefined;
+ }
+ }
+
private async verifyCodexSessionModel({
env,
pipeline,
@@ -1876,6 +2028,15 @@ export default class HeterogeneousAgentCtr {
if (!session) return;
session.cancelledByUs = true;
+ if (session.appServerSession) {
+ try {
+ await session.appServerSession.interrupt();
+ } catch (error) {
+ logger.warn('Codex app-server interrupt failed; closing session:', error);
+ session.appServerSession.close();
+ }
+ return;
+ }
if (session.sdkSession) {
session.sdkSession.close();
return;
@@ -1900,6 +2061,11 @@ export default class HeterogeneousAgentCtr {
const session = this.sessions.get(params.sessionId);
if (!session) return;
+ if (session.appServerSession) {
+ session.cancelledByUs = true;
+ session.appServerSession.close();
+ }
+
if (session.sdkSession) {
session.cancelledByUs = true;
session.sdkSession.close();
@@ -1972,6 +2138,10 @@ export default class HeterogeneousAgentCtr {
electronApp.on('before-quit', () => {
this.unlinkPendingInterventionConfigsSync();
for (const [, session] of this.sessions) {
+ if (session.appServerSession) {
+ session.cancelledByUs = true;
+ session.appServerSession.close();
+ }
if (session.sdkSession) {
session.cancelledByUs = true;
session.sdkSession.close();
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 06fcca50daa..6f58d9331bc 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -34,6 +34,7 @@ vi.mock('electron', () => ({
BrowserWindow: { getAllWindows: () => mockGetAllWindows() },
app: {
getAppPath: vi.fn(() => '/fake/appPath'),
+ getVersion: vi.fn(() => '1.0.0-test'),
getPath: vi.fn((name: string) => (name === 'desktop' ? FAKE_DESKTOP_PATH : `/fake/${name}`)),
isPackaged: false,
on: vi.fn(),
@@ -51,9 +52,18 @@ vi.mock('@/utils/logger', () => ({
}),
}));
-const { claudeSdkSessionCloseMock, claudeSdkSessionConstructMock } = vi.hoisted(() => ({
+const {
+ claudeSdkSessionCloseMock,
+ claudeSdkSessionConstructMock,
+ codexAppServerCloseMock,
+ codexAppServerConstructMock,
+ codexAppServerInterruptMock,
+} = vi.hoisted(() => ({
claudeSdkSessionCloseMock: vi.fn(),
claudeSdkSessionConstructMock: vi.fn(),
+ codexAppServerCloseMock: vi.fn(),
+ codexAppServerConstructMock: vi.fn(),
+ codexAppServerInterruptMock: vi.fn(),
}));
vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
@@ -104,9 +114,53 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
}
}
+ class MockCodexAppServerSession {
+ constructor(private readonly options: any) {
+ codexAppServerConstructMock(options);
+ }
+
+ close() {
+ codexAppServerCloseMock();
+ }
+
+ async interrupt() {
+ codexAppServerInterruptMock();
+ }
+
+ async run() {
+ const now = Date.now();
+ this.options.onRuntimeStatus({
+ activeTasks: [],
+ lastEventAt: now,
+ operationId: this.options.operationId,
+ sessionId: this.options.sessionId,
+ state: 'running',
+ transport: 'codex-app-server',
+ });
+ this.options.onSessionId('thread_app_server');
+ await this.options.onEvents([
+ {
+ data: { reason: 'complete', transport: 'codex-app-server' },
+ operationId: this.options.operationId,
+ stepIndex: 0,
+ timestamp: now,
+ type: 'agent_runtime_end',
+ },
+ ]);
+ this.options.onRuntimeStatus({
+ activeTasks: [],
+ lastEventAt: now,
+ sessionId: this.options.sessionId,
+ state: 'closed',
+ transport: 'codex-app-server',
+ });
+ }
+ }
+
return {
...actual,
ClaudeAgentSdkSession: MockClaudeAgentSdkSession,
+ CodexAppServerSession: MockCodexAppServerSession,
};
});
@@ -195,21 +249,29 @@ const getFlagValues = (args: string[], flag: string) =>
describe('HeterogeneousAgentCtr', () => {
let appStoragePath: string;
let originalClaudeSdkLabEnv: string | undefined;
+ let originalCodexAppServerLabEnv: string | undefined;
beforeEach(async () => {
originalClaudeSdkLabEnv = process.env.LOBE_CLAUDE_CODE_SDK;
+ originalCodexAppServerLabEnv = process.env.LOBE_CODEX_APP_SERVER;
appStoragePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-hetero-'));
consumeCodexRateLimitResetCreditMock.mockReset();
fetchCodexQuotaMock.mockReset();
claudeSdkSessionCloseMock.mockReset();
claudeSdkSessionConstructMock.mockReset();
+ codexAppServerCloseMock.mockReset();
+ codexAppServerConstructMock.mockReset();
+ codexAppServerInterruptMock.mockReset();
mockGetAllWindows.mockReset();
delete process.env.LOBE_CLAUDE_CODE_SDK;
+ delete process.env.LOBE_CODEX_APP_SERVER;
});
afterEach(async () => {
if (originalClaudeSdkLabEnv === undefined) delete process.env.LOBE_CLAUDE_CODE_SDK;
else process.env.LOBE_CLAUDE_CODE_SDK = originalClaudeSdkLabEnv;
+ if (originalCodexAppServerLabEnv === undefined) delete process.env.LOBE_CODEX_APP_SERVER;
+ else process.env.LOBE_CODEX_APP_SERVER = originalCodexAppServerLabEnv;
await rm(appStoragePath, { force: true, recursive: true });
});
@@ -988,6 +1050,67 @@ describe('HeterogeneousAgentCtr', () => {
expect(writes).toEqual([prompt]);
});
+ it('uses Codex app-server lab instead of spawning codex exec', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ args: ['--model', 'gpt-5.5-codex'],
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'stream this', sessionId });
+
+ expect(spawnCalls).toHaveLength(0);
+ expect(codexAppServerConstructMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: ['--model', 'gpt-5.5-codex'],
+ clientVersion: '1.0.0-test',
+ commandPath: 'codex',
+ cwd: FAKE_DESKTOP_PATH,
+ input: [{ text: 'stream this', text_elements: [], type: 'text' }],
+ operationId: 'op-test',
+ }),
+ );
+ await expect(ctr.getSessionInfo({ sessionId })).resolves.toEqual({
+ agentSessionId: 'thread_app_server',
+ });
+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
+ });
+
+ it('falls back to codex exec when app-server cannot preserve a CLI argument', async () => {
+ // Fallback path still spawns `codex exec`; without a fake process, sendPrompt hangs.
+ const { proc } = createFakeProc();
+ nextFakeProc = proc;
+
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ args: ['--profile', 'work'],
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'preserve profile', sessionId });
+
+ expect(codexAppServerConstructMock).not.toHaveBeenCalled();
+ expect(spawnCalls).toHaveLength(1);
+ expect(spawnCalls[0].args).toEqual(expect.arrayContaining(['--profile', 'work']));
+ });
+
it('places system context before the user prompt in codex stdin', async () => {
const { writes } = await runSendPrompt('user task', {}, [], {
systemContext: 'selected code context',
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 9c84e48c88f..8657262b3d4 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -5,7 +5,9 @@ import { AiAgentService } from '../index';
const {
mockDeviceFindByDeviceId,
mockDeviceFindWorkspaceDeviceById,
+ mockBuildRemoteDeviceHeteroContext,
mockDispatchAgentRun,
+ mockGetHeterogeneousResumeSessionId,
mockMessageCreate,
mockResolveAttachmentsByFileIds,
mockSpawnHeteroSandbox,
@@ -13,9 +15,11 @@ const {
mockPublishAgentRuntimeInit,
mockPublishAgentRuntimeEnd,
} = vi.hoisted(() => ({
+ mockBuildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),
mockDeviceFindByDeviceId: vi.fn(),
mockDeviceFindWorkspaceDeviceById: vi.fn(),
mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),
+ mockGetHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
mockIngestAttachment: vi.fn(),
mockMessageCreate: vi.fn(),
mockPublishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),
@@ -143,7 +147,7 @@ vi.mock('@/server/services/market', () => ({
vi.mock('@/server/services/heterogeneousAgent', () => ({
HeterogeneousAgentService: vi.fn().mockImplementation(() => ({
- getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
})),
}));
@@ -190,7 +194,7 @@ vi.mock('@/server/services/deviceGateway', () => ({
}));
vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () => ({
- buildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),
+ buildRemoteDeviceHeteroContext: mockBuildRemoteDeviceHeteroContext,
}));
describe('AiAgentService.execAgent - hetero early-exit file attachments', () => {
@@ -207,6 +211,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });
mockSpawnHeteroSandbox.mockResolvedValue(undefined);
mockDispatchAgentRun.mockResolvedValue({ success: true });
+ mockGetHeterogeneousResumeSessionId.mockResolvedValue(undefined);
mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });
mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);
mockIngestAttachment.mockReset();
@@ -371,6 +376,30 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect(dispatchParams.args).toEqual(['--model', 'opus', '--effort', 'high']);
});
+ it('does not reinject the device workspace note when resuming a native session', async () => {
+ mockGetHeterogeneousResumeSessionId.mockResolvedValue('native-session-existing');
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ } as any;
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Continue on my device',
+ });
+
+ expect(mockBuildRemoteDeviceHeteroContext).toHaveBeenCalledWith(
+ expect.objectContaining({ cwd: undefined }),
+ );
+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resumeSessionId: 'native-session-existing',
+ systemContext: 'device context',
+ }),
+ );
+ });
+
it('dispatches OpenCode to a bound device with its model args', async () => {
heteroAgentConfig.model = 'opencode';
heteroAgentConfig.provider = 'opencode';
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index c48bedba024..586121e431b 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -2469,7 +2469,9 @@ export class AiAgentService {
const deviceSystemContext = buildRemoteDeviceHeteroContext({
agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
conversationHistory,
- cwd: deviceCwd,
+ // The native CLI session already knows its cwd. Keep the explanatory workspace note
+ // on the first turn only so persistent resumed sessions do not accumulate duplicates.
+ cwd: resumeSessionId ? undefined : deviceCwd,
});
const result = await deviceGateway.dispatchAgentRun({
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index 047fa7e796c..763a5dc1dc8 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -10,6 +10,8 @@
"features.assistantMessageGroup.title": "Agent Message Grouping",
"features.claudeCodeSdk.desc": "Run Claude Code sessions through the Claude Agent SDK instead of spawning the CLI. Enables richer streaming and session control.",
"features.claudeCodeSdk.title": "Claude Code SDK Runtime",
+ "features.codexAppServer.desc": "Run Codex sessions through the local app-server instead of one-shot CLI processes. Enables token streaming and native turn control.",
+ "features.codexAppServer.title": "Codex App Server Runtime",
"features.groupChat.desc": "Enable multi-agent group chat coordination.",
"features.groupChat.title": "Group Chat (Multi-Agent)",
"features.heteroSessionImport.desc": "Add an \"Import Local Agent Sessions\" entry to the topic list menu: scan local Claude Code / Codex CLI transcripts and import them as topics, with incremental sync on re-import.",
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index 61ec9622886..905f9b0f4d2 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -10,6 +10,8 @@
"features.assistantMessageGroup.title": "代理消息分组",
"features.claudeCodeSdk.desc": "通过 Claude Agent SDK 运行 Claude Code 会话,替代 CLI 进程方式,提供更丰富的流式输出与会话控制。",
"features.claudeCodeSdk.title": "Claude Code SDK 运行时",
+ "features.codexAppServer.desc": "通过本地 App Server 运行 Codex 会话,替代一次性的 CLI 进程,提供 Token 流式输出与原生 Turn 控制。",
+ "features.codexAppServer.title": "Codex App Server 运行时",
"features.groupChat.desc": "启用多代理协同群聊功能。",
"features.groupChat.title": "群聊(多代理)",
"features.heteroSessionImport.desc": "在话题列表菜单中新增「导入本地 Agent 会话」入口:扫描本地 Claude Code / Codex CLI 的会话记录并导入为话题,重复导入时增量同步新消息。",
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index ced71538b5a..8ceabb7c796 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -153,5 +153,5 @@ export interface HeterogeneousAgentRuntimeStatus {
sessionId: string;
staleDeadlineAt?: number;
state: HeterogeneousAgentRuntimeState;
- transport: 'claude-sdk' | 'cli-spawn';
+ transport: 'claude-sdk' | 'cli-spawn' | 'codex-app-server';
}
diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.ts
index 69a43a4a33d..814909c49d4 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts
@@ -48,6 +48,106 @@ describe('CodexAdapter', () => {
});
});
+ it('streams app-server agent message deltas without duplicating the completed item', () => {
+ const adapter = new CodexAdapter();
+
+ adapter.adapt({ type: 'turn.started' });
+ const first = adapter.adapt({
+ delta: 'hello ',
+ item_id: 'item_0',
+ type: 'item.agent_message.delta',
+ });
+ const second = adapter.adapt({
+ delta: 'from app-server',
+ item_id: 'item_0',
+ type: 'item.agent_message.delta',
+ });
+ const completed = adapter.adapt({
+ item: {
+ id: 'item_0',
+ text: 'hello from app-server',
+ type: 'agent_message',
+ },
+ type: 'item.completed',
+ });
+
+ expect([...first, ...second].map((event) => event.data?.content).filter(Boolean)).toEqual([
+ 'hello ',
+ 'from app-server',
+ ]);
+ expect(completed).toEqual([]);
+ });
+
+ it('preserves whitespace-only app-server text deltas', () => {
+ const adapter = new CodexAdapter();
+ adapter.adapt({ type: 'turn.started' });
+
+ const events = adapter.adapt({
+ delta: ' ',
+ item_id: 'item_0',
+ type: 'item.agent_message.delta',
+ });
+
+ expect(events).toMatchObject([
+ { data: { chunkType: 'text', content: ' ' }, type: 'stream_chunk' },
+ ]);
+ });
+
+ it('streams cumulative command output snapshots before the final result', () => {
+ const adapter = new CodexAdapter();
+ adapter.adapt({ type: 'turn.started' });
+ adapter.adapt({
+ item: {
+ command: 'printf hello',
+ id: 'command-1',
+ status: 'in_progress',
+ type: 'command_execution',
+ },
+ type: 'item.started',
+ });
+
+ const first = adapter.adapt({
+ delta: 'hel',
+ item_id: 'command-1',
+ type: 'item.command_execution.output_delta',
+ });
+ const second = adapter.adapt({
+ delta: 'lo',
+ item_id: 'command-1',
+ type: 'item.command_execution.output_delta',
+ });
+
+ expect(first).toMatchObject([
+ {
+ data: {
+ chunkType: 'tool_state',
+ pluginState: { output: 'hel', stdout: 'hel' },
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ toolCallId: 'command-1',
+ },
+ type: 'stream_chunk',
+ },
+ ]);
+ expect(second[0]).toMatchObject({
+ data: { pluginState: { output: 'hello' }, snapshotSeq: 2 },
+ type: 'stream_chunk',
+ });
+
+ const truncated = adapter.adapt({
+ delta: 'x'.repeat(25_001),
+ item_id: 'command-1',
+ type: 'item.command_execution.output_delta',
+ });
+ const afterTruncation = adapter.adapt({
+ delta: 'not retained',
+ item_id: 'command-1',
+ type: 'item.command_execution.output_delta',
+ });
+ expect(truncated[0].data.pluginState.output).toContain('[Output truncated:');
+ expect(afterTruncation).toEqual([]);
+ });
+
it('emits model metadata when the host configures the Codex session', () => {
const adapter = new CodexAdapter();
@@ -902,6 +1002,35 @@ describe('CodexAdapter', () => {
expect(adapter.flush()).toEqual([]);
});
+ it('marks an interrupted turn as cancelled instead of successful', () => {
+ const adapter = new CodexAdapter();
+ adapter.adapt({ type: 'turn.started' });
+ adapter.adapt({
+ item: {
+ command: 'sleep 30',
+ id: 'command-interrupted',
+ status: 'in_progress',
+ type: 'command_execution',
+ },
+ type: 'item.started',
+ });
+
+ const terminal = adapter.adapt({ reason: 'interrupted', type: 'turn.completed' });
+
+ expect(terminal).toContainEqual(
+ expect.objectContaining({
+ data: { isSuccess: false, toolCallId: 'command-interrupted' },
+ type: 'tool_end',
+ }),
+ );
+ expect(terminal).toContainEqual(
+ expect.objectContaining({
+ data: { reason: 'interrupted' },
+ type: 'agent_runtime_end',
+ }),
+ );
+ });
+
it('ignores todo item.updated events that have no active started tool', () => {
const adapter = new CodexAdapter();
diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.ts
index 508258e6849..80631ec9802 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.ts
@@ -53,6 +53,12 @@ interface TodoListPluginItem {
text: string;
}
+interface StreamedCommandOutput {
+ prefix: string;
+ totalLength: number;
+ truncated: boolean;
+}
+
interface CodexTodoListItem extends CodexBaseItem {
items?: CodexTodoListEntry[];
}
@@ -799,6 +805,8 @@ export class CodexAdapter implements AgentEventAdapter {
private hasTextInCurrentStep = false;
private hasToolActivitySinceAgentMessage = false;
+ private streamedAgentMessageText = new Map<string, string>();
+ private streamedCommandOutput = new Map<string, StreamedCommandOutput>();
private deferredTodoCompletions = new Map<string, CodexTodoListItem>();
private pendingTodoToolCalls = new Set<string>();
private pendingToolCalls = new Set<string>();
@@ -845,6 +853,12 @@ export class CodexAdapter implements AgentEventAdapter {
case 'item.updated': {
return this.handleItemUpdated(raw.item);
}
+ case 'item.agent_message.delta': {
+ return this.handleAgentMessageDelta(raw);
+ }
+ case 'item.command_execution.output_delta': {
+ return this.handleCommandOutputDelta(raw);
+ }
case 'item.completed': {
return this.handleItemCompleted(raw.item);
}
@@ -870,7 +884,8 @@ export class CodexAdapter implements AgentEventAdapter {
const cumulativeUsage = toCodexUsageData(raw.usage);
const usage = toTurnUsageFromCumulative(cumulativeUsage, this.lastCumulativeUsage);
if (cumulativeUsage) this.lastCumulativeUsage = cumulativeUsage;
- const events = this.drainPendingToolEndEvents('success');
+ const interrupted = raw.reason === 'interrupted';
+ const events = this.drainPendingToolEndEvents(interrupted ? 'interrupted' : 'success');
if (!hadPendingEmptyTurn && (usage || model)) {
const data: StepCompleteData = {
@@ -889,7 +904,7 @@ export class CodexAdapter implements AgentEventAdapter {
} else if (this.started) {
events.push(this.makeEvent('visible_output_end', {}));
}
- events.push(this.makeEvent('agent_runtime_end', {}));
+ events.push(this.makeEvent('agent_runtime_end', interrupted ? { reason: 'interrupted' } : {}));
return events;
}
@@ -946,6 +961,8 @@ export class CodexAdapter implements AgentEventAdapter {
this.currentAgentMessageItemId = undefined;
this.hasTextInCurrentStep = false;
this.hasToolActivitySinceAgentMessage = false;
+ this.streamedAgentMessageText.clear();
+ this.streamedCommandOutput.clear();
this.resetStepToolCalls();
if (!this.started) {
@@ -970,16 +987,102 @@ export class CodexAdapter implements AgentEventAdapter {
const events = [...this.consumePendingTurnStart(), ...this.emitToolChunk(tool)];
if (isTodoListItem(item)) {
this.pendingTodoToolCalls.add(tool.id);
- events.push(this.createToolStateEvent(item));
+ events.push(this.createToolStateEvent(item.id, synthesizeTodoListPluginState(item)));
}
return events;
}
private handleItemUpdated(item: any): HeterogeneousAgentEvent[] {
- if (!item?.id || !isTodoListItem(item) || !this.pendingToolCalls.has(item.id)) return [];
+ if (!item?.id || !this.pendingToolCalls.has(item.id)) return [];
+
+ if (isTodoListItem(item)) {
+ return [this.createToolStateEvent(item.id, synthesizeTodoListPluginState(item))];
+ }
+ if (isFileChangeItem(item)) {
+ const pluginState = synthesizeFileChangePluginState(item);
+ return pluginState ? [this.createToolStateEvent(item.id, pluginState)] : [];
+ }
+
+ return [];
+ }
+
+ private handleAgentMessageDelta(raw: any): HeterogeneousAgentEvent[] {
+ const itemId = getStringValue(raw?.item_id) || getStringValue(raw?.itemId);
+ const delta = typeof raw?.delta === 'string' ? raw.delta : undefined;
+ if (!itemId || !delta) return [];
+
+ this.streamedAgentMessageText.set(
+ itemId,
+ `${this.streamedAgentMessageText.get(itemId) ?? ''}${delta}`,
+ );
+ return this.handleAgentMessageContent(itemId, delta);
+ }
+
+ private handleAgentMessageContent(itemId: string | undefined, content: string) {
+ const events: HeterogeneousAgentEvent[] = this.consumePendingTurnStart();
+ const shouldStartNewStep =
+ this.hasToolActivitySinceAgentMessage &&
+ !!itemId &&
+ itemId !== this.currentAgentMessageItemId;
+
+ if (shouldStartNewStep) {
+ this.stepIndex += 1;
+ this.resetStepToolCalls();
+ this.hasTextInCurrentStep = false;
+ events.push(this.makeEvent('stream_end', {}));
+ events.push(this.makeEvent('stream_start', this.getStreamStartData({ newStep: true })));
+ }
- return [this.createToolStateEvent(item)];
+ const chunk =
+ this.hasTextInCurrentStep && itemId !== this.currentAgentMessageItemId
+ ? `\n\n${content}`
+ : content;
+
+ this.currentAgentMessageItemId = itemId;
+ this.hasTextInCurrentStep = true;
+ this.hasToolActivitySinceAgentMessage = false;
+ events.push(
+ this.makeEvent('stream_chunk', {
+ chunkType: 'text',
+ content: chunk,
+ }),
+ );
+
+ return events;
+ }
+
+ private handleCommandOutputDelta(raw: any): HeterogeneousAgentEvent[] {
+ const itemId = getStringValue(raw?.item_id) || getStringValue(raw?.itemId);
+ const delta = typeof raw?.delta === 'string' ? raw.delta : undefined;
+ if (!itemId || !delta || !this.pendingToolCalls.has(itemId)) return [];
+
+ const previous = this.streamedCommandOutput.get(itemId) ?? {
+ prefix: '',
+ totalLength: 0,
+ truncated: false,
+ };
+ const remaining = Math.max(0, CODEX_COMMAND_OUTPUT_MAX_LENGTH - previous.prefix.length);
+ let appended = delta.slice(0, remaining);
+ const lastCharCode = appended.charCodeAt(appended.length - 1);
+ if (lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff) appended = appended.slice(0, -1);
+
+ const prefix = previous.prefix + appended;
+ const totalLength = previous.totalLength + delta.length;
+ const truncated = totalLength > prefix.length;
+ this.streamedCommandOutput.set(itemId, { prefix, totalLength, truncated });
+ if (previous.truncated) return [];
+
+ const snapshot = truncated
+ ? `${prefix}\n\n[Output truncated: ${totalLength - prefix.length} characters omitted. Original length: ${totalLength} characters]`
+ : prefix;
+ return [
+ this.createToolStateEvent(itemId, {
+ isBackground: false,
+ output: snapshot,
+ stdout: snapshot,
+ }),
+ ];
}
private handleItemCompleted(item: any): HeterogeneousAgentEvent[] {
@@ -988,39 +1091,20 @@ export class CodexAdapter implements AgentEventAdapter {
if (item.type === 'agent_message') {
if (!item.text) return [];
- const events: HeterogeneousAgentEvent[] = this.consumePendingTurnStart();
- const shouldStartNewStep =
- this.hasToolActivitySinceAgentMessage &&
- !!item.id &&
- item.id !== this.currentAgentMessageItemId;
-
- if (shouldStartNewStep) {
- this.stepIndex += 1;
- this.resetStepToolCalls();
- this.hasTextInCurrentStep = false;
- events.push(this.makeEvent('stream_end', {}));
- events.push(this.makeEvent('stream_start', this.getStreamStartData({ newStep: true })));
+ const streamedText = item.id ? this.streamedAgentMessageText.get(item.id) : undefined;
+ if (item.id) this.streamedAgentMessageText.delete(item.id);
+ if (streamedText !== undefined) {
+ const remainingText = item.text.startsWith(streamedText)
+ ? item.text.slice(streamedText.length)
+ : '';
+ return remainingText ? this.handleAgentMessageContent(item.id, remainingText) : [];
}
- const content =
- this.hasTextInCurrentStep && item.id !== this.currentAgentMessageItemId
- ? `\n\n${item.text}`
- : item.text;
-
- this.currentAgentMessageItemId = item.id;
- this.hasTextInCurrentStep = true;
- this.hasToolActivitySinceAgentMessage = false;
- events.push(
- this.makeEvent('stream_chunk', {
- chunkType: 'text',
- content,
- }),
- );
-
- return events;
+ return this.handleAgentMessageContent(item.id, item.text);
}
if (!item.id) return [];
+ this.streamedCommandOutput.delete(item.id);
// Codex emits the same status-less todo completion before both a successful
// turn completion and an interrupted process exit. Keep it pending until
@@ -1113,21 +1197,23 @@ export class CodexAdapter implements AgentEventAdapter {
this.pendingToolCalls.clear();
this.pendingToolCallStepIndex.clear();
this.deferredTodoCompletions.clear();
+ this.streamedCommandOutput.clear();
return events;
}
- private createToolStateEvent(item: CodexTodoListItem): HeterogeneousAgentEvent {
- const pluginState = synthesizeTodoListPluginState(item);
-
- const snapshotSeq = (this.toolStateSnapshotSeqByCallId.get(item.id) ?? 0) + 1;
- this.toolStateSnapshotSeqByCallId.set(item.id, snapshotSeq);
+ private createToolStateEvent(
+ toolCallId: string,
+ pluginState: Record<string, unknown>,
+ ): HeterogeneousAgentEvent {
+ const snapshotSeq = (this.toolStateSnapshotSeqByCallId.get(toolCallId) ?? 0) + 1;
+ this.toolStateSnapshotSeqByCallId.set(toolCallId, snapshotSeq);
return this.makeEvent('stream_chunk', {
chunkType: 'tool_state',
pluginState,
snapshotMode: 'replace',
snapshotSeq,
- toolCallId: item.id,
+ toolCallId,
} satisfies ToolStateChunkData);
}
diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
index e37ed7a636d..92ca51f5d8c 100644
--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
@@ -117,7 +117,7 @@ export interface HeterogeneousAgentRuntimeStatus {
sessionId: string;
staleDeadlineAt?: number;
state: HeterogeneousAgentRuntimeState;
- transport: 'claude-sdk' | 'cli-spawn';
+ transport: 'claude-sdk' | 'cli-spawn' | 'codex-app-server';
}
export interface ClaudeAgentSdkSessionOptions {
diff --git a/packages/heterogeneous-agents/src/spawn/codexAppServerSession.test.ts b/packages/heterogeneous-agents/src/spawn/codexAppServerSession.test.ts
new file mode 100644
index 00000000000..712623dc410
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/codexAppServerSession.test.ts
@@ -0,0 +1,615 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ buildCodexAppServerArgs,
+ buildCodexAppServerInput,
+ buildCodexAppServerThreadParams,
+ CodexAppServerSession,
+ getCodexAppServerUnsupportedArgs,
+} from './codexAppServerSession';
+
+const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));
+
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return { ...actual, spawn: spawnMock };
+});
+
+interface RpcMessage {
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown>;
+}
+
+const createAppServerProcess = ({ autoComplete = true, requestApproval = false } = {}) => {
+ const child = new EventEmitter() as any;
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ const requests: RpcMessage[] = [];
+
+ const send = (message: Record<string, unknown>) => {
+ stdout.write(`${JSON.stringify(message)}\n`);
+ };
+
+ child.pid = 987_654;
+ child.killed = false;
+ child.stdout = stdout;
+ child.stderr = stderr;
+ child.kill = vi.fn(() => {
+ child.killed = true;
+ return true;
+ });
+ child.stdin = {
+ on: vi.fn(),
+ write: vi.fn((chunk: string) => {
+ const message = JSON.parse(chunk.trim()) as RpcMessage;
+ requests.push(message);
+
+ queueMicrotask(() => {
+ switch (message.method) {
+ case 'initialize': {
+ send({ id: message.id, result: { userAgent: 'codex-test' } });
+ return;
+ }
+ case 'thread/start':
+ case 'thread/resume': {
+ send({
+ id: message.id,
+ result: { model: 'gpt-5.5-codex', thread: { id: 'thread-1' } },
+ });
+ return;
+ }
+ case 'turn/start': {
+ send({ id: message.id, result: { turn: { id: 'turn-1' } } });
+ if (requestApproval) {
+ send({
+ id: 'approval-1',
+ method: 'item/commandExecution/requestApproval',
+ params: {
+ command: 'pwd',
+ itemId: 'command-1',
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ }
+ send({
+ method: 'turn/started',
+ params: { threadId: 'thread-1', turn: { id: 'turn-1', status: 'inProgress' } },
+ });
+ if (!autoComplete) return;
+ send({
+ method: 'item/started',
+ params: {
+ item: {
+ aggregatedOutput: null,
+ command: 'pwd',
+ exitCode: null,
+ id: 'command-1',
+ status: 'inProgress',
+ type: 'commandExecution',
+ },
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/commandExecution/outputDelta',
+ params: {
+ delta: '/work',
+ itemId: 'command-1',
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/commandExecution/outputDelta',
+ params: {
+ delta: 'space\n',
+ itemId: 'command-1',
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/completed',
+ params: {
+ item: {
+ aggregatedOutput: '/workspace\n',
+ command: 'pwd',
+ exitCode: 0,
+ id: 'command-1',
+ status: 'completed',
+ type: 'commandExecution',
+ },
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'turn/plan/updated',
+ params: {
+ explanation: null,
+ plan: [
+ { status: 'completed', step: 'Inspect' },
+ { status: 'inProgress', step: 'Implement' },
+ ],
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/started',
+ params: {
+ item: {
+ changes: [],
+ id: 'file-1',
+ status: 'inProgress',
+ type: 'fileChange',
+ },
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'turn/diff/updated',
+ params: {
+ diff: '--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-old\n+new\n',
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/completed',
+ params: {
+ item: {
+ changes: [
+ {
+ diff: '@@ -1 +1 @@\n-old\n+new\n',
+ kind: { type: 'update' },
+ path: 'a.ts',
+ },
+ ],
+ id: 'file-1',
+ status: 'completed',
+ type: 'fileChange',
+ },
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/agentMessage/delta',
+ params: {
+ delta: 'hello ',
+ itemId: 'message-1',
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/agentMessage/delta',
+ params: {
+ delta: 'world',
+ itemId: 'message-1',
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'item/completed',
+ params: {
+ item: {
+ id: 'message-1',
+ text: 'hello world',
+ type: 'agentMessage',
+ },
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'thread/tokenUsage/updated',
+ params: {
+ threadId: 'thread-1',
+ tokenUsage: {
+ total: {
+ cachedInputTokens: 2,
+ inputTokens: 10,
+ outputTokens: 4,
+ reasoningOutputTokens: 1,
+ totalTokens: 14,
+ },
+ },
+ turnId: 'turn-1',
+ },
+ });
+ send({
+ method: 'turn/completed',
+ params: {
+ threadId: 'thread-1',
+ turn: { id: 'turn-1', status: 'completed' },
+ },
+ });
+ return;
+ }
+ case 'turn/interrupt': {
+ send({ id: message.id, result: {} });
+ send({
+ method: 'turn/completed',
+ params: {
+ threadId: 'thread-1',
+ turn: { id: 'turn-1', status: 'interrupted' },
+ },
+ });
+ }
+ }
+ });
+ return true;
+ }),
+ };
+
+ return { child, requests, send };
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ spawnMock.mockReset();
+});
+
+describe('CodexAppServerSession', () => {
+ it('maps app-server notifications through the existing Codex event pipeline', async () => {
+ const { child, requests } = createAppServerProcess();
+ spawnMock.mockReturnValue(child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const events: any[] = [];
+ const statuses: any[] = [];
+ const sessionIds: string[] = [];
+
+ const session = new CodexAppServerSession({
+ args: [
+ '--model',
+ 'gpt-5.5-codex',
+ '--cd',
+ 'nested',
+ '--ephemeral',
+ '-c',
+ 'model_reasoning_effort="high"',
+ ],
+ clientVersion: '1.0.0',
+ commandPath: 'codex',
+ cwd: '/workspace',
+ env: process.env,
+ input: [{ text: 'hello', text_elements: [], type: 'text' }],
+ onEvents: (batch) => {
+ events.push(...batch);
+ },
+ onRawMessage: vi.fn(),
+ onRuntimeStatus: (status) => statuses.push(status),
+ onSessionId: (sessionId) => sessionIds.push(sessionId),
+ onStderr: vi.fn(),
+ operationId: 'operation-1',
+ sessionId: 'session-1',
+ });
+
+ await session.run();
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'codex',
+ ['-c', 'model_reasoning_effort="high"', 'app-server'],
+ expect.objectContaining({ cwd: '/workspace', stdio: ['pipe', 'pipe', 'pipe'] }),
+ );
+ expect(requests.map(({ method }) => method).filter(Boolean)).toEqual([
+ 'initialize',
+ 'initialized',
+ 'thread/start',
+ 'turn/start',
+ ]);
+ expect(requests).toContainEqual({
+ id: expect.any(Number),
+ method: 'thread/start',
+ params: {
+ approvalPolicy: 'never',
+ cwd: '/workspace/nested',
+ ephemeral: true,
+ model: 'gpt-5.5-codex',
+ sandbox: 'danger-full-access',
+ },
+ });
+ expect(sessionIds).toEqual([]);
+ expect(
+ events
+ .filter((event) => event.type === 'stream_chunk' && event.data?.chunkType === 'text')
+ .map((event) => event.data.content),
+ ).toEqual(['hello ', 'world']);
+ expect(events.some((event) => event.type === 'tool_start')).toBe(true);
+ expect(events.some((event) => event.type === 'tool_result')).toBe(true);
+ expect(
+ events.some(
+ (event) =>
+ event.type === 'stream_chunk' &&
+ event.data?.chunkType === 'tool_state' &&
+ event.data?.pluginState?.stdout === '/workspace\n',
+ ),
+ ).toBe(true);
+ expect(
+ events.some(
+ (event) =>
+ event.type === 'tool_result' && event.data?.pluginState?.changes?.[0]?.kind === 'update',
+ ),
+ ).toBe(true);
+ expect(
+ events.some(
+ (event) =>
+ event.type === 'stream_chunk' &&
+ event.data?.pluginState?.todos?.items?.[1]?.text === 'Implement',
+ ),
+ ).toBe(true);
+ expect(
+ events.some(
+ (event) =>
+ event.type === 'stream_chunk' &&
+ event.data?.pluginState?.changes?.[0]?.diffText?.includes('+++ b/a.ts'),
+ ),
+ ).toBe(true);
+ expect(events.some((event) => event.type === 'agent_runtime_end')).toBe(true);
+ expect(
+ events.some(
+ (event) => event.type === 'step_complete' && event.data?.usage?.totalTokens === 14,
+ ),
+ ).toBe(true);
+ expect(statuses.map(({ state }) => state)).toEqual(['starting', 'running', 'idle', 'closed']);
+ expect(statuses.every(({ transport }) => transport === 'codex-app-server')).toBe(true);
+ });
+
+ it('interrupts an active turn through RPC instead of killing the process', async () => {
+ const { child, requests } = createAppServerProcess({ autoComplete: false });
+ spawnMock.mockReturnValue(child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const events: any[] = [];
+ const statuses: any[] = [];
+ const session = new CodexAppServerSession({
+ args: [],
+ clientVersion: '1.0.0',
+ commandPath: 'codex',
+ cwd: '/workspace',
+ env: process.env,
+ input: [{ text: 'wait', text_elements: [], type: 'text' }],
+ onEvents: (batch) => {
+ events.push(...batch);
+ },
+ onRawMessage: vi.fn(),
+ onRuntimeStatus: (status) => statuses.push(status),
+ onSessionId: vi.fn(),
+ onStderr: vi.fn(),
+ operationId: 'operation-1',
+ sessionId: 'session-1',
+ });
+
+ const run = session.run();
+ await vi.waitFor(() => expect(statuses.some(({ state }) => state === 'running')).toBe(true));
+ await session.interrupt();
+ await run;
+
+ expect(requests).toContainEqual({
+ id: expect.any(Number),
+ method: 'turn/interrupt',
+ params: { threadId: 'thread-1', turnId: 'turn-1' },
+ });
+ expect(child.kill).not.toHaveBeenCalled();
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({ reason: 'interrupted' }),
+ type: 'agent_runtime_end',
+ }),
+ );
+ });
+
+ it('surfaces a process exit that races between thread setup and turn start', async () => {
+ const { child } = createAppServerProcess({ autoComplete: false });
+ spawnMock.mockReturnValue(child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ const session = new CodexAppServerSession({
+ args: [],
+ clientVersion: '1.0.0',
+ commandPath: 'codex',
+ cwd: '/workspace',
+ env: process.env,
+ input: [{ text: 'hello', text_elements: [], type: 'text' }],
+ onEvents: vi.fn(),
+ onRawMessage: vi.fn(),
+ onRuntimeStatus: vi.fn(),
+ onSessionId: () => child.emit('exit', 1, null),
+ onStderr: vi.fn(),
+ operationId: 'operation-1',
+ sessionId: 'session-1',
+ });
+
+ await expect(session.run()).rejects.toThrow(
+ 'Codex app-server exited before the turn completed (code 1, signal null)',
+ );
+ });
+
+ it('resumes a non-interactive thread and cancels unexpected approval requests', async () => {
+ const { child, requests } = createAppServerProcess({ requestApproval: true });
+ spawnMock.mockReturnValue(child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const onSessionId = vi.fn();
+
+ const session = new CodexAppServerSession({
+ args: ['-s', 'read-only', '-a', 'never'],
+ clientVersion: '1.0.0',
+ commandPath: 'codex',
+ cwd: '/workspace',
+ env: process.env,
+ input: [{ text: 'continue', text_elements: [], type: 'text' }],
+ onEvents: vi.fn(),
+ onRawMessage: vi.fn(),
+ onRuntimeStatus: vi.fn(),
+ onSessionId,
+ onStderr: vi.fn(),
+ operationId: 'operation-1',
+ resumeSessionId: 'thread-existing',
+ sessionId: 'session-1',
+ });
+
+ await session.run();
+
+ expect(requests).toContainEqual({
+ id: expect.any(Number),
+ method: 'thread/resume',
+ params: {
+ approvalPolicy: 'never',
+ cwd: '/workspace',
+ sandbox: 'read-only',
+ threadId: 'thread-existing',
+ },
+ });
+ expect(requests).toContainEqual({ id: 'approval-1', result: { decision: 'cancel' } });
+ expect(onSessionId).toHaveBeenCalledWith('thread-1');
+ });
+
+ it('ignores terminal notifications for another thread', async () => {
+ const { child, send } = createAppServerProcess({ autoComplete: false });
+ spawnMock.mockReturnValue(child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const statuses: any[] = [];
+
+ const session = new CodexAppServerSession({
+ args: [],
+ clientVersion: '1.0.0',
+ commandPath: 'codex',
+ cwd: '/workspace',
+ env: process.env,
+ input: [{ text: 'hello', text_elements: [], type: 'text' }],
+ onEvents: vi.fn(),
+ onRawMessage: vi.fn(),
+ onRuntimeStatus: (status) => statuses.push(status),
+ onSessionId: vi.fn(),
+ onStderr: vi.fn(),
+ operationId: 'operation-1',
+ sessionId: 'session-1',
+ });
+
+ const run = session.run();
+ await vi.waitFor(() => expect(statuses.some(({ state }) => state === 'running')).toBe(true));
+ send({
+ method: 'turn/completed',
+ params: {
+ threadId: 'another-thread',
+ turn: { id: 'another-turn', status: 'completed' },
+ },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(statuses.some(({ state }) => state === 'idle')).toBe(false);
+
+ await session.interrupt();
+ await run;
+ });
+});
+
+describe('Codex app-server payload builders', () => {
+ it('starts only the app-server subcommand and translates runtime flags into thread params', () => {
+ expect(buildCodexAppServerArgs()).toEqual(['app-server']);
+ expect(
+ buildCodexAppServerArgs([
+ '--model',
+ 'gpt-5.5-codex',
+ '-c',
+ 'model_reasoning_effort="high"',
+ '--config=service_tier="fast"',
+ ]),
+ ).toEqual([
+ '-c',
+ 'model_reasoning_effort="high"',
+ '--config=service_tier="fast"',
+ 'app-server',
+ ]);
+ expect(
+ buildCodexAppServerThreadParams(
+ [
+ '--model',
+ 'gpt-5.5-codex',
+ '-s',
+ 'read-only',
+ '-a',
+ 'never',
+ '--cd',
+ 'nested',
+ '--ephemeral',
+ '-c',
+ 'model_reasoning_effort="high"',
+ '-c',
+ 'model_provider="openai"',
+ '--config=service_tier="fast"',
+ ],
+ '/workspace',
+ ),
+ ).toEqual({
+ approvalPolicy: 'never',
+ cwd: '/workspace/nested',
+ ephemeral: true,
+ model: 'gpt-5.5-codex',
+ modelProvider: 'openai',
+ sandbox: 'read-only',
+ serviceTier: 'fast',
+ });
+ expect(buildCodexAppServerThreadParams(['--full-auto'], '/workspace')).toMatchObject({
+ approvalPolicy: 'never',
+ sandbox: 'workspace-write',
+ });
+ expect(
+ buildCodexAppServerThreadParams(['--dangerously-bypass-approvals-and-sandbox'], '/workspace'),
+ ).toMatchObject({ approvalPolicy: 'never', sandbox: 'danger-full-access' });
+ });
+
+ it('falls back for unsupported or interactive CLI arguments instead of dropping them', () => {
+ expect(getCodexAppServerUnsupportedArgs(['--profile', 'work'])).toEqual(['--profile']);
+ expect(getCodexAppServerUnsupportedArgs(['--ignore-user-config'])).toEqual([
+ '--ignore-user-config',
+ ]);
+ expect(getCodexAppServerUnsupportedArgs(['--full-auto'])).toEqual(['--full-auto']);
+ expect(getCodexAppServerUnsupportedArgs(['-a', 'on-request'])).toEqual(['-a']);
+ expect(getCodexAppServerUnsupportedArgs(['-c', 'approval_policy="untrusted"'])).toEqual(['-c']);
+ expect(getCodexAppServerUnsupportedArgs(['--search'])).toEqual(['--search']);
+ expect(getCodexAppServerUnsupportedArgs(['--model', '--ephemeral'])).toEqual(['--model']);
+ expect(getCodexAppServerUnsupportedArgs(['--sandbox', 'invalid'])).toEqual(['--sandbox']);
+ expect(
+ getCodexAppServerUnsupportedArgs([
+ '--dangerously-bypass-approvals-and-sandbox',
+ '--sandbox',
+ 'read-only',
+ ]),
+ ).toEqual(['--dangerously-bypass-approvals-and-sandbox']);
+ expect(getCodexAppServerUnsupportedArgs(['--ephemeral'], { resume: true })).toEqual([
+ '--ephemeral',
+ ]);
+ expect(
+ getCodexAppServerUnsupportedArgs([
+ '--model',
+ 'gpt-5.5-codex',
+ '-c',
+ 'service_tier="fast"',
+ '--cd=src',
+ '--ephemeral',
+ ]),
+ ).toEqual([]);
+ });
+
+ it('converts Codex text and --image args into v2 turn inputs', () => {
+ expect(
+ buildCodexAppServerInput({
+ args: ['--image', '/tmp/a.png', '--image', '/tmp/b.jpg'],
+ stdin: 'describe these',
+ }),
+ ).toEqual([
+ { text: 'describe these', text_elements: [], type: 'text' },
+ { path: '/tmp/a.png', type: 'localImage' },
+ { path: '/tmp/b.jpg', type: 'localImage' },
+ ]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/codexAppServerSession.ts b/packages/heterogeneous-agents/src/spawn/codexAppServerSession.ts
new file mode 100644
index 00000000000..8fa87de39ab
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/codexAppServerSession.ts
@@ -0,0 +1,899 @@
+import type { ChildProcess } from 'node:child_process';
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+import type { UsageData } from '../types';
+import { AgentStreamPipeline } from './agentStreamPipeline';
+import type { HeterogeneousAgentRuntimeStatus } from './claudeAgentSdkSession';
+import { resolveCliSpawnPlan } from './cliSpawn';
+import type { AgentInputPlan } from './input';
+
+const APP_SERVER_RPC_TIMEOUT_MS = 30_000;
+const CODEX_APP_SERVER_TRANSPORT = 'codex-app-server' as const;
+const CODEX_DANGEROUS_BYPASS_FLAG = '--dangerously-bypass-approvals-and-sandbox';
+const CODEX_FULL_AUTO_FLAG = '--full-auto';
+const CODEX_APPROVAL_FLAGS = ['-a', '--ask-for-approval'] as const;
+const CODEX_CONFIG_FLAGS = ['-c', '--config'] as const;
+const CODEX_CWD_FLAGS = ['-C', '--cd'] as const;
+const CODEX_MODEL_FLAGS = ['-m', '--model'] as const;
+const CODEX_PROFILE_FLAGS = ['-p', '--profile'] as const;
+const CODEX_SANDBOX_FLAGS = ['-s', '--sandbox'] as const;
+const CODEX_EPHEMERAL_FLAG = '--ephemeral';
+const CODEX_IGNORE_USER_CONFIG_FLAG = '--ignore-user-config';
+
+interface CodexAppServerTextInput {
+ text: string;
+ text_elements: [];
+ type: 'text';
+}
+
+interface CodexAppServerLocalImageInput {
+ path: string;
+ type: 'localImage';
+}
+
+export type CodexAppServerUserInput = CodexAppServerLocalImageInput | CodexAppServerTextInput;
+
+interface RpcError {
+ code?: number;
+ data?: unknown;
+ message?: string;
+}
+
+interface RpcMessage {
+ error?: RpcError;
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown>;
+ result?: unknown;
+}
+
+interface PendingRpcRequest {
+ reject: (error: Error) => void;
+ resolve: (result: unknown) => void;
+ timeout: ReturnType<typeof setTimeout>;
+}
+
+interface CodexThreadResponse {
+ model?: string;
+ thread?: { id?: string };
+}
+
+interface CodexTurnResponse {
+ turn?: { id?: string };
+}
+
+interface CodexTokenUsageBreakdown {
+ cachedInputTokens?: number;
+ inputTokens?: number;
+ outputTokens?: number;
+ reasoningOutputTokens?: number;
+}
+
+interface CodexThreadTokenUsage {
+ total?: CodexTokenUsageBreakdown;
+}
+
+interface CodexTurnPlanStep {
+ status?: string;
+ step?: string;
+}
+
+interface CodexAppServerItem {
+ [key: string]: unknown;
+ id?: string;
+ type?: string;
+}
+
+type CodexAppServerApprovalPolicy = 'never' | 'on-request' | 'untrusted';
+type CodexAppServerSandboxMode = 'danger-full-access' | 'read-only' | 'workspace-write';
+
+export interface CodexAppServerThreadParams {
+ approvalPolicy: CodexAppServerApprovalPolicy;
+ cwd: string;
+ ephemeral?: boolean;
+ model?: string;
+ modelProvider?: string;
+ sandbox: CodexAppServerSandboxMode;
+ serviceTier?: string;
+}
+
+export interface CodexAppServerSessionOptions {
+ args: string[];
+ clientVersion: string;
+ commandPath: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ initialCumulativeUsage?: UsageData | undefined;
+ initialModel?: string | undefined;
+ input: CodexAppServerUserInput[];
+ onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;
+ onModel?: (model: string) => void;
+ onRawMessage: (line: string) => Promise<void> | void;
+ onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
+ onSessionId: (sessionId: string) => void;
+ onStderr: (data: string) => Promise<void> | void;
+ operationId: string;
+ resumeSessionId?: string;
+ sessionId: string;
+}
+
+const getFlagValue = (arg: string, flags: readonly string[]) => {
+ const flag = flags.find((candidate) => arg.startsWith(`${candidate}=`));
+ return flag ? arg.slice(flag.length + 1) : undefined;
+};
+
+const parseConfigValue = (raw: string): unknown => {
+ const value = raw.trim();
+ if (value === 'true') return true;
+ if (value === 'false') return false;
+ if (value === 'null') return null;
+
+ const number = Number(value);
+ if (value && Number.isFinite(number)) return number;
+
+ if (
+ (value.startsWith('"') && value.endsWith('"')) ||
+ (value.startsWith('[') && value.endsWith(']')) ||
+ (value.startsWith('{') && value.endsWith('}'))
+ ) {
+ try {
+ return JSON.parse(value);
+ } catch {
+ // Keep non-JSON TOML values as strings; app-server validates the config.
+ }
+ }
+
+ if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1);
+ return value;
+};
+
+const parseConfigOverride = (raw: string) => {
+ const separator = raw.indexOf('=');
+ if (separator <= 0) return;
+ const key = raw.slice(0, separator).trim();
+ if (!key) return;
+ return { key, value: parseConfigValue(raw.slice(separator + 1)) };
+};
+
+const isSandboxMode = (value: string): value is CodexAppServerSandboxMode =>
+ value === 'danger-full-access' || value === 'read-only' || value === 'workspace-write';
+
+/** App-server consumes global config overrides itself; preserve their raw TOML values. */
+export const buildCodexAppServerArgs = (args: string[] = []): string[] => {
+ const configArgs: string[] = [];
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (getFlagValue(arg, CODEX_CONFIG_FLAGS) !== undefined) {
+ configArgs.push(arg);
+ continue;
+ }
+ if (!CODEX_CONFIG_FLAGS.includes(arg as (typeof CODEX_CONFIG_FLAGS)[number])) continue;
+
+ const value = args[index + 1];
+ if (value) {
+ configArgs.push(arg, value);
+ index += 1;
+ }
+ }
+
+ return [...configArgs, 'app-server'];
+};
+
+/**
+ * Unknown or loader-only CLI arguments must use the existing `codex exec` path instead of being
+ * silently discarded. Interactive approval modes also stay on that path until app-server has UI.
+ */
+export const getCodexAppServerUnsupportedArgs = (
+ args: string[],
+ options: { resume?: boolean } = {},
+): string[] => {
+ const unsupported: string[] = [];
+ const hasSandboxFlag = args.some(
+ (arg) =>
+ CODEX_SANDBOX_FLAGS.includes(arg as (typeof CODEX_SANDBOX_FLAGS)[number]) ||
+ getFlagValue(arg, CODEX_SANDBOX_FLAGS) !== undefined,
+ );
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (arg === CODEX_DANGEROUS_BYPASS_FLAG) {
+ if (hasSandboxFlag) unsupported.push(arg);
+ continue;
+ }
+ if (arg === CODEX_EPHEMERAL_FLAG) {
+ if (options.resume) unsupported.push(arg);
+ continue;
+ }
+ if (arg === CODEX_FULL_AUTO_FLAG || arg === CODEX_IGNORE_USER_CONFIG_FLAG) {
+ unsupported.push(arg);
+ continue;
+ }
+
+ const valueFlags = [
+ ...CODEX_MODEL_FLAGS,
+ ...CODEX_CONFIG_FLAGS,
+ ...CODEX_CWD_FLAGS,
+ ...CODEX_APPROVAL_FLAGS,
+ ...CODEX_SANDBOX_FLAGS,
+ ];
+ const exactFlag = valueFlags.find((flag) => arg === flag);
+ const inlineFlag = valueFlags.find((flag) => arg.startsWith(`${flag}=`));
+ if (exactFlag || inlineFlag) {
+ const value = inlineFlag ? arg.slice(inlineFlag.length + 1) : args[index + 1];
+ if (!value || (!inlineFlag && value.startsWith('-'))) {
+ unsupported.push(arg);
+ continue;
+ }
+ if (!inlineFlag) index += 1;
+
+ if (
+ CODEX_APPROVAL_FLAGS.includes(
+ (exactFlag ?? inlineFlag) as (typeof CODEX_APPROVAL_FLAGS)[number],
+ ) &&
+ value !== 'never'
+ ) {
+ unsupported.push(arg);
+ }
+ if (
+ CODEX_SANDBOX_FLAGS.includes(
+ (exactFlag ?? inlineFlag) as (typeof CODEX_SANDBOX_FLAGS)[number],
+ ) &&
+ !isSandboxMode(value)
+ ) {
+ unsupported.push(arg);
+ }
+ if (
+ CODEX_CONFIG_FLAGS.includes(
+ (exactFlag ?? inlineFlag) as (typeof CODEX_CONFIG_FLAGS)[number],
+ )
+ ) {
+ const override = parseConfigOverride(value);
+ if (override?.key === 'approval_policy' && override.value !== 'never') {
+ unsupported.push(arg);
+ }
+ }
+ continue;
+ }
+
+ if (
+ CODEX_PROFILE_FLAGS.includes(arg as (typeof CODEX_PROFILE_FLAGS)[number]) ||
+ getFlagValue(arg, CODEX_PROFILE_FLAGS) !== undefined
+ ) {
+ unsupported.push(arg);
+ if (CODEX_PROFILE_FLAGS.includes(arg as (typeof CODEX_PROFILE_FLAGS)[number])) index += 1;
+ continue;
+ }
+
+ unsupported.push(arg);
+ }
+
+ return unsupported;
+};
+
+export const buildCodexAppServerThreadParams = (
+ args: string[],
+ cwd: string,
+ initialModel?: string,
+): CodexAppServerThreadParams => {
+ const approvalPolicy: CodexAppServerApprovalPolicy = 'never';
+ let effectiveCwd = cwd;
+ let ephemeral = false;
+ let model = initialModel;
+ let modelProvider: string | undefined;
+ let sandbox: CodexAppServerSandboxMode = 'danger-full-access';
+ let serviceTier: string | undefined;
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (arg === CODEX_DANGEROUS_BYPASS_FLAG) {
+ sandbox = 'danger-full-access';
+ continue;
+ }
+ if (arg === CODEX_FULL_AUTO_FLAG) {
+ sandbox = 'workspace-write';
+ continue;
+ }
+ if (arg === CODEX_EPHEMERAL_FLAG) {
+ ephemeral = true;
+ continue;
+ }
+
+ const next = args[index + 1];
+ const modelValue = getFlagValue(arg, CODEX_MODEL_FLAGS);
+ if (modelValue !== undefined) {
+ if (modelValue) model = modelValue;
+ continue;
+ }
+ if (CODEX_MODEL_FLAGS.includes(arg as (typeof CODEX_MODEL_FLAGS)[number]) && next) {
+ model = next;
+ index += 1;
+ continue;
+ }
+
+ const approvalValue = getFlagValue(arg, CODEX_APPROVAL_FLAGS);
+ if (approvalValue !== undefined) {
+ continue;
+ }
+ if (CODEX_APPROVAL_FLAGS.includes(arg as (typeof CODEX_APPROVAL_FLAGS)[number]) && next) {
+ index += 1;
+ continue;
+ }
+
+ const sandboxValue = getFlagValue(arg, CODEX_SANDBOX_FLAGS);
+ if (sandboxValue !== undefined) {
+ if (isSandboxMode(sandboxValue)) sandbox = sandboxValue;
+ continue;
+ }
+ if (CODEX_SANDBOX_FLAGS.includes(arg as (typeof CODEX_SANDBOX_FLAGS)[number]) && next) {
+ if (isSandboxMode(next)) sandbox = next;
+ index += 1;
+ continue;
+ }
+
+ const cwdValue = getFlagValue(arg, CODEX_CWD_FLAGS);
+ if (cwdValue !== undefined) {
+ if (cwdValue) effectiveCwd = path.resolve(cwd, cwdValue);
+ continue;
+ }
+ if (CODEX_CWD_FLAGS.includes(arg as (typeof CODEX_CWD_FLAGS)[number]) && next) {
+ effectiveCwd = path.resolve(cwd, next);
+ index += 1;
+ continue;
+ }
+
+ const configValue = getFlagValue(arg, CODEX_CONFIG_FLAGS);
+ const isConfigFlag = CODEX_CONFIG_FLAGS.includes(arg as (typeof CODEX_CONFIG_FLAGS)[number]);
+ if (configValue === undefined && !isConfigFlag) continue;
+ if (configValue === undefined && next) index += 1;
+ const configOverride = parseConfigOverride(configValue ?? next ?? '');
+ if (!configOverride) continue;
+ if (configOverride.key === 'model' && typeof configOverride.value === 'string') {
+ model = configOverride.value;
+ }
+ if (configOverride.key === 'model_provider' && typeof configOverride.value === 'string') {
+ modelProvider = configOverride.value;
+ }
+ if (
+ configOverride.key === 'sandbox_mode' &&
+ typeof configOverride.value === 'string' &&
+ isSandboxMode(configOverride.value)
+ )
+ sandbox = configOverride.value;
+ if (configOverride.key === 'service_tier' && typeof configOverride.value === 'string') {
+ serviceTier = configOverride.value;
+ }
+ }
+
+ return {
+ approvalPolicy,
+ cwd: effectiveCwd,
+ ...(ephemeral ? { ephemeral } : {}),
+ ...(model ? { model } : {}),
+ ...(modelProvider ? { modelProvider } : {}),
+ sandbox,
+ ...(serviceTier ? { serviceTier } : {}),
+ };
+};
+
+export const buildCodexAppServerInput = (plan: AgentInputPlan): CodexAppServerUserInput[] => {
+ const input: CodexAppServerUserInput[] = [];
+ if (plan.stdin) input.push({ text: plan.stdin, text_elements: [], type: 'text' });
+
+ for (let index = 0; index < plan.args.length; index += 1) {
+ if (plan.args[index] !== '--image') continue;
+ const imagePath = plan.args[index + 1];
+ if (imagePath) input.push({ path: imagePath, type: 'localImage' });
+ index += 1;
+ }
+
+ return input;
+};
+
+const normalizeStatus = (status: unknown): unknown => {
+ if (status === 'inProgress') return 'in_progress';
+ if (status === 'declined') return 'failed';
+ return status;
+};
+
+/** Convert stable v2 app-server items into the existing `codex exec --json` item shape. */
+const normalizeAppServerItem = (item: CodexAppServerItem): CodexAppServerItem | undefined => {
+ switch (item.type) {
+ case 'agentMessage': {
+ return { ...item, type: 'agent_message' };
+ }
+ case 'commandExecution': {
+ return {
+ ...item,
+ aggregated_output: item.aggregatedOutput,
+ exit_code: item.exitCode,
+ status: normalizeStatus(item.status),
+ type: 'command_execution',
+ };
+ }
+ case 'fileChange': {
+ const changes = Array.isArray(item.changes)
+ ? item.changes.map((change) => {
+ const value = change as Record<string, unknown>;
+ const kind = value.kind;
+ const kindValue =
+ typeof kind === 'object' && kind !== null
+ ? (kind as Record<string, unknown>)
+ : undefined;
+ return {
+ ...value,
+ diffText: value.diff,
+ kind: kindValue?.movePath ? 'rename' : (kindValue?.type ?? kind),
+ };
+ })
+ : [];
+ return {
+ ...item,
+ changes,
+ status: normalizeStatus(item.status),
+ type: 'file_change',
+ };
+ }
+ case 'mcpToolCall': {
+ return {
+ ...item,
+ status: normalizeStatus(item.status),
+ type: 'mcp_tool_call',
+ };
+ }
+ case 'collabAgentToolCall': {
+ return {
+ ...item,
+ agents_states: item.agentsStates,
+ receiver_thread_ids: item.receiverThreadIds,
+ sender_thread_id: item.senderThreadId,
+ status: normalizeStatus(item.status),
+ type: 'collab_tool_call',
+ };
+ }
+ case 'dynamicToolCall': {
+ return {
+ ...item,
+ status: normalizeStatus(item.status),
+ type: 'dynamic_tool_call',
+ };
+ }
+ case 'webSearch': {
+ return { ...item, status: normalizeStatus(item.status), type: 'web_search' };
+ }
+ default: {
+ return;
+ }
+ }
+};
+
+const toExecUsage = (usage: CodexTokenUsageBreakdown | undefined) =>
+ usage
+ ? {
+ cached_input_tokens: usage.cachedInputTokens,
+ input_tokens: usage.inputTokens,
+ output_tokens: usage.outputTokens,
+ reasoning_output_tokens: usage.reasoningOutputTokens,
+ }
+ : undefined;
+
+export class CodexAppServerSession {
+ private readonly pipeline: AgentStreamPipeline;
+ private readonly pendingRequests = new Map<string, PendingRpcRequest>();
+ private readonly threadParams: CodexAppServerThreadParams;
+ private activeFileChangeItemId?: string;
+ private child?: ChildProcess;
+ private closedByHost = false;
+ private fatalError?: Error;
+ private latestTokenUsage?: CodexThreadTokenUsage;
+ private latestPlanItem?: CodexAppServerItem;
+ private notificationQueue = Promise.resolve();
+ private nextRequestId = 0;
+ private stdoutBuffer = '';
+ private threadId?: string;
+ private turnId?: string;
+ private turnCompletion?: Promise<void>;
+ private rejectTurn?: (error: Error) => void;
+ private resolveTurn?: () => void;
+
+ constructor(private readonly options: CodexAppServerSessionOptions) {
+ this.threadParams = buildCodexAppServerThreadParams(
+ options.args,
+ options.cwd,
+ options.initialModel,
+ );
+ this.pipeline = new AgentStreamPipeline({
+ agentType: 'codex',
+ cwd: this.threadParams.cwd,
+ initialCumulativeUsage: options.initialCumulativeUsage,
+ initialModel: options.initialModel,
+ operationId: options.operationId,
+ });
+ }
+
+ async run(): Promise<void> {
+ this.emitStatus('starting');
+
+ try {
+ await this.startProcess();
+ await this.request('initialize', {
+ capabilities: { experimentalApi: false },
+ clientInfo: {
+ name: 'lobehub-desktop',
+ title: 'LobeHub Desktop',
+ version: this.options.clientVersion,
+ },
+ });
+ this.sendNotification('initialized', {});
+
+ const resumeThreadParams = { ...this.threadParams };
+ delete resumeThreadParams.ephemeral;
+ const thread = this.options.resumeSessionId
+ ? await this.request<CodexThreadResponse>('thread/resume', {
+ ...resumeThreadParams,
+ threadId: this.options.resumeSessionId,
+ })
+ : await this.request<CodexThreadResponse>('thread/start', this.threadParams);
+ const threadId = thread.thread?.id;
+ if (!threadId) throw new Error('Codex app-server returned no thread id');
+
+ this.threadId = threadId;
+ if (!this.threadParams.ephemeral) this.options.onSessionId(threadId);
+ await this.emitSynthetic({ thread_id: threadId, type: 'thread.started' });
+ if (thread.model) {
+ this.options.onModel?.(thread.model);
+ await this.emitEvents(this.pipeline.configureSession({ model: thread.model }));
+ }
+
+ this.turnCompletion = new Promise<void>((resolve, reject) => {
+ this.resolveTurn = resolve;
+ this.rejectTurn = reject;
+ });
+ void this.turnCompletion.catch(() => {});
+ const turn = await this.request<CodexTurnResponse>('turn/start', {
+ input: this.options.input,
+ threadId,
+ });
+ this.turnId = turn.turn?.id;
+ this.emitStatus('running');
+
+ await this.turnCompletion;
+ await this.notificationQueue;
+ await this.emitEvents(await this.pipeline.flush());
+ this.emitStatus('idle');
+ } catch (error) {
+ if (this.closedByHost) {
+ this.emitStatus('closed');
+ return;
+ }
+
+ this.emitStatus('error');
+ throw error;
+ } finally {
+ this.shutdownProcess('SIGTERM');
+ if (!this.closedByHost) this.emitStatus('closed');
+ }
+ }
+
+ async interrupt(): Promise<void> {
+ if (!this.threadId || !this.turnId) {
+ this.close();
+ return;
+ }
+
+ await this.request('turn/interrupt', {
+ threadId: this.threadId,
+ turnId: this.turnId,
+ });
+ }
+
+ close(): void {
+ this.closedByHost = true;
+ this.rejectTurn?.(new Error('Codex app-server session closed by host'));
+ this.rejectPendingRequests(new Error('Codex app-server session closed by host'));
+ this.shutdownProcess('SIGTERM');
+ this.emitStatus('closed');
+ }
+
+ private async startProcess(): Promise<void> {
+ const spawnPlan = await resolveCliSpawnPlan(
+ this.options.commandPath,
+ buildCodexAppServerArgs(this.options.args),
+ );
+ const child = spawn(spawnPlan.command, spawnPlan.args, {
+ cwd: this.options.cwd,
+ detached: process.platform !== 'win32',
+ env: this.options.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ this.child = child;
+
+ child.stdin?.on('error', () => {
+ // The process error/exit listener reports the actionable failure. Swallow
+ // a racing EPIPE from an RPC write so it cannot crash Electron main.
+ });
+ child.stdout?.on('data', (chunk: Buffer) => this.consumeStdout(chunk));
+ child.stderr?.on('data', (chunk: Buffer) => {
+ void this.options.onStderr(chunk.toString('utf8'));
+ });
+ child.once('error', (error) => this.fail(error));
+ child.once('exit', (code, signal) => {
+ if (this.closedByHost) return;
+ this.fail(
+ new Error(
+ `Codex app-server exited before the turn completed (code ${code ?? 'null'}, signal ${signal ?? 'null'})`,
+ ),
+ );
+ });
+ }
+
+ private consumeStdout(chunk: Buffer): void {
+ this.stdoutBuffer += chunk.toString('utf8');
+
+ let newlineIndex: number;
+ while ((newlineIndex = this.stdoutBuffer.indexOf('\n')) !== -1) {
+ const line = this.stdoutBuffer.slice(0, newlineIndex).trim();
+ this.stdoutBuffer = this.stdoutBuffer.slice(newlineIndex + 1);
+ if (!line) continue;
+
+ void this.options.onRawMessage(`${line}\n`);
+ try {
+ this.handleRpcMessage(JSON.parse(line) as RpcMessage);
+ } catch (error) {
+ this.fail(error instanceof Error ? error : new Error(String(error)));
+ }
+ }
+ }
+
+ private handleRpcMessage(message: RpcMessage): void {
+ if (message.method) {
+ if (message.id !== undefined) {
+ this.handleServerRequest(message);
+ return;
+ }
+
+ this.notificationQueue = this.notificationQueue
+ .then(() => this.handleNotification(message.method!, message.params ?? {}))
+ .catch((error) => {
+ this.fail(error instanceof Error ? error : new Error(String(error)));
+ });
+ return;
+ }
+
+ if (message.id === undefined) return;
+ const pending = this.pendingRequests.get(String(message.id));
+ if (!pending) return;
+
+ this.pendingRequests.delete(String(message.id));
+ clearTimeout(pending.timeout);
+ if (message.error) {
+ pending.reject(new Error(message.error.message ?? 'Codex app-server request failed'));
+ } else {
+ pending.resolve(message.result);
+ }
+ }
+
+ private async handleNotification(method: string, params: Record<string, unknown>): Promise<void> {
+ if (this.threadId && typeof params.threadId === 'string' && params.threadId !== this.threadId) {
+ return;
+ }
+
+ switch (method) {
+ case 'turn/started': {
+ const turn = params.turn as { id?: string } | undefined;
+ this.turnId = turn?.id ?? this.turnId;
+ await this.emitSynthetic({ turn, type: 'turn.started' });
+ return;
+ }
+ case 'item/started':
+ case 'item/completed': {
+ const item = normalizeAppServerItem((params.item ?? {}) as CodexAppServerItem);
+ if (!item) return;
+ if (method === 'item/started' && item.type === 'file_change' && item.id) {
+ this.activeFileChangeItemId = item.id;
+ }
+ await this.emitSynthetic({
+ item,
+ type: method === 'item/started' ? 'item.started' : 'item.completed',
+ });
+ if (method === 'item/completed' && item.id === this.activeFileChangeItemId) {
+ this.activeFileChangeItemId = undefined;
+ }
+ return;
+ }
+ case 'item/agentMessage/delta': {
+ await this.emitSynthetic({
+ delta: params.delta,
+ item_id: params.itemId,
+ type: 'item.agent_message.delta',
+ });
+ return;
+ }
+ case 'item/commandExecution/outputDelta': {
+ await this.emitSynthetic({
+ delta: params.delta,
+ item_id: params.itemId,
+ type: 'item.command_execution.output_delta',
+ });
+ return;
+ }
+ case 'turn/diff/updated': {
+ if (!this.activeFileChangeItemId || typeof params.diff !== 'string') return;
+ await this.emitSynthetic({
+ item: {
+ changes: [{ diffText: params.diff }],
+ id: this.activeFileChangeItemId,
+ status: 'in_progress',
+ type: 'file_change',
+ },
+ type: 'item.updated',
+ });
+ return;
+ }
+ case 'turn/plan/updated': {
+ const plan = Array.isArray(params.plan) ? (params.plan as CodexTurnPlanStep[]) : [];
+ const planItemId = `turn-plan-${String(params.turnId ?? this.turnId ?? 'current')}`;
+ const item: CodexAppServerItem = {
+ id: planItemId,
+ items: plan
+ .filter((step) => typeof step.step === 'string' && step.step.trim())
+ .map((step) => ({ completed: step.status === 'completed', text: step.step })),
+ status: 'in_progress',
+ type: 'todo_list',
+ };
+ const type = this.latestPlanItem?.id === planItemId ? 'item.updated' : 'item.started';
+ this.latestPlanItem = item;
+ await this.emitSynthetic({ item, type });
+ return;
+ }
+ case 'thread/tokenUsage/updated': {
+ this.latestTokenUsage = params.tokenUsage as CodexThreadTokenUsage;
+ return;
+ }
+ case 'error': {
+ if (params.willRetry === true) return;
+ const error = params.error as { message?: string } | undefined;
+ await this.emitSynthetic({
+ message: error?.message ?? 'Codex execution failed',
+ type: 'error',
+ });
+ return;
+ }
+ case 'turn/completed': {
+ const turn = params.turn as { error?: { message?: string }; id?: string; status?: string };
+ this.turnId = turn.id ?? this.turnId;
+ if (turn.status === 'completed') {
+ if (this.latestPlanItem) {
+ await this.emitSynthetic({
+ item: { ...this.latestPlanItem, status: 'completed' },
+ type: 'item.completed',
+ });
+ }
+ await this.emitSynthetic({
+ type: 'turn.completed',
+ usage: toExecUsage(this.latestTokenUsage?.total),
+ });
+ } else if (turn.status === 'interrupted') {
+ await this.emitSynthetic({
+ reason: 'interrupted',
+ type: 'turn.completed',
+ usage: toExecUsage(this.latestTokenUsage?.total),
+ });
+ } else {
+ await this.emitSynthetic({
+ message:
+ turn.error?.message ??
+ (turn.status === 'failed'
+ ? 'Codex execution failed'
+ : `Codex app-server returned unexpected turn status: ${turn.status ?? 'unknown'}`),
+ type: 'turn.failed',
+ });
+ }
+ this.latestPlanItem = undefined;
+ this.resolveTurn?.();
+ return;
+ }
+ }
+ }
+
+ private handleServerRequest(message: RpcMessage): void {
+ if (!this.child?.stdin || message.id === undefined) return;
+
+ if (
+ message.method === 'item/commandExecution/requestApproval' ||
+ message.method === 'item/fileChange/requestApproval'
+ ) {
+ // This transport only starts non-interactive (`never`) threads. A request is therefore an
+ // unexpected escalation; cancel it rather than silently bypassing the configured boundary.
+ this.writeRpc({ id: message.id, result: { decision: 'cancel' } });
+ return;
+ }
+
+ this.writeRpc({
+ error: { code: -32_601, message: `Unsupported Codex app-server request: ${message.method}` },
+ id: message.id,
+ });
+ }
+
+ private request<T = unknown>(method: string, params?: unknown): Promise<T> {
+ if (this.fatalError) return Promise.reject(this.fatalError);
+ if (!this.child?.stdin)
+ return Promise.reject(new Error('Codex app-server stdin is unavailable'));
+
+ const id = ++this.nextRequestId;
+ return new Promise<T>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ this.pendingRequests.delete(String(id));
+ reject(new Error(`Codex app-server request timed out: ${method}`));
+ }, APP_SERVER_RPC_TIMEOUT_MS);
+ timeout.unref?.();
+ this.pendingRequests.set(String(id), {
+ reject,
+ resolve: (result) => resolve(result as T),
+ timeout,
+ });
+ this.writeRpc({ id, method, params });
+ });
+ }
+
+ private sendNotification(method: string, params?: unknown): void {
+ this.writeRpc({ method, params });
+ }
+
+ private writeRpc(message: Record<string, unknown>): void {
+ this.child?.stdin?.write(`${JSON.stringify(message)}\n`);
+ }
+
+ private async emitSynthetic(payload: Record<string, unknown>): Promise<void> {
+ await this.emitEvents(await this.pipeline.push(`${JSON.stringify(payload)}\n`));
+ }
+
+ private async emitEvents(events: AgentStreamEvent[]): Promise<void> {
+ if (events.length > 0) await this.options.onEvents(events);
+ }
+
+ private emitStatus(state: HeterogeneousAgentRuntimeStatus['state']): void {
+ this.options.onRuntimeStatus({
+ activeTasks: [],
+ lastEventAt: Date.now(),
+ operationId: this.options.operationId,
+ sessionId: this.options.sessionId,
+ state,
+ transport: CODEX_APP_SERVER_TRANSPORT,
+ });
+ }
+
+ private fail(error: Error): void {
+ this.fatalError ??= error;
+ this.rejectTurn?.(error);
+ this.rejectPendingRequests(error);
+ }
+
+ private rejectPendingRequests(error: Error): void {
+ for (const [, pending] of this.pendingRequests) {
+ clearTimeout(pending.timeout);
+ pending.reject(error);
+ }
+ this.pendingRequests.clear();
+ }
+
+ private shutdownProcess(signal: NodeJS.Signals): void {
+ const child = this.child;
+ this.child = undefined;
+ if (!child?.pid || child.killed) return;
+
+ if (process.platform === 'win32') {
+ child.kill(signal);
+ return;
+ }
+
+ try {
+ process.kill(-child.pid, signal);
+ } catch {
+ child.kill(signal);
+ }
+ }
+}
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index f917f8eb012..fc6db7ca016 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -32,6 +32,16 @@ export {
type HeterogeneousAgentRuntimeTask,
} from './claudeAgentSdkSession';
export { type CliSpawnPlan, resolveCliSpawnPlan } from './cliSpawn';
+export {
+ buildCodexAppServerArgs,
+ buildCodexAppServerInput,
+ buildCodexAppServerThreadParams,
+ CodexAppServerSession,
+ type CodexAppServerSessionOptions,
+ type CodexAppServerThreadParams,
+ type CodexAppServerUserInput,
+ getCodexAppServerUnsupportedArgs,
+} from './codexAppServerSession';
export { CodexFileChangeTracker } from './codexFileChangeTracker';
export {
type CodexInitialModelResolution,
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index 2b6228d8479..2385fb7e31b 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -16,6 +16,9 @@ export default {
'features.claudeCodeSdk.desc':
'Run Claude Code sessions through the Claude Agent SDK instead of spawning the CLI. Enables richer streaming and session control.',
'features.claudeCodeSdk.title': 'Claude Code SDK Runtime',
+ 'features.codexAppServer.desc':
+ 'Run Codex sessions through the local app-server instead of one-shot CLI processes. Enables token streaming and native turn control.',
+ 'features.codexAppServer.title': 'Codex App Server Runtime',
'features.heteroSessionImport.desc':
'Add an "Import Local Agent Sessions" entry to the topic list menu: scan local Claude Code / Codex CLI transcripts and import them as topics, with incremental sync on re-import.',
'features.heteroSessionImport.title': 'Local Agent Session Import',
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index f738c7309a1..c12fd82063f 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -165,6 +165,10 @@ export const UserLabSchema = z.object({
* run Claude Code hetero sessions through the Claude Agent SDK instead of CLI spawn
*/
enableClaudeCodeSdk: z.boolean().optional(),
+ /**
+ * run Codex hetero sessions through codex app-server instead of one-shot CLI spawn
+ */
+ enableCodexAppServer: z.boolean().optional(),
/**
* one-click import of local Claude Code / Codex CLI sessions as topics (desktop only)
*/
diff --git a/src/routes/(main)/settings/labs/index.tsx b/src/routes/(main)/settings/labs/index.tsx
index 5f9819137b4..d0b750f0d1a 100644
--- a/src/routes/(main)/settings/labs/index.tsx
+++ b/src/routes/(main)/settings/labs/index.tsx
@@ -37,6 +37,7 @@ const LabsForm = memo(() => {
enablePlatformAgent,
enableImessage,
enableClaudeCodeSdk,
+ enableCodexAppServer,
enableHeteroSessionImport,
enableMessageTextSelectionActions,
enableOAuthApps,
@@ -54,6 +55,7 @@ const LabsForm = memo(() => {
labPreferSelectors.enablePlatformAgent(s),
labPreferSelectors.enableImessage(s),
labPreferSelectors.enableClaudeCodeSdk(s),
+ labPreferSelectors.enableCodexAppServer(s),
labPreferSelectors.enableHeteroSessionImport(s),
labPreferSelectors.enableMessageTextSelectionActions(s),
labPreferSelectors.enableOAuthApps(s),
@@ -178,8 +180,8 @@ const LabsForm = memo(() => {
} satisfies FormItemProps,
];
- // Desktop-only experiments: iMessage bridge, the Claude Code SDK runtime, and
- // the in-app browser (renderer-retained Electron webviews).
+ // Desktop-only experiments: local agent runtimes, iMessage bridge, and the
+ // in-app browser (renderer-retained Electron webviews).
const desktopItems: FormItemProps[] = [
{
children: (
@@ -207,6 +209,19 @@ const LabsForm = memo(() => {
label: tLabs('features.claudeCodeSdk.title'),
minWidth: undefined,
},
+ {
+ children: (
+ <Switch
+ checked={enableCodexAppServer}
+ loading={!isPreferenceInit}
+ onChange={(checked: boolean) => updateLab({ enableCodexAppServer: checked })}
+ />
+ ),
+ className: styles.labItem,
+ desc: tLabs('features.codexAppServer.desc'),
+ label: tLabs('features.codexAppServer.title'),
+ minWidth: undefined,
+ },
// rides on the Claude Code hetero-agent stack: scans local CLI
// transcripts via the Electron main process — desktop only
{
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index 03ca96838f4..45fcd0b808d 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -27,6 +27,7 @@ class HeterogeneousAgentService {
env?: Record<string, string>;
resumeSessionId?: string;
useClaudeCodeSdk?: boolean;
+ useCodexAppServer?: boolean;
}) {
return this.ipc.heterogeneousAgent.startSession(params);
}
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index fbfdb41054a..b295626b2ca 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -22,6 +22,7 @@ import { ThreadStatus } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useChatStore } from '@/store/chat/store';
+import { useUserStore } from '@/store/user';
import { createGatewayEventHandler } from '../transports/gateway/gatewayEventHandler';
import type { HeterogeneousAgentExecutorParams } from '../transports/hetero/heterogeneousAgentExecutor';
@@ -1679,6 +1680,36 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
+ it('should inject local workspace context only when starting a native session', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+ const params = {
+ ...defaultParams,
+ heterogeneousProvider: {
+ command: 'codex',
+ systemContext: 'Follow the agent rules.',
+ type: 'codex' as const,
+ },
+ workingDirectory: '/Users/me/repo',
+ };
+
+ await executeHeterogeneousAgent(get, params);
+
+ expect(mockSendPrompt.mock.calls[0][0].systemContext).toContain(
+ "You are running on the user's own machine. Your working directory is `/Users/me/repo`.",
+ );
+
+ await executeHeterogeneousAgent(get, {
+ ...params,
+ resumeSessionId: 'codex-thread-existing',
+ });
+
+ const resumedSystemContext = mockSendPrompt.mock.calls[1][0].systemContext;
+ expect(resumedSystemContext).toBe('Follow the agent rules.');
+ expect(resumedSystemContext).not.toContain('## Workspace');
+ expect(resumedSystemContext).not.toContain('/Users/me/repo');
+ });
+
it('should forward context selections as heterogeneous system context', async () => {
const store = createMockStore();
const get = vi.fn(() => store);
@@ -1765,6 +1796,33 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
});
+ it('should pass the Codex app-server lab preference to the desktop session', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+ const previousLab = useUserStore.getState().preference.lab;
+ useUserStore.setState((state) => ({
+ preference: {
+ ...state.preference,
+ lab: { ...state.preference.lab, enableCodexAppServer: true },
+ },
+ }));
+
+ try {
+ await executeHeterogeneousAgent(get, {
+ ...defaultParams,
+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },
+ });
+ } finally {
+ useUserStore.setState((state) => ({
+ preference: { ...state.preference, lab: previousLab },
+ }));
+ }
+
+ expect(mockStartSession).toHaveBeenCalledWith(
+ expect.objectContaining({ useCodexAppServer: true }),
+ );
+ });
+
it('should preserve Claude Code defaults when model and effort are not selected', async () => {
const store = createMockStore();
const get = vi.fn(() => store);
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 1708a69e7a6..bb2c5ffb82c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -1949,6 +1949,7 @@ export const executeHeterogeneousAgent = async (
env: sessionEnv,
resumeSessionId,
useClaudeCodeSdk: labPreferSelectors.enableClaudeCodeSdk(useUserStore.getState()),
+ useCodexAppServer: labPreferSelectors.enableCodexAppServer(useUserStore.getState()),
});
// Attribute the run to the login the FINAL env actually resolves to (an
@@ -2421,7 +2422,9 @@ export const executeHeterogeneousAgent = async (
agentSystemContext: heterogeneousProvider.systemContext,
contextSelections,
pageSelections,
- workingDirectory,
+ // The native CLI session already retains its workspace context. Reinjecting this note on
+ // every resumed turn makes it accumulate in persistent Codex/Claude conversations.
+ workingDirectory: resumeSessionId ? undefined : workingDirectory,
});
// When resuming, hand main the prior turns so it can rebuild a Claude Code
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index bfabc3bda05..cf3c7292be2 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -12,6 +12,7 @@ export const labPreferSelectors = {
enableArtifactDeployment: (s: UserState): boolean =>
s.preference.lab?.enableArtifactDeployment ?? false,
enableClaudeCodeSdk: (s: UserState): boolean => s.preference.lab?.enableClaudeCodeSdk ?? false,
+ enableCodexAppServer: (s: UserState): boolean => s.preference.lab?.enableCodexAppServer ?? false,
enableHeteroSessionImport: (s: UserState): boolean =>
s.preference.lab?.enableHeteroSessionImport ?? false,
enableImessage: (s: UserState): boolean => s.preference.lab?.enableImessage ?? false,