Skip to content

Commit 2404d41

Browse files
fix(codex): preserve delegation when image generation is denied (#124598)
Forward exact audited tool denies into agent harnesses so Codex can disable native image generation without dropping delegation. Fail closed when managed policy forces image generation and rotate retained threads when effective native config changes. Co-authored-by: Marvinthebored <[email protected]>
1 parent 01a23bc commit 2404d41

13 files changed

Lines changed: 227 additions & 34 deletions

File tree

‎docs/plugins/sdk-agent-harness.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,13 @@ does not set this flag.
5656
Harnesses with an independently managed native surface can also declare
5757
`conversationToolPolicySafeDenyTools` using canonical OpenClaw tool names. Core
5858
preserves the native surface only when every expanded deny is a known core tool
59-
in that audited safe list. Finite allowlists, undeclared or unknown tool names,
60-
wildcards, and groups containing any undeclared name remain native-surface
61-
restrictions. Omit the list to retain the conservative behavior where every
62-
explicit restriction isolates the native surface. Because omissions fail
63-
closed, new tools cannot silently relax the policy boundary.
59+
in that audited safe list and passes the matching names in
60+
`params.pluginHarnessToolPolicySafeDeniedTools`. The harness must disable any
61+
native equivalents for those names. Finite allowlists, undeclared or unknown
62+
tool names, wildcards, and groups containing any undeclared name remain
63+
native-surface restrictions. Omit the list to retain the conservative behavior
64+
where every explicit restriction isolates the native surface. Because omissions
65+
fail closed, new tools cannot silently relax the policy boundary.
6466

6567
Omit the declaration when any native capability can bypass those layers.
6668
OpenClaw then visibly rejects explicitly restricted turns before invoking the

‎extensions/codex/harness.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ describe("Codex agent harness supports()", () => {
3535
});
3636

3737
it("keeps computer-control denies out of the native-surface exemption", () => {
38+
expect(harness.conversationToolPolicySafeDenyTools).toContain("image_generate");
3839
expect(harness.conversationToolPolicySafeDenyTools).not.toEqual(
3940
expect.arrayContaining(["browser", "computer", "mobile_ui", "nodes", "screen"]),
4041
);

‎extensions/codex/harness.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ import type { CodexSessionCatalogControlFactory } from "./src/session-catalog-ty
1717
const DEFAULT_CODEX_HARNESS_PROVIDER_IDS = new Set(["codex", "openai"]);
1818
const SHARED_CODEX_APP_SERVER_CLIENT_DISPOSER = Symbol.for("openclaw.codexAppServerClientDisposer");
1919
// Audited against @openai/codex 0.147.0 (rust-v0.147.0). These exact denies
20-
// target OpenClaw-owned capabilities with no Codex-native equivalent. Keep the
21-
// list positive and conservative: an omitted tool isolates the native surface.
20+
// either have no Codex-native equivalent or are enforced by the harness. Keep
21+
// the list positive and conservative: an omitted tool isolates the native surface.
2222
const CODEX_TOOL_POLICY_SAFE_DENY_NAMES = [
2323
"web_fetch",
2424
"x_search",
@@ -32,6 +32,7 @@ const CODEX_TOOL_POLICY_SAFE_DENY_NAMES = [
3232
"automations",
3333
"gateway",
3434
"skill_workshop",
35+
"image_generate",
3536
"music_generate",
3637
"video_generate",
3738
"tts",

‎extensions/codex/src/app-server/bounded-turn.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import {
4646
} from "./shared-client.js";
4747
import { buildCodexRuntimeThreadConfig } from "./thread-lifecycle.js";
4848
import {
49-
assertCodexRestrictedToolSurfaceHasNoManagedHooks,
49+
assertCodexManagedRequirementsDoNotOverrideToolPolicy,
5050
attestCodexRestrictedToolSurfaceMcpServersDisabled,
5151
buildCodexRingZeroThreadConfigPatch,
5252
readCodexInheritedMcpServerNames,
@@ -250,7 +250,11 @@ async function runBoundedCodexAppServerTurnInWorkspace(
250250
? await readCodexInheritedMcpServerNames(client, workspace.cwd, abortController.signal)
251251
: [];
252252
if (params.requireNoExternalCapabilities) {
253-
await assertCodexRestrictedToolSurfaceHasNoManagedHooks(client, abortController.signal);
253+
await assertCodexManagedRequirementsDoNotOverrideToolPolicy(
254+
client,
255+
{ restrictedToolSurface: true },
256+
abortController.signal,
257+
);
254258
}
255259
const threadConfig = buildCodexRuntimeThreadConfig(
256260
resolveBoundedThreadConfig(params, workspace, inheritedMcpServerNames),

‎extensions/codex/src/app-server/thread-lifecycle-preflight.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
import { createCodexThreadLifecycleTimingTracker } from "./thread-lifecycle-timing.js";
2525
import type { CodexStartOrResumeThreadParams } from "./thread-lifecycle-types.js";
2626
import {
27-
assertCodexRestrictedToolSurfaceHasNoManagedHooks,
27+
assertCodexManagedRequirementsDoNotOverrideToolPolicy,
2828
buildCodexRingZeroThreadConfigPatch,
2929
CODEX_RING_ZERO_BASE_INSTRUCTIONS,
3030
readCodexInheritedMcpServerNames,
@@ -107,6 +107,8 @@ export async function prepareCodexThreadLifecyclePreflight(params: CodexStartOrR
107107
ringZeroActive ||
108108
messageOnlySourceReply ||
109109
params.params.pluginHarnessToolPolicyRestricted === true;
110+
const imageGenerationDenied =
111+
params.params.pluginHarnessToolPolicySafeDeniedTools?.includes("image_generate") === true;
110112
if (restrictedToolSurface && params.nativeCodeModeEnabled !== false) {
111113
throw new Error("Codex restricted tool surfaces require native code mode to be disabled");
112114
}
@@ -115,9 +117,16 @@ export async function prepareCodexThreadLifecyclePreflight(params: CodexStartOrR
115117
readCodexInheritedMcpServerNames(params.client, params.cwd, params.signal),
116118
)
117119
: [];
118-
if (restrictedToolSurface) {
119-
await lifecycleTiming.measure("restricted-tool-surface-config-requirements-read", () =>
120-
assertCodexRestrictedToolSurfaceHasNoManagedHooks(params.client, params.signal),
120+
if (restrictedToolSurface || imageGenerationDenied) {
121+
await lifecycleTiming.measure("tool-policy-config-requirements-read", () =>
122+
assertCodexManagedRequirementsDoNotOverrideToolPolicy(
123+
params.client,
124+
{
125+
restrictedToolSurface,
126+
additionalDeniedFeatures: imageGenerationDenied ? ["image_generation"] : undefined,
127+
},
128+
params.signal,
129+
),
121130
);
122131
}
123132
const ringZeroConfigFingerprint = ringZeroActive

‎extensions/codex/src/app-server/thread-lifecycle.binding.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,66 @@ describe("Codex app-server thread lifecycle bindings", () => {
409409
});
410410
});
411411

412+
it("cold-resumes a warm thread when final config adds an image-generation deny", async () => {
413+
const sessionFile = path.join(tempDir, "warm-image-deny-session.jsonl");
414+
const workspaceDir = path.join(tempDir, "warm-image-deny-workspace");
415+
const params = createParams(sessionFile, workspaceDir);
416+
const request = vi.fn(async (method: string, _params?: unknown) => {
417+
if (method === "configRequirements/read") {
418+
return { requirements: null };
419+
}
420+
if (method === "thread/start" || method === "thread/resume") {
421+
return threadStartResult("thread-warm-image-deny");
422+
}
423+
if (method === "thread/unsubscribe") {
424+
return {};
425+
}
426+
throw new Error(`unexpected method: ${method}`);
427+
});
428+
const client = {
429+
getInstanceId: () => "client-warm-image-deny",
430+
request,
431+
addNotificationHandler: () => () => undefined,
432+
addRequestHandler: () => () => undefined,
433+
addCloseHandler: () => () => undefined,
434+
} as never;
435+
ensureCodexAppServerClientRuntime(client, { agentDir: workspaceDir });
436+
const common = {
437+
client,
438+
params,
439+
cwd: workspaceDir,
440+
dynamicTools: [],
441+
appServer: createThreadLifecycleAppServerOptions(),
442+
userMcpServersEnabled: false,
443+
};
444+
445+
const started = await startOrResumeThread(common);
446+
await expect(
447+
retainCodexAppServerLiveThread(
448+
client,
449+
started.threadId,
450+
undefined,
451+
started.liveThreadConfigFingerprint,
452+
),
453+
).resolves.toBe(true);
454+
params.pluginHarnessToolPolicySafeDeniedTools = ["image_generate"];
455+
const resumed = await startOrResumeThread(common);
456+
457+
expect(resumed).toMatchObject({
458+
threadId: "thread-warm-image-deny",
459+
lifecycle: { action: "resumed" },
460+
});
461+
expect(request.mock.calls.map(([method]) => method)).toEqual([
462+
"thread/start",
463+
"configRequirements/read",
464+
"thread/unsubscribe",
465+
"thread/resume",
466+
]);
467+
expect(request.mock.calls.find(([method]) => method === "thread/resume")?.[1]).toMatchObject({
468+
config: { "features.image_generation": false },
469+
});
470+
});
471+
412472
it("keeps a warm native session across sticky environment selection changes", async () => {
413473
const sessionFile = path.join(tempDir, "environment-session.jsonl");
414474
const workspaceDir = path.join(tempDir, "environment-workspace");
@@ -1711,6 +1771,34 @@ describe("Codex app-server thread lifecycle bindings", () => {
17111771
]);
17121772
});
17131773

1774+
it("fails closed when requirements pin denied image generation on", async () => {
1775+
const sessionFile = path.join(tempDir, "session.jsonl");
1776+
const workspaceDir = path.join(tempDir, "workspace");
1777+
const params = createParams(sessionFile, workspaceDir);
1778+
params.pluginHarnessToolPolicySafeDeniedTools = ["image_generate"];
1779+
const request = vi.fn(async (method: string) => {
1780+
if (method === "config/read") {
1781+
return { config: {}, layers: [] };
1782+
}
1783+
if (method === "configRequirements/read") {
1784+
return { requirements: { featureRequirements: { image_generation: true } } };
1785+
}
1786+
throw new Error(`unexpected method: ${method}`);
1787+
});
1788+
1789+
await expect(
1790+
startOrResumeThread({
1791+
client: { request } as never,
1792+
params,
1793+
cwd: workspaceDir,
1794+
dynamicTools: [],
1795+
appServer: createThreadLifecycleAppServerOptions(),
1796+
userMcpServersEnabled: false,
1797+
}),
1798+
).rejects.toThrow("cannot override required feature image_generation");
1799+
expect(request.mock.calls.map(([method]) => method)).toEqual(["configRequirements/read"]);
1800+
});
1801+
17141802
it.each([
17151803
"apps",
17161804
"artifact",

‎extensions/codex/src/app-server/thread-lifecycle.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,36 @@ describe("Codex delegation capability", () => {
237237
}
238238
});
239239

240+
it("disables only native image generation for an audited image_generate deny", () => {
241+
const params = createAttemptParams({ provider: "openai" });
242+
params.pluginHarnessToolPolicySafeDeniedTools = ["image_generate"];
243+
const appServer = createAppServerOptions() as never;
244+
const config = {
245+
"features.image_generation": true,
246+
"features.multi_agent": true,
247+
"features.multi_agent_v2": true,
248+
};
249+
const start = buildThreadStartParams(params, {
250+
appServer,
251+
cwd: "/repo",
252+
dynamicTools: [],
253+
config,
254+
});
255+
const resume = buildThreadResumeParams(params, {
256+
appServer,
257+
dynamicTools: [],
258+
threadId: "thread-1",
259+
config,
260+
});
261+
262+
for (const request of [start, resume]) {
263+
expect(request.config?.["features.image_generation"]).toBe(false);
264+
expect(request.config?.["features.multi_agent"]).toBe(true);
265+
expect(request.config?.["features.multi_agent_v2"]).toBe(true);
266+
expect(request.config?.["agents.enabled"]).toBeUndefined();
267+
}
268+
});
269+
240270
it("keeps message-only completion threads and prompts free of native delegation", () => {
241271
const params = createAttemptParams({ provider: "openai" });
242272
params.toolsAllow = ["message"];

‎extensions/codex/src/app-server/thread-requests.ts‎

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,9 @@ export function buildCodexRuntimeThreadConfigForRun(
426426
mergeCodexThreadConfigs(
427427
baseConfig,
428428
options.appServer?.networkProxy?.configPatch,
429+
params.pluginHarnessToolPolicySafeDeniedTools?.includes("image_generate")
430+
? { "features.image_generation": false }
431+
: undefined,
429432
shouldDisableCodexToolSearchForModel(params.modelId)
430433
? CODEX_TOOL_SEARCH_UNSUPPORTED_THREAD_CONFIG
431434
: undefined,
@@ -524,8 +527,12 @@ export async function readCodexInheritedMcpServerNames(
524527
return Object.keys(configuredServers).toSorted();
525528
}
526529

527-
export async function assertCodexRestrictedToolSurfaceHasNoManagedHooks(
530+
export async function assertCodexManagedRequirementsDoNotOverrideToolPolicy(
528531
client: Pick<CodexAppServerClient, "request">,
532+
options: {
533+
restrictedToolSurface: boolean;
534+
additionalDeniedFeatures?: readonly string[];
535+
},
529536
signal?: AbortSignal,
530537
): Promise<void> {
531538
const response: CodexConfigRequirementsReadResponse = await client.request(
@@ -542,18 +549,21 @@ export async function assertCodexRestrictedToolSurfaceHasNoManagedHooks(
542549
if (!isJsonObject(response.requirements)) {
543550
throw new Error("Codex configRequirements/read returned invalid requirements");
544551
}
545-
for (const key of ["hooks", "managedHooks", "managed_hooks"] as const) {
546-
const hooks = response.requirements[key];
547-
if (hooks === undefined || hooks === null) {
548-
continue;
549-
}
550-
if (!isJsonObject(hooks)) {
551-
throw new Error("Codex configRequirements/read returned invalid managed hooks");
552-
}
553-
if (hasNonEmptyJsonValue(hooks)) {
554-
throw new Error("Codex restricted tool surface cannot override managed hooks");
552+
if (options.restrictedToolSurface) {
553+
for (const key of ["hooks", "managedHooks", "managed_hooks"] as const) {
554+
const hooks = response.requirements[key];
555+
if (hooks === undefined || hooks === null) {
556+
continue;
557+
}
558+
if (!isJsonObject(hooks)) {
559+
throw new Error("Codex configRequirements/read returned invalid managed hooks");
560+
}
561+
if (hasNonEmptyJsonValue(hooks)) {
562+
throw new Error("Codex restricted tool surface cannot override managed hooks");
563+
}
555564
}
556565
}
566+
const additionalDeniedFeatures = new Set(options.additionalDeniedFeatures);
557567
for (const key of ["featureRequirements", "feature_requirements"] as const) {
558568
const requirements = response.requirements[key];
559569
if (requirements === undefined || requirements === null) {
@@ -567,10 +577,12 @@ export async function assertCodexRestrictedToolSurfaceHasNoManagedHooks(
567577
throw new Error("Codex configRequirements/read returned invalid feature requirements");
568578
}
569579
const canonicalFeature = CODEX_RING_ZERO_RESTRICTED_FEATURE_ALIASES.get(feature) ?? feature;
570-
if (enabled && CODEX_RING_ZERO_RESTRICTED_FEATURES.has(canonicalFeature)) {
571-
throw new Error(
572-
`Codex restricted tool surface cannot override required feature ${feature}`,
573-
);
580+
const deniedByToolPolicy =
581+
(options.restrictedToolSurface &&
582+
CODEX_RING_ZERO_RESTRICTED_FEATURES.has(canonicalFeature)) ||
583+
additionalDeniedFeatures.has(canonicalFeature);
584+
if (enabled && deniedByToolPolicy) {
585+
throw new Error(`Codex tool policy cannot override required feature ${feature}`);
574586
}
575587
}
576588
}

‎src/agents/embedded-agent-runner/run/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ export type EmbeddedRunAttemptParams = EmbeddedRunAttemptBase & {
114114
operation?: EmbeddedRunAttemptOperation;
115115
/** Core-prepared fact that explicit requester/config policy restricts plugin-native tools. */
116116
pluginHarnessToolPolicyRestricted?: boolean;
117+
/** Audited exact denies that the plugin harness must enforce against native equivalents. */
118+
pluginHarnessToolPolicySafeDeniedTools?: readonly string[];
117119
preparedModelRuntime?: PreparedModelRuntimeSnapshot;
118120
/** Active file-backed artifact target resolved by the run/session target seam. */
119121
sessionFile: string;

‎src/agents/harness/selection.test.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1303,9 +1303,15 @@ describe("runAgentHarnessAttempt", () => {
13031303
});
13041304

13051305
it("isolates native tools unless every exact deny is explicitly safe", async () => {
1306-
const received: boolean[] = [];
1306+
const received: Array<{
1307+
restricted: boolean;
1308+
safeDeniedTools?: readonly string[];
1309+
}> = [];
13071310
const runAttempt = vi.fn<AgentHarness["runAttempt"]>(async (attempt) => {
1308-
received.push(attempt.pluginHarnessToolPolicyRestricted === true);
1311+
received.push({
1312+
restricted: attempt.pluginHarnessToolPolicyRestricted === true,
1313+
safeDeniedTools: attempt.pluginHarnessToolPolicySafeDeniedTools,
1314+
});
13091315
return createAttemptResult("codex");
13101316
});
13111317
const harness: AgentHarness = {
@@ -1315,6 +1321,7 @@ describe("runAgentHarnessAttempt", () => {
13151321
conversationToolPolicySafeDenyTools: [
13161322
"tts",
13171323
"music_generate",
1324+
"image_generate",
13181325
"browser",
13191326
"unknown_native_tool",
13201327
],
@@ -1325,6 +1332,7 @@ describe("runAgentHarnessAttempt", () => {
13251332
registerAgentHarness(harness, { ownerPluginId: "codex" });
13261333

13271334
const policies = [
1335+
{ deny: ["image_generate"] },
13281336
{ deny: ["tts", "music_generate"] },
13291337
{ deny: ["browser"] },
13301338
{ deny: ["exec"] },
@@ -1341,7 +1349,18 @@ describe("runAgentHarnessAttempt", () => {
13411349
});
13421350
}
13431351

1344-
expect(received).toEqual([false, false, true, true, true, true, true, true]);
1352+
expect(received.map((attempt) => attempt.restricted)).toEqual([
1353+
false,
1354+
false,
1355+
false,
1356+
true,
1357+
true,
1358+
true,
1359+
true,
1360+
true,
1361+
true,
1362+
]);
1363+
expect(received[0]?.safeDeniedTools).toEqual(["image_generate"]);
13451364
});
13461365

13471366
it("marks only explicit restrictive policy layers for plugin harness isolation", async () => {

0 commit comments

Comments
 (0)