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(desktop): complete Codex app-server session lifecycle (#18275)

AmAzing-3fc02f550113
diff --git a/.prettierignore b/.prettierignore
index 1d6c7360757..368957d81f5 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -66,3 +66,6 @@ Dockerfile*
# generated files (regenerate with `bun generate` in packages/sdk)
packages/sdk/src/generated/
+
+# generated files (regenerate with `codex app-server generate-ts`)
+packages/heterogeneous-agents/src/codex/protocol/generated.ts
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 45239200216..9778f558e35 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -48,21 +48,25 @@ import {
buildAgentInput,
buildCodexAppServerArgs,
buildCodexAppServerInput,
+ buildCodexAppServerThreadParams,
buildGrokAcpArgs,
buildGrokAcpPrompt,
buildTraeAcpArgs,
buildTraeAcpPrompt,
ClaudeAgentSdkSession,
- CodexAppServerSession,
+ CodexAppServerClient,
+ CodexThreadSession,
createFileStoreImageUploader,
ensureClaudeCodeResumeTranscript,
getCodexAppServerUnsupportedArgs,
GrokAcpSession,
+ isCodexAppServerCompatibilityError,
readCodexSessionModel,
resolveCliSpawnPlan,
resolveCodexInitialModel,
TraeAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
+import { truncateTitle } from '@lobechat/heterogeneous-agents/transcript';
import type {
HeterogeneousAgentModelCatalog,
HeteroSessionImportMessage,
@@ -294,7 +298,7 @@ export interface SessionInfo {
interface AgentSession {
agentSessionId?: string;
agentType: HeterogeneousCliAgentType;
- appServerSession?: CodexAppServerSession;
+ appServerSession?: CodexThreadSession;
args: string[];
/**
* True when *we* initiated the kill (cancelSession / stopSession / before-quit).
@@ -304,6 +308,7 @@ interface AgentSession {
* intentional, not agent failures.
*/
cancelledByUs?: boolean;
+ codexAppServerFallback?: boolean;
command: string;
cwd?: string;
env?: Record<string, string>;
@@ -406,6 +411,8 @@ export default class HeterogeneousAgentCtr {
/** Lazy single MCP server, started on first claude-code prompt. */
private builtinMcpServer?: LobeBuiltinMcpServer;
private builtinMcpStartPromise?: Promise<LobeBuiltinMcpServer>;
+ /** One lazy, long-lived native Codex app-server connection shared by thread sessions. */
+ private codexAppServerClient?: CodexAppServerClient;
// Fresh window sits under the renderer's 2-minute auto-refresh so each
// scheduled poll reaches the usage API instead of a cache echo.
private readonly claudeCodeQuotaCache = new QuotaSnapshotCache<ClaudeCodeQuotaSnapshot>({
@@ -1155,18 +1162,25 @@ export default class HeterogeneousAgentCtr {
if (
session.agentType === 'codex' &&
+ !session.codexAppServerFallback &&
(session.useCodexAppServer || this.isCodexAppServerLabEnabled)
) {
const unsupportedArgs = getCodexAppServerUnsupportedArgs(session.args, {
resume: !!session.agentSessionId,
});
if (unsupportedArgs.length === 0) {
- return this.sendPromptWithCodexAppServer(params, session);
+ if (await this.sendPromptWithCodexAppServer(params, session)) return;
+ } else if (session.agentSessionId) {
+ const message = `Codex app-server cannot safely resume this session without dropping CLI arguments: ${unsupportedArgs.join(', ')}`;
+ this.broadcast('heteroAgentSessionError', { error: message, sessionId: session.sessionId });
+ throw new Error(message);
+ } else {
+ session.codexAppServerFallback = true;
+ logger.warn('Falling back to codex exec because app-server cannot preserve CLI args:', {
+ sessionId: session.sessionId,
+ unsupportedArgs,
+ });
}
- logger.warn('Falling back to codex exec because app-server cannot preserve CLI args:', {
- sessionId: session.sessionId,
- unsupportedArgs,
- });
}
if (session.agentType === 'grok-build') {
@@ -1416,7 +1430,7 @@ export default class HeterogeneousAgentCtr {
private async sendPromptWithCodexAppServer(
params: SendPromptParams,
session: AgentSession,
- ): Promise<void> {
+ ): Promise<boolean> {
const cwd = session.cwd || electronApp.getPath('desktop');
const spawnEnv = this.buildSessionSpawnEnv(session);
const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);
@@ -1456,39 +1470,69 @@ export default class HeterogeneousAgentCtr {
});
void this.writeCliTraceFile(traceSession, 'stdin.txt', inputPayload);
- const appServerSession = new CodexAppServerSession({
- args: session.args,
+ const clientOptions = {
+ args: appServerArgs.slice(0, -1),
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,
- });
+ };
+ const existingClient = this.codexAppServerClient;
+ if (existingClient && !existingClient.canReuseFor(clientOptions)) {
+ if (!existingClient.hasConsumers) {
+ existingClient.close();
+ if (this.codexAppServerClient === existingClient) this.codexAppServerClient = undefined;
+ } else {
+ const message =
+ 'The running Codex app-server uses a different binary, global configuration, or environment';
+ logger.error('Cannot reuse the native Codex app-server client:', {
+ sessionId: session.sessionId,
+ });
+ void this.writeCliTraceJson(traceSession, 'process-error.json', {
+ message,
+ transport: 'codex-app-server',
+ });
+ await this.flushCliTrace(traceSession);
+ this.broadcast('heteroAgentSessionError', {
+ error: message,
+ sessionId: session.sessionId,
+ });
+ throw new Error(message);
+ }
+ }
+
+ const client =
+ this.codexAppServerClient ??
+ (this.codexAppServerClient = new CodexAppServerClient(clientOptions));
+ const appServerSession =
+ session.appServerSession ??
+ new CodexThreadSession({
+ client,
+ initialCumulativeUsage,
+ initialModel: session.model,
+ initialThreadId: session.agentSessionId,
+ threadName: truncateTitle(params.prompt),
+ 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';
+ },
+ onRuntimeStatus: (status) => {
+ this.broadcast('heteroAgentRuntimeStatus', status);
+ },
+ onSessionId: (agentSessionId) => {
+ if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;
+ },
+ sessionId: session.sessionId,
+ threadParams: buildCodexAppServerThreadParams(session.args, cwd, session.model),
+ });
session.appServerSession = appServerSession;
logger.info('Starting Codex app-server session:', {
@@ -1498,15 +1542,55 @@ export default class HeterogeneousAgentCtr {
});
try {
- await appServerSession.run();
+ await appServerSession.run({
+ input,
+ onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),
+ operationId: params.operationId,
+ });
void this.writeCliTraceJson(traceSession, 'exit.json', {
finishedAt: new Date().toISOString(),
transport: 'codex-app-server',
});
await this.flushCliTrace(traceSession);
this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return true;
} catch (error) {
+ if (appServerSession.canFallbackToExec && isCodexAppServerCompatibilityError(error)) {
+ session.codexAppServerFallback = true;
+ logger.warn('Falling back to codex exec because native app-server is unavailable:', {
+ message: this.getErrorMessage(error),
+ sessionId: session.sessionId,
+ });
+ void this.writeCliTraceJson(traceSession, 'fallback.json', {
+ message: this.getErrorMessage(error),
+ transport: 'codex-app-server',
+ });
+ await this.flushCliTrace(traceSession);
+ this.broadcast('heteroAgentEvent', {
+ event: {
+ data: {
+ message:
+ 'Codex app-server is unavailable or incompatible. Upgrade Codex to use the Labs transport; continuing with codex exec.',
+ },
+ operationId: params.operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'stream_retry',
+ } satisfies AgentStreamEvent,
+ sessionId: session.sessionId,
+ });
+ appServerSession.close();
+ if (session.appServerSession === appServerSession) session.appServerSession = undefined;
+ if (!client.hasConsumers) {
+ client.close();
+ if (this.codexAppServerClient === client) this.codexAppServerClient = undefined;
+ }
+ return false;
+ }
+
logger.error('Codex app-server session error:', error);
+ appServerSession.close();
+ if (session.appServerSession === appServerSession) session.appServerSession = undefined;
void this.writeCliTraceJson(traceSession, 'process-error.json', {
message: error instanceof Error ? error.message : String(error),
name: error instanceof Error ? error.name : 'Error',
@@ -1516,7 +1600,7 @@ export default class HeterogeneousAgentCtr {
if (session.cancelledByUs) {
this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- return;
+ return true;
}
const sessionError = this.getSessionErrorPayload(error, session);
@@ -1527,8 +1611,6 @@ export default class HeterogeneousAgentCtr {
throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {
cause: error,
});
- } finally {
- if (session.appServerSession === appServerSession) session.appServerSession = undefined;
}
}
@@ -2160,11 +2242,13 @@ export default class HeterogeneousAgentCtr {
return;
}
if (session.appServerSession) {
+ const appServerSession = session.appServerSession;
try {
- await session.appServerSession.interrupt();
+ await appServerSession.interrupt();
} catch (error) {
logger.warn('Codex app-server interrupt failed; closing session:', error);
- session.appServerSession.close();
+ appServerSession.close();
+ if (session.appServerSession === appServerSession) session.appServerSession = undefined;
}
return;
}
@@ -2203,6 +2287,11 @@ export default class HeterogeneousAgentCtr {
if (session.appServerSession) {
session.cancelledByUs = true;
+ try {
+ await session.appServerSession.interrupt();
+ } catch (error) {
+ logger.warn('Codex app-server interrupt failed while stopping the session:', error);
+ }
session.appServerSession.close();
}
@@ -2304,6 +2393,8 @@ export default class HeterogeneousAgentCtr {
this.killProcessTree(session.process, 'SIGTERM');
}
}
+ this.codexAppServerClient?.close();
+ this.codexAppServerClient = undefined;
this.sessions.clear();
// The exit handlers will tear each per-op intervention down, but if
// CC's stdio close races shutdown we'd leave the MCP server bound to
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 00acd1f2435..bd2464d85e8 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -100,9 +100,17 @@ vi.mock('@/utils/logger', () => ({
const {
claudeSdkSessionCloseMock,
claudeSdkSessionConstructMock,
+ codexAppServerCanReuse,
+ codexAppServerClientCloseMock,
+ codexAppServerClientConstructMock,
codexAppServerCloseMock,
+ codexAppServerConsumerCount,
codexAppServerConstructMock,
codexAppServerInterruptMock,
+ codexAppServerRunMock,
+ codexAppServerShouldFailAfterThread,
+ codexAppServerShouldFailResume,
+ codexAppServerShouldFallback,
grokAcpSessionCloseMock,
grokAcpSessionConstructMock,
grokAcpSessionInterruptMock,
@@ -114,9 +122,17 @@ const {
} = vi.hoisted(() => ({
claudeSdkSessionCloseMock: vi.fn(),
claudeSdkSessionConstructMock: vi.fn(),
+ codexAppServerCanReuse: { value: true },
+ codexAppServerClientCloseMock: vi.fn(),
+ codexAppServerClientConstructMock: vi.fn(),
codexAppServerCloseMock: vi.fn(),
+ codexAppServerConsumerCount: { value: 0 },
codexAppServerConstructMock: vi.fn(),
codexAppServerInterruptMock: vi.fn(),
+ codexAppServerRunMock: vi.fn(),
+ codexAppServerShouldFailAfterThread: { value: false },
+ codexAppServerShouldFailResume: { value: false },
+ codexAppServerShouldFallback: { value: false },
grokAcpSessionCloseMock: vi.fn(),
grokAcpSessionConstructMock: vi.fn(),
grokAcpSessionInterruptMock: vi.fn(),
@@ -175,25 +191,70 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
}
}
- class MockCodexAppServerSession {
+ class MockCodexAppServerClient {
+ constructor(options: any) {
+ codexAppServerClientConstructMock(options);
+ }
+
+ canReuseFor() {
+ return codexAppServerCanReuse.value;
+ }
+
+ get hasConsumers() {
+ return codexAppServerConsumerCount.value > 0;
+ }
+
+ close() {
+ codexAppServerClientCloseMock();
+ }
+ }
+
+ class MockCodexThreadSession {
+ canFallbackToExec = true;
+ private closed = false;
+
constructor(private readonly options: any) {
+ codexAppServerConsumerCount.value += 1;
codexAppServerConstructMock(options);
}
close() {
+ if (!this.closed) {
+ this.closed = true;
+ codexAppServerConsumerCount.value -= 1;
+ }
codexAppServerCloseMock();
}
async interrupt() {
- codexAppServerInterruptMock();
+ return codexAppServerInterruptMock();
}
- async run() {
+ async run(runOptions: any) {
+ codexAppServerRunMock(runOptions);
+ if (codexAppServerShouldFailResume.value && this.options.initialThreadId) {
+ this.canFallbackToExec = false;
+ const error = new Error('Thread not found');
+ error.name = 'CodexAppServerConnectionError';
+ throw error;
+ }
+ if (codexAppServerShouldFallback.value) {
+ const error = new Error('Method not found: initialize');
+ error.name = 'CodexAppServerConnectionError';
+ throw error;
+ }
+
const now = Date.now();
+ this.canFallbackToExec = false;
+ if (codexAppServerShouldFailAfterThread.value) {
+ const error = new Error('Codex app-server disconnected');
+ error.name = 'CodexAppServerConnectionError';
+ throw error;
+ }
this.options.onRuntimeStatus({
activeTasks: [],
lastEventAt: now,
- operationId: this.options.operationId,
+ operationId: runOptions.operationId,
sessionId: this.options.sessionId,
state: 'running',
transport: 'codex-app-server',
@@ -202,7 +263,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
await this.options.onEvents([
{
data: { reason: 'complete', transport: 'codex-app-server' },
- operationId: this.options.operationId,
+ operationId: runOptions.operationId,
stepIndex: 0,
timestamp: now,
type: 'agent_runtime_end',
@@ -286,7 +347,10 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
return {
...actual,
ClaudeAgentSdkSession: MockClaudeAgentSdkSession,
- CodexAppServerSession: MockCodexAppServerSession,
+ CodexAppServerClient: MockCodexAppServerClient,
+ CodexThreadSession: MockCodexThreadSession,
+ isCodexAppServerCompatibilityError: (error: Error) =>
+ error.name === 'CodexAppServerConnectionError',
GrokAcpSession: MockGrokAcpSession,
TraeAcpSession: MockTraeAcpSession,
};
@@ -387,9 +451,17 @@ describe('HeterogeneousAgentCtr', () => {
fetchCodexQuotaMock.mockReset();
claudeSdkSessionCloseMock.mockReset();
claudeSdkSessionConstructMock.mockReset();
+ codexAppServerCanReuse.value = true;
+ codexAppServerClientCloseMock.mockReset();
+ codexAppServerClientConstructMock.mockReset();
codexAppServerCloseMock.mockReset();
+ codexAppServerConsumerCount.value = 0;
codexAppServerConstructMock.mockReset();
codexAppServerInterruptMock.mockReset();
+ codexAppServerRunMock.mockReset();
+ codexAppServerShouldFailAfterThread.value = false;
+ codexAppServerShouldFailResume.value = false;
+ codexAppServerShouldFallback.value = false;
grokAcpSessionCloseMock.mockReset();
grokAcpSessionConstructMock.mockReset();
grokAcpSessionInterruptMock.mockReset();
@@ -1654,12 +1726,25 @@ describe('HeterogeneousAgentCtr', () => {
await ctr.sendPrompt({ operationId: 'op-test', prompt: 'stream this', sessionId });
expect(spawnCalls).toHaveLength(0);
- expect(codexAppServerConstructMock).toHaveBeenCalledWith(
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledWith(
expect.objectContaining({
- args: ['--model', 'gpt-5.5-codex'],
+ args: [],
clientVersion: '1.0.0-test',
commandPath: 'codex',
cwd: FAKE_DESKTOP_PATH,
+ }),
+ );
+ expect(codexAppServerConstructMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ threadName: 'stream this',
+ threadParams: expect.objectContaining({
+ cwd: FAKE_DESKTOP_PATH,
+ model: 'gpt-5.5-codex',
+ }),
+ }),
+ );
+ expect(codexAppServerRunMock).toHaveBeenCalledWith(
+ expect.objectContaining({
input: [{ text: 'stream this', text_elements: [], type: 'text' }],
operationId: 'op-test',
}),
@@ -1670,11 +1755,134 @@ describe('HeterogeneousAgentCtr', () => {
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.
+ it('reuses one native app-server client for multiple new Codex sessions', async () => {
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const first = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ const second = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId: first.sessionId });
+ await ctr.sendPrompt({ operationId: 'op-2', prompt: 'second', sessionId: second.sessionId });
+
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);
+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('reuses one native thread session across multiple turns', async () => {
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId });
+ await ctr.sendPrompt({ operationId: 'op-2', prompt: 'second', sessionId });
+
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);
+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(1);
+ expect(codexAppServerRunMock.mock.calls.map(([options]) => options.operationId)).toEqual([
+ 'op-1',
+ 'op-2',
+ ]);
+ });
+
+ it('does not switch to exec when the shared native client is incompatible', async () => {
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const first = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ const second = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId: first.sessionId });
+
+ codexAppServerCanReuse.value = false;
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-2', prompt: 'second', sessionId: second.sessionId }),
+ ).rejects.toThrow('different binary, global configuration, or environment');
+
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);
+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(1);
+ expect(spawnCalls).toHaveLength(0);
+ });
+
+ it('replaces an incompatible shared client after its last thread session closes', async () => {
+ codexAppServerShouldFailAfterThread.value = true;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const first = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-1', prompt: 'fail', sessionId: first.sessionId }),
+ ).rejects.toThrow('Codex app-server disconnected');
+ expect(codexAppServerConsumerCount.value).toBe(0);
+
+ codexAppServerShouldFailAfterThread.value = false;
+ codexAppServerCanReuse.value = false;
+ const second = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ await ctr.sendPrompt({ operationId: 'op-2', prompt: 'retry', sessionId: second.sessionId });
+
+ expect(codexAppServerClientCloseMock).toHaveBeenCalledOnce();
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(2);
+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([
+ { args: ['--profile', 'work'], label: 'profile' },
+ { args: ['-a', 'on-request'], label: 'interactive approval policy' },
+ ])('keeps unsupported Codex $label arguments on exec', async ({ args }) => {
const { proc } = createFakeProc();
nextFakeProc = proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ args,
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'preserve CLI semantics', sessionId });
+
+ expect(codexAppServerClientConstructMock).not.toHaveBeenCalled();
+ expect(codexAppServerConstructMock).not.toHaveBeenCalled();
+ expect(spawnCalls).toHaveLength(1);
+ expect(spawnCalls[0].args).toEqual(expect.arrayContaining(args));
+ });
+
+ it('does not replay an existing thread through exec when its arguments are unsupported', async () => {
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
@@ -1683,14 +1891,151 @@ describe('HeterogeneousAgentCtr', () => {
agentType: 'codex',
args: ['--profile', 'work'],
command: 'codex',
+ resumeSessionId: 'thread-existing',
useCodexAppServer: true,
});
- await ctr.sendPrompt({ operationId: 'op-test', prompt: 'preserve profile', sessionId });
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-test', prompt: 'preserve CLI semantics', sessionId }),
+ ).rejects.toThrow('cannot safely resume this session');
+ expect(codexAppServerClientConstructMock).not.toHaveBeenCalled();
expect(codexAppServerConstructMock).not.toHaveBeenCalled();
+ expect(spawnCalls).toHaveLength(0);
+ });
+
+ it('falls back to codex exec when the native handshake is incompatible', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ const { proc } = createFakeProc();
+ nextFakeProc = proc;
+ codexAppServerShouldFallback.value = true;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'fallback safely', sessionId });
+
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);
+ expect(codexAppServerClientCloseMock).toHaveBeenCalledTimes(1);
expect(spawnCalls).toHaveLength(1);
- expect(spawnCalls[0].args).toEqual(expect.arrayContaining(['--profile', 'work']));
+ expect(spawnCalls[0].args).toEqual(expect.arrayContaining(['exec', '--json']));
+ expect(send).toHaveBeenCalledWith('heteroAgentEvent', {
+ event: expect.objectContaining({
+ data: expect.objectContaining({ message: expect.stringContaining('Upgrade Codex') }),
+ operationId: 'op-test',
+ type: 'stream_retry',
+ }),
+ sessionId,
+ });
+
+ codexAppServerShouldFallback.value = false;
+ const { proc: retryProc } = createFakeProc();
+ nextFakeProc = retryProc;
+ await ctr.sendPrompt({ operationId: 'op-retry', prompt: 'stay on exec', sessionId });
+
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);
+ expect(spawnCalls).toHaveLength(2);
+ });
+
+ it('does not fall back to exec after the native thread is established', async () => {
+ codexAppServerShouldFailAfterThread.value = true;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-test', prompt: 'do not replay', sessionId }),
+ ).rejects.toThrow('Codex app-server disconnected');
+
+ expect(codexAppServerClientCloseMock).not.toHaveBeenCalled();
+ expect(codexAppServerCloseMock).toHaveBeenCalledOnce();
+ expect(spawnCalls).toHaveLength(0);
+
+ codexAppServerShouldFailAfterThread.value = false;
+ await ctr.sendPrompt({ operationId: 'op-retry', prompt: 'resume natively', sessionId });
+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('clears a closed native thread session after a genuine interrupt failure', async () => {
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ useCodexAppServer: true,
+ });
+ await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId });
+ codexAppServerInterruptMock.mockRejectedValueOnce(new Error('Interrupt rejected'));
+
+ await ctr.cancelSession({ sessionId });
+ await ctr.sendPrompt({ operationId: 'op-2', prompt: 'continue', sessionId });
+
+ expect(codexAppServerCloseMock).toHaveBeenCalledOnce();
+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);
+ expect(codexAppServerClientConstructMock).toHaveBeenCalledOnce();
+ });
+
+ it('resumes existing Codex threads through native app-server', async () => {
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ resumeSessionId: 'thread-existing',
+ useCodexAppServer: true,
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-test', prompt: 'continue', sessionId });
+
+ expect(codexAppServerConstructMock).toHaveBeenCalledWith(
+ expect.objectContaining({ initialThreadId: 'thread-existing' }),
+ );
+ expect(codexAppServerRunMock).toHaveBeenCalledTimes(1);
+ expect(spawnCalls).toHaveLength(0);
+ });
+
+ it('does not replay an existing Codex thread through exec when thread/resume fails', async () => {
+ codexAppServerShouldFailResume.value = true;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ resumeSessionId: 'thread-existing',
+ useCodexAppServer: true,
+ });
+
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-test', prompt: 'continue', sessionId }),
+ ).rejects.toThrow('saved Codex thread could not be found');
+
+ expect(codexAppServerRunMock).toHaveBeenCalledTimes(1);
+ expect(codexAppServerClientCloseMock).not.toHaveBeenCalled();
+ expect(spawnCalls).toHaveLength(0);
});
it('places system context before the user prompt in codex stdin', async () => {
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 0a72e938fa8..f90cb9e769b 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -127,6 +127,8 @@ export default eslint(
'packages/openapi/openapi.yml',
// generated files (regenerate with `bun generate` in packages/sdk)
'packages/sdk/src/generated/**',
+ // generated files (regenerate with `codex app-server generate-ts`)
+ 'packages/heterogeneous-agents/src/codex/protocol/generated.ts',
],
next: true,
react: 'next',
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index 4d03726adc4..e536871e70c 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -27,6 +27,7 @@
"@anthropic-ai/sdk": "^0.93.0",
"@lobechat/agent-gateway-client": "workspace:*",
"@lobechat/types": "workspace:*",
+ "@lobechat/utils": "workspace:*",
"@lobehub/icons": "^5.15.0",
"@modelcontextprotocol/sdk": "^1.29.0",
"diff": "^8.0.4",
diff --git a/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-single-turn.jsonl b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-single-turn.jsonl
new file mode 100644
index 00000000000..83515bed9a9
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-single-turn.jsonl
@@ -0,0 +1,14 @@
+{"method":"turn/started","params":{"threadId":"thread-1","turn":{"id":"turn-1","items":[],"itemsView":"full","status":"inProgress","error":null,"startedAt":1,"completedAt":null,"durationMs":null}}}
+{"method":"item/reasoning/summaryTextDelta","params":{"threadId":"thread-1","turnId":"turn-1","itemId":"reasoning-1","summaryIndex":0,"delta":"Inspecting the workspace"}}
+{"method":"item/completed","params":{"threadId":"thread-1","turnId":"turn-1","completedAtMs":2,"item":{"type":"reasoning","id":"reasoning-1","summary":["Inspecting the workspace"],"content":[]}}}
+{"method":"item/started","params":{"threadId":"thread-1","turnId":"turn-1","startedAtMs":3,"item":{"type":"commandExecution","id":"command-1","command":"pwd","aggregatedOutput":null,"exitCode":null,"durationMs":null,"status":"inProgress"}}}
+{"method":"item/commandExecution/outputDelta","params":{"threadId":"thread-1","turnId":"turn-1","itemId":"command-1","delta":"/work"}}
+{"method":"item/completed","params":{"threadId":"thread-1","turnId":"turn-1","completedAtMs":4,"item":{"type":"commandExecution","id":"command-1","command":"pwd","aggregatedOutput":"/workspace\n","exitCode":0,"durationMs":1,"status":"completed"}}}
+{"method":"item/started","params":{"threadId":"thread-1","turnId":"turn-1","startedAtMs":5,"item":{"type":"mcpToolCall","id":"mcp-1","server":"docs","tool":"lookup","status":"inProgress","arguments":{"query":"Codex"},"result":null,"error":null}}}
+{"method":"item/completed","params":{"threadId":"thread-1","turnId":"turn-1","completedAtMs":6,"item":{"type":"mcpToolCall","id":"mcp-1","server":"docs","tool":"lookup","status":"completed","arguments":{"query":"Codex"},"result":{"content":[{"type":"text","text":"Found docs"}],"structuredContent":null,"_meta":null},"error":null}}}
+{"method":"turn/plan/updated","params":{"threadId":"thread-1","turnId":"turn-1","explanation":null,"plan":[{"step":"Inspect","status":"completed"},{"step":"Answer","status":"inProgress"}]}}
+{"method":"item/agentMessage/delta","params":{"threadId":"thread-1","turnId":"turn-1","itemId":"message-1","delta":"Done."}}
+{"method":"item/completed","params":{"threadId":"thread-1","turnId":"turn-1","completedAtMs":7,"item":{"type":"agentMessage","id":"message-1","text":"Done.","phase":"final_answer","memoryCitation":null}}}
+{"method":"thread/tokenUsage/updated","params":{"threadId":"thread-1","turnId":"turn-1","tokenUsage":{"total":{"totalTokens":17,"inputTokens":10,"cachedInputTokens":2,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":3},"last":{"totalTokens":17,"inputTokens":10,"cachedInputTokens":2,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":3},"modelContextWindow":200000}}}
+{"method":"future/notification","params":{"threadId":"thread-1","value":true}}
+{"method":"turn/completed","params":{"threadId":"thread-1","turn":{"id":"turn-1","items":[],"itemsView":"full","status":"completed","error":null,"startedAt":1,"completedAt":2,"durationMs":1000}}}
diff --git a/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-vs-exec.json b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-vs-exec.json
new file mode 100644
index 00000000000..287e7721e2c
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-vs-exec.json
@@ -0,0 +1,149 @@
+{
+ "appServer": [
+ {
+ "method": "turn/started",
+ "params": {
+ "threadId": "thread-1",
+ "turn": {
+ "id": "turn-1",
+ "items": [],
+ "itemsView": "full",
+ "status": "inProgress",
+ "error": null,
+ "startedAt": 1,
+ "completedAt": null,
+ "durationMs": null
+ }
+ }
+ },
+ {
+ "method": "item/started",
+ "params": {
+ "threadId": "thread-1",
+ "turnId": "turn-1",
+ "startedAtMs": 2,
+ "item": {
+ "type": "commandExecution",
+ "id": "command-1",
+ "command": "pwd",
+ "aggregatedOutput": null,
+ "exitCode": null,
+ "durationMs": null,
+ "status": "inProgress"
+ }
+ }
+ },
+ {
+ "method": "item/completed",
+ "params": {
+ "threadId": "thread-1",
+ "turnId": "turn-1",
+ "completedAtMs": 3,
+ "item": {
+ "type": "commandExecution",
+ "id": "command-1",
+ "command": "pwd",
+ "aggregatedOutput": "/workspace\n",
+ "exitCode": 0,
+ "durationMs": 1,
+ "status": "completed"
+ }
+ }
+ },
+ {
+ "method": "item/completed",
+ "params": {
+ "threadId": "thread-1",
+ "turnId": "turn-1",
+ "completedAtMs": 4,
+ "item": {
+ "type": "agentMessage",
+ "id": "message-1",
+ "text": "Done.",
+ "phase": "final_answer",
+ "memoryCitation": null
+ }
+ }
+ },
+ {
+ "method": "thread/tokenUsage/updated",
+ "params": {
+ "threadId": "thread-1",
+ "turnId": "turn-1",
+ "tokenUsage": {
+ "total": {
+ "totalTokens": 17,
+ "inputTokens": 10,
+ "cachedInputTokens": 2,
+ "cacheWriteInputTokens": 0,
+ "outputTokens": 7,
+ "reasoningOutputTokens": 3
+ },
+ "last": {
+ "totalTokens": 17,
+ "inputTokens": 10,
+ "cachedInputTokens": 2,
+ "cacheWriteInputTokens": 0,
+ "outputTokens": 7,
+ "reasoningOutputTokens": 3
+ },
+ "modelContextWindow": 200000
+ }
+ }
+ },
+ {
+ "method": "turn/completed",
+ "params": {
+ "threadId": "thread-1",
+ "turn": {
+ "id": "turn-1",
+ "items": [],
+ "itemsView": "full",
+ "status": "completed",
+ "error": null,
+ "startedAt": 1,
+ "completedAt": 2,
+ "durationMs": 1000
+ }
+ }
+ }
+ ],
+ "exec": [
+ { "type": "turn.started" },
+ {
+ "type": "item.started",
+ "item": {
+ "type": "command_execution",
+ "id": "command-1",
+ "command": "pwd",
+ "aggregated_output": null,
+ "exit_code": null,
+ "status": "in_progress"
+ }
+ },
+ {
+ "type": "item.completed",
+ "item": {
+ "type": "command_execution",
+ "id": "command-1",
+ "command": "pwd",
+ "aggregated_output": "/workspace\n",
+ "exit_code": 0,
+ "status": "completed"
+ }
+ },
+ {
+ "type": "item.completed",
+ "item": { "type": "agent_message", "id": "message-1", "text": "Done." }
+ },
+ {
+ "type": "turn.completed",
+ "usage": {
+ "input_tokens": 10,
+ "cached_input_tokens": 2,
+ "output_tokens": 7,
+ "reasoning_output_tokens": 3
+ }
+ }
+ ]
+}
diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.ts
index 80631ec9802..409db78e564 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.ts
@@ -10,6 +10,10 @@ import type {
ToolStateChunkData,
UsageData,
} from '../types';
+import {
+ CODEX_COMMAND_OUTPUT_MAX_LENGTH,
+ truncateCodexCommandOutput,
+} from '../utils/codexCommandOutput';
import { toCodexUsageData, toTurnUsageFromCumulative } from '../utils/codexUsage';
const CODEX_IDENTIFIER = 'codex';
@@ -20,7 +24,6 @@ const CODEX_MCP_TOOL_CALL_API = 'mcp_tool_call';
const CODEX_TODO_LIST_API = 'todo_list';
const CODEX_WEB_SEARCH_API = 'web_search';
const CODEX_USAGE_SETTINGS_URL = 'https://chatgpt.com/codex/settings/usage';
-const CODEX_COMMAND_OUTPUT_MAX_LENGTH = 25_000;
const CODEX_USER_RATE_LIMIT_PATTERNS = [
/you'?ve hit your usage limit/i,
@@ -469,31 +472,6 @@ const isSuccessfulToolCompletion = (item: CodexToolItem): boolean => {
return item.status !== 'cancelled' && item.status !== 'error' && item.status !== 'failed';
};
-const truncateCodexCommandOutput = (content: string) => {
- if (!content || content.length <= CODEX_COMMAND_OUTPUT_MAX_LENGTH) {
- return {
- output: content,
- truncated: false,
- };
- }
-
- let cutoff = CODEX_COMMAND_OUTPUT_MAX_LENGTH;
- const lastCharCode = content.charCodeAt(cutoff - 1);
- if (lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff) {
- cutoff -= 1;
- }
-
- const omittedCharacters = content.length - cutoff;
- const notice = `\n\n[Output truncated: ${omittedCharacters} characters omitted. Original length: ${content.length} characters]`;
-
- return {
- omittedCharacters,
- originalLength: content.length,
- output: content.slice(0, cutoff) + notice,
- truncated: true,
- };
-};
-
const getToolResultData = (item: CodexToolItem): ToolResultData => {
const isSuccess = isSuccessfulToolCompletion(item);
const output = getToolContent(item, isSuccess);
diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts
new file mode 100644
index 00000000000..a9f5dc5b997
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts
@@ -0,0 +1,230 @@
+import { readFile } from 'node:fs/promises';
+
+import { describe, expect, it } from 'vitest';
+
+import { CodexAdapter } from './codex';
+import { CodexAppServerAdapter } from './codexAppServer';
+
+const loadFixture = async () => {
+ const source = await readFile(
+ new URL('./__fixtures__/codex/app-server-single-turn.jsonl', import.meta.url),
+ 'utf8',
+ );
+ return source
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line) as { method: string; params: unknown });
+};
+
+const loadParityFixture = async () => {
+ const source = await readFile(
+ new URL('./__fixtures__/codex/app-server-vs-exec.json', import.meta.url),
+ 'utf8',
+ );
+ return JSON.parse(source) as {
+ appServer: Array<{ method: string; params: unknown }>;
+ exec: unknown[];
+ };
+};
+
+describe('CodexAppServerAdapter', () => {
+ it('maps a native v2 turn directly into the existing stream contract', async () => {
+ const adapter = new CodexAppServerAdapter({ initialModel: 'gpt-5.5-codex' });
+ const raw = await loadFixture();
+ const events = raw.flatMap(({ method, params }) => adapter.adapt(method, params));
+
+ expect(
+ events.filter(({ type }) => type === 'stream_chunk').map(({ data }) => data.chunkType),
+ ).toEqual([
+ 'reasoning',
+ 'tools_calling',
+ 'tool_state',
+ 'tools_calling',
+ 'tools_calling',
+ 'tool_state',
+ 'text',
+ ]);
+ expect(
+ events
+ .findLast(({ data, type }) => type === 'stream_chunk' && data.chunkType === 'tools_calling')
+ ?.data.toolsCalling.map(({ id }: { id: string }) => id),
+ ).toEqual(['command-1', 'mcp-1', 'turn-plan-turn-1']);
+ expect(
+ events.filter(({ type }) => type === 'tool_result').map(({ data }) => data.toolCallId),
+ ).toEqual(['command-1', 'mcp-1', 'turn-plan-turn-1']);
+ expect(
+ events.find(({ data, type }) => type === 'stream_chunk' && data.chunkType === 'reasoning')
+ ?.data.reasoning,
+ ).toBe('Inspecting the workspace');
+ expect(
+ events
+ .filter(({ data, type }) => type === 'stream_chunk' && data.chunkType === 'text')
+ .map(({ data }) => data.content),
+ ).toEqual(['Done.']);
+ expect(
+ events.find(({ data, type }) => type === 'step_complete' && data.usage)?.data.usage,
+ ).toMatchObject({
+ inputCachedTokens: 2,
+ inputCacheMissTokens: 8,
+ outputReasoningTokens: 3,
+ outputTextTokens: 4,
+ totalTokens: 17,
+ });
+ expect(events.at(-1)).toMatchObject({ type: 'agent_runtime_end' });
+ });
+
+ it('ignores unknown notification methods for forward compatibility', () => {
+ const adapter = new CodexAppServerAdapter();
+
+ expect(adapter.adapt('future/notification', { threadId: 'thread-1' })).toEqual([]);
+ });
+
+ it('keeps unfinished plan state when a turn is interrupted', () => {
+ const adapter = new CodexAppServerAdapter();
+ const planEvents = adapter.adapt('turn/plan/updated', {
+ explanation: null,
+ plan: [
+ { status: 'completed', step: 'Inspect' },
+ { status: 'inProgress', step: 'Implement' },
+ { status: 'pending', step: 'Verify' },
+ ],
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ });
+
+ const terminalEvents = adapter.interruptForTransportFailure();
+
+ expect(
+ planEvents.find(({ data }) => data.chunkType === 'tool_state')?.data.pluginState.todos.items,
+ ).toEqual([
+ { status: 'completed', text: 'Inspect' },
+ { status: 'processing', text: 'Implement' },
+ { status: 'todo', text: 'Verify' },
+ ]);
+ expect(
+ terminalEvents.find(
+ ({ data, type }) => type === 'tool_end' && data.toolCallId === 'turn-plan-turn-1',
+ ),
+ ).toMatchObject({ data: { isSuccess: false } });
+ expect(
+ terminalEvents.some(
+ ({ data, type }) => type === 'tool_result' && data.toolCallId === 'turn-plan-turn-1',
+ ),
+ ).toBe(false);
+ });
+
+ it('truncates oversized completed command output before persisting the result', () => {
+ const adapter = new CodexAppServerAdapter();
+ const item = {
+ aggregatedOutput: 'x'.repeat(25_010),
+ command: 'print-output',
+ durationMs: 1,
+ exitCode: 0,
+ id: 'command-large',
+ status: 'completed',
+ type: 'commandExecution',
+ };
+ adapter.adapt('item/started', {
+ item: {
+ ...item,
+ aggregatedOutput: null,
+ durationMs: null,
+ exitCode: null,
+ status: 'inProgress',
+ },
+ startedAtMs: 1,
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ });
+
+ const events = adapter.adapt('item/completed', {
+ completedAtMs: 2,
+ item,
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ });
+ const result = events.find(({ type }) => type === 'tool_result')?.data;
+
+ expect(result.content).toContain(
+ '[Output truncated: 10 characters omitted. Original length: 25010 characters]',
+ );
+ expect(result.pluginState).toMatchObject({
+ omittedOutputCharacters: 10,
+ originalOutputLength: 25_010,
+ outputTruncated: true,
+ });
+ expect(result.content).toHaveLength(25_078);
+ expect(result.pluginState.output).toBe(result.content);
+ expect(result.pluginState.stdout).toBe(result.content);
+ });
+
+ it.each([
+ {
+ code: 'rate_limit',
+ info: 'usageLimitExceeded',
+ kind: 'usage_limit',
+ message: 'Usage limit reached',
+ },
+ {
+ code: 'overloaded',
+ info: 'serverOverloaded',
+ kind: 'server_overloaded',
+ message: 'Server overloaded',
+ },
+ {
+ code: 'overloaded',
+ info: { responseStreamDisconnected: { httpStatusCode: 502 } },
+ kind: 'network_drop',
+ message: 'Response stream disconnected',
+ },
+ ])('classifies native $kind failures', ({ code, info, kind, message }) => {
+ const adapter = new CodexAppServerAdapter();
+
+ const events = adapter.adapt('error', {
+ error: { additionalDetails: null, codexErrorInfo: info, message },
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ willRetry: false,
+ });
+
+ expect(events.at(-1)).toMatchObject({
+ data: {
+ code,
+ details: {
+ codexErrorInfo: info,
+ kind,
+ ...(kind === 'network_drop' ? { httpStatusCode: 502 } : {}),
+ },
+ message,
+ },
+ type: 'error',
+ });
+ });
+
+ it('keeps native and exec adapters semantically aligned during migration', async () => {
+ const fixture = await loadParityFixture();
+ const nativeAdapter = new CodexAppServerAdapter();
+ const execAdapter = new CodexAdapter();
+ const nativeEvents = fixture.appServer.flatMap(({ method, params }) =>
+ nativeAdapter.adapt(method, params),
+ );
+ const execEvents = fixture.exec.flatMap((event) => execAdapter.adapt(event));
+ const summarize = (events: typeof nativeEvents) => ({
+ text: events
+ .filter(({ data, type }) => type === 'stream_chunk' && data.chunkType === 'text')
+ .map(({ data }) => data.content)
+ .join(''),
+ toolResults: events
+ .filter(({ type }) => type === 'tool_result')
+ .map(({ data }) => ({ content: data.content, id: data.toolCallId })),
+ toolStarts: events
+ .filter(({ type }) => type === 'tool_start')
+ .map(({ data }) => data.toolCallId),
+ totalTokens: events.find(({ data, type }) => type === 'step_complete' && data.usage)?.data
+ .usage.totalTokens,
+ types: events.map(({ type }) => type),
+ });
+
+ expect(summarize(nativeEvents)).toEqual(summarize(execEvents));
+ });
+});
diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts
new file mode 100644
index 00000000000..d37edc0ea8c
--- /dev/null
+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts
@@ -0,0 +1,769 @@
+import type {
+ AgentMessageDeltaNotification,
+ CodexErrorInfo,
+ CommandExecutionOutputDeltaNotification,
+ ErrorNotification,
+ FileChangePatchUpdatedNotification,
+ FileUpdateChange,
+ ItemCompletedNotification,
+ ItemStartedNotification,
+ McpToolCallProgressNotification,
+ ReasoningSummaryTextDeltaNotification,
+ ReasoningTextDeltaNotification,
+ ThreadItem,
+ ThreadTokenUsageUpdatedNotification,
+ TokenUsageBreakdown,
+ TurnCompletedNotification,
+ TurnError,
+ TurnPlanUpdatedNotification,
+ TurnStartedNotification,
+} from '../codex/protocol';
+import type { HeteroErrorKind } from '../errors/specs';
+import type {
+ HeterogeneousAgentEvent,
+ HeterogeneousTerminalErrorData,
+ StepCompleteData,
+ StreamStartData,
+ ToolCallPayload,
+ ToolResultData,
+ ToolStateChunkData,
+ UsageData,
+} from '../types';
+import {
+ CODEX_COMMAND_OUTPUT_MAX_LENGTH,
+ truncateCodexCommandOutput,
+} from '../utils/codexCommandOutput';
+import { toTurnUsageFromCumulative } from '../utils/codexUsage';
+
+const CODEX_IDENTIFIER = 'codex';
+
+type CommandItem = Extract<ThreadItem, { type: 'commandExecution' }>;
+type AgentMessageItem = Extract<ThreadItem, { type: 'agentMessage' }>;
+type ReasoningItem = Extract<ThreadItem, { type: 'reasoning' }>;
+type FileChangeItem = Extract<ThreadItem, { type: 'fileChange' }>;
+type McpToolItem = Extract<ThreadItem, { type: 'mcpToolCall' }>;
+type DynamicToolItem = Extract<ThreadItem, { type: 'dynamicToolCall' }>;
+type CollabToolItem = Extract<ThreadItem, { type: 'collabAgentToolCall' }>;
+type WebSearchItem = Extract<ThreadItem, { type: 'webSearch' }>;
+type ToolItem =
+ CollabToolItem | CommandItem | DynamicToolItem | FileChangeItem | McpToolItem | WebSearchItem;
+
+interface StreamedOutput {
+ prefix: string;
+ totalLength: number;
+ truncated: boolean;
+}
+
+interface PlanState {
+ id: string;
+ items: Array<{ status: 'completed' | 'processing' | 'todo'; text: string }>;
+}
+
+interface CodexErrorClassification {
+ code?: 'auth_required' | 'overloaded' | 'rate_limit';
+ httpStatusCode?: number;
+ kind: HeteroErrorKind;
+}
+
+const isToolItem = (item: ThreadItem): item is ToolItem =>
+ item.type === 'collabAgentToolCall' ||
+ item.type === 'commandExecution' ||
+ item.type === 'dynamicToolCall' ||
+ item.type === 'fileChange' ||
+ item.type === 'mcpToolCall' ||
+ item.type === 'webSearch';
+
+const stringify = (value: unknown): string => {
+ if (typeof value === 'string') return value;
+ if (value === null || value === undefined) return '';
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+};
+
+const toApiName = (item: ToolItem): string => {
+ switch (item.type) {
+ case 'collabAgentToolCall': {
+ return 'collab_tool_call';
+ }
+ case 'commandExecution': {
+ return 'command_execution';
+ }
+ case 'dynamicToolCall': {
+ return 'dynamic_tool_call';
+ }
+ case 'fileChange': {
+ return 'file_change';
+ }
+ case 'mcpToolCall': {
+ return 'mcp_tool_call';
+ }
+ case 'webSearch': {
+ return 'web_search';
+ }
+ }
+};
+
+const toToolPayload = (item: ToolItem): ToolCallPayload => ({
+ apiName: toApiName(item),
+ arguments: JSON.stringify(
+ item.type === 'commandExecution'
+ ? { command: item.command }
+ : item.type === 'mcpToolCall'
+ ? { arguments: item.arguments, server: item.server, tool: item.tool }
+ : item,
+ ),
+ id: item.id,
+ identifier: CODEX_IDENTIFIER,
+ type: 'default',
+});
+
+const toFileChangeState = (changes: FileUpdateChange[]) => ({
+ changes: changes.map((change) => ({
+ diffText: change.diff,
+ kind: change.kind.type === 'update' && change.kind.move_path ? 'rename' : change.kind.type,
+ path: change.path,
+ })),
+});
+
+const toMcpContent = (item: McpToolItem): string => {
+ if (item.error) return item.error.message;
+ if (!item.result) return '';
+ return item.result.content
+ .map((content) => {
+ if (typeof content === 'string') return content;
+ if (content && typeof content === 'object' && 'text' in content) {
+ return typeof content.text === 'string' ? content.text : stringify(content);
+ }
+ return stringify(content);
+ })
+ .filter(Boolean)
+ .join('\n\n');
+};
+
+const getWebSearchQuery = (item: WebSearchItem): string => {
+ if (item.query) return item.query;
+ if (item.action?.type === 'search') {
+ return item.action.query || item.action.queries?.[0] || '';
+ }
+ return '';
+};
+
+const isSuccessful = (item: ToolItem): boolean => {
+ switch (item.type) {
+ case 'commandExecution': {
+ return item.status === 'completed' && (item.exitCode === null || item.exitCode === 0);
+ }
+ case 'dynamicToolCall': {
+ return item.status === 'completed' && item.success !== false;
+ }
+ case 'mcpToolCall': {
+ return item.status === 'completed' && !item.error;
+ }
+ case 'webSearch': {
+ return true;
+ }
+ default: {
+ return item.status === 'completed';
+ }
+ }
+};
+
+const toToolResult = (item: ToolItem): ToolResultData => {
+ const success = isSuccessful(item);
+
+ switch (item.type) {
+ case 'commandExecution': {
+ const output = truncateCodexCommandOutput(item.aggregatedOutput ?? '');
+ return {
+ content: output.output,
+ isError: !success,
+ pluginState: {
+ ...(item.exitCode === null ? {} : { exitCode: item.exitCode }),
+ isBackground: false,
+ ...(output.truncated
+ ? {
+ omittedOutputCharacters: output.omittedCharacters,
+ originalOutputLength: output.originalLength,
+ outputTruncated: true,
+ }
+ : {}),
+ output: output.output,
+ stdout: output.output,
+ success,
+ },
+ toolCallId: item.id,
+ };
+ }
+ case 'fileChange': {
+ return {
+ content: success ? 'File changes applied.' : 'File changes failed.',
+ isError: !success,
+ pluginState: toFileChangeState(item.changes),
+ toolCallId: item.id,
+ };
+ }
+ case 'mcpToolCall': {
+ return {
+ content: toMcpContent(item),
+ isError: !success,
+ pluginState: {
+ arguments: item.arguments,
+ error: item.error,
+ result: item.result,
+ server: item.server,
+ status: item.status,
+ tool: item.tool,
+ },
+ toolCallId: item.id,
+ };
+ }
+ case 'webSearch': {
+ return {
+ content: 'Completed web_search.',
+ isError: false,
+ pluginState: {
+ action: item.action,
+ query: getWebSearchQuery(item),
+ results: item.results,
+ status: 'completed',
+ },
+ toolCallId: item.id,
+ };
+ }
+ case 'dynamicToolCall': {
+ const content = item.contentItems
+ ?.map((entry) => (entry.type === 'inputText' ? entry.text : stringify(entry)))
+ .join('\n\n');
+ return {
+ content: content || `${item.tool} ${success ? 'completed' : 'failed'}.`,
+ isError: !success,
+ pluginState: {
+ arguments: item.arguments,
+ contentItems: item.contentItems,
+ namespace: item.namespace,
+ status: item.status,
+ success: item.success,
+ tool: item.tool,
+ },
+ toolCallId: item.id,
+ };
+ }
+ case 'collabAgentToolCall': {
+ return {
+ content: `${item.tool} ${success ? 'completed' : 'failed'}.`,
+ isError: !success,
+ pluginState: {
+ agents_states: item.agentsStates,
+ prompt: item.prompt,
+ receiver_thread_ids: item.receiverThreadIds,
+ sender_thread_id: item.senderThreadId,
+ status: item.status,
+ tool: item.tool,
+ },
+ toolCallId: item.id,
+ };
+ }
+ }
+};
+
+const toUsage = (usage: TokenUsageBreakdown): UsageData | undefined => {
+ const totalInputTokens = Math.max(usage.inputTokens, usage.cachedInputTokens);
+ const totalOutputTokens = usage.outputTokens;
+ if (totalInputTokens + totalOutputTokens === 0) return;
+
+ return {
+ inputCachedTokens: usage.cachedInputTokens || undefined,
+ inputCacheMissTokens: Math.max(0, totalInputTokens - usage.cachedInputTokens),
+ inputWriteCacheTokens: usage.cacheWriteInputTokens || undefined,
+ outputReasoningTokens: usage.reasoningOutputTokens || undefined,
+ outputTextTokens: Math.max(0, totalOutputTokens - usage.reasoningOutputTokens),
+ totalInputTokens,
+ totalOutputTokens,
+ totalTokens: usage.totalTokens || totalInputTokens + totalOutputTokens,
+ };
+};
+
+const classifyCodexError = (info: CodexErrorInfo | null): CodexErrorClassification => {
+ if (typeof info === 'object' && info) {
+ if ('activeTurnNotSteerable' in info) return { kind: 'agent_failed' };
+ const connection =
+ 'httpConnectionFailed' in info
+ ? info.httpConnectionFailed
+ : 'responseStreamConnectionFailed' in info
+ ? info.responseStreamConnectionFailed
+ : 'responseStreamDisconnected' in info
+ ? info.responseStreamDisconnected
+ : info.responseTooManyFailedAttempts;
+ return {
+ code: 'overloaded',
+ ...(connection.httpStatusCode === null ? {} : { httpStatusCode: connection.httpStatusCode }),
+ kind: 'network_drop',
+ };
+ }
+
+ switch (info) {
+ case 'sessionBudgetExceeded':
+ case 'usageLimitExceeded': {
+ return { code: 'rate_limit', kind: 'usage_limit' };
+ }
+ case 'internalServerError':
+ case 'serverOverloaded': {
+ return { code: 'overloaded', kind: 'server_overloaded' };
+ }
+ case 'unauthorized': {
+ return { code: 'auth_required', kind: 'auth_required' };
+ }
+ case 'badRequest':
+ case 'contextWindowExceeded':
+ case 'cyberPolicy': {
+ return { kind: 'invalid_request' };
+ }
+ default: {
+ return { kind: 'agent_failed' };
+ }
+ }
+};
+
+/** Direct app-server v2 notification → unified heterogeneous event adapter. */
+export class CodexAppServerAdapter {
+ private currentAgentMessageItemId?: string;
+ private currentModel?: string;
+ private hasTextInCurrentStep = false;
+ private hasToolActivity = false;
+ private lastCumulativeUsage?: UsageData;
+ private latestCumulativeUsage?: UsageData;
+ private latestPlan?: PlanState;
+ private readonly pendingTools = new Map<string, ToolCallPayload>();
+ private readonly streamedAgentText = new Map<string, string>();
+ private readonly streamedCommandOutput = new Map<string, StreamedOutput>();
+ private readonly streamedReasoning = new Set<string>();
+ private readonly toolStateSequence = new Map<string, number>();
+ private stepToolCalls: ToolCallPayload[] = [];
+ private started = false;
+ private stepIndex = 0;
+ private terminal = false;
+
+ constructor(options: { initialCumulativeUsage?: UsageData; initialModel?: string } = {}) {
+ this.currentModel = options.initialModel;
+ this.lastCumulativeUsage = options.initialCumulativeUsage;
+ }
+
+ get cumulativeUsage(): UsageData | undefined {
+ return this.latestCumulativeUsage ?? this.lastCumulativeUsage;
+ }
+
+ configureModel(model: string): HeterogeneousAgentEvent[] {
+ if (model === this.currentModel) return [];
+ this.currentModel = model;
+ return [this.makeEvent('step_complete', this.turnMetadata())];
+ }
+
+ adapt(method: string, rawParams: unknown): HeterogeneousAgentEvent[] {
+ if (this.terminal) return [];
+
+ switch (method) {
+ case 'turn/started': {
+ return this.handleTurnStarted(rawParams as TurnStartedNotification);
+ }
+ case 'item/started': {
+ return this.handleItemStarted(rawParams as ItemStartedNotification);
+ }
+ case 'item/completed': {
+ return this.handleItemCompleted(rawParams as ItemCompletedNotification);
+ }
+ case 'item/agentMessage/delta': {
+ return this.handleAgentMessageDelta(rawParams as AgentMessageDeltaNotification);
+ }
+ case 'item/reasoning/summaryTextDelta': {
+ return this.handleReasoningDelta(rawParams as ReasoningSummaryTextDeltaNotification);
+ }
+ case 'item/reasoning/textDelta': {
+ return this.handleReasoningDelta(rawParams as ReasoningTextDeltaNotification);
+ }
+ case 'item/commandExecution/outputDelta': {
+ return this.handleCommandOutput(rawParams as CommandExecutionOutputDeltaNotification);
+ }
+ case 'item/fileChange/patchUpdated': {
+ return this.handleFileChangeUpdate(rawParams as FileChangePatchUpdatedNotification);
+ }
+ case 'item/mcpToolCall/progress': {
+ return this.handleMcpProgress(rawParams as McpToolCallProgressNotification);
+ }
+ case 'turn/plan/updated': {
+ return this.handlePlanUpdated(rawParams as TurnPlanUpdatedNotification);
+ }
+ case 'thread/tokenUsage/updated': {
+ this.latestCumulativeUsage = toUsage(
+ (rawParams as ThreadTokenUsageUpdatedNotification).tokenUsage.total,
+ );
+ return [];
+ }
+ case 'error': {
+ return this.handleError(rawParams as ErrorNotification);
+ }
+ case 'turn/completed': {
+ return this.handleTurnCompleted(rawParams as TurnCompletedNotification);
+ }
+ default: {
+ return [];
+ }
+ }
+ }
+
+ flush(): HeterogeneousAgentEvent[] {
+ return this.drainPendingTools();
+ }
+
+ /** A crashed transport cannot recover its in-flight turn, but the thread remains resumable. */
+ interruptForTransportFailure(): HeterogeneousAgentEvent[] {
+ return this.completeTurn('interrupted');
+ }
+
+ private handleTurnStarted(_params: TurnStartedNotification): HeterogeneousAgentEvent[] {
+ if (this.started) return [];
+ this.started = true;
+ return [this.makeEvent('stream_start', this.streamStartData())];
+ }
+
+ private handleItemStarted({ item }: ItemStartedNotification): HeterogeneousAgentEvent[] {
+ if (!isToolItem(item)) return [];
+ this.hasToolActivity = true;
+ const payload = toToolPayload(item);
+ this.pendingTools.set(item.id, payload);
+ this.stepToolCalls.push(payload);
+ return [
+ this.makeEvent('stream_chunk', {
+ chunkType: 'tools_calling',
+ toolsCalling: [...this.stepToolCalls],
+ }),
+ this.makeEvent('tool_start', { toolCallId: item.id }),
+ ];
+ }
+
+ private handleItemCompleted({ item }: ItemCompletedNotification): HeterogeneousAgentEvent[] {
+ if (item.type === 'agentMessage') {
+ const message = item as AgentMessageItem;
+ const streamed = this.streamedAgentText.get(message.id);
+ this.streamedAgentText.delete(message.id);
+ if (streamed !== undefined) {
+ const remainder = message.text.startsWith(streamed)
+ ? message.text.slice(streamed.length)
+ : '';
+ return remainder ? this.emitText(message.id, remainder) : [];
+ }
+ return message.text ? this.emitText(message.id, message.text) : [];
+ }
+ if (item.type === 'reasoning') {
+ const reasoningItem = item as ReasoningItem;
+ if (this.streamedReasoning.delete(reasoningItem.id)) return [];
+ const reasoning = [...reasoningItem.summary, ...reasoningItem.content]
+ .filter(Boolean)
+ .join('\n\n');
+ return reasoning ? this.emitReasoning(reasoningItem.id, reasoning) : [];
+ }
+ if (!isToolItem(item)) return [];
+
+ this.streamedCommandOutput.delete(item.id);
+ const payload = this.pendingTools.get(item.id) ?? toToolPayload(item);
+ const events = this.pendingTools.has(item.id) ? [] : this.startLateTool(payload);
+ this.pendingTools.delete(item.id);
+ const result = toToolResult(item);
+ const success = isSuccessful(item);
+ events.push(
+ this.makeEvent('tool_result', result),
+ this.makeEvent('tool_end', {
+ isSuccess: success,
+ payload: { toolCalling: payload },
+ result: {
+ content: result.content,
+ success,
+ ...(result.pluginState ? { state: result.pluginState } : {}),
+ },
+ toolCallId: item.id,
+ }),
+ );
+ return events;
+ }
+
+ private handleAgentMessageDelta(
+ params: AgentMessageDeltaNotification,
+ ): HeterogeneousAgentEvent[] {
+ this.streamedAgentText.set(
+ params.itemId,
+ `${this.streamedAgentText.get(params.itemId) ?? ''}${params.delta}`,
+ );
+ return params.delta ? this.emitText(params.itemId, params.delta) : [];
+ }
+
+ private handleReasoningDelta(
+ params: ReasoningSummaryTextDeltaNotification | ReasoningTextDeltaNotification,
+ ): HeterogeneousAgentEvent[] {
+ if (!params.delta) return [];
+ this.streamedReasoning.add(params.itemId);
+ return this.emitReasoning(params.itemId, params.delta);
+ }
+
+ private handleCommandOutput(
+ params: CommandExecutionOutputDeltaNotification,
+ ): HeterogeneousAgentEvent[] {
+ if (!params.delta || !this.pendingTools.has(params.itemId)) return [];
+ const previous = this.streamedCommandOutput.get(params.itemId) ?? {
+ prefix: '',
+ totalLength: 0,
+ truncated: false,
+ };
+ const remaining = Math.max(0, CODEX_COMMAND_OUTPUT_MAX_LENGTH - previous.prefix.length);
+ const prefix = previous.prefix + params.delta.slice(0, remaining);
+ const totalLength = previous.totalLength + params.delta.length;
+ const truncated = totalLength > prefix.length;
+ this.streamedCommandOutput.set(params.itemId, { prefix, totalLength, truncated });
+ if (previous.truncated) return [];
+
+ const output = truncated
+ ? `${prefix}\n\n[Output truncated: ${totalLength - prefix.length} characters omitted. Original length: ${totalLength} characters]`
+ : prefix;
+ return [
+ this.toolState(params.itemId, {
+ isBackground: false,
+ output,
+ stdout: output,
+ }),
+ ];
+ }
+
+ private handleFileChangeUpdate(
+ params: FileChangePatchUpdatedNotification,
+ ): HeterogeneousAgentEvent[] {
+ return this.pendingTools.has(params.itemId)
+ ? [this.toolState(params.itemId, toFileChangeState(params.changes))]
+ : [];
+ }
+
+ private handleMcpProgress(params: McpToolCallProgressNotification): HeterogeneousAgentEvent[] {
+ return this.pendingTools.has(params.itemId)
+ ? [this.toolState(params.itemId, { message: params.message, status: 'inProgress' })]
+ : [];
+ }
+
+ private handlePlanUpdated(params: TurnPlanUpdatedNotification): HeterogeneousAgentEvent[] {
+ const id = `turn-plan-${params.turnId}`;
+ let foundProcessing = false;
+ const plan: PlanState = {
+ id,
+ items: params.plan.map(({ status, step }) => {
+ if (status === 'completed') return { status: 'completed', text: step };
+ if (!foundProcessing && status === 'inProgress') {
+ foundProcessing = true;
+ return { status: 'processing', text: step };
+ }
+ return { status: 'todo', text: step };
+ }),
+ };
+ const events: HeterogeneousAgentEvent[] = [];
+ if (!this.latestPlan) {
+ const payload: ToolCallPayload = {
+ apiName: 'todo_list',
+ arguments: JSON.stringify({ items: plan.items }),
+ id,
+ identifier: CODEX_IDENTIFIER,
+ type: 'default',
+ };
+ this.pendingTools.set(id, payload);
+ this.stepToolCalls.push(payload);
+ this.hasToolActivity = true;
+ events.push(
+ this.makeEvent('stream_chunk', {
+ chunkType: 'tools_calling',
+ toolsCalling: [...this.stepToolCalls],
+ }),
+ this.makeEvent('tool_start', { toolCallId: id }),
+ );
+ }
+ this.latestPlan = plan;
+ events.push(
+ this.toolState(id, { todos: { items: plan.items, updatedAt: new Date().toISOString() } }),
+ );
+ return events;
+ }
+
+ private handleError(params: ErrorNotification): HeterogeneousAgentEvent[] {
+ if (params.willRetry) {
+ return [this.makeEvent('stream_retry', { message: params.error.message })];
+ }
+ return this.terminalError(params.error);
+ }
+
+ private handleTurnCompleted({ turn }: TurnCompletedNotification): HeterogeneousAgentEvent[] {
+ if (turn.status === 'failed') {
+ return this.terminalError(
+ turn.error ?? {
+ additionalDetails: null,
+ codexErrorInfo: null,
+ message: 'Codex execution failed',
+ },
+ );
+ }
+ if (turn.status !== 'completed' && turn.status !== 'interrupted') return [];
+
+ return this.completeTurn(turn.status);
+ }
+
+ private completeTurn(status: 'completed' | 'interrupted'): HeterogeneousAgentEvent[] {
+ if (this.terminal) return [];
+ this.terminal = true;
+ const events = [
+ ...(status === 'completed' ? this.completePlan() : []),
+ ...this.drainPendingTools(),
+ ];
+ const usage = toTurnUsageFromCumulative(this.latestCumulativeUsage, this.lastCumulativeUsage);
+ if (usage || this.currentModel) {
+ events.push(this.makeEvent('step_complete', this.turnMetadata(usage)));
+ }
+ if (this.started) {
+ events.push(this.makeEvent('stream_end', {}), this.makeEvent('visible_output_end', {}));
+ }
+ events.push(
+ this.makeEvent(
+ 'agent_runtime_end',
+ status === 'interrupted' ? { reason: 'interrupted' } : {},
+ ),
+ );
+ return events;
+ }
+
+ private emitText(itemId: string, content: string): HeterogeneousAgentEvent[] {
+ const events = this.prepareVisibleContent(itemId);
+ const chunk =
+ this.hasTextInCurrentStep && itemId !== this.currentAgentMessageItemId
+ ? `\n\n${content}`
+ : content;
+ this.currentAgentMessageItemId = itemId;
+ this.hasTextInCurrentStep = true;
+ events.push(this.makeEvent('stream_chunk', { chunkType: 'text', content: chunk }));
+ return events;
+ }
+
+ private emitReasoning(itemId: string, reasoning: string): HeterogeneousAgentEvent[] {
+ const events = this.prepareVisibleContent(itemId);
+ events.push(this.makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning }));
+ return events;
+ }
+
+ private prepareVisibleContent(_itemId: string): HeterogeneousAgentEvent[] {
+ if (!this.hasToolActivity) return [];
+ this.hasToolActivity = false;
+ this.stepIndex += 1;
+ this.stepToolCalls = [];
+ this.hasTextInCurrentStep = false;
+ this.currentAgentMessageItemId = undefined;
+ return [
+ this.makeEvent('stream_end', {}),
+ this.makeEvent('stream_start', this.streamStartData({ newStep: true })),
+ ];
+ }
+
+ private startLateTool(payload: ToolCallPayload): HeterogeneousAgentEvent[] {
+ this.stepToolCalls.push(payload);
+ return [
+ this.makeEvent('stream_chunk', {
+ chunkType: 'tools_calling',
+ toolsCalling: [...this.stepToolCalls],
+ }),
+ this.makeEvent('tool_start', { toolCallId: payload.id }),
+ ];
+ }
+
+ private completePlan(): HeterogeneousAgentEvent[] {
+ const plan = this.latestPlan;
+ if (!plan || !this.pendingTools.has(plan.id)) return [];
+ this.pendingTools.delete(plan.id);
+ const pluginState = {
+ todos: {
+ items: plan.items.map((item) => ({ ...item, status: 'completed' })),
+ updatedAt: new Date().toISOString(),
+ },
+ };
+ return [
+ this.makeEvent('tool_result', {
+ content: 'Todo list completed.',
+ pluginState,
+ toolCallId: plan.id,
+ } satisfies ToolResultData),
+ this.makeEvent('tool_end', { isSuccess: true, toolCallId: plan.id }),
+ ];
+ }
+
+ private drainPendingTools(): HeterogeneousAgentEvent[] {
+ const events = [...this.pendingTools.keys()].map((toolCallId) =>
+ this.makeEvent('tool_end', { isSuccess: false, toolCallId }),
+ );
+ this.pendingTools.clear();
+ return events;
+ }
+
+ private terminalError(error: TurnError): HeterogeneousAgentEvent[] {
+ if (this.terminal) return [];
+ this.terminal = true;
+ const classification = classifyCodexError(error.codexErrorInfo);
+ const details = {
+ ...(error.additionalDetails ? { additionalDetails: error.additionalDetails } : {}),
+ ...(error.codexErrorInfo ? { codexErrorInfo: error.codexErrorInfo } : {}),
+ ...(classification.httpStatusCode === undefined
+ ? {}
+ : { httpStatusCode: classification.httpStatusCode }),
+ kind: classification.kind,
+ };
+ const events = this.drainPendingTools();
+ if (this.started) {
+ events.push(this.makeEvent('stream_end', {}), this.makeEvent('visible_output_end', {}));
+ }
+ events.push(
+ this.makeEvent('error', {
+ agentType: CODEX_IDENTIFIER,
+ clearEchoedContent: true,
+ ...(classification.code ? { code: classification.code } : {}),
+ details,
+ error: error.message,
+ message: error.message,
+ stderr: error.message,
+ } satisfies HeterogeneousTerminalErrorData),
+ );
+ return events;
+ }
+
+ private toolState(toolCallId: string, pluginState: Record<string, unknown>) {
+ const snapshotSeq = (this.toolStateSequence.get(toolCallId) ?? 0) + 1;
+ this.toolStateSequence.set(toolCallId, snapshotSeq);
+ return this.makeEvent('stream_chunk', {
+ chunkType: 'tool_state',
+ pluginState,
+ snapshotMode: 'replace',
+ snapshotSeq,
+ toolCallId,
+ } satisfies ToolStateChunkData);
+ }
+
+ private turnMetadata(usage?: UsageData): StepCompleteData {
+ return {
+ ...(this.currentModel ? { model: this.currentModel } : {}),
+ phase: 'turn_metadata',
+ provider: CODEX_IDENTIFIER,
+ ...(usage ? { usage } : {}),
+ };
+ }
+
+ private streamStartData(extra: Record<string, unknown> = {}): StreamStartData {
+ return {
+ ...(this.currentModel ? { model: this.currentModel } : {}),
+ provider: CODEX_IDENTIFIER,
+ ...extra,
+ };
+ }
+
+ private makeEvent(type: HeterogeneousAgentEvent['type'], data: unknown): HeterogeneousAgentEvent {
+ return { data, stepIndex: this.stepIndex, timestamp: Date.now(), type };
+ }
+}
diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.ts
index 6f6206d7a60..a40d86d0d34 100644
--- a/packages/heterogeneous-agents/src/adapters/index.ts
+++ b/packages/heterogeneous-agents/src/adapters/index.ts
@@ -2,6 +2,7 @@ export { AmpAdapter } from './amp';
export { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from './claudeCode';
export { CodeBuddyAdapter } from './codeBuddy';
export { CodexAdapter } from './codex';
+export { CodexAppServerAdapter } from './codexAppServer';
export { CursorAdapter } from './cursor';
export { GrokBuildAdapter } from './grokBuild';
export { KimiCodeAdapter } from './kimiCode';
diff --git a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.test.ts b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.test.ts
new file mode 100644
index 00000000000..ee414677c1d
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.test.ts
@@ -0,0 +1,564 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ CodexAppServerClient,
+ CodexAppServerConnectionError,
+ CodexAppServerRpcError,
+ isCodexAppServerCompatibilityError,
+} from './CodexAppServerClient';
+
+const { resolveCliSpawnPlanMock, spawnMock } = vi.hoisted(() => ({
+ resolveCliSpawnPlanMock: vi.fn(),
+ spawnMock: vi.fn(),
+}));
+
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return { ...actual, spawn: spawnMock };
+});
+
+vi.mock('../spawn/cliSpawn', () => ({ resolveCliSpawnPlan: resolveCliSpawnPlanMock }));
+
+interface RpcMessage {
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown>;
+ result?: unknown;
+}
+
+const createProcess = (
+ options: {
+ exitAfterResume?: boolean;
+ exitOnResume?: boolean;
+ rejectInitializeCode?: number;
+ throwOnMethod?: string;
+ } = {},
+) => {
+ const child = new EventEmitter() as any;
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ const messages: 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(() => true);
+ child.stdin = {
+ on: vi.fn(),
+ write: vi.fn((line: string) => {
+ const message = JSON.parse(line) as RpcMessage;
+ if (options.throwOnMethod && message.method === options.throwOnMethod) {
+ throw new Error('stdin write failed');
+ }
+ messages.push(message);
+ queueMicrotask(() => {
+ if (message.method === 'initialize') {
+ if (options.rejectInitializeCode) {
+ send({
+ error: { code: options.rejectInitializeCode, message: 'Initialize failed' },
+ id: message.id,
+ });
+ } else {
+ const response = `${JSON.stringify({
+ id: message.id,
+ result: {
+ codexHome: '/tmp/codex',
+ platformFamily: 'unix',
+ platformOs: 'linux',
+ userAgent: 'codex-test',
+ },
+ })}\n`;
+ stdout.write(response.slice(0, 9));
+ stdout.write(response.slice(9));
+ }
+ }
+ if (message.method === 'thread/start') {
+ send({ id: message.id, result: { thread: { id: 'thread-1' } } });
+ send({
+ method: 'turn/started',
+ params: { threadId: 'thread-1', turn: { id: 'turn-1' } },
+ });
+ send({
+ id: 'approval-1',
+ method: 'item/commandExecution/requestApproval',
+ params: { itemId: 'command-1', threadId: 'thread-1', turnId: 'turn-1' },
+ });
+ }
+ if (message.method === 'thread/resume') {
+ if (options.exitOnResume) {
+ child.emit('exit', 1, null);
+ return;
+ }
+ send({
+ id: message.id,
+ result: { model: 'gpt-5.5-codex', thread: { id: 'thread-1' } },
+ });
+ if (options.exitAfterResume) child.emit('exit', 1, null);
+ }
+ });
+ return true;
+ }),
+ };
+
+ return { child, messages, send, stderr, stdout };
+};
+
+const createClient = (
+ options: {
+ reconnectBaseDelayMs?: number;
+ reconnectMaxAttempts?: number;
+ reconnectMaxDelayMs?: number;
+ } = {},
+) =>
+ new CodexAppServerClient({
+ clientVersion: '1.0.0',
+ commandPath: 'codex',
+ cwd: '/workspace',
+ env: process.env,
+ ...options,
+ });
+
+beforeEach(() => {
+ resolveCliSpawnPlanMock.mockImplementation(async (command: string, args: string[]) => ({
+ args,
+ command,
+ }));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ resolveCliSpawnPlanMock.mockReset();
+ spawnMock.mockReset();
+});
+
+describe('CodexAppServerClient', () => {
+ it('only reuses a process for the same binary, global arguments, and environment', () => {
+ const client = new CodexAppServerClient({
+ args: ['--config', 'model_provider="openai"'],
+ clientVersion: '1.0.0',
+ commandPath: '/usr/local/bin/codex',
+ cwd: '/first-workspace',
+ env: { ...process.env, CODEX_HOME: '/tmp/codex', IGNORED: undefined },
+ });
+ const launchOptions = {
+ args: ['--config', 'model_provider="openai"'],
+ commandPath: '/usr/local/bin/codex',
+ cwd: '/second-workspace',
+ env: { ...process.env, CODEX_HOME: '/tmp/codex' },
+ };
+
+ expect(client.canReuseFor(launchOptions)).toBe(true);
+ expect(client.canReuseFor({ ...launchOptions, commandPath: '/opt/codex' })).toBe(false);
+ expect(client.canReuseFor({ ...launchOptions, args: [] })).toBe(false);
+ expect(
+ client.canReuseFor({
+ ...launchOptions,
+ env: { ...process.env, CODEX_HOME: '/other' },
+ }),
+ ).toBe(false);
+ });
+
+ it('does not reuse a relative custom command across working directories', () => {
+ const client = new CodexAppServerClient({
+ clientVersion: '1.0.0',
+ commandPath: './bin/codex',
+ cwd: '/first-workspace',
+ env: process.env,
+ });
+ const launchOptions = {
+ commandPath: './bin/codex',
+ cwd: '/first-workspace',
+ env: process.env,
+ };
+
+ expect(client.canReuseFor(launchOptions)).toBe(true);
+ expect(client.canReuseFor({ ...launchOptions, cwd: '/second-workspace' })).toBe(false);
+ });
+
+ it('tracks client consumers independently from attached thread registrations', () => {
+ const client = createClient();
+ const release = client.acquireConsumer();
+
+ expect(client.hasConsumers).toBe(true);
+ release();
+ release();
+
+ expect(client.hasConsumers).toBe(false);
+ client.close();
+ });
+
+ it('does not spawn a process after close wins a delayed spawn-plan race', async () => {
+ let resolveSpawnPlan!: (plan: { args: string[]; command: string }) => void;
+ resolveCliSpawnPlanMock.mockReturnValue(
+ new Promise((resolve) => {
+ resolveSpawnPlan = resolve;
+ }),
+ );
+ const client = createClient();
+ const connecting = client.connect();
+
+ client.close();
+ resolveSpawnPlan({ args: ['app-server'], command: 'codex' });
+
+ await expect(connecting).rejects.toThrow('closed by host');
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('frames NDJSON once and routes responses, notifications, and server requests', async () => {
+ const { child, messages } = createProcess();
+ spawnMock.mockReturnValue(child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const client = createClient();
+ const notifications: string[] = [];
+ const serverRequests: string[] = [];
+ client.subscribe('thread-1', (method) => {
+ notifications.push(method);
+ });
+ client.subscribeServerRequests('thread-1', (method) => {
+ serverRequests.push(method);
+ return { decision: 'cancel' };
+ });
+
+ await client.connect();
+ const response = await client.request<{ thread: { id: string } }>('thread/start', {});
+ await vi.waitFor(() =>
+ expect(messages).toContainEqual({ id: 'approval-1', result: { decision: 'cancel' } }),
+ );
+
+ expect(response.thread.id).toBe('thread-1');
+ expect(messages.map(({ method }) => method).filter(Boolean)).toEqual([
+ 'initialize',
+ 'initialized',
+ 'thread/start',
+ ]);
+ expect(notifications).toEqual(['turn/started']);
+ expect(serverRequests).toEqual(['item/commandExecution/requestApproval']);
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'codex',
+ ['app-server'],
+ expect.objectContaining({ stdio: ['pipe', 'pipe', 'pipe'] }),
+ );
+
+ client.close();
+ });
+
+ it('routes raw messages only to the matching thread trace', async () => {
+ const process = createProcess();
+ spawnMock.mockReturnValue(process.child);
+ vi.spyOn(globalThis.process, 'kill').mockImplementation(() => true);
+ const client = createClient();
+ const firstThreadLines: string[] = [];
+ const secondThreadLines: string[] = [];
+ client.onRawMessage('thread-1', (line) => {
+ firstThreadLines.push(line);
+ });
+ client.onRawMessage('thread-2', (line) => {
+ secondThreadLines.push(line);
+ });
+ await client.connect();
+
+ process.send({ method: 'item/started', params: { item: {}, threadId: 'thread-1' } });
+ process.send({ method: 'item/started', params: { item: {}, threadId: 'thread-2' } });
+ await vi.waitFor(() => {
+ expect(firstThreadLines).toHaveLength(1);
+ expect(secondThreadLines).toHaveLength(1);
+ });
+ await client.request('thread/resume', { threadId: 'thread-1' });
+
+ expect(firstThreadLines[0]).toContain('"threadId":"thread-1"');
+ expect(firstThreadLines[0]).not.toContain('"threadId":"thread-2"');
+ expect(firstThreadLines[1]).toContain('"result"');
+ expect(secondThreadLines[0]).toContain('"threadId":"thread-2"');
+ expect(secondThreadLines[0]).not.toContain('"threadId":"thread-1"');
+ expect(secondThreadLines).toHaveLength(1);
+ client.close();
+ });
+
+ it.each([-32_601, -32_602])(
+ 'classifies initialize RPC error %s as a compatibility fallback error',
+ async (rejectInitializeCode) => {
+ const { child } = createProcess({ rejectInitializeCode });
+ spawnMock.mockReturnValue(child);
+ const client = createClient();
+
+ const error = await client.connect().catch((cause) => cause);
+
+ expect(error).toBeInstanceOf(CodexAppServerRpcError);
+ expect(error).toMatchObject({ method: 'initialize' });
+ expect(isCodexAppServerCompatibilityError(error)).toBe(true);
+ },
+ );
+
+ it('does not classify an ordinary thread RPC failure as a compatibility error', () => {
+ const error = new CodexAppServerRpcError('Invalid model', -32_602, undefined, 'thread/start');
+
+ expect(isCodexAppServerCompatibilityError(error)).toBe(false);
+ });
+
+ it('only classifies connection failures from the initial handshake as compatible', () => {
+ expect(
+ isCodexAppServerCompatibilityError(
+ new CodexAppServerConnectionError('transport disconnected'),
+ ),
+ ).toBe(false);
+ expect(
+ isCodexAppServerCompatibilityError(
+ new CodexAppServerConnectionError('initialize failed', { phase: 'initialize' }),
+ ),
+ ).toBe(true);
+ });
+
+ it('restarts with exponential backoff and resumes every registered thread', async () => {
+ vi.useFakeTimers();
+ const first = createProcess();
+ const failedReconnect = createProcess({ rejectInitializeCode: -32_601 });
+ const recovered = createProcess();
+ spawnMock
+ .mockReturnValueOnce(first.child)
+ .mockReturnValueOnce(failedReconnect.child)
+ .mockReturnValueOnce(recovered.child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const client = createClient({ reconnectBaseDelayMs: 10 });
+ let resumedCount = 0;
+ let resolveResumed!: () => void;
+ const resumed = new Promise<void>((resolve) => {
+ resolveResumed = resolve;
+ });
+ const onResume = () => {
+ resumedCount += 1;
+ if (resumedCount === 2) resolveResumed();
+ };
+
+ await client.connect();
+ client.registerThread(
+ 'thread-1',
+ { approvalPolicy: 'never', sandbox: 'danger-full-access', threadId: 'thread-1' },
+ {
+ onResume,
+ onResumeError: vi.fn(),
+ },
+ );
+ client.registerThread(
+ 'thread-2',
+ { cwd: '/workspace/two', threadId: 'thread-2' },
+ {
+ onResume,
+ onResumeError: vi.fn(),
+ },
+ );
+ first.child.emit('exit', 1, null);
+
+ await vi.advanceTimersByTimeAsync(10);
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(19);
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1);
+ await resumed;
+
+ expect(spawnMock).toHaveBeenCalledTimes(3);
+ expect(
+ recovered.messages
+ .filter(({ method }) => method === 'thread/resume')
+ .map(({ params }) => params),
+ ).toEqual([
+ { approvalPolicy: 'never', sandbox: 'danger-full-access', threadId: 'thread-1' },
+ { cwd: '/workspace/two', threadId: 'thread-2' },
+ ]);
+ client.close();
+ });
+
+ it('ignores late stdout from an exited process after the replacement starts', async () => {
+ vi.useFakeTimers();
+ const first = createProcess();
+ const recovered = createProcess();
+ spawnMock.mockReturnValueOnce(first.child).mockReturnValueOnce(recovered.child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const client = createClient({ reconnectBaseDelayMs: 10 });
+ let resolveResumed!: () => void;
+ const resumed = new Promise<void>((resolve) => {
+ resolveResumed = resolve;
+ });
+
+ await client.connect();
+ client.registerThread(
+ 'thread-1',
+ { approvalPolicy: 'never', threadId: 'thread-1' },
+ { onResume: resolveResumed, onResumeError: vi.fn() },
+ );
+ first.child.emit('exit', 1, null);
+ first.stdout.write('{"stale":');
+
+ await vi.advanceTimersByTimeAsync(10);
+ await resumed;
+
+ expect(client.isConnected).toBe(true);
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ client.close();
+ });
+
+ it('keeps backing off when the replacement process dies while resuming threads', async () => {
+ vi.useFakeTimers();
+ const first = createProcess();
+ const failedReconnect = createProcess({ exitOnResume: true });
+ const recovered = createProcess();
+ spawnMock
+ .mockReturnValueOnce(first.child)
+ .mockReturnValueOnce(failedReconnect.child)
+ .mockReturnValueOnce(recovered.child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const client = createClient({ reconnectBaseDelayMs: 10 });
+ let resolveResumed!: () => void;
+ const resumed = new Promise<void>((resolve) => {
+ resolveResumed = resolve;
+ });
+ const onResume = vi.fn(resolveResumed);
+ const onResumeError = vi.fn();
+
+ await client.connect();
+ client.registerThread('thread-1', { threadId: 'thread-1' }, { onResume, onResumeError });
+ first.child.emit('exit', 1, null);
+
+ await vi.advanceTimersByTimeAsync(10);
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ expect(onResumeError).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(19);
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1);
+ await resumed;
+
+ expect(spawnMock).toHaveBeenCalledTimes(3);
+ expect(onResume).toHaveBeenCalledOnce();
+ client.close();
+ });
+
+ it('does not publish a stale resume after its process exits', async () => {
+ vi.useFakeTimers();
+ const first = createProcess();
+ const staleReconnect = createProcess({ exitAfterResume: true });
+ const recovered = createProcess();
+ spawnMock
+ .mockReturnValueOnce(first.child)
+ .mockReturnValueOnce(staleReconnect.child)
+ .mockReturnValueOnce(recovered.child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const client = createClient({ reconnectBaseDelayMs: 10 });
+ let resolveResumed!: () => void;
+ const resumed = new Promise<void>((resolve) => {
+ resolveResumed = resolve;
+ });
+ const onResume = vi.fn(resolveResumed);
+
+ await client.connect();
+ client.registerThread(
+ 'thread-1',
+ { threadId: 'thread-1' },
+ { onResume, onResumeError: vi.fn() },
+ );
+ first.child.emit('exit', 1, null);
+
+ await vi.advanceTimersByTimeAsync(10);
+ expect(onResume).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(20);
+ await resumed;
+
+ expect(onResume).toHaveBeenCalledOnce();
+ expect(client.isConnected).toBe(true);
+ client.close();
+ });
+
+ it('stops automatic reconnect at the attempt budget and retries on explicit demand', async () => {
+ vi.useFakeTimers();
+ const first = createProcess();
+ const failedOne = createProcess({ rejectInitializeCode: -32_601 });
+ const failedTwo = createProcess({ rejectInitializeCode: -32_601 });
+ const recovered = createProcess();
+ spawnMock
+ .mockReturnValueOnce(first.child)
+ .mockReturnValueOnce(failedOne.child)
+ .mockReturnValueOnce(failedTwo.child)
+ .mockReturnValueOnce(recovered.child);
+ vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const client = createClient({ reconnectBaseDelayMs: 10, reconnectMaxAttempts: 2 });
+ const onResume = vi.fn();
+ const onResumeError = vi.fn();
+
+ await client.connect();
+ client.registerThread('thread-1', { threadId: 'thread-1' }, { onResume, onResumeError });
+ first.child.emit('exit', 1, null);
+
+ await vi.advanceTimersByTimeAsync(10);
+ await vi.advanceTimersByTimeAsync(20);
+ await Promise.resolve();
+
+ expect(spawnMock).toHaveBeenCalledTimes(3);
+ expect(onResumeError).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(spawnMock).toHaveBeenCalledTimes(3);
+
+ await client.connect();
+
+ expect(spawnMock).toHaveBeenCalledTimes(4);
+ expect(onResume).toHaveBeenCalledOnce();
+ expect(client.isConnected).toBe(true);
+ client.close();
+ });
+
+ it('drops a server-request response when its process disconnects while the handler waits', async () => {
+ const process = createProcess();
+ spawnMock.mockReturnValue(process.child);
+ vi.spyOn(globalThis.process, 'kill').mockImplementation(() => true);
+ const client = createClient();
+ let resolveApproval!: () => void;
+ const approval = new Promise<void>((resolve) => {
+ resolveApproval = resolve;
+ });
+ const handler = vi.fn(async () => {
+ await approval;
+ return { decision: 'accept' };
+ });
+ client.subscribeServerRequests('thread-1', handler);
+ await client.connect();
+ const writesBeforeRequest = process.messages.length;
+
+ process.send({
+ id: 'approval-late',
+ method: 'item/commandExecution/requestApproval',
+ params: { threadId: 'thread-1' },
+ });
+ await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce());
+ process.child.emit('exit', 1, null);
+ resolveApproval();
+ await approval;
+ await Promise.resolve();
+
+ expect(process.messages).toHaveLength(writesBeforeRequest);
+ client.close();
+ });
+
+ it('clears a pending request when stdin.write throws synchronously', async () => {
+ vi.useFakeTimers();
+ const process = createProcess({ throwOnMethod: 'thread/start' });
+ spawnMock.mockReturnValue(process.child);
+ vi.spyOn(globalThis.process, 'kill').mockImplementation(() => true);
+ const client = createClient();
+ const onDisconnect = vi.fn();
+ client.onDisconnect(onDisconnect);
+ await client.connect();
+
+ await expect(client.request('thread/start', {})).rejects.toMatchObject({
+ cause: expect.objectContaining({ message: 'stdin write failed' }),
+ message: 'Failed to write Codex app-server request: thread/start',
+ });
+ expect(onDisconnect).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(onDisconnect).toHaveBeenCalledOnce();
+ client.close();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts
new file mode 100644
index 00000000000..c815ed77f07
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts
@@ -0,0 +1,754 @@
+import type { ChildProcess } from 'node:child_process';
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+
+import { isRecord, pickString } from '@lobechat/utils/object';
+
+import { resolveCliSpawnPlan } from '../spawn/cliSpawn';
+import type {
+ ClientNotification,
+ InitializeParams,
+ InitializeResponse,
+ RequestId,
+ ThreadResumeParams,
+ ThreadResumeResponse,
+} from './protocol';
+
+const APP_SERVER_RPC_TIMEOUT_MS = 30_000;
+const DEFAULT_RECONNECT_BASE_DELAY_MS = 250;
+const DEFAULT_RECONNECT_MAX_DELAY_MS = 4000;
+const DEFAULT_RECONNECT_MAX_ATTEMPTS = 5;
+const APPROVAL_REQUEST_METHODS = new Set([
+ 'item/commandExecution/requestApproval',
+ 'item/fileChange/requestApproval',
+]);
+
+interface PendingRequest {
+ generation: number;
+ method: string;
+ reject: (error: Error) => void;
+ resolve: (result: unknown) => void;
+ threadId?: string;
+ timeout: ReturnType<typeof setTimeout>;
+}
+
+interface ThreadRegistration {
+ onResume: (response: ThreadResumeResponse) => Promise<void> | void;
+ onResumeError: (error: Error) => Promise<void> | void;
+}
+
+interface ThreadRegistrationGroup {
+ params: ThreadResumeParams;
+ registrations: Set<ThreadRegistration>;
+}
+
+interface ProcessGeneration {
+ child: ChildProcess;
+ generation: number;
+ stdoutBuffer: string;
+}
+
+interface ConnectionState {
+ generation: number;
+ promise: Promise<InitializeResponse>;
+}
+
+type NotificationHandler = (method: string, params: unknown) => Promise<void> | void;
+type ServerRequestHandler = (method: string, params: unknown) => Promise<unknown> | unknown;
+type TextHandler = (data: string) => Promise<void> | void;
+
+export interface CodexAppServerClientOptions {
+ args?: string[];
+ clientVersion: string;
+ commandPath: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ reconnectBaseDelayMs?: number;
+ reconnectMaxAttempts?: number;
+ reconnectMaxDelayMs?: number;
+}
+
+export class CodexAppServerRpcError extends Error {
+ constructor(
+ message: string,
+ readonly code?: number,
+ readonly data?: unknown,
+ readonly method?: string,
+ ) {
+ super(message);
+ this.name = 'CodexAppServerRpcError';
+ }
+}
+
+export class CodexAppServerConnectionError extends Error {
+ readonly phase?: 'initialize' | 'thread-start';
+
+ constructor(message: string, options?: ErrorOptions & { phase?: 'initialize' | 'thread-start' }) {
+ super(message, options);
+ this.name = 'CodexAppServerConnectionError';
+ this.phase = options?.phase;
+ }
+}
+
+export const isCodexAppServerCompatibilityError = (error: unknown): boolean =>
+ (error instanceof CodexAppServerConnectionError &&
+ (error.phase === 'initialize' || error.phase === 'thread-start')) ||
+ (error instanceof CodexAppServerRpcError &&
+ (error.method === 'initialize' || error.code === -32_601));
+
+/**
+ * One long-lived, bidirectional NDJSON client for `codex app-server`.
+ *
+ * stdout has exactly one reader here. It correlates RPC responses, publishes
+ * notifications to the owning thread session, and separately routes
+ * server-initiated requests back to that thread.
+ */
+export class CodexAppServerClient {
+ private activeGeneration = 0;
+ private closedByHost = false;
+ private connectionState?: ConnectionState;
+ private connectionError?: Error;
+ private connected = false;
+ private consumerCount = 0;
+ private generationSequence = 0;
+ private hasConnected = false;
+ private nextRequestId = 0;
+ private readonly pendingRequests = new Map<string, PendingRequest>();
+ private readonly notificationHandlers = new Map<string, Set<NotificationHandler>>();
+ private readonly serverRequestHandlers = new Map<string, Set<ServerRequestHandler>>();
+ private readonly disconnectHandlers = new Set<(error: Error) => void>();
+ private readonly rawMessageHandlers = new Map<string, Set<TextHandler>>();
+ private readonly stderrHandlers = new Set<TextHandler>();
+ private readonly threadRegistrations = new Map<string, ThreadRegistrationGroup>();
+ private processGeneration?: ProcessGeneration;
+ private reconnectAttempt = 0;
+ private reconnectEpoch = 0;
+ private reconnectExhaustedEpoch?: number;
+ private reconnectTimer?: ReturnType<typeof setTimeout>;
+
+ constructor(private readonly options: CodexAppServerClientOptions) {}
+
+ get isConnected(): boolean {
+ return this.connected && !this.connectionError;
+ }
+
+ get hasConsumers(): boolean {
+ return this.consumerCount > 0;
+ }
+
+ acquireConsumer(): () => void {
+ if (this.closedByHost) {
+ throw new CodexAppServerConnectionError('Codex app-server client closed by host');
+ }
+ this.consumerCount += 1;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ this.consumerCount -= 1;
+ };
+ }
+
+ /** Process-global options must stay identical while this long-lived client is reused. */
+ canReuseFor(
+ options: Pick<CodexAppServerClientOptions, 'args' | 'commandPath' | 'cwd' | 'env'>,
+ ): boolean {
+ const currentArgs = this.options.args ?? [];
+ const nextArgs = options.args ?? [];
+ const commandIsRelativePath =
+ !path.isAbsolute(this.options.commandPath) &&
+ (this.options.commandPath.includes('/') || this.options.commandPath.includes('\\'));
+ if (
+ this.options.commandPath !== options.commandPath ||
+ (commandIsRelativePath && this.options.cwd !== options.cwd) ||
+ currentArgs.length !== nextArgs.length ||
+ currentArgs.some((arg, index) => arg !== nextArgs[index])
+ ) {
+ return false;
+ }
+
+ const currentEnv = Object.entries(this.options.env).filter(([, value]) => value !== undefined);
+ const nextEnv = Object.entries(options.env).filter(([, value]) => value !== undefined);
+ return (
+ currentEnv.length === nextEnv.length &&
+ currentEnv.every(([key, value]) => options.env[key] === value)
+ );
+ }
+
+ connect(): Promise<InitializeResponse> {
+ if (this.closedByHost) {
+ return Promise.reject(
+ new CodexAppServerConnectionError('Codex app-server client closed by host'),
+ );
+ }
+ if (this.connectionState && !this.connectionError) return this.connectionState.promise;
+ this.startUserRecoveryEpoch();
+ return this.startConnection();
+ }
+
+ async request<T>(method: string, params?: unknown): Promise<T> {
+ if (!this.connected) await this.connect();
+ if (this.connectionError) throw this.connectionError;
+ return this.requestForGeneration<T>(this.activeGeneration, method, params);
+ }
+
+ notify(notification: ClientNotification): void {
+ this.writeForGeneration(this.activeGeneration, { ...notification });
+ }
+
+ subscribe(threadId: string, handler: NotificationHandler): () => void {
+ const handlers = this.notificationHandlers.get(threadId) ?? new Set();
+ handlers.add(handler);
+ this.notificationHandlers.set(threadId, handlers);
+ return () => this.removeHandler(this.notificationHandlers, threadId, handler);
+ }
+
+ subscribeServerRequests(threadId: string, handler: ServerRequestHandler): () => void {
+ const handlers = this.serverRequestHandlers.get(threadId) ?? new Set();
+ handlers.add(handler);
+ this.serverRequestHandlers.set(threadId, handlers);
+ return () => this.removeHandler(this.serverRequestHandlers, threadId, handler);
+ }
+
+ registerThread(
+ threadId: string,
+ params: ThreadResumeParams,
+ registration: ThreadRegistration,
+ ): () => void {
+ if (params.threadId !== threadId) {
+ throw new Error(`Codex resume params do not match registered thread: ${threadId}`);
+ }
+ const existing = this.threadRegistrations.get(threadId);
+ if (existing && JSON.stringify(existing.params) !== JSON.stringify(params)) {
+ throw new Error(`Conflicting Codex resume params for thread: ${threadId}`);
+ }
+ const group = existing ?? { params, registrations: new Set() };
+ group.registrations.add(registration);
+ this.threadRegistrations.set(threadId, group);
+
+ if (!this.connected && this.connectionError) this.scheduleReconnect();
+ return () => {
+ group.registrations.delete(registration);
+ if (group.registrations.size === 0) this.threadRegistrations.delete(threadId);
+ if (this.threadRegistrations.size === 0 && this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = undefined;
+ }
+ };
+ }
+
+ onDisconnect(handler: (error: Error) => void): () => void {
+ this.disconnectHandlers.add(handler);
+ return () => this.disconnectHandlers.delete(handler);
+ }
+
+ onRawMessage(threadId: string, handler: TextHandler): () => void {
+ const handlers = this.rawMessageHandlers.get(threadId) ?? new Set();
+ handlers.add(handler);
+ this.rawMessageHandlers.set(threadId, handlers);
+ return () => this.removeHandler(this.rawMessageHandlers, threadId, handler);
+ }
+
+ onStderr(handler: TextHandler): () => void {
+ this.stderrHandlers.add(handler);
+ return () => this.stderrHandlers.delete(handler);
+ }
+
+ close(): void {
+ if (this.closedByHost) return;
+ this.closedByHost = true;
+ this.reconnectEpoch += 1;
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = undefined;
+ }
+ const error = new CodexAppServerConnectionError('Codex app-server client closed by host');
+ const generation = this.activeGeneration;
+ this.activeGeneration = ++this.generationSequence;
+ this.connected = false;
+ this.connectionError = error;
+ this.connectionState = undefined;
+ const processGeneration = this.processGeneration;
+ this.processGeneration = undefined;
+ this.rejectPendingRequests(generation, error);
+ this.emitDisconnect(error);
+ this.terminateChild(processGeneration?.child);
+ }
+
+ private startConnection(): Promise<InitializeResponse> {
+ if (this.closedByHost) {
+ return Promise.reject(
+ new CodexAppServerConnectionError('Codex app-server client closed by host'),
+ );
+ }
+ const generation = ++this.generationSequence;
+ const isReconnect = this.hasConnected;
+ this.activeGeneration = generation;
+ this.connected = false;
+ this.connectionError = undefined;
+ const promise = this.initialize(generation, isReconnect);
+ this.connectionState = { generation, promise };
+ return promise;
+ }
+
+ private async initialize(generation: number, isReconnect: boolean): Promise<InitializeResponse> {
+ try {
+ await this.startProcess(generation);
+ const params: InitializeParams = {
+ capabilities: {
+ experimentalApi: false,
+ requestAttestation: false,
+ },
+ clientInfo: {
+ name: 'lobehub-desktop',
+ title: 'LobeHub Desktop',
+ version: this.options.clientVersion,
+ },
+ };
+ const response = await this.requestForGeneration<InitializeResponse>(
+ generation,
+ 'initialize',
+ params,
+ );
+ this.writeForGeneration(generation, { method: 'initialized' });
+ if (!this.isCurrentGeneration(generation)) {
+ throw new CodexAppServerConnectionError('Codex app-server connection was replaced');
+ }
+ this.connected = true;
+ this.hasConnected = true;
+ if (isReconnect) {
+ await this.resumeRegisteredThreads(generation);
+ if (!this.isCurrentGeneration(generation) || !this.connected || this.connectionError) {
+ throw (
+ this.connectionError ??
+ new CodexAppServerConnectionError(
+ 'Codex app-server disconnected while resuming threads',
+ )
+ );
+ }
+ }
+ this.reconnectAttempt = 0;
+ this.reconnectExhaustedEpoch = undefined;
+ return response;
+ } catch (error) {
+ const failure = this.toConnectionError(error, 'Codex app-server handshake failed');
+ if (!this.isCurrentGeneration(generation)) throw failure;
+ const connectionError =
+ !isReconnect && failure instanceof CodexAppServerConnectionError
+ ? new CodexAppServerConnectionError(failure.message, {
+ cause: failure,
+ phase: 'initialize',
+ })
+ : failure;
+ this.fail(connectionError, generation);
+ throw connectionError;
+ }
+ }
+
+ private async startProcess(generation: number): Promise<void> {
+ const spawnPlan = await resolveCliSpawnPlan(this.options.commandPath, [
+ ...(this.options.args ?? []),
+ 'app-server',
+ ]);
+ if (!this.isCurrentGeneration(generation)) {
+ throw new CodexAppServerConnectionError(
+ this.closedByHost
+ ? 'Codex app-server client closed by host'
+ : 'Codex app-server connection was replaced',
+ );
+ }
+
+ const child = spawn(spawnPlan.command, spawnPlan.args, {
+ cwd: this.options.cwd,
+ detached: process.platform !== 'win32',
+ env: this.options.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ const processGeneration = { child, generation, stdoutBuffer: '' };
+ if (!this.isCurrentGeneration(generation)) {
+ this.terminateChild(child);
+ throw new CodexAppServerConnectionError('Codex app-server connection was replaced');
+ }
+ this.processGeneration = processGeneration;
+ child.stdin?.on('error', () => {
+ // The process error/exit listener owns the actionable failure. Ignore a racing EPIPE.
+ });
+ child.stdout?.on('data', (chunk: Buffer) => {
+ if (!this.ownsProcess(processGeneration)) return;
+ this.consumeStdout(processGeneration, chunk);
+ });
+ child.stderr?.on('data', (chunk: Buffer) => {
+ if (!this.ownsProcess(processGeneration)) return;
+ this.emitText(this.stderrHandlers, chunk.toString());
+ });
+ child.once('error', (error) => {
+ if (!this.ownsProcess(processGeneration)) return;
+ this.fail(
+ new CodexAppServerConnectionError(`Failed to start Codex app-server: ${error.message}`, {
+ cause: error,
+ }),
+ generation,
+ );
+ });
+ child.once('exit', (code, signal) => {
+ if (!this.ownsProcess(processGeneration)) return;
+ this.fail(
+ new CodexAppServerConnectionError(
+ `Codex app-server exited (code ${code ?? 'null'}, signal ${signal ?? 'null'})`,
+ ),
+ generation,
+ );
+ });
+ }
+
+ private requestForGeneration<T>(
+ generation: number,
+ method: string,
+ params?: unknown,
+ ): Promise<T> {
+ const processGeneration = this.processGeneration;
+ if (
+ !processGeneration ||
+ !this.ownsProcess(processGeneration) ||
+ generation !== this.activeGeneration
+ ) {
+ return Promise.reject(
+ new CodexAppServerConnectionError('Codex app-server stdin is unavailable'),
+ );
+ }
+
+ const id = ++this.nextRequestId;
+ const key = String(id);
+ return new Promise<T>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ const current = this.pendingRequests.get(key);
+ if (!current || current.generation !== generation) return;
+ this.pendingRequests.delete(key);
+ const error = new CodexAppServerConnectionError(
+ `Codex app-server request timed out: ${method}`,
+ );
+ reject(error);
+ this.fail(error, generation);
+ }, APP_SERVER_RPC_TIMEOUT_MS);
+ timeout.unref?.();
+ const pending: PendingRequest = {
+ generation,
+ method,
+ reject,
+ resolve: (result) => resolve(result as T),
+ threadId: isRecord(params) ? pickString(params.threadId) : undefined,
+ timeout,
+ };
+ this.pendingRequests.set(key, pending);
+ try {
+ this.writeToProcess(processGeneration, { id, method, params });
+ } catch (error) {
+ if (this.pendingRequests.get(key) === pending) this.pendingRequests.delete(key);
+ clearTimeout(timeout);
+ const connectionError = this.toConnectionError(
+ error,
+ `Failed to write Codex app-server request: ${method}`,
+ );
+ reject(connectionError);
+ this.fail(connectionError, generation);
+ }
+ });
+ }
+
+ private consumeStdout(processGeneration: ProcessGeneration, chunk: Buffer): void {
+ processGeneration.stdoutBuffer += chunk.toString('utf8');
+ let newlineIndex: number;
+
+ while ((newlineIndex = processGeneration.stdoutBuffer.indexOf('\n')) >= 0) {
+ const line = processGeneration.stdoutBuffer.slice(0, newlineIndex).trim();
+ processGeneration.stdoutBuffer = processGeneration.stdoutBuffer.slice(newlineIndex + 1);
+ if (!line) continue;
+
+ try {
+ const message = JSON.parse(line);
+ const threadId = this.getMessageThreadId(processGeneration.generation, message);
+ const rawHandlers = threadId ? this.rawMessageHandlers.get(threadId) : undefined;
+ if (rawHandlers) this.emitText(rawHandlers, `${line}\n`);
+ this.routeMessage(processGeneration.generation, message);
+ } catch (error) {
+ this.fail(
+ new CodexAppServerConnectionError('Codex app-server emitted invalid NDJSON', {
+ cause: error,
+ }),
+ processGeneration.generation,
+ );
+ return;
+ }
+ }
+ }
+
+ private getMessageThreadId(generation: number, message: unknown): string | undefined {
+ if (!isRecord(message)) return;
+ if (isRecord(message.params)) {
+ const threadId = pickString(message.params.threadId);
+ if (threadId) return threadId;
+ }
+
+ const id = message.id as RequestId | undefined;
+ if (id === undefined) return;
+ const pending = this.pendingRequests.get(String(id));
+ return pending?.generation === generation ? pending.threadId : undefined;
+ }
+
+ private routeMessage(generation: number, message: unknown): void {
+ if (!this.isCurrentGeneration(generation)) return;
+ if (!isRecord(message)) throw new TypeError('Expected an app-server RPC object');
+ const method = pickString(message.method);
+ const id = message.id as RequestId | undefined;
+
+ if (method) {
+ if (id !== undefined) {
+ void this.routeServerRequest(generation, id, method, message.params);
+ } else {
+ this.routeNotification(method, message.params);
+ }
+ return;
+ }
+
+ if (id === undefined) return;
+ const key = String(id);
+ const pending = this.pendingRequests.get(key);
+ if (!pending || pending.generation !== generation) return;
+
+ this.pendingRequests.delete(key);
+ clearTimeout(pending.timeout);
+ if (isRecord(message.error)) {
+ pending.reject(
+ new CodexAppServerRpcError(
+ pickString(message.error.message) ?? `Codex app-server request failed: ${pending.method}`,
+ typeof message.error.code === 'number' ? message.error.code : undefined,
+ message.error.data,
+ pending.method,
+ ),
+ );
+ } else {
+ pending.resolve(message.result);
+ }
+ }
+
+ private routeNotification(method: string, params: unknown): void {
+ const threadId = isRecord(params) ? pickString(params.threadId) : undefined;
+ if (!threadId) return;
+ for (const handler of this.notificationHandlers.get(threadId) ?? []) {
+ void handler(method, params);
+ }
+ }
+
+ private async routeServerRequest(
+ generation: number,
+ id: RequestId,
+ method: string,
+ params: unknown,
+ ): Promise<void> {
+ const threadId = isRecord(params) ? pickString(params.threadId) : undefined;
+ const handlers = threadId ? this.serverRequestHandlers.get(threadId) : undefined;
+ const handler = handlers?.values().next().value as ServerRequestHandler | undefined;
+ let response: Record<string, unknown>;
+
+ try {
+ if (handler) {
+ response = { id, result: await handler(method, params) };
+ } else if (APPROVAL_REQUEST_METHODS.has(method)) {
+ response = { id, result: { decision: 'cancel' } };
+ } else {
+ response = {
+ error: { code: -32_601, message: `Unsupported Codex app-server request: ${method}` },
+ id,
+ };
+ }
+ } catch (error) {
+ response = {
+ error: {
+ code: -32_603,
+ message: error instanceof Error ? error.message : 'Codex server request failed',
+ },
+ id,
+ };
+ }
+
+ if (!this.isCurrentGeneration(generation)) return;
+ try {
+ this.writeForGeneration(generation, response);
+ } catch (error) {
+ this.fail(
+ this.toConnectionError(error, 'Failed to write Codex app-server response'),
+ generation,
+ );
+ }
+ }
+
+ private writeForGeneration(generation: number, message: Record<string, unknown>): void {
+ const processGeneration = this.processGeneration;
+ if (!processGeneration || processGeneration.generation !== generation) {
+ throw new CodexAppServerConnectionError('Codex app-server stdin is unavailable');
+ }
+ this.writeToProcess(processGeneration, message);
+ }
+
+ private writeToProcess(
+ processGeneration: ProcessGeneration,
+ message: Record<string, unknown>,
+ ): void {
+ if (!this.ownsProcess(processGeneration) || !processGeneration.child.stdin) {
+ throw new CodexAppServerConnectionError('Codex app-server stdin is unavailable');
+ }
+ processGeneration.child.stdin.write(`${JSON.stringify(message)}\n`);
+ }
+
+ private emitText(handlers: Set<TextHandler>, data: string): void {
+ for (const handler of handlers) void handler(data);
+ }
+
+ private removeHandler<T>(map: Map<string, Set<T>>, key: string, handler: T): void {
+ const handlers = map.get(key);
+ handlers?.delete(handler);
+ if (handlers?.size === 0) map.delete(key);
+ }
+
+ private fail(error: Error, generation: number, reconnect = true): void {
+ if (!this.isCurrentGeneration(generation) || this.connectionError) return;
+ this.connectionError = error;
+ this.connected = false;
+ if (this.connectionState?.generation === generation) this.connectionState = undefined;
+ const processGeneration = this.processGeneration;
+ if (processGeneration?.generation === generation) {
+ this.processGeneration = undefined;
+ this.terminateChild(processGeneration.child);
+ }
+ this.rejectPendingRequests(generation, error);
+ this.emitDisconnect(error);
+ if (reconnect) this.scheduleReconnect();
+ }
+
+ private scheduleReconnect(): void {
+ if (this.closedByHost || this.reconnectTimer || this.threadRegistrations.size === 0) {
+ return;
+ }
+
+ const maxAttempts = Math.max(
+ 0,
+ Math.floor(this.options.reconnectMaxAttempts ?? DEFAULT_RECONNECT_MAX_ATTEMPTS),
+ );
+ const epoch = this.reconnectEpoch;
+ if (this.reconnectAttempt >= maxAttempts) {
+ if (this.reconnectExhaustedEpoch === epoch) return;
+ this.reconnectExhaustedEpoch = epoch;
+ const error = new CodexAppServerConnectionError(
+ `Codex app-server reconnect exhausted after ${maxAttempts} attempts`,
+ );
+ this.notifyResumeErrors(error);
+ return;
+ }
+
+ const baseDelay = this.options.reconnectBaseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS;
+ const maxDelay = this.options.reconnectMaxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
+ const delay = Math.min(baseDelay * 2 ** this.reconnectAttempt, maxDelay);
+ this.reconnectAttempt += 1;
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = undefined;
+ if (epoch !== this.reconnectEpoch || this.closedByHost) return;
+ void this.startConnection().catch(() => {
+ // initialize() records the failure and schedules the next backoff attempt.
+ });
+ }, delay);
+ this.reconnectTimer.unref?.();
+ }
+
+ private async resumeRegisteredThreads(generation: number): Promise<void> {
+ await Promise.all(
+ [...this.threadRegistrations.values()].map(async ({ params, registrations }) => {
+ try {
+ const response = await this.requestForGeneration<ThreadResumeResponse>(
+ generation,
+ 'thread/resume',
+ params,
+ );
+ if (!this.isCurrentGeneration(generation) || !this.connected) return;
+ await Promise.allSettled([...registrations].map(({ onResume }) => onResume(response)));
+ } catch (error) {
+ // A second transport failure schedules another reconnect attempt; keep
+ // sessions waiting instead of treating the thread itself as invalid.
+ if (!this.isCurrentGeneration(generation) || !this.connected) return;
+ const resumeError = error instanceof Error ? error : new Error(String(error));
+ await Promise.allSettled(
+ [...registrations].map(({ onResumeError }) => onResumeError(resumeError)),
+ );
+ }
+ }),
+ );
+ }
+
+ private startUserRecoveryEpoch(): void {
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = undefined;
+ }
+ this.reconnectAttempt = 0;
+ this.reconnectEpoch += 1;
+ this.reconnectExhaustedEpoch = undefined;
+ }
+
+ private notifyResumeErrors(error: Error): void {
+ void Promise.allSettled(
+ [...this.threadRegistrations.values()].flatMap(({ registrations }) =>
+ [...registrations].map(({ onResumeError }) => onResumeError(error)),
+ ),
+ );
+ }
+
+ private rejectPendingRequests(generation: number, error: Error): void {
+ for (const [key, pending] of this.pendingRequests) {
+ if (pending.generation !== generation) continue;
+ this.pendingRequests.delete(key);
+ clearTimeout(pending.timeout);
+ pending.reject(error);
+ }
+ }
+
+ private emitDisconnect(error: Error): void {
+ for (const handler of this.disconnectHandlers) {
+ try {
+ handler(error);
+ } catch (handlerError) {
+ console.error('Codex app-server disconnect handler failed:', handlerError);
+ }
+ }
+ }
+
+ private isCurrentGeneration(generation: number): boolean {
+ return !this.closedByHost && this.activeGeneration === generation;
+ }
+
+ private ownsProcess(processGeneration: ProcessGeneration): boolean {
+ return (
+ this.isCurrentGeneration(processGeneration.generation) &&
+ this.processGeneration === processGeneration
+ );
+ }
+
+ private toConnectionError(error: unknown, message: string): Error {
+ if (error instanceof CodexAppServerRpcError || error instanceof CodexAppServerConnectionError) {
+ return error;
+ }
+ return new CodexAppServerConnectionError(message, { cause: error });
+ }
+
+ private terminateChild(child?: ChildProcess): void {
+ if (!child?.pid || child.killed) return;
+
+ if (process.platform !== 'win32') {
+ try {
+ process.kill(-child.pid, 'SIGTERM');
+ return;
+ } catch {
+ // Fall through to a direct signal when the process group is already gone.
+ }
+ }
+ child.kill('SIGTERM');
+ }
+}
diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts
new file mode 100644
index 00000000000..91dcb1c4311
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts
@@ -0,0 +1,528 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ CodexAppServerConnectionError,
+ CodexAppServerRpcError,
+ isCodexAppServerCompatibilityError,
+} from './CodexAppServerClient';
+import { CodexThreadSession } from './CodexThreadSession';
+
+const turn = (id: string, status: 'completed' | 'inProgress' | 'interrupted') => ({
+ completedAt: status === 'inProgress' ? null : 2,
+ durationMs: status === 'inProgress' ? null : 1000,
+ error: null,
+ id,
+ items: [],
+ itemsView: 'full',
+ startedAt: 1,
+ status,
+});
+
+interface ClientHarness {
+ client: any;
+ disconnect: () => void;
+ notify: (method: string, params: unknown) => Promise<void> | void;
+ registeredResumeParams: () => unknown;
+ releaseConsumer: ReturnType<typeof vi.fn>;
+ requests: Array<{ method: string; params: unknown }>;
+ resolveThreadStart: () => void;
+ resolveTurnStart: () => void;
+ resume: (model?: string) => Promise<void> | void;
+}
+
+const createClientHarness = (
+ options: {
+ autoComplete?: boolean;
+ delayThreadStart?: boolean;
+ delayTurnStart?: boolean;
+ disconnectOnInterrupt?: boolean;
+ connectError?: Error;
+ failResume?: boolean;
+ initialThreadId?: string;
+ interruptError?: Error;
+ malformedThreadStart?: boolean;
+ threadNameError?: Error;
+ } = {},
+): ClientHarness => {
+ let disconnectHandler: (() => void) | undefined;
+ let notificationHandler: ((method: string, params: unknown) => Promise<void>) | undefined;
+ let registration:
+ | {
+ onResume: (response: unknown) => Promise<void> | void;
+ onResumeError: (error: Error) => Promise<void> | void;
+ }
+ | undefined;
+ let resumeParams: unknown;
+ let turnSequence = 0;
+ const releaseConsumer = vi.fn();
+ const requests: Array<{ method: string; params: unknown }> = [];
+ const notify = (method: string, params: unknown) => notificationHandler?.(method, params);
+ let resolveThreadStart = () => {};
+ const threadStartGate = options.delayThreadStart
+ ? new Promise<void>((resolve) => {
+ resolveThreadStart = resolve;
+ })
+ : Promise.resolve();
+ let resolveTurnStart = () => {};
+ const turnStartGate = options.delayTurnStart
+ ? new Promise<void>((resolve) => {
+ resolveTurnStart = resolve;
+ })
+ : Promise.resolve();
+
+ const client = {
+ acquireConsumer: vi.fn(() => releaseConsumer),
+ connect: options.connectError
+ ? vi.fn().mockRejectedValue(options.connectError)
+ : vi.fn().mockResolvedValue({ userAgent: 'codex-test' }),
+ onDisconnect: vi.fn((handler: () => void) => {
+ disconnectHandler = handler;
+ return vi.fn();
+ }),
+ onRawMessage: vi.fn(() => vi.fn()),
+ onStderr: vi.fn(() => vi.fn()),
+ registerThread: vi.fn((_threadId: string, params: unknown, value: typeof registration) => {
+ resumeParams = params;
+ registration = value;
+ return vi.fn();
+ }),
+ request: vi.fn(async (method: string, params: unknown) => {
+ requests.push({ method, params });
+ if (method === 'thread/start') {
+ await threadStartGate;
+ if (options.malformedThreadStart) return { thread: {} };
+ return { model: 'gpt-5.5-codex', thread: { id: 'thread-1' } };
+ }
+ if (method === 'thread/resume') {
+ if (options.failResume) throw new Error('Thread not found');
+ return {
+ model: 'gpt-5.5-codex',
+ thread: { id: options.initialThreadId ?? 'thread-1' },
+ };
+ }
+ if (method === 'thread/name/set') {
+ if (options.threadNameError) throw options.threadNameError;
+ return {};
+ }
+ if (method === 'turn/start') {
+ await turnStartGate;
+ const turnId = `turn-${++turnSequence}`;
+ if (options.autoComplete !== false) {
+ setTimeout(() => {
+ void notify('turn/started', {
+ threadId: options.initialThreadId ?? 'thread-1',
+ turn: turn(turnId, 'inProgress'),
+ });
+ void notify('item/agentMessage/delta', {
+ delta: `answer-${turnSequence}`,
+ itemId: `message-${turnSequence}`,
+ threadId: options.initialThreadId ?? 'thread-1',
+ turnId,
+ });
+ void notify('turn/completed', {
+ threadId: options.initialThreadId ?? 'thread-1',
+ turn: turn(turnId, 'completed'),
+ });
+ }, 0);
+ }
+ return { turn: turn(turnId, 'inProgress') };
+ }
+ if (method === 'turn/interrupt') {
+ if (options.disconnectOnInterrupt) disconnectHandler?.();
+ if (options.interruptError) throw options.interruptError;
+ const { threadId, turnId } = params as { threadId: string; turnId: string };
+ setTimeout(() => {
+ void notify('turn/completed', {
+ threadId,
+ turn: turn(turnId, 'interrupted'),
+ });
+ }, 0);
+ return {};
+ }
+ }),
+ subscribe: vi.fn((_threadId: string, handler: typeof notificationHandler) => {
+ notificationHandler = handler;
+ return vi.fn();
+ }),
+ subscribeServerRequests: vi.fn(() => vi.fn()),
+ };
+
+ return {
+ client,
+ disconnect: () => disconnectHandler?.(),
+ notify,
+ registeredResumeParams: () => resumeParams,
+ releaseConsumer,
+ requests,
+ resolveThreadStart,
+ resolveTurnStart,
+ resume: (model = 'gpt-5.5-codex') =>
+ registration?.onResume({ model, thread: { id: options.initialThreadId ?? 'thread-1' } }),
+ };
+};
+
+const createSession = (
+ harness: ClientHarness,
+ options: { initialThreadId?: string; onEventsError?: Error; threadName?: string } = {},
+) => {
+ const events: any[] = [];
+ const statuses: string[] = [];
+ const onSessionId = vi.fn();
+ const session = new CodexThreadSession({
+ client: harness.client,
+ initialThreadId: options.initialThreadId,
+ threadName: options.threadName,
+ onEvents: (batch) => {
+ if (options.onEventsError) throw options.onEventsError;
+ events.push(...batch);
+ },
+ onRuntimeStatus: ({ state }) => statuses.push(state),
+ onSessionId,
+ sessionId: 'session-1',
+ threadParams: {
+ approvalPolicy: 'never',
+ cwd: '/workspace',
+ sandbox: 'danger-full-access',
+ },
+ });
+ const run = (operationId: string, text: string) =>
+ session.run({
+ input: [{ text, text_elements: [], type: 'text' }],
+ onRawMessage: vi.fn(),
+ operationId,
+ });
+ return { events, onSessionId, run, session, statuses };
+};
+
+describe('CodexThreadSession', () => {
+ it('sets the original prompt as the name of a new persisted thread', async () => {
+ const harness = createClientHarness();
+ const { run, session } = createSession(harness, { threadName: 'Original prompt title' });
+
+ await run('operation-1', 'workspace-enriched input');
+ session.close();
+
+ expect(harness.requests.slice(0, 3)).toEqual([
+ {
+ method: 'thread/start',
+ params: {
+ approvalPolicy: 'never',
+ cwd: '/workspace',
+ sandbox: 'danger-full-access',
+ },
+ },
+ {
+ method: 'thread/name/set',
+ params: { name: 'Original prompt title', threadId: 'thread-1' },
+ },
+ {
+ method: 'turn/start',
+ params: {
+ input: [{ text: 'workspace-enriched input', text_elements: [], type: 'text' }],
+ threadId: 'thread-1',
+ },
+ },
+ ]);
+ });
+
+ it('does not block the first turn when thread naming is unsupported', async () => {
+ const harness = createClientHarness({ threadNameError: new Error('Method not found') });
+ const { run, session } = createSession(harness, { threadName: 'Original prompt title' });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ try {
+ await expect(run('operation-1', 'workspace-enriched input')).resolves.toBeUndefined();
+ expect(harness.requests.map(({ method }) => method)).toEqual([
+ 'thread/start',
+ 'thread/name/set',
+ 'turn/start',
+ ]);
+ } finally {
+ warn.mockRestore();
+ session.close();
+ }
+ });
+
+ it('reuses one native thread across multiple turns', async () => {
+ const harness = createClientHarness();
+ const { events, onSessionId, run, session, statuses } = createSession(harness);
+
+ await run('operation-1', 'first');
+ await run('operation-2', 'second');
+ session.close();
+
+ expect(harness.requests.map(({ method }) => method)).toEqual([
+ 'thread/start',
+ 'turn/start',
+ 'turn/start',
+ ]);
+ expect(harness.client.onRawMessage).toHaveBeenCalledWith('thread-1', expect.any(Function));
+ expect(onSessionId).toHaveBeenCalledOnce();
+ expect(statuses).toEqual([
+ 'starting',
+ 'running',
+ 'idle',
+ 'starting',
+ 'running',
+ 'idle',
+ 'closed',
+ ]);
+ expect(
+ events
+ .filter(({ data, type }) => type === 'stream_chunk' && data.chunkType === 'text')
+ .map(({ operationId, data }) => ({ content: data.content, operationId })),
+ ).toEqual([
+ { content: 'answer-1', operationId: 'operation-1' },
+ { content: 'answer-2', operationId: 'operation-2' },
+ ]);
+ });
+
+ it('resumes an existing thread before starting its first native turn', async () => {
+ const harness = createClientHarness({ initialThreadId: 'thread-existing' });
+ const { onSessionId, run, session } = createSession(harness, {
+ initialThreadId: 'thread-existing',
+ threadName: 'Do not rename existing thread',
+ });
+
+ await run('operation-1', 'continue');
+ session.close();
+
+ expect(harness.requests.slice(0, 2)).toEqual([
+ {
+ method: 'thread/resume',
+ params: {
+ approvalPolicy: 'never',
+ cwd: '/workspace',
+ sandbox: 'danger-full-access',
+ threadId: 'thread-existing',
+ },
+ },
+ {
+ method: 'turn/start',
+ params: {
+ input: [{ text: 'continue', text_elements: [], type: 'text' }],
+ threadId: 'thread-existing',
+ },
+ },
+ ]);
+ expect(onSessionId).not.toHaveBeenCalled();
+ expect(harness.registeredResumeParams()).toEqual({
+ approvalPolicy: 'never',
+ cwd: '/workspace',
+ sandbox: 'danger-full-access',
+ threadId: 'thread-existing',
+ });
+ });
+
+ it('never allows exec fallback for an existing thread, including initialize failures', async () => {
+ const initializeError = new CodexAppServerConnectionError('Initialize failed', {
+ phase: 'initialize',
+ });
+ const harness = createClientHarness({
+ connectError: initializeError,
+ initialThreadId: 'thread-existing',
+ });
+ const { run, session } = createSession(harness, { initialThreadId: 'thread-existing' });
+
+ await expect(run('operation-1', 'continue')).rejects.toBe(initializeError);
+
+ expect(session.canFallbackToExec).toBe(false);
+ session.close();
+ });
+
+ it('does not allow exec fallback after initialize succeeds for an existing thread', async () => {
+ const harness = createClientHarness({
+ failResume: true,
+ initialThreadId: 'thread-existing',
+ });
+ const { run, session } = createSession(harness, { initialThreadId: 'thread-existing' });
+
+ await expect(run('operation-1', 'continue')).rejects.toThrow('Thread not found');
+
+ expect(session.canFallbackToExec).toBe(false);
+ session.close();
+ });
+
+ it('classifies a malformed initial thread/start response for safe exec fallback', async () => {
+ const harness = createClientHarness({ malformedThreadStart: true });
+ const { run, session } = createSession(harness);
+
+ const error = await run('operation-1', 'start').catch((cause) => cause);
+
+ expect(error).toBeInstanceOf(CodexAppServerConnectionError);
+ expect(isCodexAppServerCompatibilityError(error)).toBe(true);
+ expect(session.canFallbackToExec).toBe(true);
+ session.close();
+ });
+
+ it('does not register a thread if the host closes while thread/start is pending', async () => {
+ const harness = createClientHarness({ delayThreadStart: true });
+ const { run, session, statuses } = createSession(harness);
+ const running = run('operation-1', 'wait');
+ await vi.waitFor(() =>
+ expect(harness.requests.some(({ method }) => method === 'thread/start')).toBe(true),
+ );
+
+ session.close();
+ harness.resolveThreadStart();
+ await running;
+
+ expect(harness.client.registerThread).not.toHaveBeenCalled();
+ expect(harness.releaseConsumer).toHaveBeenCalledOnce();
+ expect(statuses).toEqual(['starting', 'closed']);
+ });
+
+ it('interrupts the active turn through turn/interrupt', async () => {
+ const harness = createClientHarness({ autoComplete: false });
+ const { events, run, session } = createSession(harness);
+
+ const running = run('operation-1', 'wait');
+ await vi.waitFor(() =>
+ expect(harness.requests.some(({ method }) => method === 'turn/start')).toBe(true),
+ );
+ await session.interrupt();
+ await running;
+ session.close();
+
+ expect(harness.requests).toContainEqual({
+ method: 'turn/interrupt',
+ params: { threadId: 'thread-1', turnId: 'turn-1' },
+ });
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ data: { reason: 'interrupted' },
+ type: 'agent_runtime_end',
+ }),
+ );
+ });
+
+ it('keeps the thread reusable when interrupt loses a race with transport disconnect', async () => {
+ const harness = createClientHarness({
+ autoComplete: false,
+ disconnectOnInterrupt: true,
+ interruptError: new CodexAppServerConnectionError('Transport disconnected'),
+ });
+ const { run, session } = createSession(harness);
+ const interrupted = run('operation-1', 'wait');
+ await vi.waitFor(() =>
+ expect(harness.requests.some(({ method }) => method === 'turn/start')).toBe(true),
+ );
+
+ await expect(session.interrupt()).resolves.toBeUndefined();
+ await interrupted;
+
+ const nextTurn = run('operation-2', 'continue');
+ await vi.waitFor(() =>
+ expect(harness.requests.filter(({ method }) => method === 'turn/start')).toHaveLength(2),
+ );
+ harness.disconnect();
+ await nextTurn;
+ session.close();
+ });
+
+ it('does not suppress a genuine interrupt RPC error when transport also disconnects', async () => {
+ const rpcError = new CodexAppServerRpcError(
+ 'Turn cannot be interrupted',
+ -32_602,
+ undefined,
+ 'turn/interrupt',
+ );
+ const harness = createClientHarness({
+ autoComplete: false,
+ disconnectOnInterrupt: true,
+ interruptError: rpcError,
+ });
+ const { run, session } = createSession(harness);
+ const interrupted = run('operation-1', 'wait');
+ await vi.waitFor(() =>
+ expect(harness.requests.some(({ method }) => method === 'turn/start')).toBe(true),
+ );
+
+ await expect(session.interrupt()).rejects.toBe(rpcError);
+ await interrupted;
+ session.close();
+ });
+
+ it('remembers an interrupt requested before turn/start returns its turn id', async () => {
+ const harness = createClientHarness({ autoComplete: false, delayTurnStart: true });
+ const { run, session } = createSession(harness);
+
+ const running = run('operation-1', 'wait');
+ await vi.waitFor(() =>
+ expect(harness.requests.some(({ method }) => method === 'turn/start')).toBe(true),
+ );
+ await session.interrupt();
+ harness.resolveTurnStart();
+ await running;
+ session.close();
+
+ expect(harness.requests).toContainEqual({
+ method: 'turn/interrupt',
+ params: { threadId: 'thread-1', turnId: 'turn-1' },
+ });
+ });
+
+ it('does not turn a received completion into an interruption if the transport exits next', async () => {
+ const harness = createClientHarness({ autoComplete: false });
+ const { events, run, session } = createSession(harness);
+ const running = run('operation-1', 'finish');
+ await vi.waitFor(() =>
+ expect(harness.requests.some(({ method }) => method === 'turn/start')).toBe(true),
+ );
+
+ const notification = harness.notify('turn/completed', {
+ threadId: 'thread-1',
+ turn: turn('turn-1', 'completed'),
+ });
+ harness.disconnect();
+ await notification;
+ await running;
+ session.close();
+
+ const terminalEvents = events.filter(({ type }) => type === 'agent_runtime_end');
+ expect(terminalEvents).toHaveLength(1);
+ expect(terminalEvents[0].data).toEqual({});
+ });
+
+ it('settles a crashed turn immediately as interrupted, then resumes on the next turn', async () => {
+ const harness = createClientHarness({ autoComplete: false });
+ const { events, run, session } = createSession(harness);
+ let settled = false;
+
+ const crashedTurn = run('operation-1', 'crash').finally(() => {
+ settled = true;
+ });
+ await vi.waitFor(() =>
+ expect(harness.requests.some(({ method }) => method === 'turn/start')).toBe(true),
+ );
+ harness.disconnect();
+ await crashedTurn;
+ expect(settled).toBe(true);
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ data: { reason: 'interrupted' },
+ operationId: 'operation-1',
+ type: 'agent_runtime_end',
+ }),
+ );
+
+ const nextTurn = run('operation-2', 'continue');
+ await vi.waitFor(() =>
+ expect(harness.requests.filter(({ method }) => method === 'turn/start')).toHaveLength(2),
+ );
+ harness.disconnect();
+ await nextTurn;
+ session.close();
+ });
+
+ it('surfaces notification emission failures instead of completing a partial turn', async () => {
+ const emissionError = new Error('Renderer event delivery failed');
+ const harness = createClientHarness();
+ const { run, session, statuses } = createSession(harness, { onEventsError: emissionError });
+
+ await expect(run('operation-1', 'fail delivery')).rejects.toBe(emissionError);
+
+ expect(statuses).toEqual(['starting', 'running', 'error']);
+ session.close();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts
new file mode 100644
index 00000000000..d77b72cb424
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts
@@ -0,0 +1,421 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { isRecord, pickString } from '@lobechat/utils/object';
+
+import { CodexAppServerAdapter } from '../adapters/codexAppServer';
+import type { HeterogeneousAgentRuntimeStatus } from '../spawn/claudeAgentSdkSession';
+import { toStreamEvent } from '../spawn/streamEvent';
+import type { UsageData } from '../types';
+import type { CodexAppServerClient } from './CodexAppServerClient';
+import { CodexAppServerConnectionError } from './CodexAppServerClient';
+import type {
+ ThreadResumeParams,
+ ThreadResumeResponse,
+ ThreadStartParams,
+ ThreadStartResponse,
+ TurnCompletedNotification,
+ TurnInterruptParams,
+ TurnStartParams,
+ TurnStartResponse,
+ UserInput,
+} from './protocol';
+
+const CODEX_APP_SERVER_TRANSPORT = 'codex-app-server' as const;
+
+const toThreadResumeParams = (threadId: string, params: ThreadStartParams): ThreadResumeParams => {
+ const resumeParams = { ...params };
+ delete resumeParams.ephemeral;
+ delete resumeParams.serviceName;
+ delete resumeParams.sessionStartSource;
+ delete resumeParams.threadSource;
+ return { ...resumeParams, threadId };
+};
+
+interface ActiveTurn {
+ adapter: CodexAppServerAdapter;
+ completion: Promise<void>;
+ interruptRequest?: Promise<void>;
+ interruptRequested: boolean;
+ notificationError?: Error;
+ notificationQueue: Promise<void>;
+ operationId: string;
+ resolve: () => void;
+ terminalNotificationReceived: boolean;
+ transportInterrupted: boolean;
+ turnId?: string;
+}
+
+interface ThreadNameSetParams {
+ name: string;
+ threadId: string;
+}
+
+export interface CodexThreadTurnOptions {
+ input: UserInput[];
+ onRawMessage: (line: string) => Promise<void> | void;
+ operationId: string;
+}
+
+export interface CodexThreadSessionOptions {
+ client: CodexAppServerClient;
+ initialCumulativeUsage?: UsageData;
+ initialModel?: string;
+ initialThreadId?: string;
+ onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;
+ onModel?: (model: string) => void;
+ onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
+ onSessionId: (sessionId: string) => void;
+ sessionId: string;
+ /** A short title derived from the original user prompt, before injected context. */
+ threadName?: string;
+ threadParams: ThreadStartParams;
+}
+
+/** A persistent Codex thread state machine backed by the shared app-server client. */
+export class CodexThreadSession {
+ private activeTurn?: ActiveTurn;
+ private attached = false;
+ private canFallback: boolean;
+ private closedByHost = false;
+ private cumulativeUsage?: UsageData;
+ private interruptRequested = false;
+ private lastOperationId?: string;
+ private model?: string;
+ private running = false;
+ private readonly sessionUnsubscribers: Array<() => void> = [];
+ private threadId?: string;
+ private readonly threadUnsubscribers: Array<() => void> = [];
+
+ constructor(private readonly options: CodexThreadSessionOptions) {
+ this.canFallback = !options.initialThreadId;
+ this.cumulativeUsage = options.initialCumulativeUsage;
+ this.model = options.initialModel;
+ this.threadId = options.initialThreadId;
+ this.sessionUnsubscribers.push(
+ options.client.acquireConsumer(),
+ options.client.onDisconnect(() => this.handleDisconnect()),
+ );
+ }
+
+ get canFallbackToExec(): boolean {
+ return this.canFallback;
+ }
+
+ async run(options: CodexThreadTurnOptions): Promise<void> {
+ if (this.closedByHost) throw new Error('Codex thread session is closed');
+ if (this.running) throw new Error('Codex thread already has a running turn');
+
+ this.running = true;
+ this.interruptRequested = false;
+ this.lastOperationId = options.operationId;
+ this.emitStatus('starting', options.operationId);
+ const traceUnsubscribers: Array<() => void> = [];
+
+ try {
+ await this.ensureThread();
+ if (this.closedByHost) return;
+ const threadId = this.threadId;
+ if (!threadId) throw new Error('Codex thread is not attached');
+ traceUnsubscribers.push(this.options.client.onRawMessage(threadId, options.onRawMessage));
+
+ const adapter = new CodexAppServerAdapter({
+ initialCumulativeUsage: this.cumulativeUsage,
+ initialModel: this.model,
+ });
+ let resolveTurn!: () => void;
+ const completion = new Promise<void>((resolve) => {
+ resolveTurn = resolve;
+ });
+ const activeTurn: ActiveTurn = {
+ adapter,
+ completion,
+ interruptRequested: this.interruptRequested,
+ notificationQueue: Promise.resolve(),
+ operationId: options.operationId,
+ resolve: resolveTurn,
+ terminalNotificationReceived: false,
+ transportInterrupted: false,
+ };
+ this.activeTurn = activeTurn;
+
+ const turnParams: TurnStartParams = { input: options.input, threadId };
+ this.canFallback = false;
+ const turn = await this.options.client.request<TurnStartResponse>('turn/start', turnParams);
+ activeTurn.turnId = turn?.turn?.id;
+ if (!activeTurn.turnId) throw new Error('Codex app-server returned no turn id');
+ if (activeTurn.interruptRequested || this.closedByHost)
+ await this.requestInterrupt(activeTurn);
+ if (this.closedByHost) return;
+ this.emitStatus('running', options.operationId);
+
+ await activeTurn.completion;
+ await activeTurn.notificationQueue;
+ if (this.closedByHost) return;
+ if (activeTurn.notificationError) throw activeTurn.notificationError;
+ if (activeTurn.transportInterrupted) {
+ this.cumulativeUsage = adapter.cumulativeUsage;
+ this.emitStatus('idle', options.operationId);
+ return;
+ }
+ await this.emitEvents(adapter.flush(), options.operationId);
+ this.cumulativeUsage = adapter.cumulativeUsage;
+ this.emitStatus('idle', options.operationId);
+ } catch (error) {
+ if (this.closedByHost) return;
+ if (this.activeTurn?.transportInterrupted) {
+ await this.activeTurn.notificationQueue;
+ if (this.activeTurn.notificationError) {
+ this.emitStatus('error', options.operationId);
+ throw this.activeTurn.notificationError;
+ }
+ this.cumulativeUsage = this.activeTurn.adapter.cumulativeUsage;
+ this.emitStatus('idle', options.operationId);
+ return;
+ }
+ this.emitStatus('error', options.operationId);
+ throw error;
+ } finally {
+ for (const unsubscribe of traceUnsubscribers) unsubscribe();
+ this.activeTurn = undefined;
+ this.interruptRequested = false;
+ this.running = false;
+ }
+ }
+
+ async interrupt(): Promise<void> {
+ if (!this.running) return;
+ this.interruptRequested = true;
+ const activeTurn = this.activeTurn;
+ if (!activeTurn) return;
+
+ activeTurn.interruptRequested = true;
+ if (!activeTurn.turnId) return;
+ try {
+ await this.requestInterrupt(activeTurn);
+ } catch (error) {
+ if (
+ this.activeTurn === activeTurn &&
+ activeTurn.transportInterrupted &&
+ error instanceof CodexAppServerConnectionError
+ ) {
+ return;
+ }
+ throw error;
+ }
+ }
+
+ close(): void {
+ if (this.closedByHost) return;
+ this.closedByHost = true;
+ this.interruptRequested = true;
+ if (this.activeTurn) {
+ this.activeTurn.interruptRequested = true;
+ if (this.activeTurn.turnId) {
+ void this.requestInterrupt(this.activeTurn).catch((error) => {
+ console.error('Failed to interrupt Codex turn while closing the session:', error);
+ });
+ }
+ this.interruptActiveTurn();
+ }
+ this.unsubscribeAll(this.threadUnsubscribers);
+ this.unsubscribeAll(this.sessionUnsubscribers);
+ if (this.lastOperationId) this.emitStatus('closed', this.lastOperationId);
+ }
+
+ private async ensureThread(): Promise<void> {
+ await this.options.client.connect();
+ if (this.attached || this.closedByHost) return;
+
+ if (this.threadId) {
+ // Once initialize succeeds, an existing native thread must never be replayed via exec.
+ this.canFallback = false;
+ const params = toThreadResumeParams(this.threadId, this.options.threadParams);
+ const response = await this.options.client.request<ThreadResumeResponse>(
+ 'thread/resume',
+ params,
+ );
+ if (this.closedByHost) return;
+ await this.attachThread(response.thread.id, response.model);
+ return;
+ }
+
+ const response = await this.options.client.request<ThreadStartResponse>(
+ 'thread/start',
+ this.options.threadParams,
+ );
+ if (this.closedByHost) return;
+ const threadId = response?.thread?.id;
+ if (!threadId) {
+ throw new CodexAppServerConnectionError(
+ 'Codex app-server returned an incompatible thread/start response',
+ { phase: 'thread-start' },
+ );
+ }
+
+ await this.attachThread(threadId, response.model);
+ if (!this.options.threadParams.ephemeral) {
+ await this.setThreadName(threadId);
+ this.options.onSessionId(threadId);
+ }
+ }
+
+ private async setThreadName(threadId: string): Promise<void> {
+ const name = this.options.threadName?.trim();
+ if (!name) return;
+
+ try {
+ const params: ThreadNameSetParams = { name, threadId };
+ await this.options.client.request<Record<string, never>>('thread/name/set', params);
+ } catch (error) {
+ console.warn('Failed to set Codex thread name:', { error, threadId });
+ }
+ }
+
+ private async attachThread(threadId: string, model?: string): Promise<void> {
+ this.threadId = threadId;
+ this.attached = true;
+ this.canFallback = false;
+ if (model) this.updateModel(model);
+ if (this.threadUnsubscribers.length > 0) return;
+
+ this.threadUnsubscribers.push(
+ this.options.client.subscribe(threadId, (method, params) =>
+ this.enqueueNotification(method, params),
+ ),
+ this.options.client.subscribeServerRequests(threadId, (method) => {
+ if (
+ method === 'item/commandExecution/requestApproval' ||
+ method === 'item/fileChange/requestApproval'
+ ) {
+ return { decision: 'cancel' };
+ }
+ throw new Error(`Unsupported Codex app-server request: ${method}`);
+ }),
+ this.options.client.registerThread(
+ threadId,
+ toThreadResumeParams(threadId, this.options.threadParams),
+ {
+ onResume: (response) => this.handleReconnect(response),
+ onResumeError: () => {
+ this.attached = false;
+ },
+ },
+ ),
+ );
+ }
+
+ private async handleReconnect(response: ThreadResumeResponse): Promise<void> {
+ if (this.closedByHost) return;
+ this.attached = true;
+ if (response.model) this.updateModel(response.model);
+ }
+
+ private handleDisconnect(): void {
+ if (this.closedByHost) return;
+ this.attached = false;
+ if (this.activeTurn && !this.activeTurn.terminalNotificationReceived) {
+ this.interruptActiveTurn();
+ }
+ }
+
+ private requestInterrupt(activeTurn: ActiveTurn): Promise<void> {
+ const threadId = this.threadId;
+ const turnId = activeTurn.turnId;
+ if (!threadId || !turnId) return Promise.resolve();
+ if (activeTurn.interruptRequest) return activeTurn.interruptRequest;
+
+ const params: TurnInterruptParams = { threadId, turnId };
+ activeTurn.interruptRequest = this.options.client.request('turn/interrupt', params);
+ return activeTurn.interruptRequest;
+ }
+
+ private interruptActiveTurn(): void {
+ const activeTurn = this.activeTurn;
+ if (!activeTurn || activeTurn.transportInterrupted) return;
+ activeTurn.transportInterrupted = true;
+ activeTurn.notificationQueue = activeTurn.notificationQueue
+ .then(() =>
+ this.emitEvents(activeTurn.adapter.interruptForTransportFailure(), activeTurn.operationId),
+ )
+ .catch((error) => this.recordNotificationError(activeTurn, error))
+ .finally(activeTurn.resolve);
+ }
+
+ private enqueueNotification(method: string, params: unknown): Promise<void> {
+ const activeTurn = this.activeTurn;
+ if (!activeTurn || !this.isCurrentTurnNotification(method, params, activeTurn)) {
+ return Promise.resolve();
+ }
+ if (method === 'turn/completed') {
+ const notification = params as TurnCompletedNotification;
+ if (notification.turn.status !== 'inProgress') {
+ activeTurn.terminalNotificationReceived = true;
+ }
+ }
+
+ activeTurn.notificationQueue = activeTurn.notificationQueue
+ .then(async () => {
+ if (activeTurn.notificationError) return;
+ await this.emitEvents(activeTurn.adapter.adapt(method, params), activeTurn.operationId);
+ if (method !== 'turn/completed') return;
+ const notification = params as TurnCompletedNotification;
+ if (activeTurn.turnId && notification.turn.id !== activeTurn.turnId) return;
+ if (notification.turn.status !== 'inProgress') activeTurn.resolve();
+ })
+ .catch((error) => {
+ this.recordNotificationError(activeTurn, error);
+ activeTurn.resolve();
+ });
+ return activeTurn.notificationQueue;
+ }
+
+ private isCurrentTurnNotification(
+ method: string,
+ params: unknown,
+ activeTurn: ActiveTurn,
+ ): boolean {
+ if (!isRecord(params)) return false;
+ const notificationTurnId =
+ method === 'turn/started' || method === 'turn/completed'
+ ? isRecord(params.turn)
+ ? pickString(params.turn.id)
+ : undefined
+ : pickString(params.turnId);
+ if (method === 'turn/started' && !activeTurn.turnId && notificationTurnId) {
+ activeTurn.turnId = notificationTurnId;
+ }
+ return !activeTurn.turnId || !notificationTurnId || activeTurn.turnId === notificationTurnId;
+ }
+
+ private async emitEvents(
+ events: ReturnType<CodexAppServerAdapter['flush']>,
+ operationId: string,
+ ): Promise<void> {
+ if (events.length === 0) return;
+ await this.options.onEvents(events.map((event) => toStreamEvent(event, operationId)));
+ }
+
+ private updateModel(model: string): void {
+ this.model = model;
+ this.options.onModel?.(model);
+ }
+
+ private recordNotificationError(activeTurn: ActiveTurn, error: unknown): void {
+ if (activeTurn.notificationError) return;
+ activeTurn.notificationError = error instanceof Error ? error : new Error(String(error));
+ }
+
+ private emitStatus(state: HeterogeneousAgentRuntimeStatus['state'], operationId: string): void {
+ this.options.onRuntimeStatus({
+ activeTasks: [],
+ lastEventAt: Date.now(),
+ operationId,
+ sessionId: this.options.sessionId,
+ state,
+ transport: CODEX_APP_SERVER_TRANSPORT,
+ });
+ }
+
+ private unsubscribeAll(unsubscribers: Array<() => void>): void {
+ for (const unsubscribe of unsubscribers.splice(0)) unsubscribe();
+ }
+}
diff --git a/packages/heterogeneous-agents/src/codex/appServerParams.test.ts b/packages/heterogeneous-agents/src/codex/appServerParams.test.ts
new file mode 100644
index 00000000000..101337b90c5
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/appServerParams.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildCodexAppServerArgs,
+ buildCodexAppServerInput,
+ buildCodexAppServerThreadParams,
+ getCodexAppServerUnsupportedArgs,
+} from './appServerParams';
+
+describe('Codex app-server payload builders', () => {
+ it('keeps process args global 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(['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',
+ config: {
+ model_provider: 'openai',
+ model_reasoning_effort: 'high',
+ service_tier: 'fast',
+ },
+ 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('keeps unsupported and interactive CLI arguments on the exec transport', () => {
+ 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',
+ '-a',
+ 'never',
+ '-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/codex/appServerParams.ts b/packages/heterogeneous-agents/src/codex/appServerParams.ts
new file mode 100644
index 00000000000..d84041c6c6b
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/appServerParams.ts
@@ -0,0 +1,267 @@
+import path from 'node:path';
+
+import type { AgentInputPlan } from '../spawn/input';
+import type { JsonValue, SandboxMode, ThreadStartParams, UserInput } from './protocol';
+
+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_EPHEMERAL_FLAG = '--ephemeral';
+const CODEX_IGNORE_USER_CONFIG_FLAG = '--ignore-user-config';
+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 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): JsonValue => {
+ 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) as JsonValue;
+ } 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 SandboxMode =>
+ value === 'danger-full-access' || value === 'read-only' || value === 'workspace-write';
+
+/** Thread-scoped configuration is sent over RPC; the shared process needs only its subcommand. */
+export const buildCodexAppServerArgs = (_args: string[] = []): string[] => ['app-server'];
+
+/** Keep CLI semantics on exec when they cannot be represented by the app-server thread contract. */
+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,
+): ThreadStartParams => {
+ const config: Record<string, JsonValue> = {};
+ let effectiveCwd = cwd;
+ let ephemeral = false;
+ let model = initialModel;
+ let modelProvider: string | undefined;
+ let sandbox: SandboxMode = '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;
+ config[configOverride.key] = configOverride.value;
+ 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: 'never',
+ ...(Object.keys(config).length > 0 ? { config } : {}),
+ cwd: effectiveCwd,
+ ...(ephemeral ? { ephemeral } : {}),
+ ...(model ? { model } : {}),
+ ...(modelProvider ? { modelProvider } : {}),
+ sandbox,
+ ...(serviceTier ? { serviceTier } : {}),
+ };
+};
+
+export const buildCodexAppServerInput = (plan: AgentInputPlan): UserInput[] => {
+ const input: UserInput[] = [];
+ 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;
+};
diff --git a/packages/heterogeneous-agents/src/codex/index.ts b/packages/heterogeneous-agents/src/codex/index.ts
new file mode 100644
index 00000000000..ea1e8e9a2ea
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/index.ts
@@ -0,0 +1,20 @@
+export {
+ buildCodexAppServerArgs,
+ buildCodexAppServerInput,
+ buildCodexAppServerThreadParams,
+ getCodexAppServerUnsupportedArgs,
+} from './appServerParams';
+export {
+ CodexAppServerClient,
+ type CodexAppServerClientOptions,
+ CodexAppServerConnectionError,
+ CodexAppServerRpcError,
+ isCodexAppServerCompatibilityError,
+} from './CodexAppServerClient';
+export {
+ CodexThreadSession,
+ type CodexThreadSessionOptions,
+ type CodexThreadTurnOptions,
+} from './CodexThreadSession';
+export type * from './protocol';
+export { CODEX_APP_SERVER_PROTOCOL_REVISION } from './protocol';
diff --git a/packages/heterogeneous-agents/src/codex/protocol/README.md b/packages/heterogeneous-agents/src/codex/protocol/README.md
new file mode 100644
index 00000000000..67fae0d0200
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/protocol/README.md
@@ -0,0 +1,13 @@
+# Codex app-server protocol
+
+`generated.ts` vendors the stable TypeScript protocol emitted by Codex at revision
+`5e32f728f1f86a967c6be057351f12505778df8f`.
+
+Generate the upstream files with:
+
+```bash
+codex app-server generate-ts --out <directory>
+```
+
+The vendored file is the transitive stable subset used by LobeHub's native app-server client. Keep
+wire names and nullability identical to the generated files; do not hand-edit protocol types.
diff --git a/packages/heterogeneous-agents/src/codex/protocol/generated.ts b/packages/heterogeneous-agents/src/codex/protocol/generated.ts
new file mode 100644
index 00000000000..3d11da83d0f
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/protocol/generated.ts
@@ -0,0 +1,756 @@
+// GENERATED CODE! DO NOT MODIFY BY HAND!
+
+// Bundled from `codex app-server generate-ts` output. See README.md.
+
+// Source: AbsolutePathBuf.ts
+/**
+ * A path that is guaranteed to be absolute and normalized (though it is not
+ * guaranteed to be canonicalized or exist on the filesystem).
+ *
+ * IMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set
+ * using [AbsolutePathBufGuard::new]. If no base path is set, the
+ * deserialization will fail unless the path being deserialized is already
+ * absolute.
+ */
+export type AbsolutePathBuf = string;
+
+// Source: AgentPath.ts
+export type AgentPath = string;
+
+// Source: ClientInfo.ts
+export type ClientInfo = { name: string, title: string | null, version: string, };
+
+// Source: ClientNotification.ts
+export type ClientNotification = { "method": "initialized" };
+
+// Source: ImageDetail.ts
+export type ImageDetail = "auto" | "low" | "high" | "original";
+
+// Source: ImageGenerationFailure.ts
+export type ImageGenerationFailure = { "type": "usageLimitExceeded", limitId: string, resetsAt: number | null, };
+
+// Source: ImageGenerationItem.ts
+export type ImageGenerationItem = { id: string, status: string, revisedPrompt: string | null, result: string, transparentBackground?: boolean, failure: ImageGenerationFailure | null, savedPath?: AbsolutePathBuf, };
+
+// Source: InitializeCapabilities.ts
+/**
+ * Client-declared capabilities negotiated during initialize.
+ */
+export type InitializeCapabilities = {
+/**
+ * Opt into receiving experimental API methods and fields.
+ */
+experimentalApi: boolean,
+/**
+ * Opt into `attestation/generate` requests for upstream `x-oai-attestation`.
+ */
+requestAttestation: boolean,
+/**
+ * Legacy opt-in for the `openai/form` MCP extension.
+ *
+ * New clients should declare `openai/form` in [`Self::extensions`].
+ */
+mcpServerOpenaiFormElicitation?: boolean,
+/**
+ * Exact notification method names that should be suppressed for this
+ * connection (for example `thread/started`).
+ */
+optOutNotificationMethods?: Array<string> | null,
+/**
+ * MCP extension settings declared by the app-server client.
+ */
+extensions?: { [key in string]?: JsonValue } | null, };
+
+// Source: InitializeParams.ts
+export type InitializeParams = { clientInfo: ClientInfo, capabilities: InitializeCapabilities | null, };
+
+// Source: InitializeResponse.ts
+export type InitializeResponse = { userAgent: string,
+/**
+ * Absolute path to the server's $CODEX_HOME directory.
+ */
+codexHome: AbsolutePathBuf,
+/**
+ * Platform family for the running app-server target, for example
+ * `"unix"` or `"windows"`.
+ */
+platformFamily: string,
+/**
+ * Operating system for the running app-server target, for example
+ * `"macos"`, `"linux"`, or `"windows"`.
+ */
+platformOs: string, };
+
+// Source: LegacyAppPathString.ts
+/**
+ * A UTF-8 path for preserving raw path compatibility at the app-server API
+ * boundary while Codex migrates to [`PathUri`].
+ *
+ * Supports storing arbitrary strings read from the API and converting to and
+ * from [`PathUri`] using an explicitly selected native path convention.
+ *
+ * When converting from [`PathUri`], "native" refers to the supplied
+ * [`PathConvention`], which may be foreign to the operating system running
+ * this process. The inner string is private so path-producing code must use a
+ * path conversion method instead of bypassing the intended conversion
+ * boundary. Non-UTF-8 paths are converted to UTF-8 lossily because this API
+ * value is serialized as a JSON string.
+ *
+ * Deserialization and [`Self::from_string`] accept any UTF-8 string without
+ * interpreting or validating it. Use [`Self::from_string`] when a caller
+ * already owns legacy app-server path text and needs to preserve its wire
+ * spelling; use [`Self::from_path`], [`Self::from_abs_path`], or
+ * [`Self::from_path_uri`] when converting an actual path value. Relative
+ * path text remains valid until an operation such as [`Self::to_path_uri`]
+ * requires an absolute path.
+ */
+export type LegacyAppPathString = string;
+
+// Source: MessagePhase.ts
+/**
+ * Classifies an assistant message as interim commentary or final answer text.
+ *
+ * Providers do not emit this consistently, so callers must treat `None` as
+ * "phase unknown" and keep compatibility behavior for legacy models.
+ */
+export type MessagePhase = "commentary" | "final_answer";
+
+// Source: Personality.ts
+export type Personality = "none" | "friendly" | "pragmatic";
+
+// Source: ReasoningEffort.ts
+/**
+ * See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning
+ */
+export type ReasoningEffort = string;
+
+// Source: ReasoningSummary.ts
+/**
+ * A summary of the reasoning performed by the model. This can be useful for
+ * debugging and understanding the model's reasoning process.
+ * See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries
+ */
+export type ReasoningSummary = "auto" | "concise" | "detailed" | "none";
+
+// Source: RequestId.ts
+export type RequestId = string | number;
+
+// Source: SleepItem.ts
+/**
+ * Display item emitted by the interruptible `clock.sleep` tool.
+ */
+export type SleepItem = { id: string, durationMs: number, };
+
+// Source: SubAgentSource.ts
+export type SubAgentSource = "review" | "compact" | { "thread_spawn": { parent_thread_id: ThreadId, depth: number, agent_path: AgentPath | null, agent_nickname: string | null, agent_role: string | null, } } | "memory_consolidation" | { "other": string };
+
+// Source: ThreadId.ts
+/**
+ * Identifier for a Codex thread.
+ *
+ * Codex-generated thread IDs are UUIDv7, and some use cases rely on that.
+ */
+export type ThreadId = string;
+
+// Source: WebSearchItem.ts
+export type WebSearchItem = { id: string, query: string, action: WebSearchAction | null,
+/**
+ * Structured search results returned out-of-band by standalone web search.
+ *
+ * These stay as opaque JSON at the extension/app-server boundary so new
+ * result fields and result types can pass through without a Codex release.
+ */
+results: Array<JsonValue> | null, };
+
+// Source: serde_json/JsonValue.ts
+export type JsonValue = number | string | boolean | Array<JsonValue> | { [key in string]?: JsonValue } | null;
+
+// Source: v2/AgentMessageDeltaNotification.ts
+export type AgentMessageDeltaNotification = { threadId: string, turnId: string, itemId: string, delta: string, };
+
+// Source: v2/ApprovalsReviewer.ts
+/**
+ * Configures who approval requests are routed to for review. Examples
+ * include sandbox escapes, blocked network access, MCP approval prompts, and
+ * ARC escalations. Defaults to `user`. `auto_review` uses a carefully
+ * prompted subagent to gather relevant context and apply a risk-based
+ * decision framework before approving or denying the request.
+ */
+export type ApprovalsReviewer = "user" | "auto_review" | "guardian_subagent";
+
+// Source: v2/AskForApproval.ts
+export type AskForApproval = "untrusted" | "on-request" | { "granular": { sandbox_approval: boolean, rules: boolean, skill_approval: boolean, request_permissions: boolean, mcp_elicitations: boolean, } } | "never";
+
+// Source: v2/ByteRange.ts
+export type ByteRange = { start: number, end: number, };
+
+// Source: v2/CodexErrorInfo.ts
+/**
+ * This translation layer make sure that we expose codex error code in camel case.
+ *
+ * When an upstream HTTP status is available (for example, from the Responses API or a provider),
+ * it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.
+ */
+export type CodexErrorInfo = "contextWindowExceeded" | "sessionBudgetExceeded" | "usageLimitExceeded" | "serverOverloaded" | "cyberPolicy" | { "httpConnectionFailed": { httpStatusCode: number | null, } } | { "responseStreamConnectionFailed": { httpStatusCode: number | null, } } | "internalServerError" | "unauthorized" | "badRequest" | "threadRollbackFailed" | "sandboxError" | { "responseStreamDisconnected": { httpStatusCode: number | null, } } | { "responseTooManyFailedAttempts": { httpStatusCode: number | null, } } | { "activeTurnNotSteerable": { turnKind: NonSteerableTurnKind, } } | "other";
+
+// Source: v2/CollabAgentState.ts
+export type CollabAgentState = { status: CollabAgentStatus, message: string | null, };
+
+// Source: v2/CollabAgentStatus.ts
+export type CollabAgentStatus = "pendingInit" | "running" | "interrupted" | "completed" | "errored" | "shutdown" | "notFound";
+
+// Source: v2/CollabAgentTool.ts
+export type CollabAgentTool = "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
+
+// Source: v2/CollabAgentToolCallStatus.ts
+export type CollabAgentToolCallStatus = "inProgress" | "completed" | "failed";
+
+// Source: v2/CommandAction.ts
+export type CommandAction = { "type": "read", command: string, name: string, path: LegacyAppPathString, } | { "type": "listFiles", command: string, path: string | null, } | { "type": "search", command: string, query: string | null, path: string | null, } | { "type": "unknown", command: string, };
+
+// Source: v2/CommandExecutionOutputDeltaNotification.ts
+export type CommandExecutionOutputDeltaNotification = { threadId: string, turnId: string, itemId: string, delta: string, };
+
+// Source: v2/CommandExecutionRequestApprovalParams.ts
+export type CommandExecutionRequestApprovalParams = {threadId: string, turnId: string, itemId: string, /**
+ * Unix timestamp (in milliseconds) when this approval request started.
+ */
+startedAtMs: number, /**
+ * Unique identifier for this specific approval callback.
+ *
+ * For regular shell/unified_exec approvals, this is null.
+ *
+ * For zsh-exec-bridge subcommand approvals, multiple callbacks can belong to
+ * one parent `itemId`, so `approvalId` is a distinct opaque callback id
+ * (a UUID) used to disambiguate routing.
+ */
+approvalId?: string | null, /**
+ * Environment in which the command will run.
+ */
+environmentId: string | null, /**
+ * Optional explanatory reason (e.g. request for network access).
+ */
+reason?: string | null, /**
+ * Optional context for a managed-network approval prompt.
+ */
+networkApprovalContext?: NetworkApprovalContext | null, /**
+ * The command to be executed.
+ */
+command?: string | null, /**
+ * The command's working directory.
+ */
+cwd?: LegacyAppPathString | null, /**
+ * Best-effort parsed command actions for friendly display.
+ */
+commandActions?: Array<CommandAction> | null, /**
+ * Optional proposed execpolicy amendment to allow similar commands without prompting.
+ */
+proposedExecpolicyAmendment?: ExecPolicyAmendment | null, /**
+ * Optional proposed network policy amendments (allow/deny host) for future requests.
+ */
+proposedNetworkPolicyAmendments?: Array<NetworkPolicyAmendment> | null};
+
+// Source: v2/CommandExecutionSource.ts
+export type CommandExecutionSource = "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
+
+// Source: v2/CommandExecutionStatus.ts
+export type CommandExecutionStatus = "inProgress" | "completed" | "failed" | "declined";
+
+// Source: v2/DynamicToolCallOutputContentItem.ts
+export type DynamicToolCallOutputContentItem = { "type": "inputText", text: string, } | { "type": "inputImage", imageUrl: string, } | { "type": "inputAudio", audioUrl: string, };
+
+// Source: v2/DynamicToolCallStatus.ts
+export type DynamicToolCallStatus = "inProgress" | "completed" | "failed";
+
+// Source: v2/ErrorNotification.ts
+export type ErrorNotification = { error: TurnError, willRetry: boolean, threadId: string, turnId: string, };
+
+// Source: v2/ExecPolicyAmendment.ts
+export type ExecPolicyAmendment = Array<string>;
+
+// Source: v2/FileChangePatchUpdatedNotification.ts
+export type FileChangePatchUpdatedNotification = { threadId: string, turnId: string, itemId: string, changes: Array<FileUpdateChange>, };
+
+// Source: v2/FileChangeRequestApprovalParams.ts
+export type FileChangeRequestApprovalParams = { threadId: string, turnId: string, itemId: string,
+/**
+ * Unix timestamp (in milliseconds) when this approval request started.
+ */
+startedAtMs: number,
+/**
+ * Optional explanatory reason (e.g. request for extra write access).
+ */
+reason?: string | null,
+/**
+ * [UNSTABLE] When set, the agent is asking the user to allow writes under this root
+ * for the remainder of the session (unclear if this is honored today).
+ */
+grantRoot?: string | null, };
+
+// Source: v2/FileUpdateChange.ts
+export type FileUpdateChange = { path: string, kind: PatchChangeKind, diff: string, };
+
+// Source: v2/GitInfo.ts
+export type GitInfo = { sha: string | null, branch: string | null, originUrl: string | null, };
+
+// Source: v2/HookPromptFragment.ts
+export type HookPromptFragment = { text: string, hookRunId: string, };
+
+// Source: v2/ItemCompletedNotification.ts
+export type ItemCompletedNotification = { item: ThreadItem, threadId: string, turnId: string,
+/**
+ * Unix timestamp (in milliseconds) when this item lifecycle completed.
+ */
+completedAtMs: number, };
+
+// Source: v2/ItemStartedNotification.ts
+export type ItemStartedNotification = { item: ThreadItem, threadId: string, turnId: string,
+/**
+ * Unix timestamp (in milliseconds) when this item lifecycle started.
+ */
+startedAtMs: number, };
+
+// Source: v2/McpToolCallAppContext.ts
+export type McpToolCallAppContext = { connectorId: string, linkId: string | null, resourceUri: string | null, appName: string | null, actionName: string | null, };
+
+// Source: v2/McpToolCallError.ts
+export type McpToolCallError = { message: string, };
+
+// Source: v2/McpToolCallProgressNotification.ts
+export type McpToolCallProgressNotification = { threadId: string, turnId: string, itemId: string, message: string, };
+
+// Source: v2/McpToolCallResult.ts
+export type McpToolCallResult = { content: Array<JsonValue>, structuredContent: JsonValue | null, _meta: JsonValue | null, };
+
+// Source: v2/McpToolCallStatus.ts
+export type McpToolCallStatus = "inProgress" | "completed" | "failed";
+
+// Source: v2/MemoryCitation.ts
+export type MemoryCitation = { entries: Array<MemoryCitationEntry>, threadIds: Array<string>, };
+
+// Source: v2/MemoryCitationEntry.ts
+export type MemoryCitationEntry = { path: string, lineStart: number, lineEnd: number, note: string, };
+
+// Source: v2/NetworkAccess.ts
+export type NetworkAccess = "restricted" | "enabled";
+
+// Source: v2/NetworkApprovalContext.ts
+export type NetworkApprovalContext = { host: string, protocol: NetworkApprovalProtocol, };
+
+// Source: v2/NetworkApprovalProtocol.ts
+export type NetworkApprovalProtocol = "http" | "https" | "socks5Tcp" | "socks5Udp";
+
+// Source: v2/NetworkPolicyAmendment.ts
+export type NetworkPolicyAmendment = { host: string, action: NetworkPolicyRuleAction, };
+
+// Source: v2/NetworkPolicyRuleAction.ts
+export type NetworkPolicyRuleAction = "allow" | "deny";
+
+// Source: v2/NonSteerableTurnKind.ts
+export type NonSteerableTurnKind = "review" | "compact";
+
+// Source: v2/PatchApplyStatus.ts
+export type PatchApplyStatus = "inProgress" | "completed" | "failed" | "declined";
+
+// Source: v2/PatchChangeKind.ts
+export type PatchChangeKind = { "type": "add" } | { "type": "delete" } | { "type": "update", move_path: string | null, };
+
+// Source: v2/ReasoningSummaryPartAddedNotification.ts
+export type ReasoningSummaryPartAddedNotification = { threadId: string, turnId: string, itemId: string, summaryIndex: number, };
+
+// Source: v2/ReasoningSummaryTextDeltaNotification.ts
+export type ReasoningSummaryTextDeltaNotification = { threadId: string, turnId: string, itemId: string, delta: string, summaryIndex: number, };
+
+// Source: v2/ReasoningTextDeltaNotification.ts
+export type ReasoningTextDeltaNotification = { threadId: string, turnId: string, itemId: string, delta: string, contentIndex: number, };
+
+// Source: v2/SandboxMode.ts
+export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
+
+// Source: v2/SandboxPolicy.ts
+export type SandboxPolicy = { "type": "dangerFullAccess" } | { "type": "readOnly", networkAccess: boolean, } | { "type": "externalSandbox", networkAccess: NetworkAccess, } | { "type": "workspaceWrite", writableRoots: Array<AbsolutePathBuf>, networkAccess: boolean, excludeTmpdirEnvVar: boolean, excludeSlashTmp: boolean, };
+
+// Source: v2/SessionSource.ts
+export type SessionSource = "cli" | "vscode" | "exec" | "appServer" | { "custom": string } | { "subAgent": SubAgentSource } | "unknown";
+
+// Source: v2/SubAgentActivityKind.ts
+export type SubAgentActivityKind = "started" | "interacted" | "interrupted";
+
+// Source: v2/TextElement.ts
+export type TextElement = {
+/**
+ * Byte range in the parent `text` buffer that this element occupies.
+ */
+byteRange: ByteRange,
+/**
+ * Optional human-readable placeholder for the element, displayed in the UI.
+ */
+placeholder: string | null, };
+
+// Source: v2/Thread.ts
+export type Thread = {/**
+ * Identifier for this thread. Codex-generated thread IDs are UUIDv7.
+ */
+id: string, /**
+ * Session id shared by threads that belong to the same session tree.
+ */
+sessionId: string, /**
+ * Source thread id when this thread was created by forking another thread.
+ */
+forkedFromId: string | null, /**
+ * The ID of the parent thread. This will only be set if this thread is a subagent.
+ */
+parentThreadId: string | null, /**
+ * Usually the first user message in the thread, if available.
+ */
+preview: string, /**
+ * Whether the thread is ephemeral and should not be materialized on disk.
+ */
+ephemeral: boolean, /**
+ * The independently persisted section selected for this thread, if any.
+ */
+section: ThreadSection | null, /**
+ * Unix timestamp in seconds when the thread entered its current section.
+ */
+sectionEnteredAt: number | null, /**
+ * Model provider used for this thread (for example, 'openai').
+ */
+modelProvider: string, /**
+ * Unix timestamp (in seconds) when the thread was created.
+ */
+createdAt: number, /**
+ * Unix timestamp (in seconds) when the thread was last updated.
+ */
+updatedAt: number, /**
+ * Unix timestamp (in seconds) used for thread recency ordering.
+ */
+recencyAt: number | null, /**
+ * Current runtime status for the thread.
+ */
+status: ThreadStatus, /**
+ * [UNSTABLE] Path to the thread on disk.
+ */
+path: string | null, /**
+ * Working directory captured for the thread.
+ */
+cwd: AbsolutePathBuf, /**
+ * Version of the CLI that created the thread.
+ */
+cliVersion: string, /**
+ * Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).
+ */
+source: SessionSource, /**
+ * Optional analytics source classification for this thread.
+ */
+threadSource: ThreadSource | null, /**
+ * Optional random unique nickname assigned to an AgentControl-spawned sub-agent.
+ */
+agentNickname: string | null, /**
+ * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.
+ */
+agentRole: string | null, /**
+ * Optional Git metadata captured when the thread was created.
+ */
+gitInfo: GitInfo | null, /**
+ * Optional user-facing thread title.
+ */
+name: string | null, /**
+ * Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read`
+ * (when `includeTurns` is true) responses.
+ * For all other responses and notifications returning a Thread,
+ * the turns field will be an empty list.
+ */
+turns: Array<Turn>};
+
+// Source: v2/ThreadActiveFlag.ts
+export type ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
+
+// Source: v2/ThreadItem.ts
+export type ThreadItem = { "type": "userMessage", id: string, clientId: string | null, content: Array<UserInput>, } | { "type": "hookPrompt", id: string, fragments: Array<HookPromptFragment>, } | { "type": "agentMessage", id: string, text: string, phase: MessagePhase | null, memoryCitation: MemoryCitation | null, } | { "type": "plan", id: string, text: string, } | { "type": "reasoning", id: string, summary: Array<string>, content: Array<string>, } | { "type": "commandExecution", id: string,
+/**
+ * Trusted first-party plugin id when this command resolves to one plugin script.
+ */
+pluginId: string | null,
+/**
+ * Safe plugin-relative path when this command resolves to one plugin script.
+ */
+scriptPath: string | null,
+/**
+ * The command to be executed.
+ */
+command: string,
+/**
+ * The command's working directory.
+ */
+cwd: LegacyAppPathString,
+/**
+ * Identifier for the underlying PTY process (when available).
+ */
+processId: string | null, source: CommandExecutionSource, status: CommandExecutionStatus,
+/**
+ * A best-effort parsing of the command to understand the action(s) it will perform.
+ * This returns a list of CommandAction objects because a single shell command may
+ * be composed of many commands piped together.
+ */
+commandActions: Array<CommandAction>,
+/**
+ * The command's output, aggregated from stdout and stderr.
+ */
+aggregatedOutput: string | null,
+/**
+ * The command's exit code.
+ */
+exitCode: number | null,
+/**
+ * The duration of the command execution in milliseconds.
+ */
+durationMs: number | null, } | { "type": "fileChange", id: string, changes: Array<FileUpdateChange>, status: PatchApplyStatus, } | { "type": "mcpToolCall", id: string, server: string, tool: string, status: McpToolCallStatus, arguments: JsonValue, appContext: McpToolCallAppContext | null,
+/**
+ * Deprecated: use `appContext.resourceUri` instead.
+ */
+mcpAppResourceUri?: string, pluginId: string | null, readOnlyHint: boolean | null, result: McpToolCallResult | null, error: McpToolCallError | null,
+/**
+ * The duration of the MCP tool call in milliseconds.
+ */
+durationMs: number | null, } | { "type": "dynamicToolCall", id: string, namespace: string | null, tool: string, arguments: JsonValue, status: DynamicToolCallStatus, contentItems: Array<DynamicToolCallOutputContentItem> | null, success: boolean | null,
+/**
+ * The duration of the dynamic tool call in milliseconds.
+ */
+durationMs: number | null, } | { "type": "collabAgentToolCall",
+/**
+ * Unique identifier for this collab tool call.
+ */
+id: string,
+/**
+ * Name of the collab tool that was invoked.
+ */
+tool: CollabAgentTool,
+/**
+ * Current status of this collab tool call.
+ */
+status: CollabAgentToolCallStatus,
+/**
+ * Thread ID of the agent issuing the collab request.
+ */
+senderThreadId: string,
+/**
+ * Thread ID of the receiving agent, when applicable. In case of spawn operation,
+ * this corresponds to the newly spawned agent.
+ */
+receiverThreadIds: Array<string>,
+/**
+ * Prompt text sent as part of the collab tool call, when available.
+ */
+prompt: string | null,
+/**
+ * Model requested for the spawned agent, when applicable.
+ */
+model: string | null,
+/**
+ * Reasoning effort requested for the spawned agent, when applicable.
+ */
+reasoningEffort: ReasoningEffort | null,
+/**
+ * Last known status of the target agents, when available.
+ */
+agentsStates: { [key in string]?: CollabAgentState }, } | { "type": "subAgentActivity", id: string, kind: SubAgentActivityKind, agentThreadId: string, agentPath: string, } | { "type": "webSearch" } & WebSearchItem | { "type": "imageView", id: string, path: LegacyAppPathString, } | { "type": "sleep" } & SleepItem | { "type": "imageGeneration" } & ImageGenerationItem | { "type": "enteredReviewMode", id: string, review: string, } | { "type": "exitedReviewMode", id: string, review: string, } | { "type": "contextCompaction", id: string, };
+
+// Source: v2/ThreadSection.ts
+/**
+ * An independently persisted, user-visible thread section.
+ */
+export type ThreadSection = {
+/**
+ * Opaque UUIDv7 identity that remains stable when the section is renamed.
+ */
+id: string,
+/**
+ * The current user-visible section name.
+ */
+name: string,
+/**
+ * Optional appearance synchronized across clients.
+ */
+appearance: ThreadSectionAppearance | null, };
+
+// Source: v2/ThreadSectionAppearance.ts
+/**
+ * Extensible visual presentation for a custom thread section.
+ */
+export type ThreadSectionAppearance = { icon: string | null, color: string | null, };
+
+// Source: v2/ThreadResumeParams.ts
+/**
+ * Resume a persisted or currently loaded thread by id.
+ */
+export type ThreadResumeParams = {threadId: string, /**
+ * Configuration overrides for the resumed thread, if any.
+ */
+model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /**
+ * Override where approval requests are routed for review on this thread
+ * and subsequent turns.
+ */
+approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null};
+
+// Source: v2/ThreadResumeResponse.ts
+export type ThreadResumeResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: string | null, cwd: AbsolutePathBuf, /**
+ * Environment-native paths to instruction source files currently loaded for this thread.
+ */
+instructionSources: Array<LegacyAppPathString>, approvalPolicy: AskForApproval, /**
+ * Reviewer currently used for approval requests on this thread.
+ */
+approvalsReviewer: ApprovalsReviewer, /**
+ * Legacy sandbox policy retained for compatibility. Experimental clients
+ * should prefer `activePermissionProfile` for profile provenance.
+ */
+sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null};
+
+// Source: v2/ThreadSource.ts
+export type ThreadSource = string;
+
+// Source: v2/ThreadStartParams.ts
+export type ThreadStartParams = {model?: string | null, modelProvider?: string | null, serviceTier?: string | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /**
+ * Override where approval requests are routed for review on this thread
+ * and subsequent turns.
+ */
+approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, ephemeral?: boolean | null, sessionStartSource?: ThreadStartSource | null, /**
+ * Optional client-supplied analytics source classification for this thread.
+ */
+threadSource?: ThreadSource | null};
+
+// Source: v2/ThreadStartResponse.ts
+export type ThreadStartResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: string | null, cwd: AbsolutePathBuf, /**
+ * Environment-native paths to instruction source files currently loaded for this thread.
+ */
+instructionSources: Array<LegacyAppPathString>, approvalPolicy: AskForApproval, /**
+ * Reviewer currently used for approval requests on this thread.
+ */
+approvalsReviewer: ApprovalsReviewer, /**
+ * Legacy sandbox policy retained for compatibility. Experimental clients
+ * should prefer `activePermissionProfile` for profile provenance.
+ */
+sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null};
+
+// Source: v2/ThreadStartSource.ts
+export type ThreadStartSource = "startup" | "clear";
+
+// Source: v2/ThreadStatus.ts
+export type ThreadStatus = { "type": "notLoaded" } | { "type": "idle" } | { "type": "systemError" } | { "type": "active", activeFlags: Array<ThreadActiveFlag>, };
+
+// Source: v2/ThreadTokenUsage.ts
+export type ThreadTokenUsage = { total: TokenUsageBreakdown, last: TokenUsageBreakdown, modelContextWindow: number | null, };
+
+// Source: v2/ThreadTokenUsageUpdatedNotification.ts
+export type ThreadTokenUsageUpdatedNotification = { threadId: string, turnId: string, tokenUsage: ThreadTokenUsage, };
+
+// Source: v2/TokenUsageBreakdown.ts
+export type TokenUsageBreakdown = { totalTokens: number, inputTokens: number, cachedInputTokens: number, cacheWriteInputTokens: number, outputTokens: number, reasoningOutputTokens: number, };
+
+// Source: v2/Turn.ts
+export type Turn = {
+/**
+ * Identifier for this turn. Codex-generated turn IDs are UUIDv7.
+ */
+id: string,
+/**
+ * Thread items currently included in this turn payload.
+ */
+items: Array<ThreadItem>,
+/**
+ * Describes how much of `items` has been loaded for this turn.
+ */
+itemsView: TurnItemsView, status: TurnStatus,
+/**
+ * Only populated when the Turn's status is failed.
+ */
+error: TurnError | null,
+/**
+ * Unix timestamp (in seconds) when the turn started.
+ */
+startedAt: number | null,
+/**
+ * Unix timestamp (in seconds) when the turn completed.
+ */
+completedAt: number | null,
+/**
+ * Duration between turn start and completion in milliseconds, if known.
+ */
+durationMs: number | null, };
+
+// Source: v2/TurnCompletedNotification.ts
+export type TurnCompletedNotification = { threadId: string, turn: Turn, };
+
+// Source: v2/TurnError.ts
+export type TurnError = { message: string, codexErrorInfo: CodexErrorInfo | null, additionalDetails: string | null, };
+
+// Source: v2/TurnInterruptParams.ts
+export type TurnInterruptParams = { threadId: string, turnId: string, };
+
+// Source: v2/TurnInterruptResponse.ts
+export type TurnInterruptResponse = Record<string, never>;
+
+// Source: v2/TurnItemsView.ts
+export type TurnItemsView = "notLoaded" | "summary" | "full";
+
+// Source: v2/TurnPlanStep.ts
+export type TurnPlanStep = { step: string, status: TurnPlanStepStatus, };
+
+// Source: v2/TurnPlanStepStatus.ts
+export type TurnPlanStepStatus = "pending" | "inProgress" | "completed";
+
+// Source: v2/TurnPlanUpdatedNotification.ts
+export type TurnPlanUpdatedNotification = { threadId: string, turnId: string, explanation: string | null, plan: Array<TurnPlanStep>, };
+
+// Source: v2/TurnStartParams.ts
+export type TurnStartParams = {threadId: string, clientUserMessageId?: string | null, input: Array<UserInput>, /**
+ * Override the working directory for this turn and subsequent turns.
+ */
+cwd?: string | null, /**
+ * Override the approval policy for this turn and subsequent turns.
+ */
+approvalPolicy?: AskForApproval | null, /**
+ * Override where approval requests are routed for review on this turn and
+ * subsequent turns.
+ */
+approvalsReviewer?: ApprovalsReviewer | null, /**
+ * Override the sandbox policy for this turn and subsequent turns.
+ */
+sandboxPolicy?: SandboxPolicy | null, /**
+ * Override the model for this turn and subsequent turns.
+ */
+model?: string | null, /**
+ * Override the service tier for this turn and subsequent turns.
+ */
+serviceTier?: string | null | null, /**
+ * Override the reasoning effort for this turn and subsequent turns.
+ */
+effort?: ReasoningEffort | null, /**
+ * Override the reasoning summary for this turn and subsequent turns.
+ */
+summary?: ReasoningSummary | null, /**
+ * Override the personality for this turn and subsequent turns.
+ */
+personality?: Personality | null, /**
+ * Optional JSON Schema used to constrain the final assistant message for
+ * this turn.
+ */
+outputSchema?: JsonValue | null};
+
+// Source: v2/TurnStartResponse.ts
+export type TurnStartResponse = { turn: Turn, };
+
+// Source: v2/TurnStartedNotification.ts
+export type TurnStartedNotification = { threadId: string, turn: Turn, };
+
+// Source: v2/TurnStatus.ts
+export type TurnStatus = "completed" | "interrupted" | "failed" | "inProgress";
+
+// Source: v2/UserInput.ts
+export type UserInput = { "type": "text", text: string,
+/**
+ * UI-defined spans within `text` used to render or persist special elements.
+ */
+text_elements: Array<TextElement>, } | { "type": "image", detail?: ImageDetail, url: string, } | { "type": "localImage", detail?: ImageDetail, path: string, } | { "type": "audio", url: string, } | { "type": "localAudio", path: string, } | { "type": "skill", name: string, path: string, } | { "type": "mention", name: string, path: string, };
+
+// Source: v2/WebSearchAction.ts
+export type WebSearchAction = { "type": "search", query: string | null, queries: Array<string> | null, } | { "type": "openPage", url: string | null, } | { "type": "findInPage", url: string | null, pattern: string | null, } | { "type": "other" };
diff --git a/packages/heterogeneous-agents/src/codex/protocol/index.ts b/packages/heterogeneous-agents/src/codex/protocol/index.ts
new file mode 100644
index 00000000000..312874fabf3
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/protocol/index.ts
@@ -0,0 +1,4 @@
+export type * from './generated';
+
+/** Codex source revision used to generate the vendored stable protocol subset. */
+export const CODEX_APP_SERVER_PROTOCOL_REVISION = '5e32f728f1f86a967c6be057351f12505778df8f';
diff --git a/packages/heterogeneous-agents/src/spawn/codexAppServerSession.test.ts b/packages/heterogeneous-agents/src/spawn/codexAppServerSession.test.ts
deleted file mode 100644
index 712623dc410..00000000000
--- a/packages/heterogeneous-agents/src/spawn/codexAppServerSession.test.ts
+++ /dev/null
@@ -1,615 +0,0 @@
-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
deleted file mode 100644
index 8fa87de39ab..00000000000
--- a/packages/heterogeneous-agents/src/spawn/codexAppServerSession.ts
+++ /dev/null
@@ -1,899 +0,0 @@
-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 4c9040efbca..0d5250a209a 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -12,6 +12,19 @@
* `@lobechat/agent-gateway-client` (which is a browser-side WebSocket client
* that producers have no business pulling in).
*/
+export {
+ buildCodexAppServerArgs,
+ buildCodexAppServerInput,
+ buildCodexAppServerThreadParams,
+ CodexAppServerClient,
+ type CodexAppServerClientOptions,
+ CodexAppServerConnectionError,
+ CodexAppServerRpcError,
+ CodexThreadSession,
+ type CodexThreadSessionOptions,
+ getCodexAppServerUnsupportedArgs,
+ isCodexAppServerCompatibilityError,
+} from '../codex';
export type { UsageData } from '../types';
export {
type AcpRpcErrorData,
@@ -41,16 +54,6 @@ 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/heterogeneous-agents/src/utils/codexCommandOutput.ts b/packages/heterogeneous-agents/src/utils/codexCommandOutput.ts
new file mode 100644
index 00000000000..e8634a48dbe
--- /dev/null
+++ b/packages/heterogeneous-agents/src/utils/codexCommandOutput.ts
@@ -0,0 +1,24 @@
+export const CODEX_COMMAND_OUTPUT_MAX_LENGTH = 25_000;
+
+export const truncateCodexCommandOutput = (content: string) => {
+ if (!content || content.length <= CODEX_COMMAND_OUTPUT_MAX_LENGTH) {
+ return {
+ output: content,
+ truncated: false,
+ };
+ }
+
+ let cutoff = CODEX_COMMAND_OUTPUT_MAX_LENGTH;
+ const lastCharCode = content.charCodeAt(cutoff - 1);
+ if (lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff) cutoff -= 1;
+
+ const omittedCharacters = content.length - cutoff;
+ const notice = `\n\n[Output truncated: ${omittedCharacters} characters omitted. Original length: ${content.length} characters]`;
+
+ return {
+ omittedCharacters,
+ originalLength: content.length,
+ output: content.slice(0, cutoff) + notice,
+ truncated: true,
+ };
+};
diff --git a/packages/utils/package.json b/packages/utils/package.json
index 596d18a92d5..99900fa6572 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -24,6 +24,7 @@
"dayjs": "^1.11.21",
"debug": "^4.4.3",
"dompurify": "^3.4.11",
+ "es-toolkit": "^1.50.0",
"fast-deep-equal": "^3.1.3",
"file-type": "^21.3.4",
"mime": "^4.1.0",