Skip to content

Commit 764ea2b

Browse files
authored
feat(codex): answer async questions while agents keep working (#144664)
* feat(codex): support async questions in chat * fix(ui): keep async question contracts acyclic * refactor(ui): reuse the current reply quote owner * refactor(ui): simplify reply target selection
1 parent c0a92e7 commit 764ea2b

24 files changed

Lines changed: 1168 additions & 156 deletions

‎docs/plugins/codex-harness-runtime/permissions.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,5 +70,25 @@ Only an explicit field `isSecret: true` or Codex question
7070
at a time through the warned ephemeral text-reply path and never create durable
7171
Gateway question records. OpenClaw does not infer secrecy from field names.
7272

73+
## Async questions
74+
75+
When the selected Codex model advertises `request_user_input_async`, Codex can
76+
ask structured questions while continuing work. The tool returns immediately.
77+
OpenClaw preserves the questions on the async assistant message, and the Control
78+
UI shows suggested answers and a free-text field. Selecting a suggestion does
79+
not send it; the user must explicitly submit an answer.
80+
81+
Answers use normal chat delivery: they steer an active turn or start a new turn
82+
in the same conversation after it finishes. The question is quoted alongside
83+
the answer so Codex can identify which question it addresses. Async questions
84+
do not create a waiting tool call or use the blocking question queue above.
85+
They follow the same tool and message-delivery restrictions as other native
86+
async messages. Silence and preselected answers never grant approval.
87+
88+
Channels receive Codex's readable question text and choices and accept normal
89+
replies. The Control UI supports up to 12 questions per message and four choices
90+
per question, with titles up to 4,096 characters and choices up to 256 characters.
91+
Unsupported structured payloads retain the complete plain-text question.
92+
7393
For the general plugin approval flow that carries these prompts, see
7494
[Plugin permission requests](/plugins/plugin-permission-requests).
Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import type { EmbeddedRunAttemptParamsV2 as EmbeddedRunAttemptParams } from "openclaw/plugin-sdk/agent-harness-runtime";
4+
import { createAgentHarnessHostCapabilitiesForTest } from "openclaw/plugin-sdk/plugin-test-runtime";
5+
import { upsertSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
6+
import { readSessionTranscriptEvents } from "openclaw/plugin-sdk/session-transcript-runtime";
7+
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
8+
import { afterEach, describe, expect, it, vi } from "vitest";
9+
import {
10+
resolveCodexAppServerHomeDir,
11+
resolveCodexAppServerUserHomeDir,
12+
} from "./auth-start-options.js";
13+
import { resolveCodexAppServerRuntimeOptions } from "./config.js";
14+
import { setManagedCodexPluginRoot } from "./managed-binary.js";
15+
import { isJsonObject } from "./protocol.js";
16+
import { runCodexAppServerAttempt } from "./run-attempt.js";
17+
import {
18+
createCodexTestBindingStore,
19+
sessionBindingIdentity,
20+
} from "./session-binding.test-helpers.js";
21+
import { createIsolatedCodexAppServerClient } from "./shared-client.js";
22+
23+
const LIVE =
24+
process.env.OPENCLAW_LIVE_TEST === "1" && process.env.OPENCLAW_LIVE_CODEX_ASYNC_QUESTIONS === "1";
25+
const describeLive = LIVE ? describe : describe.skip;
26+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
27+
28+
afterEach(() => {
29+
setManagedCodexPluginRoot(undefined);
30+
vi.unstubAllEnvs();
31+
});
32+
33+
describeLive("Codex async questions real-binary bridge", () => {
34+
it("continues work before an answer and consumes a later ordinary reply on the same thread", async () => {
35+
const runtimeModelId = process.env.OPENCLAW_LIVE_CODEX_MODEL?.trim();
36+
if (!runtimeModelId) {
37+
throw new Error("Set OPENCLAW_LIVE_CODEX_MODEL to a model with async question support");
38+
}
39+
const root = tempDirs.make("openclaw-codex-async-questions-");
40+
const workspace = path.join(root, "workspace");
41+
const agentDir = path.join(root, "agent");
42+
const nativeHome = resolveCodexAppServerHomeDir(agentDir);
43+
await fs.mkdir(workspace, { recursive: true });
44+
await fs.mkdir(nativeHome, { recursive: true, mode: 0o700 });
45+
// Copy only the existing login into the disposable home, never user config or sessions.
46+
const authFile = path.join(nativeHome, "auth.json");
47+
await fs.copyFile(path.join(resolveCodexAppServerUserHomeDir(), "auth.json"), authFile);
48+
await fs.chmod(authFile, 0o600);
49+
vi.stubEnv("OPENCLAW_STATE_DIR", path.join(root, "state"));
50+
setManagedCodexPluginRoot(path.resolve(import.meta.dirname, "../.."));
51+
52+
const pluginConfig = { appServer: { homeScope: "agent" } };
53+
const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig, env: {} });
54+
const client = await createIsolatedCodexAppServerClient({
55+
startOptions: runtime.start,
56+
agentDir,
57+
authProfileId: null,
58+
timeoutMs: 120_000,
59+
});
60+
let closeHost: (() => void) | undefined;
61+
try {
62+
const completedKinds: string[] = [];
63+
const questionItemIds: string[] = [];
64+
const serverRequestMethods: string[] = [];
65+
client.addRequestHandler((request) => {
66+
serverRequestMethods.push(request.method);
67+
return undefined;
68+
});
69+
client.addNotificationHandler((notification) => {
70+
if (notification.method !== "item/completed" || !isJsonObject(notification.params)) {
71+
return;
72+
}
73+
const item = notification.params.item;
74+
if (!isJsonObject(item) || typeof item.type !== "string") {
75+
return;
76+
}
77+
if (
78+
item.type === "agentMessage" &&
79+
item.delivery === "async" &&
80+
Array.isArray(item.questions) &&
81+
typeof item.id === "string"
82+
) {
83+
questionItemIds.push(item.id);
84+
completedKinds.push("asyncQuestion");
85+
} else {
86+
completedKinds.push(item.type);
87+
}
88+
});
89+
90+
const questions = [
91+
{ title: "Which output format?", options: ["Markdown", "Plain text"] },
92+
{ title: "Who is the audience?" },
93+
];
94+
const deliveredTexts: string[] = [];
95+
const modelId = runtimeModelId;
96+
const sessionTarget = {
97+
agentId: "async-questions",
98+
sessionId: "async-questions-session",
99+
sessionKey: "agent:async-questions:main",
100+
storePath: path.join(agentDir, "openclaw-agent.sqlite"),
101+
};
102+
const params = {
103+
agentId: sessionTarget.agentId,
104+
sessionId: sessionTarget.sessionId,
105+
sessionKey: sessionTarget.sessionKey,
106+
sessionTarget,
107+
sessionFile: path.join(root, "session.jsonl"),
108+
workspaceDir: workspace,
109+
cwd: workspace,
110+
agentDir,
111+
provider: "openai",
112+
modelId,
113+
model: {
114+
id: modelId,
115+
name: modelId,
116+
provider: "openai",
117+
api: "openai-chatgpt-responses",
118+
reasoning: true,
119+
input: ["text"],
120+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
121+
contextWindow: 200_000,
122+
maxTokens: 8_000,
123+
compat: { supportsTools: false },
124+
},
125+
prompt: [
126+
"This is a synthetic async question integration check. All files belong to this disposable workspace.",
127+
"First call request_user_input_async exactly once with these exact arguments:",
128+
JSON.stringify({ questions }),
129+
"These are optional preferences. Immediately after that tool returns, continue independent work without waiting for an answer.",
130+
"Use a native shell command to create async-question-marker.txt containing exactly AFTER_ASYNC_QUESTION followed by a newline.",
131+
"Then end this turn with QUESTION_READY. Do not use request_user_input or ask another question.",
132+
].join("\n"),
133+
runId: "async-questions-first-run",
134+
contextTokenBudget: 150_000,
135+
contextWindowInfo: {
136+
tokens: 150_000,
137+
referenceTokens: 200_000,
138+
source: "agentContextTokens",
139+
},
140+
thinkLevel: "medium",
141+
disableTools: false,
142+
config: { tools: { web: { search: { enabled: false } } } },
143+
timeoutMs: 180_000,
144+
trigger: "user",
145+
oneShotCliRun: true,
146+
senderIsOwner: true,
147+
authStorage: {},
148+
authProfileStore: { version: 1, profiles: {} },
149+
modelRegistry: {},
150+
onBlockReply: async (payload: { text?: string }) => {
151+
if (payload.text) {
152+
deliveredTexts.push(payload.text);
153+
}
154+
},
155+
} as unknown as EmbeddedRunAttemptParams;
156+
await upsertSessionEntry({
157+
...sessionTarget,
158+
entry: {
159+
sessionId: sessionTarget.sessionId,
160+
sessionFile: params.sessionFile,
161+
updatedAt: Date.now(),
162+
},
163+
});
164+
const host = await createAgentHarnessHostCapabilitiesForTest({
165+
attempt: params,
166+
pluginId: "codex",
167+
});
168+
params.hostCapabilities = host.capabilities;
169+
closeHost = host.close;
170+
const bindingStore = createCodexTestBindingStore();
171+
const options = {
172+
bindingStore,
173+
pluginConfig,
174+
clientFactory: async () => client,
175+
};
176+
const first = await runCodexAppServerAttempt(params, options);
177+
178+
expect(first.terminal.kind).toBe("ok");
179+
expect(questionItemIds).toHaveLength(1);
180+
expect(completedKinds.indexOf("commandExecution")).toBeGreaterThan(
181+
completedKinds.indexOf("asyncQuestion"),
182+
);
183+
expect(await fs.readFile(path.join(workspace, "async-question-marker.txt"), "utf8")).toBe(
184+
"AFTER_ASYNC_QUESTION\n",
185+
);
186+
expect(
187+
first.messagesSnapshot.filter(
188+
(message) => message.role === "assistant" && "openclawAsyncDelivery" in message,
189+
),
190+
).toEqual([
191+
expect.objectContaining({
192+
openclawAsyncDelivery: { itemId: questionItemIds[0], questions },
193+
}),
194+
]);
195+
expect(deliveredTexts).toHaveLength(1);
196+
expect(deliveredTexts[0]).toContain("Which output format?");
197+
expect(deliveredTexts[0]).toContain("Who is the audience?");
198+
const persisted = await readSessionTranscriptEvents(sessionTarget);
199+
expect(
200+
persisted.filter(
201+
(event) =>
202+
isJsonObject(event) &&
203+
isJsonObject(event.message) &&
204+
isJsonObject(event.message.openclawAsyncDelivery),
205+
),
206+
).toHaveLength(1);
207+
expect(serverRequestMethods).not.toContain("item/tool/requestUserInput");
208+
const firstBinding = bindingStore.read(sessionBindingIdentity(params));
209+
expect(firstBinding).toBeDefined();
210+
expect(firstBinding?.model === runtimeModelId).toBe(true);
211+
const firstThreadId = firstBinding?.threadId;
212+
expect(firstThreadId).toEqual(expect.any(String));
213+
214+
closeHost();
215+
closeHost = undefined;
216+
const followUp = {
217+
...params,
218+
runId: "async-questions-answer-run",
219+
prompt: [
220+
"> Which output format?",
221+
"",
222+
"Plain text",
223+
"",
224+
"> Who is the audience?",
225+
"",
226+
"release reviewers",
227+
"",
228+
"Use those answers to create async-question-answer.txt containing the chosen format, a vertical bar, then the audience, followed by a newline.",
229+
"Do not ask further questions. Then reply ANSWER_USED.",
230+
].join("\n"),
231+
};
232+
const answerHost = await createAgentHarnessHostCapabilitiesForTest({
233+
attempt: followUp,
234+
pluginId: "codex",
235+
});
236+
followUp.hostCapabilities = answerHost.capabilities;
237+
closeHost = answerHost.close;
238+
const answered = await runCodexAppServerAttempt(followUp, options);
239+
240+
expect(answered.terminal.kind).toBe("ok");
241+
expect(bindingStore.read(sessionBindingIdentity(followUp))?.threadId).toBe(firstThreadId);
242+
expect(await fs.readFile(path.join(workspace, "async-question-answer.txt"), "utf8")).toBe(
243+
"Plain text|release reviewers\n",
244+
);
245+
expect(serverRequestMethods).not.toContain("item/tool/requestUserInput");
246+
} finally {
247+
closeHost?.();
248+
await client.closeAndWait();
249+
}
250+
}, 480_000);
251+
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
2+
3+
export type CodexAsyncQuestion = {
4+
title: string;
5+
options?: string[];
6+
};
7+
8+
/** Keep unsupported question payloads on Codex's complete plain-text fallback. */
9+
export function readCodexAsyncQuestions(value: unknown): CodexAsyncQuestion[] | undefined {
10+
if (!Array.isArray(value) || value.length === 0 || value.length > 12) {
11+
return undefined;
12+
}
13+
const questions: CodexAsyncQuestion[] = [];
14+
for (const entry of value) {
15+
const question = asOptionalRecord(entry);
16+
if (!question || !isQuestionText(question.title, 4_096)) {
17+
return undefined;
18+
}
19+
const options = question.options;
20+
if (options === undefined || options === null) {
21+
questions.push({ title: question.title });
22+
continue;
23+
}
24+
if (
25+
!Array.isArray(options) ||
26+
options.length === 0 ||
27+
options.length > 4 ||
28+
!options.every((option): option is string => isQuestionText(option, 256))
29+
) {
30+
return undefined;
31+
}
32+
questions.push({ title: question.title, options: [...options] });
33+
}
34+
return questions;
35+
}
36+
37+
function isQuestionText(value: unknown, maxLength: number): value is string {
38+
return typeof value === "string" && value.length <= maxLength && value.trim().length > 0;
39+
}

‎extensions/codex/src/app-server/event-projector-assistant-message.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
type AgentHarnessAttemptParamsV2,
55
} from "openclaw/plugin-sdk/agent-harness-runtime";
66
import type { AssistantMessage, Usage } from "openclaw/plugin-sdk/llm";
7+
import type { CodexAsyncQuestion } from "./async-questions.js";
78
import type { CodexProviderRefusal } from "./event-projector-values.js";
89
import {
910
resolveCodexLocalRuntimeAttribution,
@@ -31,7 +32,7 @@ export type AssistantMessageOptions = {
3132
};
3233

3334
export type CodexAsyncAssistantMessage = AssistantMessage & {
34-
openclawAsyncDelivery: { itemId: string };
35+
openclawAsyncDelivery: { itemId: string; questions?: CodexAsyncQuestion[] };
3536
};
3637

3738
const ZERO_USAGE: Usage = {
@@ -142,10 +143,11 @@ export function createAssistantAsyncMessage(
142143
text: string,
143144
itemId: string,
144145
timestamp: number,
146+
questions?: CodexAsyncQuestion[],
145147
): CodexAsyncAssistantMessage {
146148
return {
147149
...createNonterminalAssistantMessage(params, [{ type: "text", text }], timestamp),
148-
openclawAsyncDelivery: { itemId },
150+
openclawAsyncDelivery: { itemId, ...(questions ? { questions } : {}) },
149151
};
150152
}
151153

0 commit comments

Comments
 (0)