Skip to content

Commit a19132e

Browse files
authored
fix(codex): prevent approval promotion from blocking unattended runs (#116117)
* fix(codex): honor hook approval ownership * fix(codex): keep permission grants human-gated
1 parent d8074d7 commit a19132e

16 files changed

Lines changed: 443 additions & 21 deletions

‎extensions/codex/src/app-server/approval-bridge.test.ts‎

Lines changed: 98 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,86 @@ describe("Codex app-server approval bridge", () => {
197197
});
198198
});
199199

200+
it.each([
201+
["item/commandExecution/requestApproval", "cmd-policy-allow", { command: "gh run view 1" }],
202+
[
203+
"item/fileChange/requestApproval",
204+
"patch-policy-allow",
205+
{ reason: "write memory/2026-07-29.md" },
206+
],
207+
] as const)(
208+
"auto-accepts %s when the promoted OpenClaw tool policy allows it",
209+
async (method, itemId, requestFields) => {
210+
const params = createParams();
211+
212+
const result = await handleCodexAppServerApprovalRequest({
213+
method,
214+
requestParams: {
215+
threadId: "thread-1",
216+
turnId: "turn-1",
217+
itemId,
218+
...requestFields,
219+
},
220+
paramsForRun: params,
221+
threadId: "thread-1",
222+
turnId: "turn-1",
223+
autoApproveOpenClawToolPolicy: true,
224+
});
225+
226+
expect(result).toEqual({ decision: "accept" });
227+
expect(mockCallGatewayTool).not.toHaveBeenCalled();
228+
findApprovalEvent(params, {
229+
status: "approved",
230+
message: "Codex app-server approval accepted by OpenClaw tool policy.",
231+
});
232+
},
233+
);
234+
235+
it.each([
236+
["promoted tool policy", { autoApproveOpenClawToolPolicy: true }],
237+
["full-auto runtime policy", { autoApprove: true }],
238+
] as const)("keeps permission grants on the human path under %s", async (_label, policy) => {
239+
const params = createParams();
240+
mockCallGatewayTool
241+
.mockResolvedValueOnce({ id: "plugin:permission-policy-allow", status: "accepted" })
242+
.mockResolvedValueOnce({
243+
id: "plugin:permission-policy-allow",
244+
decision: "allow-once",
245+
});
246+
247+
const result = await handleCodexAppServerApprovalRequest({
248+
method: "item/permissions/requestApproval",
249+
requestParams: {
250+
threadId: "thread-1",
251+
turnId: "turn-1",
252+
itemId: "permission-policy-allow",
253+
permissions: {
254+
network: { enabled: true },
255+
fileSystem: { write: ["/workspace"] },
256+
},
257+
},
258+
paramsForRun: params,
259+
threadId: "thread-1",
260+
turnId: "turn-1",
261+
...policy,
262+
});
263+
264+
expect(result).toEqual({
265+
permissions: {
266+
network: { enabled: true },
267+
fileSystem: { write: ["/workspace"] },
268+
},
269+
scope: "turn",
270+
});
271+
expect(mockRunBeforeToolCallHook).toHaveBeenCalledWith(
272+
expect.objectContaining({ toolName: "codex_permission_approval" }),
273+
);
274+
expect(mockCallGatewayTool.mock.calls.map(([method]) => method)).toEqual([
275+
"plugin.approval.request",
276+
"plugin.approval.waitDecision",
277+
]);
278+
});
279+
200280
it("routes command approvals through plugin approvals and accepts allowed commands", async () => {
201281
const params = createParams();
202282
mockCallGatewayTool
@@ -248,6 +328,11 @@ describe("Codex app-server approval bridge", () => {
248328
agentId: "main",
249329
sessionKey: "agent:main:session-1",
250330
channelId: "chat-1",
331+
workspaceDir: undefined,
332+
turnSourceChannel: "telegram",
333+
turnSourceTo: "chat-1",
334+
turnSourceAccountId: "default",
335+
turnSourceThreadId: "thread-ts",
251336
},
252337
});
253338
findApprovalEvent(params, { status: "pending", approvalId: "plugin:approval-1" });
@@ -2425,8 +2510,11 @@ describe("Codex app-server approval bridge", () => {
24252510
});
24262511
});
24272512

2428-
it("fails closed for unsupported native approval methods without requesting plugin approval", async () => {
2513+
it("routes unknown approval methods to the human path and still fails closed", async () => {
24292514
const params = createParams();
2515+
mockCallGatewayTool
2516+
.mockResolvedValueOnce({ id: "plugin:future-approval", status: "accepted" })
2517+
.mockResolvedValueOnce({ id: "plugin:future-approval", decision: "deny" });
24302518

24312519
const result = await handleCodexAppServerApprovalRequest({
24322520
method: "future/requestApproval",
@@ -2444,8 +2532,15 @@ describe("Codex app-server approval bridge", () => {
24442532
decision: "decline",
24452533
reason: "OpenClaw codex app-server bridge does not grant native approvals yet.",
24462534
});
2447-
expect(mockCallGatewayTool).not.toHaveBeenCalled();
2448-
expect(params.onAgentEvent).not.toHaveBeenCalled();
2535+
expect(mockRunBeforeToolCallHook).not.toHaveBeenCalled();
2536+
expect(mockCallGatewayTool.mock.calls.map(([method]) => method)).toEqual([
2537+
"plugin.approval.request",
2538+
"plugin.approval.waitDecision",
2539+
]);
2540+
findApprovalEvent(params, {
2541+
status: "denied",
2542+
approvalId: "plugin:future-approval",
2543+
});
24492544
});
24502545
it("labels permission approvals explicitly with permission detail", async () => {
24512546
const params = createParams();

‎extensions/codex/src/app-server/approval-bridge.ts‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ const PERMISSION_VALUE_MAX_LENGTH = 48;
3434
const COMMAND_PREVIEW_WITH_DETAILS_MAX_LENGTH = 80;
3535
const APPROVAL_PREVIEW_SCAN_MAX_LENGTH = 4096;
3636
const APPROVAL_PREVIEW_OMITTED = "[preview truncated or unsafe content omitted]";
37+
// Automatic approval is limited to concrete calls. A before_tool_call allow
38+
// covers the evaluated call, not future scope; new or grant-shaped methods stay human-gated.
39+
const CONCRETE_TOOL_AUTO_APPROVAL_METHODS = new Set([
40+
"item/commandExecution/requestApproval",
41+
"item/fileChange/requestApproval",
42+
]);
3743
const ANSI_OSC_SEQUENCE_RE = new RegExp(
3844
String.raw`(?:\u001b]|\u009d)[^\u001b\u009c\u0007]*(?:\u0007|\u001b\\|\u009c)`,
3945
"g",
@@ -76,6 +82,7 @@ export async function handleCodexAppServerApprovalRequest(params: {
7682
"allowedEvents" | "generation" | "relayId"
7783
>;
7884
autoApprove?: boolean;
85+
autoApproveOpenClawToolPolicy?: boolean;
7986
signal?: AbortSignal;
8087
onNativeToolFailureDisposition?: (
8188
itemId: string,
@@ -86,10 +93,6 @@ export async function handleCodexAppServerApprovalRequest(params: {
8693
if (!matchesCurrentTurn(requestParams, params.threadId, params.turnId)) {
8794
return undefined;
8895
}
89-
if (!isSupportedAppServerApprovalMethod(params.method)) {
90-
return unsupportedApprovalResponse();
91-
}
92-
9396
const context = buildApprovalContext({
9497
method: params.method,
9598
requestParams,
@@ -134,7 +137,24 @@ export async function handleCodexAppServerApprovalRequest(params: {
134137
});
135138
return buildApprovalResponse(params.method, context.requestParams, policyOutcome.outcome);
136139
}
137-
if (params.autoApprove === true) {
140+
const canAutoApproveConcreteToolCall = CONCRETE_TOOL_AUTO_APPROVAL_METHODS.has(params.method);
141+
if (
142+
canAutoApproveConcreteToolCall &&
143+
params.autoApproveOpenClawToolPolicy === true &&
144+
policyOutcome?.outcome === "allowed"
145+
) {
146+
emitApprovalEvent(params.paramsForRun, {
147+
phase: "resolved",
148+
kind: context.kind,
149+
status: "approved",
150+
title: context.title,
151+
...context.eventDetails,
152+
...approvalEventScope(params.method, "approved-once"),
153+
message: "Codex app-server approval accepted by OpenClaw tool policy.",
154+
});
155+
return buildApprovalResponse(params.method, context.requestParams, "approved-once");
156+
}
157+
if (canAutoApproveConcreteToolCall && params.autoApprove === true) {
138158
emitApprovalEvent(params.paramsForRun, {
139159
phase: "resolved",
140160
kind: context.kind,
@@ -396,7 +416,7 @@ type ApprovalPolicyOutcome =
396416
failureDisposition?: Exclude<BeforeToolCallFailureDisposition, "blocked">;
397417
}
398418
| { outcome: "approved-once" | "approved-session" }
399-
| { outcome: "no-decision" };
419+
| { outcome: "allowed" };
400420

401421
async function runOpenClawToolPolicyForApprovalRequest(params: {
402422
method: string;
@@ -441,7 +461,7 @@ async function runOpenClawToolPolicyForApprovalRequest(params: {
441461
return { outcome: nativeRelayOutcome.outcome };
442462
}
443463
if (nativeRelayOutcome?.handled) {
444-
return { outcome: "no-decision" };
464+
return { outcome: "allowed" };
445465
}
446466
const hookChannelId = buildAgentHookContextChannelFields({
447467
sessionKey: params.paramsForRun.sessionKey,
@@ -465,6 +485,13 @@ async function runOpenClawToolPolicyForApprovalRequest(params: {
465485
...(params.paramsForRun.sessionId ? { sessionId: params.paramsForRun.sessionId } : {}),
466486
...(params.paramsForRun.runId ? { runId: params.paramsForRun.runId } : {}),
467487
...(hookChannelId ? { channelId: hookChannelId } : {}),
488+
trigger: params.paramsForRun.trigger,
489+
approvalReviewerDeviceId: params.paramsForRun.approvalReviewerDeviceId,
490+
turnSourceChannel: params.paramsForRun.messageChannel ?? params.paramsForRun.messageProvider,
491+
turnSourceTo:
492+
params.paramsForRun.currentMessagingTarget ?? params.paramsForRun.currentChannelId,
493+
turnSourceAccountId: params.paramsForRun.agentAccountId,
494+
turnSourceThreadId: params.paramsForRun.currentThreadTs,
468495
},
469496
});
470497
if (outcome.blocked) {
@@ -490,7 +517,7 @@ async function runOpenClawToolPolicyForApprovalRequest(params: {
490517
outcome: "approved-once",
491518
};
492519
}
493-
return undefined;
520+
return { outcome: "allowed" };
494521
}
495522

496523
async function runNativeRelayToolPolicyForApprovalRequest(params: {
@@ -1236,14 +1263,6 @@ function approvalKindForMethod(method: string): AgentApprovalEventData["kind"] {
12361263
return "unknown";
12371264
}
12381265

1239-
function isSupportedAppServerApprovalMethod(method: string): boolean {
1240-
return (
1241-
method === "item/commandExecution/requestApproval" ||
1242-
method === "item/fileChange/requestApproval" ||
1243-
method === "item/permissions/requestApproval"
1244-
);
1245-
}
1246-
12471266
function emitApprovalEvent(params: EmbeddedRunAttemptParams, data: AgentApprovalEventData): void {
12481267
void params.onAgentEvent?.({
12491268
stream: "approval",

‎extensions/codex/src/app-server/native-hook-relay.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ export function createCodexNativeHookRelay(params: {
144144
runId: string;
145145
channelId?: string;
146146
requester?: NonNullable<PluginHookToolContext["requester"]>;
147+
approvalContext?: Parameters<typeof registerNativeHookRelay>[0]["approvalContext"];
147148
attemptTimeoutMs: number;
148149
startupTimeoutMs: number;
149150
turnStartTimeoutMs: number;
@@ -172,6 +173,7 @@ export function createCodexNativeHookRelay(params: {
172173
runId: params.runId,
173174
...(params.channelId ? { channelId: params.channelId } : {}),
174175
...(params.requester ? { requester: params.requester } : {}),
176+
...(params.approvalContext ? { approvalContext: params.approvalContext } : {}),
175177
allowedEvents: params.events,
176178
preToolUseLoopDetection: params.loopDetectionPreToolUseRelay,
177179
ttlMs: resolveCodexNativeHookRelayTtlMs({

‎extensions/codex/src/app-server/run-attempt-connection.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,5 +122,28 @@ describe("prepareCodexAttemptConnection", () => {
122122
expect(readApprovalRequirements).toHaveBeenCalledOnce();
123123
expect(readApprovalRequirements).toHaveBeenCalledWith("untrusted");
124124
expect(connection.appServer.approvalPolicy).toBe("untrusted");
125+
expect(connection.approvalPolicyPromotedForOpenClawToolPolicy).toBe(true);
126+
});
127+
128+
it("does not give OpenClaw ownership of an explicit operator approval policy", async () => {
129+
initializeGlobalHookRunner(
130+
createMockPluginRegistry([{ hookName: "before_tool_call", handler: vi.fn() }]),
131+
);
132+
const sessionFile = path.join(tempDir, "explicit-approval-policy.jsonl");
133+
const workspaceDir = path.join(tempDir, "workspace-explicit-approval-policy");
134+
const params = createParams(sessionFile, workspaceDir);
135+
params.agentDir = path.join(tempDir, "agent");
136+
registerCodexTestSessionIdentity(sessionFile, params.sessionId, params.sessionKey);
137+
138+
const connection = await prepareCodexAttemptConnection({
139+
params,
140+
options: {
141+
bindingStore: testCodexAppServerBindingStore,
142+
pluginConfig: { appServer: { approvalPolicy: "untrusted" } },
143+
},
144+
});
145+
146+
expect(connection.appServer.approvalPolicy).toBe("untrusted");
147+
expect(connection.approvalPolicyPromotedForOpenClawToolPolicy).toBe(false);
125148
});
126149
});

‎extensions/codex/src/app-server/run-attempt-connection.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,9 @@ export async function prepareCodexAttemptConnection({ params, options }: CodexRu
310310
env: process.env,
311311
agentDir,
312312
});
313-
if (configuredAppServer.approvalPolicy === "never" && appServer.approvalPolicy === "untrusted") {
313+
let approvalPolicyPromotedForOpenClawToolPolicy =
314+
configuredAppServer.approvalPolicy === "never" && appServer.approvalPolicy === "untrusted";
315+
if (approvalPolicyPromotedForOpenClawToolPolicy) {
314316
embeddedAgentLog.info("codex app-server approval policy promoted for OpenClaw tool policy", {
315317
from: "never",
316318
to: "untrusted",
@@ -387,6 +389,8 @@ export async function prepareCodexAttemptConnection({ params, options }: CodexRu
387389
env: process.env,
388390
agentDir,
389391
});
392+
approvalPolicyPromotedForOpenClawToolPolicy =
393+
configuredAppServer.approvalPolicy === "never" && appServer.approvalPolicy === "untrusted";
390394
}
391395
const nativeHookRelayEvents = resolveCodexNativeHookRelayEvents({
392396
configuredEvents: options.nativeHookRelay?.events,
@@ -444,6 +448,7 @@ export async function prepareCodexAttemptConnection({ params, options }: CodexRu
444448
effectiveWorkspace,
445449
effectiveCwd,
446450
appServer,
451+
approvalPolicyPromotedForOpenClawToolPolicy,
447452
nativeHookRelayEvents,
448453
runAbortController,
449454
terminalState,

‎extensions/codex/src/app-server/run-attempt-resources.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,14 @@ export function prepareCodexAttemptResources(prompt: CodexAttemptPrompt) {
211211
runId: params.runId,
212212
channelId: hookChannelId,
213213
...(hasRequester ? { requester } : {}),
214+
approvalContext: {
215+
trigger: params.trigger,
216+
approvalReviewerDeviceId: params.approvalReviewerDeviceId,
217+
turnSourceChannel: requesterChannel,
218+
turnSourceTo: params.currentMessagingTarget ?? params.currentChannelId,
219+
turnSourceAccountId: params.agentAccountId,
220+
turnSourceThreadId: params.currentThreadTs,
221+
},
214222
attemptTimeoutMs: params.timeoutMs,
215223
startupTimeoutMs,
216224
turnStartTimeoutMs: params.timeoutMs,

‎extensions/codex/src/app-server/run-attempt-server-requests.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,14 @@ export function createCodexAttemptServerRequestController(
4242
const { context } = prompt;
4343
const { runtime, attemptTools } = context;
4444
const { connection } = runtime;
45-
const { params, computerUseConfig, runAbortController, appServer, sessionAgentId } = connection;
45+
const {
46+
params,
47+
computerUseConfig,
48+
runAbortController,
49+
appServer,
50+
approvalPolicyPromotedForOpenClawToolPolicy,
51+
sessionAgentId,
52+
} = connection;
4653
const {
4754
toolBridge,
4855
toolOutcomeOrdinals,
@@ -125,6 +132,7 @@ export function createCodexAttemptServerRequestController(
125132
turnId,
126133
nativeHookRelay: resourceState.nativeHookRelay,
127134
autoApprove: shouldAutoApproveCodexAppServerApprovals(appServer),
135+
autoApproveOpenClawToolPolicy: approvalPolicyPromotedForOpenClawToolPolicy,
128136
signal,
129137
onNativeToolFailureDisposition: (itemId, disposition) =>
130138
projector?.recordNativeToolApprovalFailure(itemId, disposition),

‎extensions/codex/src/app-server/run-attempt-tools.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ export function handleApprovalRequest(params: {
8888
turnId: string;
8989
nativeHookRelay?: NativeHookRelayRegistrationHandle;
9090
autoApprove?: boolean;
91+
autoApproveOpenClawToolPolicy?: boolean;
9192
signal?: AbortSignal;
9293
onNativeToolFailureDisposition?: Parameters<
9394
typeof handleCodexAppServerApprovalRequest
@@ -101,6 +102,7 @@ export function handleApprovalRequest(params: {
101102
turnId: params.turnId,
102103
nativeHookRelay: params.nativeHookRelay,
103104
autoApprove: params.autoApprove,
105+
autoApproveOpenClawToolPolicy: params.autoApproveOpenClawToolPolicy,
104106
signal: params.signal,
105107
onNativeToolFailureDisposition: params.onNativeToolFailureDisposition,
106108
});

0 commit comments

Comments
 (0)