Skip to content

Commit 6fc1c2d

Browse files
authored
refactor(agents): reduce per-turn policy and tool preparation (#134246)
* perf(agents): reduce repeated turn preparation * test(agents): keep timeout proof independent of auth discovery * test(parsers): measure prefix work without wall-clock limits
1 parent b75d04d commit 6fc1c2d

20 files changed

Lines changed: 434 additions & 400 deletions

‎extensions/codex/src/app-server/dynamic-tool-build.test.ts‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
} from "./dynamic-tool-profile.js";
3737
import { createCodexDynamicToolBridge } from "./dynamic-tools.js";
3838
import { createCodexTestHostCapabilities } from "./host-capability.test-support.js";
39+
import * as nativeExecutionPolicy from "./native-execution-policy.js";
3940
import { flattenCodexDynamicToolFunctions } from "./protocol.js";
4041
import { createCodexTestModel } from "./test-support.js";
4142

@@ -1101,6 +1102,7 @@ describe("Codex app-server dynamic tool build", () => {
11011102
expect(tools.map((tool) => tool.name)).toEqual(["message"]);
11021103
expect(persistentWebSearchAllowed).toBe(true);
11031104
expect(webSearchAllowed).toBe(false);
1105+
expect(hoisted.resolveWebSearchToolPolicy).not.toHaveBeenCalled();
11041106
});
11051107

11061108
it("keeps persistent search denied when runtime toolsAllow also excludes it", async () => {
@@ -1191,7 +1193,10 @@ describe("Codex app-server dynamic tool build", () => {
11911193
return [createRuntimeDynamicTool("message")];
11921194
});
11931195

1194-
await buildDynamicToolsForTest(params, workspaceDir);
1196+
const onPersistentWebSearchPolicyResolved = vi.fn();
1197+
await buildDynamicToolsForTest(params, workspaceDir, {
1198+
onPersistentWebSearchPolicyResolved,
1199+
});
11951200

11961201
expect(receivedOptions).toMatchObject({
11971202
inputProvenance: params.inputProvenance,
@@ -1205,6 +1210,7 @@ describe("Codex app-server dynamic tool build", () => {
12051210
scheduledToolPolicy: params.scheduledToolPolicy,
12061211
}),
12071212
);
1213+
expect(onPersistentWebSearchPolicyResolved).toHaveBeenCalledWith(false);
12081214
});
12091215

12101216
it("keeps persistent search denied when global and sender policy both deny it", async () => {
@@ -1784,11 +1790,20 @@ describe("Codex app-server dynamic tool build", () => {
17841790
params.disableTools = false;
17851791
params.runtimePlan = createCodexRuntimePlanFixture();
17861792
await bindProductionCodexHostCapabilities(params);
1793+
const resolveExecutionPolicy = vi.spyOn(
1794+
nativeExecutionPolicy,
1795+
"resolveCodexNativeExecutionPolicy",
1796+
);
17871797

17881798
const tools = await buildDynamicToolsForTest(params, workspaceDir, {
1799+
sandbox: null,
17891800
nativeToolSurfaceEnabled: true,
17901801
});
17911802

1803+
expect(resolveExecutionPolicy).toHaveBeenCalledOnce();
1804+
expect(resolveExecutionPolicy).toHaveBeenCalledWith(
1805+
expect.objectContaining({ sandboxAvailable: false }),
1806+
);
17921807
expect(shellTestToolNames(tools)).toEqual([
17931808
"message",
17941809
"gateway_exec",
@@ -1934,6 +1949,10 @@ describe("Codex app-server dynamic tool build", () => {
19341949
const params = createParams(sessionFile, workspaceDir);
19351950
params.disableTools = false;
19361951
params.runtimePlan = createCodexRuntimePlanFixture();
1952+
const resolveExecutionPolicy = vi.spyOn(
1953+
nativeExecutionPolicy,
1954+
"resolveCodexNativeExecutionPolicy",
1955+
);
19371956

19381957
const tools = await buildDynamicToolsForTest(params, workspaceDir, {
19391958
sandbox: {
@@ -1944,6 +1963,10 @@ describe("Codex app-server dynamic tool build", () => {
19441963
nativeToolSurfaceEnabled: false,
19451964
});
19461965

1966+
expect(resolveExecutionPolicy).toHaveBeenCalledOnce();
1967+
expect(resolveExecutionPolicy).toHaveBeenCalledWith(
1968+
expect.objectContaining({ sandboxAvailable: true }),
1969+
);
19471970
expect(tools.map((tool) => tool.name)).toEqual(["message", "sandbox_exec", "sandbox_process"]);
19481971
expect(tools.find((tool) => tool.name === "sandbox_exec")?.description).toContain(
19491972
"Docker container-path bind layout",
@@ -2327,6 +2350,7 @@ describe("Codex app-server dynamic tool build", () => {
23272350
messageTool.description,
23282351
heartbeatTool.description,
23292352
]);
2353+
expect(hoisted.resolveWebSearchToolPolicy).not.toHaveBeenCalled();
23302354
});
23312355

23322356
it("passes runtime config into Codex exec dynamic tool construction", async () => {
@@ -2525,21 +2549,31 @@ describe("Codex app-server dynamic tool build", () => {
25252549
expect(tools.map((tool) => tool.name)).toEqual(["sessions_spawn"]);
25262550
});
25272551

2528-
it("disables Codex native tool surfaces for restricted runtime allowlists", () => {
2552+
it.each([
2553+
{ label: "unresolved", sandbox: undefined, sandboxAvailable: undefined },
2554+
{ label: "resolved absent", sandbox: null, sandboxAvailable: false },
2555+
])("disables native tools for restricted allowlists with $label sandbox", (testCase) => {
25292556
const workspaceDir = path.join(tempDir, "workspace");
25302557
const params = createParams(path.join(tempDir, "session.jsonl"), workspaceDir);
25312558
params.disableTools = false;
2559+
const resolveExecutionPolicy = vi.spyOn(
2560+
nativeExecutionPolicy,
2561+
"resolveCodexNativeExecutionPolicy",
2562+
);
25322563

2533-
expect(shouldEnableCodexAppServerNativeToolSurface(params)).toBe(true);
2564+
expect(shouldEnableCodexAppServerNativeToolSurface(params, testCase.sandbox)).toBe(true);
2565+
expect(resolveExecutionPolicy).toHaveBeenCalledWith(
2566+
expect.objectContaining({ sandboxAvailable: testCase.sandboxAvailable }),
2567+
);
25342568

25352569
params.toolsAllow = ["*"];
2536-
expect(shouldEnableCodexAppServerNativeToolSurface(params)).toBe(true);
2570+
expect(shouldEnableCodexAppServerNativeToolSurface(params, testCase.sandbox)).toBe(true);
25372571

25382572
params.toolsAllow = [];
2539-
expect(shouldEnableCodexAppServerNativeToolSurface(params)).toBe(false);
2573+
expect(shouldEnableCodexAppServerNativeToolSurface(params, testCase.sandbox)).toBe(false);
25402574

25412575
params.toolsAllow = ["message"];
2542-
expect(shouldEnableCodexAppServerNativeToolSurface(params)).toBe(false);
2576+
expect(shouldEnableCodexAppServerNativeToolSurface(params, testCase.sandbox)).toBe(false);
25432577
});
25442578

25452579
it("disables Codex native tool surfaces when all tools are disabled", () => {

‎extensions/codex/src/app-server/dynamic-tool-build.ts‎

Lines changed: 56 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -270,11 +270,11 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
270270
const modelHasVision = params.model.input?.includes("image") ?? false;
271271
const agentDir = params.agentDir ?? resolveAgentDir(params.config ?? {}, input.sessionAgentId);
272272
const injectedOpenClawCodingToolsFactory = dynamicToolBuildState.openClawCodingToolsFactory;
273-
let agentHarnessModule: typeof import("openclaw/plugin-sdk/agent-harness") | undefined;
274-
const loadAgentHarnessModule = async () =>
275-
(agentHarnessModule ??= await import("openclaw/plugin-sdk/agent-harness"));
276-
toolBuildStages.mark("load-agent-harness-tools");
277-
const nativeExecutionPolicy = resolveCodexNativeExecutionPolicyForDynamicTools(input);
273+
const nativeExecutionPolicy = resolveCodexNativeExecutionPolicyForRun(params, {
274+
agentId: input.policyAgentId,
275+
runtimeSessionKey: input.sandboxSessionKey,
276+
sandbox: input.sandbox,
277+
});
278278
const webSearchPlan = resolveCodexWebSearchPlan({
279279
config: params.config,
280280
disableTools: params.disableTools,
@@ -455,6 +455,7 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
455455
: profileFilteredTools,
456456
readableAllTools,
457457
input,
458+
nativeExecutionPolicy,
458459
),
459460
readableAllTools,
460461
input,
@@ -476,42 +477,42 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
476477
!(input.pluginConfig.codexDynamicToolsExclude ?? []).some(
477478
(name) => normalizeCodexDynamicToolName(name) === "web_search",
478479
);
479-
// An injected tool factory can prove that no managed or native search surface exists.
480-
// Avoid loading the heavyweight default factory graph when no search policy can affect output.
481-
const webSearchPolicy =
482-
webSearchPresent || persistentCodexWebSearchSurface
483-
? (await loadAgentHarnessModule()).resolveWebSearchToolPolicy({
484-
config: params.config,
485-
modelProvider: params.model.provider,
486-
modelId: params.modelId,
487-
agentId: input.policyAgentId,
488-
sessionKey: input.sandboxSessionKey,
489-
sandboxToolPolicy: input.sandbox?.tools,
490-
messageProvider: resolveCodexMessageToolProvider(params),
491-
agentAccountId: params.agentAccountId,
492-
groupId: params.groupId,
493-
groupChannel: params.groupChannel,
494-
groupSpace: params.groupSpace,
495-
spawnedBy: params.spawnedBy,
496-
senderId: params.senderId,
497-
senderName: params.senderName,
498-
senderUsername: params.senderUsername,
499-
senderE164: params.senderE164,
500-
inputProvenance: params.inputProvenance,
501-
trustedInternalHandoff: params.trustedInternalHandoff,
502-
scheduledToolPolicy: params.scheduledToolPolicy,
503-
})
504-
: { allowed: false, persistentAllowed: false };
505-
const senderScopedWebSearchRestriction =
506-
!webSearchPolicy.allowed && webSearchPolicy.persistentAllowed;
507-
const transientWebSearchRestriction =
508-
senderScopedWebSearchRestriction || isCodexMemoryFlushRun(params);
509-
input.onPersistentWebSearchPolicyResolved?.(
510-
webSearchPresent ||
511-
(persistentCodexWebSearchSurface &&
512-
transientWebSearchRestriction &&
513-
webSearchPolicy.persistentAllowed),
514-
);
480+
// An authorized search tool already proves persistent availability. Only absent
481+
// tools need policy resolution to distinguish transient restrictions from denial.
482+
let persistentWebSearchAllowed = webSearchPresent;
483+
if (
484+
input.onPersistentWebSearchPolicyResolved &&
485+
!webSearchPresent &&
486+
persistentCodexWebSearchSurface
487+
) {
488+
const webSearchPolicy = (
489+
await import("openclaw/plugin-sdk/agent-harness")
490+
).resolveWebSearchToolPolicy({
491+
config: params.config,
492+
modelProvider: params.model.provider,
493+
modelId: params.modelId,
494+
agentId: input.policyAgentId,
495+
sessionKey: input.sandboxSessionKey,
496+
sandboxToolPolicy: input.sandbox?.tools,
497+
messageProvider: resolveCodexMessageToolProvider(params),
498+
agentAccountId: params.agentAccountId,
499+
groupId: params.groupId,
500+
groupChannel: params.groupChannel,
501+
groupSpace: params.groupSpace,
502+
spawnedBy: params.spawnedBy,
503+
senderId: params.senderId,
504+
senderName: params.senderName,
505+
senderUsername: params.senderUsername,
506+
senderE164: params.senderE164,
507+
inputProvenance: params.inputProvenance,
508+
trustedInternalHandoff: params.trustedInternalHandoff,
509+
scheduledToolPolicy: params.scheduledToolPolicy,
510+
});
511+
persistentWebSearchAllowed =
512+
webSearchPolicy.persistentAllowed &&
513+
(!webSearchPolicy.allowed || isCodexMemoryFlushRun(params));
514+
}
515+
input.onPersistentWebSearchPolicyResolved?.(persistentWebSearchAllowed);
515516
const filteredTools = filterCodexDynamicToolsForAllowlist(
516517
visionFilteredTools,
517518
toolRunContext.runtimeToolAllowlist,
@@ -657,11 +658,11 @@ export function shouldEnableCodexAppServerNativeToolSurface(
657658
return false;
658659
}
659660
if (
660-
isCodexNativeExecutionBlockedByNodeExecHost(params, {
661+
!resolveCodexNativeExecutionPolicyForRun(params, {
661662
agentId: options.agentId,
662663
runtimeSessionKey: options.runtimeSessionKey,
663664
sandbox,
664-
})
665+
}).nativeToolSurfaceAllowed
665666
) {
666667
return false;
667668
}
@@ -677,24 +678,24 @@ export function shouldEnableCodexAppServerNativeToolSurface(
677678
canCodexAppServerNativeToolSurfaceHonorSandbox(sandbox, options)
678679
);
679680
}
680-
/** Returns true when OpenClaw policy requires the Node-owned exec/process tools instead. */
681-
function isCodexNativeExecutionBlockedByNodeExecHost(
681+
function resolveCodexNativeExecutionPolicyForRun(
682682
params: EmbeddedRunAttemptParams,
683683
options: {
684684
agentId?: string;
685685
runtimeSessionKey?: string;
686686
sandbox?: OpenClawSandboxContext;
687687
} = {},
688-
): boolean {
689-
return !resolveCodexNativeExecutionPolicy({
688+
): CodexNativeExecutionPolicy {
689+
return resolveCodexNativeExecutionPolicy({
690690
config: params.config,
691691
sessionKey: resolveCodexRuntimePolicySessionKey(params, options.runtimeSessionKey),
692692
sessionId: params.sessionId,
693693
agentId: options.agentId,
694694
execOverrides: params.execOverrides,
695-
sandboxAvailable: options.sandbox?.enabled,
695+
// A resolved null sandbox is absence; undefined still requests runtime discovery.
696+
sandboxAvailable: options.sandbox === null ? false : options.sandbox?.enabled,
696697
readRuntimeSessionEntry: true,
697-
}).nativeToolSurfaceAllowed;
698+
});
698699
}
699700
function resolveCodexRuntimePolicySessionKey(
700701
params: EmbeddedRunAttemptParams,
@@ -822,9 +823,14 @@ function addSandboxShellDynamicToolsIfAvailable(
822823
filteredTools: OpenClawDynamicTool[],
823824
allTools: OpenClawDynamicTool[],
824825
input: DynamicToolBuildParams,
826+
executionPolicy: CodexNativeExecutionPolicy,
825827
): OpenClawDynamicTool[] {
826828
if (
827-
!shouldExposeSandboxExecDynamicTool(input) ||
829+
isCodexMemoryFlushRun(input.params) ||
830+
!executionPolicy.nativeToolSurfaceAllowed ||
831+
!input.sandbox?.enabled ||
832+
!input.sandbox.backendId.trim() ||
833+
input.nativeToolSurfaceEnabled !== false ||
828834
isSandboxShellDynamicToolExcluded(input.pluginConfig)
829835
) {
830836
return filteredTools;
@@ -866,22 +872,6 @@ function addSandboxShellDynamicToolsIfAvailable(
866872
};
867873
return [...filteredTools, sandboxExecTool, sandboxProcessTool];
868874
}
869-
function shouldExposeSandboxExecDynamicTool(input: DynamicToolBuildParams): boolean {
870-
if (isCodexMemoryFlushRun(input.params)) {
871-
return false;
872-
}
873-
if (
874-
isCodexNativeExecutionBlockedByNodeExecHost(input.params, {
875-
agentId: input.policyAgentId,
876-
runtimeSessionKey: input.sandboxSessionKey,
877-
sandbox: input.sandbox,
878-
})
879-
) {
880-
return false;
881-
}
882-
const backendId = input.sandbox?.enabled ? input.sandbox.backendId.trim().toLowerCase() : "";
883-
return Boolean(backendId && input.nativeToolSurfaceEnabled === false);
884-
}
885875
function isSandboxShellDynamicToolExcluded(config: CodexPluginConfig): boolean {
886876
return isCodexDynamicToolExcluded(config, ["exec", "sandbox_exec", "process", "sandbox_process"]);
887877
}
@@ -927,19 +917,6 @@ function shouldKeepOpenClawShellDynamicTools(
927917
nodePolicy.effectiveExecHost !== "node"
928918
);
929919
}
930-
function resolveCodexNativeExecutionPolicyForDynamicTools(
931-
input: DynamicToolBuildParams,
932-
): CodexNativeExecutionPolicy {
933-
return resolveCodexNativeExecutionPolicy({
934-
config: input.params.config,
935-
sessionKey: resolveCodexRuntimePolicySessionKey(input.params, input.sandboxSessionKey),
936-
sessionId: input.params.sessionId,
937-
agentId: input.policyAgentId,
938-
execOverrides: input.params.execOverrides,
939-
sandboxAvailable: input.sandbox?.enabled,
940-
readRuntimeSessionEntry: true,
941-
});
942-
}
943920
/** Applies a normalized tool allowlist while preserving shell aliases for exec/process. */
944921
function filterCodexDynamicToolsForAllowlist<T extends { name: string }>(
945922
tools: T[],

0 commit comments

Comments
 (0)