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.

🐛 fix(codex): show async questions in the AskQuestion tray (#23452)

Mochad3e62bb84862
diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts
index 91778510ee0..dd6845bd744 100644
--- a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts
+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts
@@ -392,21 +392,31 @@ export class CodexAppServerAdapter {
private started = false;
/** A steered message was read; the next visible output opens a new step. */
private steerStepPending = false;
- private stepIndex = 0;
+ private stepIndex: number;
private terminal = false;
constructor(
- options: { initialCumulativeUsage?: UsageData; initialModel?: string; sessionId?: string } = {},
+ options: {
+ initialCumulativeUsage?: UsageData;
+ initialModel?: string;
+ initialStepIndex?: number;
+ sessionId?: string;
+ } = {},
) {
this.currentModel = options.initialModel;
this.lastCumulativeUsage = options.initialCumulativeUsage;
this.sessionId = options.sessionId;
+ this.stepIndex = options.initialStepIndex ?? 0;
}
get cumulativeUsage(): UsageData | undefined {
return this.latestCumulativeUsage ?? this.lastCumulativeUsage;
}
+ get nextStepIndex(): number {
+ return this.stepIndex + 1;
+ }
+
startUserInput(toolCallId: string, args: unknown): HeterogeneousAgentEvent[] {
const payload: ToolCallPayload = {
apiName: 'askUserQuestion',
@@ -513,7 +523,15 @@ export class CodexAppServerAdapter {
if (this.started) return [];
this.started = true;
this.currentTurnId = params.turn.id;
- return [this.makeEvent('stream_start', this.streamStartData({ messageId: params.turn.id }))];
+ return [
+ this.makeEvent(
+ 'stream_start',
+ this.streamStartData({
+ messageId: params.turn.id,
+ newStep: this.stepIndex > 0 || undefined,
+ }),
+ ),
+ ];
}
private handleItemStarted({ item }: ItemStartedNotification): HeterogeneousAgentEvent[] {
diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts
index f2f1f0640fb..b456b349f54 100644
--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts
+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts
@@ -327,6 +327,97 @@ describe('CodexThreadSession', () => {
ctx.session.close();
};
+ const announceAsyncQuestion = (ctx: Awaited<ReturnType<typeof start>>) =>
+ ctx.harness.notify('item/completed', {
+ item: {
+ delivery: 'async',
+ id: 'async-1',
+ questions: [{ options: ['Staging', 'Production'], title: 'Which environment?' }],
+ text: 'Which environment?\n- Staging\n- Production',
+ type: 'agentMessage',
+ },
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ });
+
+ it('keeps an async question actionable after completion and continues the original thread', async () => {
+ const ctx = await start();
+ await announceAsyncQuestion(ctx);
+ expect(ctx.bridge.pendingCount).toBe(1);
+ expect((await ctx.bridge.events()[Symbol.asyncIterator]().next()).value).toMatchObject({
+ data: { apiName: 'askUserQuestion', identifier: 'codex', toolCallId: 'async-1' },
+ type: 'agent_intervention_request',
+ });
+ await ctx.harness.notify('turn/completed', {
+ threadId: 'thread-1',
+ turn: turn('turn-1', 'completed'),
+ });
+ expect(ctx.bridge.pendingCount).toBe(1);
+ expect(ctx.events.some(({ type }) => type === 'agent_runtime_end')).toBe(false);
+
+ ctx.bridge.resolve('async-1', { result: { 'Which environment?': 'Staging' } });
+ await vi.waitFor(() => {
+ expect(ctx.harness.requests.filter(({ method }) => method === 'turn/start')).toHaveLength(
+ 2,
+ );
+ });
+ expect(ctx.harness.requests.at(-1)).toMatchObject({
+ method: 'turn/start',
+ params: {
+ input: [{ text: expect.stringContaining('"answer":"Staging"'), type: 'text' }],
+ threadId: 'thread-1',
+ },
+ });
+ expect(JSON.stringify(ctx.harness.requests.at(-1))).toContain('request_user_input_async');
+ await ctx.harness.notify('turn/started', {
+ threadId: 'thread-1',
+ turn: turn('turn-2', 'inProgress'),
+ });
+ await ctx.harness.notify('turn/completed', {
+ threadId: 'thread-1',
+ turn: turn('turn-2', 'completed'),
+ });
+ await ctx.running;
+ expect(ctx.events.filter(({ type }) => type === 'agent_runtime_end')).toHaveLength(1);
+ expect(ctx.events).toContainEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({ newStep: true }),
+ type: 'stream_start',
+ }),
+ );
+ });
+
+ it('stops waiting on an async question without starting another native turn when skipped', async () => {
+ const ctx = await start();
+ await announceAsyncQuestion(ctx);
+ expect(ctx.bridge.pendingCount).toBe(1);
+ await ctx.harness.notify('turn/completed', {
+ threadId: 'thread-1',
+ turn: turn('turn-1', 'completed'),
+ });
+ ctx.bridge.resolve('async-1', { cancelled: true, cancelReason: 'user_cancelled' });
+ await ctx.running;
+ expect(ctx.harness.requests.filter(({ method }) => method === 'turn/start')).toHaveLength(1);
+ expect(ctx.events.filter(({ type }) => type === 'agent_runtime_end')).toHaveLength(1);
+ ctx.session.close();
+ });
+
+ it('stops waiting without interrupting a native turn that has already completed', async () => {
+ const ctx = await start();
+ await announceAsyncQuestion(ctx);
+ await ctx.harness.notify('turn/completed', {
+ threadId: 'thread-1',
+ turn: turn('turn-1', 'completed'),
+ });
+ await ctx.session.interrupt();
+ await ctx.running;
+ expect(ctx.bridge.pendingCount).toBe(0);
+ expect(ctx.harness.requests.filter(({ method }) => method === 'turn/start')).toHaveLength(1);
+ expect(ctx.harness.requests.some(({ method }) => method === 'turn/interrupt')).toBe(false);
+ expect(ctx.events.filter(({ type }) => type === 'agent_runtime_end')).toHaveLength(1);
+ ctx.session.close();
+ });
+
it('presents native questions and returns selected/custom answers by their original ids', async () => {
const ctx = await start();
const reply = ctx.harness.serverRequest(
diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts
index 93d1402f8ea..bd123be677c 100644
--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts
+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts
@@ -2,10 +2,15 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { isRecord, pickString } from '@lobechat/utils/object';
import { CodexAppServerAdapter } from '../adapters/codexAppServer';
-import type { AskUserBridge } from '../askUser';
+import type { AskUserBridge, InterventionAnswer } from '../askUser';
import type { HeterogeneousAgentRuntimeStatus } from '../spawn/claudeAgentSdkSession';
import { toStreamEvent } from '../spawn/streamEvent';
import type { UsageData } from '../types';
+import {
+ codexAsyncAnswers,
+ formatCodexAsyncReplies,
+ readCodexAsyncQuestion,
+} from './asyncUserInput';
import type { CodexAppServerClient } from './CodexAppServerClient';
import { CodexAppServerConnectionError, CodexAppServerRpcError } from './CodexAppServerClient';
import type { CodexRunProvenance } from './environment';
@@ -43,16 +48,21 @@ const toThreadResumeParams = (threadId: string, params: ThreadStartParams): Thre
return { ...resumeParams, threadId };
};
+type AsyncQuestion = NonNullable<ReturnType<typeof readCodexAsyncQuestion>>;
+
interface ActiveTurn {
adapter: CodexAppServerAdapter;
askUserBridge?: AskUserBridge;
+ asyncQuestions: Map<string, { answer: Promise<InterventionAnswer>; request: AsyncQuestion }>;
completion: Promise<void>;
+ deferredCompletion?: TurnCompletedNotification;
interruptRequest?: Promise<void>;
interruptRequested: boolean;
notificationError?: Error;
notificationQueue: Promise<void>;
operationId: string;
resolve: () => void;
+ synchronousQuestions: Set<string>;
terminalNotificationReceived: boolean;
transportInterrupted: boolean;
turnId?: string;
@@ -158,51 +168,14 @@ export class CodexThreadSession {
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,
- // An ephemeral thread cannot be resumed, so it is never reported as the session.
- sessionId: this.options.threadParams.ephemeral ? undefined : threadId,
- });
- let resolveTurn!: () => void;
- const completion = new Promise<void>((resolve) => {
- resolveTurn = resolve;
- });
- const activeTurn: ActiveTurn = {
- adapter,
- askUserBridge: options.askUserBridge,
- 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;
+ let input: UserInput[] | undefined = options.input;
+ let stepIndex = 0;
+ while (input && !this.closedByHost) {
+ const result = await this.runNativeTurn(options, threadId, input, stepIndex);
+ input = result?.input;
+ stepIndex = result?.stepIndex ?? 0;
}
- await this.emitEvents(adapter.flush(), options.operationId);
- this.cumulativeUsage = adapter.cumulativeUsage;
- this.emitStatus('idle', options.operationId);
+ if (!this.closedByHost) this.emitStatus('idle', options.operationId);
} catch (error) {
if (this.closedByHost) return;
if (this.activeTurn?.transportInterrupted) {
@@ -226,6 +199,66 @@ export class CodexThreadSession {
}
}
+ private async runNativeTurn(
+ options: CodexThreadTurnOptions,
+ threadId: string,
+ input: UserInput[],
+ stepIndex: number,
+ ): Promise<{ input: UserInput[]; stepIndex: number } | undefined> {
+ const adapter = new CodexAppServerAdapter({
+ initialCumulativeUsage: this.cumulativeUsage,
+ initialModel: this.model,
+ initialStepIndex: stepIndex,
+ // An ephemeral thread cannot be resumed, so it is never reported as the session.
+ sessionId: this.options.threadParams.ephemeral ? undefined : threadId,
+ });
+ let resolveTurn!: () => void;
+ const completion = new Promise<void>((resolve) => {
+ resolveTurn = resolve;
+ });
+ const activeTurn: ActiveTurn = {
+ adapter,
+ askUserBridge: options.askUserBridge,
+ asyncQuestions: new Map(),
+ completion,
+ interruptRequested: this.interruptRequested,
+ notificationQueue: Promise.resolve(),
+ operationId: options.operationId,
+ resolve: resolveTurn,
+ synchronousQuestions: new Set(),
+ terminalNotificationReceived: false,
+ transportInterrupted: false,
+ };
+ this.activeTurn = activeTurn;
+
+ const turnParams: TurnStartParams = { 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;
+ if (stepIndex === 0) this.emitStatus('running', options.operationId);
+
+ await activeTurn.completion;
+ await activeTurn.notificationQueue;
+ if (this.closedByHost) return;
+ if (activeTurn.notificationError) throw activeTurn.notificationError;
+ const continuation = activeTurn.deferredCompletion
+ ? await this.finishAsyncQuestions(activeTurn, activeTurn.deferredCompletion)
+ : undefined;
+ if (!activeTurn.transportInterrupted) {
+ await this.emitEvents(adapter.flush(), options.operationId);
+ }
+ this.cumulativeUsage = adapter.cumulativeUsage;
+ return continuation
+ ? {
+ input: [{ text: continuation, text_elements: [], type: 'text' }],
+ stepIndex: adapter.nextStepIndex,
+ }
+ : undefined;
+ }
+
/**
* Add a user message to the running turn (`turn/steer`). The model reads it
* at its next step; the app-server reports it back as a `userMessage` item
@@ -239,7 +272,13 @@ export class CodexThreadSession {
): Promise<CodexSteerOutcome> {
const activeTurn = this.activeTurn;
const threadId = this.threadId;
- if (!activeTurn?.turnId || !threadId || activeTurn.interruptRequested || this.closedByHost)
+ if (
+ !activeTurn?.turnId ||
+ !threadId ||
+ activeTurn.terminalNotificationReceived ||
+ activeTurn.interruptRequested ||
+ this.closedByHost
+ )
return 'rejected';
try {
@@ -266,7 +305,7 @@ export class CodexThreadSession {
activeTurn.interruptRequested = true;
activeTurn.askUserBridge?.cancelAll('session_ended');
- if (!activeTurn.turnId) return;
+ if (!activeTurn.turnId || activeTurn.terminalNotificationReceived) return;
try {
await this.requestInterrupt(activeTurn);
} catch (error) {
@@ -287,7 +326,7 @@ export class CodexThreadSession {
this.interruptRequested = true;
if (this.activeTurn) {
this.activeTurn.interruptRequested = true;
- if (this.activeTurn.turnId) {
+ if (this.activeTurn.turnId && !this.activeTurn.terminalNotificationReceived) {
void this.requestInterrupt(this.activeTurn).catch((error) => {
console.error('Failed to interrupt Codex turn while closing the session:', error);
});
@@ -458,10 +497,13 @@ export class CodexThreadSession {
activeTurn.transportInterrupted
)
return { answers: {} };
- const answer = await bridge.pending(
- { arguments: args, toolCallId: request.itemId },
- request.autoResolutionMs ? { timeoutMs: request.autoResolutionMs } : {},
- );
+ activeTurn.synchronousQuestions.add(request.itemId);
+ const answer = await bridge
+ .pending(
+ { arguments: args, toolCallId: request.itemId },
+ request.autoResolutionMs ? { timeoutMs: request.autoResolutionMs } : {},
+ )
+ .finally(() => activeTurn.synchronousQuestions.delete(request.itemId));
activeTurn.notificationQueue = activeTurn.notificationQueue.then(() =>
this.emitEvents(
activeTurn.adapter.completeUserInput(request.itemId, answer),
@@ -475,7 +517,10 @@ export class CodexThreadSession {
private handleDisconnect(): void {
if (this.closedByHost) return;
this.attached = false;
- if (this.activeTurn && !this.activeTurn.terminalNotificationReceived) {
+ if (
+ this.activeTurn &&
+ (!this.activeTurn.terminalNotificationReceived || this.activeTurn.asyncQuestions.size > 0)
+ ) {
this.interruptActiveTurn();
}
}
@@ -483,7 +528,7 @@ export class CodexThreadSession {
private requestInterrupt(activeTurn: ActiveTurn): Promise<void> {
const threadId = this.threadId;
const turnId = activeTurn.turnId;
- if (!threadId || !turnId) return Promise.resolve();
+ if (!threadId || !turnId || activeTurn.terminalNotificationReceived) return Promise.resolve();
if (activeTurn.interruptRequest) return activeTurn.interruptRequest;
const params: TurnInterruptParams = { threadId, turnId };
@@ -513,13 +558,32 @@ export class CodexThreadSession {
const notification = params as TurnCompletedNotification;
if (notification.turn.status !== 'inProgress') {
activeTurn.terminalNotificationReceived = true;
- activeTurn.askUserBridge?.cancelAll('session_ended');
+ for (const id of activeTurn.synchronousQuestions) {
+ activeTurn.askUserBridge?.cancel(id, 'session_ended');
+ }
}
}
activeTurn.notificationQueue = activeTurn.notificationQueue
.then(async () => {
if (activeTurn.notificationError) return;
+ if (method === 'item/completed' && (await this.startAsyncQuestion(activeTurn, params)))
+ return;
+ if (method === 'turn/completed') {
+ const notification = params as TurnCompletedNotification;
+ if (
+ notification.turn.status === 'completed' &&
+ activeTurn.asyncQuestions.size > 0 &&
+ !activeTurn.transportInterrupted
+ ) {
+ activeTurn.deferredCompletion = notification;
+ activeTurn.resolve();
+ return;
+ }
+ if (notification.turn.status !== 'inProgress') {
+ activeTurn.askUserBridge?.cancelAll('session_ended');
+ }
+ }
await this.emitEvents(activeTurn.adapter.adapt(method, params), activeTurn.operationId);
if (method !== 'turn/completed') return;
const notification = params as TurnCompletedNotification;
@@ -533,6 +597,64 @@ export class CodexThreadSession {
return activeTurn.notificationQueue;
}
+ private async startAsyncQuestion(activeTurn: ActiveTurn, params: unknown): Promise<boolean> {
+ const bridge = activeTurn.askUserBridge;
+ if (!bridge || bridge.operationId !== activeTurn.operationId) return false;
+ const request = readCodexAsyncQuestion(params);
+ if (!request) return false;
+ if (activeTurn.asyncQuestions.has(request.itemId)) return true;
+ if (activeTurn.interruptRequested || activeTurn.transportInterrupted) return false;
+
+ const { itemId } = request;
+ const args = codexUserInputArguments(request);
+ await this.emitEvents(activeTurn.adapter.startUserInput(itemId, args), activeTurn.operationId);
+ if (activeTurn.interruptRequested || activeTurn.transportInterrupted) return true;
+
+ const answer = bridge.pending({ arguments: args, toolCallId: itemId }).catch((error) => {
+ this.recordNotificationError(activeTurn, error);
+ return { cancelled: true };
+ });
+ activeTurn.asyncQuestions.set(itemId, { answer, request });
+ return true;
+ }
+
+ private async finishAsyncQuestions(
+ activeTurn: ActiveTurn,
+ notification: TurnCompletedNotification,
+ ): Promise<string | undefined> {
+ const { adapter, asyncQuestions, operationId } = activeTurn;
+ // Codex completes its native turn while the LobeHub operation is still collecting answers.
+ // Continue the same thread only after that native turn has settled.
+ const answers = await Promise.all(
+ [...asyncQuestions.values()].map(async ({ answer, request }) => ({
+ answer: await answer,
+ request,
+ })),
+ );
+ if (activeTurn.notificationError) throw activeTurn.notificationError;
+ if (this.closedByHost || activeTurn.transportInterrupted) {
+ await activeTurn.notificationQueue;
+ return;
+ }
+ const replies = [];
+ for (const { answer, request } of answers) {
+ await this.emitEvents(adapter.completeUserInput(request.itemId, answer), operationId);
+ replies.push(...codexAsyncAnswers(request, answer));
+ }
+
+ const turnEnded = ({ type }: { type: string }) =>
+ type === 'agent_runtime_end' || type === 'visible_output_end';
+ const events = adapter.adapt('turn/completed', notification);
+ await this.emitEvents(
+ events.filter((event) => !turnEnded(event)),
+ operationId,
+ );
+ if (!activeTurn.interruptRequested && !activeTurn.transportInterrupted && replies.length > 0) {
+ return formatCodexAsyncReplies(replies);
+ }
+ await this.emitEvents(events.filter(turnEnded), operationId);
+ }
+
private isCurrentTurnNotification(
method: string,
params: unknown,
diff --git a/packages/heterogeneous-agents/src/codex/asyncUserInput.test.ts b/packages/heterogeneous-agents/src/codex/asyncUserInput.test.ts
new file mode 100644
index 00000000000..8b373fb070e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/asyncUserInput.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ codexAsyncAnswers,
+ formatCodexAsyncReplies,
+ readCodexAsyncQuestion,
+} from './asyncUserInput';
+
+describe('Codex async question replies', () => {
+ it('returns selected and free-text answers with their original question IDs', () => {
+ const request = readCodexAsyncQuestion({
+ item: {
+ delivery: 'async',
+ id: 'call-1',
+ questions: [
+ { options: ['Staging', 'Production'], title: 'Which environment?' },
+ { options: null, title: 'Any notes?' },
+ ],
+ type: 'agentMessage',
+ },
+ });
+ expect(request).toBeDefined();
+ const content = formatCodexAsyncReplies(
+ codexAsyncAnswers(request!, {
+ result: { 'Any notes?': 'Use a "dry run"\nfirst.', 'Which environment?': 'Staging' },
+ }),
+ );
+ expect(content).toBe(
+ '<send_user_message_question_reply>\n' +
+ '[{"answer":"Staging","question":"Which environment?",' +
+ '"questionItemId":"[\\"request_user_input_async\\",\\"call-1\\",0]"},' +
+ '{"answer":"Use a \\"dry run\\"\\nfirst.","question":"Any notes?",' +
+ '"questionItemId":"[\\"request_user_input_async\\",\\"call-1\\",1]"}]\n' +
+ '</send_user_message_question_reply>',
+ );
+ });
+
+ it('keeps duplicate prompt titles separately answerable', () => {
+ const request = readCodexAsyncQuestion({
+ item: {
+ delivery: 'async',
+ id: 'call-2',
+ questions: [{ title: 'Name?' }, { options: [], title: 'Name?' }],
+ type: 'agentMessage',
+ },
+ });
+ expect(codexAsyncAnswers(request!, { result: { 'Name?': 'Foo', 'Name? (2)': 'Bar' } })).toEqual(
+ [
+ {
+ answer: 'Foo',
+ question: 'Name?',
+ questionItemId: '["request_user_input_async","call-2",0]',
+ },
+ {
+ answer: 'Bar',
+ question: 'Name?',
+ questionItemId: '["request_user_input_async","call-2",1]',
+ },
+ ],
+ );
+ });
+});
diff --git a/packages/heterogeneous-agents/src/codex/asyncUserInput.ts b/packages/heterogeneous-agents/src/codex/asyncUserInput.ts
new file mode 100644
index 00000000000..1dbb43e4661
--- /dev/null
+++ b/packages/heterogeneous-agents/src/codex/asyncUserInput.ts
@@ -0,0 +1,51 @@
+import { z } from 'zod';
+
+import type { InterventionAnswer } from '../askUser';
+import { codexUserInputResponse } from './requestUserInput';
+
+const nonBlank = z.string().refine((value) => value.trim().length > 0);
+const notificationSchema = z.object({
+ item: z.object({
+ delivery: z.literal('async'),
+ id: nonBlank,
+ questions: z.array(z.object({ options: z.array(nonBlank).nullish(), title: nonBlank })).min(1),
+ type: z.literal('agentMessage'),
+ }),
+});
+
+export const readCodexAsyncQuestion = (params: unknown) => {
+ const item = notificationSchema.safeParse(params).data?.item;
+ if (!item) return;
+ const questionNames = new Set(['__freeform__', '__supplement__']);
+ const questions = item.questions.map(({ options, title }, index) => {
+ let question = title;
+ for (let suffix = 2; questionNames.has(question); suffix++) {
+ question = `${title} (${suffix})`;
+ }
+ questionNames.add(question);
+ return {
+ header: '',
+ id: JSON.stringify(['request_user_input_async', item.id, index]),
+ isSecret: false as const,
+ options: [...new Set(options)].map((label) => ({ description: '', label })),
+ question,
+ title,
+ };
+ });
+ return { itemId: item.id, questions };
+};
+
+export const codexAsyncAnswers = (
+ request: NonNullable<ReturnType<typeof readCodexAsyncQuestion>>,
+ answer: InterventionAnswer,
+) => {
+ const { answers } = codexUserInputResponse(request, answer);
+ return request.questions.flatMap(({ id, title }) => {
+ const response = answers[id]?.answers.join('\n');
+ return response ? [{ answer: response, question: title, questionItemId: id }] : [];
+ });
+};
+
+// Codex recognizes the same reply envelope its CLI and Desktop send on the original thread.
+export const formatCodexAsyncReplies = (replies: ReturnType<typeof codexAsyncAnswers>) =>
+ `<send_user_message_question_reply>\n${JSON.stringify(replies)}\n</send_user_message_question_reply>`;
diff --git a/packages/heterogeneous-agents/src/codex/requestUserInput.ts b/packages/heterogeneous-agents/src/codex/requestUserInput.ts
index 2b85f619201..face17d471d 100644
--- a/packages/heterogeneous-agents/src/codex/requestUserInput.ts
+++ b/packages/heterogeneous-agents/src/codex/requestUserInput.ts
@@ -34,7 +34,9 @@ export const parseCodexUserInput = (params: unknown) => {
return request;
};
-export const codexUserInputArguments = (request: ReturnType<typeof parseCodexUserInput>) => ({
+type UserInputQuestions = Pick<ReturnType<typeof parseCodexUserInput>, 'questions'>;
+
+export const codexUserInputArguments = (request: UserInputQuestions) => ({
questions: request.questions.map((question) => ({
header: question.header,
multiSelect: false,
@@ -48,7 +50,7 @@ export const codexUserInputArguments = (request: ReturnType<typeof parseCodexUse
});
export const codexUserInputResponse = (
- request: ReturnType<typeof parseCodexUserInput>,
+ request: UserInputQuestions,
answer: InterventionAnswer,
): ToolRequestUserInputResponse => {
if (answer.cancelled || !isRecord(answer.result)) return { answers: {} };