Skip to content

Commit d863dd5

Browse files
committed
refactor(agents): bind tool policy to exact execution identity
1 parent 2a0bbd2 commit d863dd5

39 files changed

Lines changed: 1223 additions & 219 deletions
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
type OpenClawCodingToolsFactory =
22
(typeof import("openclaw/plugin-sdk/agent-harness"))["createOpenClawCodingTools"];
3+
type AgentHarnessCodingToolsFactory =
4+
(typeof import("openclaw/plugin-sdk/agent-harness-tool-runtime"))["createOpenClawCodingToolsForAgentHarness"];
35

46
/** Mutable dependency seam shared by dynamic-tool construction and its behavioral tests. */
57
export const dynamicToolBuildState: {
68
openClawCodingToolsFactory?: OpenClawCodingToolsFactory;
9+
agentHarnessCodingToolsFactory?: AgentHarnessCodingToolsFactory;
710
} = {};
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { afterEach, expect, it, vi } from "vitest";
2+
3+
afterEach(() => {
4+
vi.doUnmock("openclaw/plugin-sdk/agent-harness-tool-runtime");
5+
vi.resetModules();
6+
});
7+
8+
it("does not load the private tool builder before a tool-capable turn", async () => {
9+
let toolBuilderImports = 0;
10+
vi.doMock("openclaw/plugin-sdk/agent-harness-tool-runtime", () => {
11+
toolBuilderImports += 1;
12+
return {
13+
createOpenClawCodingToolsForAgentHarness: vi.fn(() => []),
14+
};
15+
});
16+
17+
const { buildDynamicTools } = await import("./dynamic-tool-build.js");
18+
await import("./side-question.js");
19+
expect(toolBuilderImports).toBe(0);
20+
21+
await expect(
22+
buildDynamicTools({
23+
attributionAttempt: {} as never,
24+
params: { disableTools: true } as never,
25+
} as never),
26+
).resolves.toEqual([]);
27+
expect(toolBuilderImports).toBe(0);
28+
29+
await expect(
30+
buildDynamicTools({
31+
attributionAttempt: {} as never,
32+
params: {
33+
disableTools: false,
34+
model: { compat: { supportsTools: false } },
35+
} as never,
36+
} as never),
37+
).resolves.toEqual([]);
38+
expect(toolBuilderImports).toBe(0);
39+
});

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ function setOpenClawCodingToolsFactoryForTests(
6363

6464
function resetOpenClawCodingToolsFactoryForTests(): void {
6565
dynamicToolBuildState.openClawCodingToolsFactory = undefined;
66+
dynamicToolBuildState.agentHarnessCodingToolsFactory = undefined;
6667
}
6768

6869
type RuntimeDynamicToolForTest = Parameters<
@@ -141,6 +142,7 @@ async function buildDynamicToolsForTest(
141142
throw new Error("createParams must provide a sessionKey for Codex dynamic tool tests.");
142143
}
143144
return buildDynamicTools({
145+
attributionAttempt: params,
144146
params,
145147
resolvedWorkspace: workspaceDir,
146148
effectiveWorkspace: workspaceDir,
@@ -156,6 +158,26 @@ async function buildDynamicToolsForTest(
156158
}
157159

158160
describe("Codex app-server dynamic tool build", () => {
161+
it("uses the exact host-admitted attempt for private tool attribution", async () => {
162+
const workspaceDir = path.join(tempDir, "workspace");
163+
const admittedAttempt = createParams(path.join(tempDir, "session.jsonl"), workspaceDir);
164+
admittedAttempt.disableTools = false;
165+
admittedAttempt.runtimePlan = createCodexRuntimePlanFixture();
166+
const runtimeParams = { ...admittedAttempt };
167+
const factory = vi.fn<NonNullable<typeof dynamicToolBuildState.agentHarnessCodingToolsFactory>>(
168+
() => [],
169+
);
170+
dynamicToolBuildState.agentHarnessCodingToolsFactory = factory;
171+
172+
await buildDynamicToolsForTest(runtimeParams, workspaceDir, {
173+
attributionAttempt: admittedAttempt,
174+
});
175+
176+
expect(factory).toHaveBeenCalledOnce();
177+
expect(factory.mock.calls[0]?.[0]).toBe(admittedAttempt);
178+
expect(factory.mock.calls[0]?.[0]).not.toBe(runtimeParams);
179+
});
180+
159181
it("removes account-wide app access when native tools are restricted", () => {
160182
expect(
161183
disableCodexPluginThreadConfig({

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ function preserveRingZeroSystemAgentTool<T extends { name: string; catalogMode?:
8383
}
8484
/** Runtime inputs needed to derive the exact Codex dynamic tool surface for a turn. */
8585
type DynamicToolBuildParams = {
86+
attributionAttempt: EmbeddedRunAttemptParams;
8687
params: EmbeddedRunAttemptParams;
8788
resolvedWorkspace: string;
8889
effectiveWorkspace: string;
@@ -231,9 +232,15 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
231232
let agentHarnessModule: typeof import("openclaw/plugin-sdk/agent-harness") | undefined;
232233
const loadAgentHarnessModule = async () =>
233234
(agentHarnessModule ??= await import("openclaw/plugin-sdk/agent-harness"));
235+
const agentHarnessCodingToolsFactory = injectedOpenClawCodingToolsFactory
236+
? undefined
237+
: (dynamicToolBuildState.agentHarnessCodingToolsFactory ??
238+
(await import("openclaw/plugin-sdk/agent-harness-tool-runtime"))
239+
.createOpenClawCodingToolsForAgentHarness);
234240
const createOpenClawCodingTools =
235241
injectedOpenClawCodingToolsFactory ??
236-
(await loadAgentHarnessModule()).createOpenClawCodingTools;
242+
((options: OpenClawCodingToolsOptions) =>
243+
agentHarnessCodingToolsFactory!(input.attributionAttempt, options));
237244
toolBuildStages.mark("load-agent-harness-tools");
238245
const sessionKeys = resolveOpenClawCodingToolsSessionKeys(params, input.sandboxSessionKey);
239246
const nativeExecutionPolicy = resolveCodexNativeExecutionPolicyForDynamicTools(input);

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,9 @@ export async function prepareCodexAttemptTools(runtime: CodexAttemptRuntime) {
109109
frameImageIdentity?: string;
110110
} = { value: 0 };
111111
const commonToolParams = {
112+
// Private attribution is bound to the exact host-admitted object. Codex
113+
// runtime/tool clones carry behavior only and must not replace this owner.
114+
attributionAttempt: params,
112115
params: dynamicToolParams,
113116
resolvedWorkspace,
114117
effectiveWorkspace,

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,7 @@ async function buildDynamicToolsForTest(
394394
throw new Error("createParams must provide a sessionKey for Codex dynamic tool tests.");
395395
}
396396
return testing.buildDynamicTools({
397+
attributionAttempt: params,
397398
params,
398399
resolvedWorkspace: workspaceDir,
399400
effectiveWorkspace: workspaceDir,
@@ -498,6 +499,7 @@ async function startThreadWithDisabledNativeSurfaceForTest(
498499
}
499500
const nativeToolSurfaceEnabled = testing.shouldEnableCodexAppServerNativeToolSurface(params);
500501
const dynamicTools = await testing.buildDynamicTools({
502+
attributionAttempt: params,
501503
params,
502504
resolvedWorkspace: workspaceDir,
503505
effectiveWorkspace: workspaceDir,
@@ -1120,6 +1122,7 @@ describe("runCodexAppServerAttempt", () => {
11201122
sandbox,
11211123
);
11221124
const dynamicTools = await testing.buildDynamicTools({
1125+
attributionAttempt: params,
11231126
params,
11241127
resolvedWorkspace: workspaceDir,
11251128
effectiveWorkspace: workspaceDir,
@@ -1223,6 +1226,7 @@ describe("runCodexAppServerAttempt", () => {
12231226
{ sandboxExecServerEnabled: true },
12241227
);
12251228
const dynamicTools = await testing.buildDynamicTools({
1229+
attributionAttempt: params,
12261230
params,
12271231
resolvedWorkspace: workspaceDir,
12281232
effectiveWorkspace: "/workspace",

‎extensions/codex/src/app-server/side-question.test.ts‎

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ const isCodexAppServerNativeAuthProfileMock = vi.fn();
3232
const getSharedCodexAppServerClientMock = vi.fn();
3333
const refreshCodexAppServerAuthTokensMock = vi.fn();
3434
const createOpenClawCodingToolsMock = vi.fn();
35+
let sideQuestionToolParams: unknown;
36+
const createOpenClawCodingToolsForSideQuestionMock = vi.fn((params: unknown, options: unknown) => {
37+
sideQuestionToolParams = params;
38+
return createOpenClawCodingToolsMock(options);
39+
});
3540
const toolExecuteMock = vi.fn();
3641
const handleCodexAppServerApprovalRequestMock = vi.fn();
3742
const resolveCodexProviderWebSearchSupportForClientMock = vi.fn();
@@ -95,8 +100,9 @@ vi.mock("./provider-capabilities.js", () => ({
95100
resolveCodexProviderWebSearchSupportForClientMock(...args),
96101
}));
97102

98-
vi.mock("openclaw/plugin-sdk/agent-harness", () => ({
99-
createOpenClawCodingTools: (...args: unknown[]) => createOpenClawCodingToolsMock(...args),
103+
vi.mock("openclaw/plugin-sdk/agent-harness-tool-runtime", () => ({
104+
createOpenClawCodingToolsForAgentHarnessSideQuestion: (params: unknown, options: unknown) =>
105+
createOpenClawCodingToolsForSideQuestionMock(params, options),
100106
}));
101107

102108
const { runCodexAppServerSideQuestion: runCodexAppServerSideQuestionImpl } =
@@ -474,6 +480,8 @@ describe("runCodexAppServerSideQuestion", () => {
474480
getSharedCodexAppServerClientMock.mockReset();
475481
refreshCodexAppServerAuthTokensMock.mockReset();
476482
createOpenClawCodingToolsMock.mockReset();
483+
createOpenClawCodingToolsForSideQuestionMock.mockClear();
484+
sideQuestionToolParams = undefined;
477485
toolExecuteMock.mockReset();
478486
handleCodexAppServerApprovalRequestMock.mockReset();
479487
resolveCodexProviderWebSearchSupportForClientMock.mockReset();
@@ -536,33 +544,34 @@ describe("runCodexAppServerSideQuestion", () => {
536544
it("forks an ephemeral side thread and returns the completed assistant text", async () => {
537545
const client = createFakeClient();
538546
getSharedCodexAppServerClientMock.mockResolvedValue(client);
547+
const params = sideParams({
548+
messageChannel: "discord",
549+
messageProvider: "discord-voice",
550+
chatId: "discord-native-room",
551+
chatType: "channel",
552+
sessionKey: "agent:main:conversation",
553+
sandboxSessionKey: "agent:main:runtime-policy",
554+
messageActionTurnCapability: "turn-capability-1",
555+
currentChannelId: "voice-room",
556+
agentAccountId: "account-1",
557+
messageTo: "channel-1",
558+
messageThreadId: "thread-1",
559+
groupId: "group-1",
560+
groupChannel: "#ops",
561+
groupSpace: "workspace-1",
562+
spawnedBy: "agent:main:parent",
563+
senderId: "sender-1",
564+
senderName: "Rosita",
565+
senderUsername: "rosita",
566+
senderE164: "+15550001",
567+
senderIsOwner: true,
568+
});
539569

540-
const result = await runCodexAppServerSideQuestion(
541-
sideParams({
542-
messageChannel: "discord",
543-
messageProvider: "discord-voice",
544-
chatId: "discord-native-room",
545-
chatType: "channel",
546-
sessionKey: "agent:main:conversation",
547-
sandboxSessionKey: "agent:main:runtime-policy",
548-
messageActionTurnCapability: "turn-capability-1",
549-
currentChannelId: "voice-room",
550-
agentAccountId: "account-1",
551-
messageTo: "channel-1",
552-
messageThreadId: "thread-1",
553-
groupId: "group-1",
554-
groupChannel: "#ops",
555-
groupSpace: "workspace-1",
556-
spawnedBy: "agent:main:parent",
557-
senderId: "sender-1",
558-
senderName: "Rosita",
559-
senderUsername: "rosita",
560-
senderE164: "+15550001",
561-
senderIsOwner: true,
562-
}),
563-
);
570+
const result = await runCodexAppServerSideQuestion(params);
564571

565572
expect(result).toEqual({ text: "Side answer." });
573+
expect(sideQuestionToolParams).toBe(params);
574+
expect(params).not.toHaveProperty("attribution");
566575
expect(mockCall(getSharedCodexAppServerClientMock)[0]).toMatchObject({
567576
preparedAuth: {
568577
kind: "profile",

‎extensions/codex/src/app-server/side-question.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,7 @@ export async function runCodexAppServerSideQuestion(
413413
})
414414
: "unsupported";
415415
const { toolBridge, webSearchPlan } = await createCodexSideToolBridge({
416+
attributionParams: params,
416417
params: effectiveParams,
417418
cwd,
418419
pluginConfig,
@@ -920,6 +921,7 @@ function buildSideRunAttemptParams(
920921
}
921922

922923
async function createCodexSideToolBridge(input: {
924+
attributionParams: AgentHarnessSideQuestionParams;
923925
params: AgentHarnessSideQuestionParams;
924926
cwd: string;
925927
pluginConfig: ReturnType<typeof readCodexPluginConfig>;
@@ -935,8 +937,8 @@ async function createCodexSideToolBridge(input: {
935937
const messageToolProvider = resolveCodexMessageToolProvider(input.params);
936938
let tools: AnyAgentTool[] = [];
937939
if (supportsModelTools(runtimeModel)) {
938-
const createOpenClawCodingTools = (await import("openclaw/plugin-sdk/agent-harness"))
939-
.createOpenClawCodingTools;
940+
const { createOpenClawCodingToolsForAgentHarnessSideQuestion } =
941+
await import("openclaw/plugin-sdk/agent-harness-tool-runtime");
940942
const sandboxSessionKey =
941943
input.params.sandboxSessionKey?.trim() ||
942944
input.params.sessionKey?.trim() ||
@@ -947,7 +949,7 @@ async function createCodexSideToolBridge(input: {
947949
sessionKey: sandboxSessionKey,
948950
workspaceDir: input.cwd,
949951
});
950-
const allTools = createOpenClawCodingTools({
952+
const allTools = createOpenClawCodingToolsForAgentHarnessSideQuestion(input.attributionParams, {
951953
agentId: input.sessionAgentId,
952954
sessionKey: sandboxSessionKey,
953955
runSessionKey:

‎extensions/copilot/src/attempt-execution.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,9 @@ export async function runCopilotExecution(context: {
272272
sandbox,
273273
spawnWorkspaceDir: sandboxAwareSpawnWorkspaceDir,
274274
abortSignal: params.abortSignal,
275-
attemptParams: observeToolTerminal ? { ...input, observeToolTerminal } : input,
275+
admittedAttempt: input,
276+
attemptParams: input,
277+
observeToolTerminal,
276278
computerContextEpoch,
277279
sessionRef,
278280
onYieldDetected: () => {

‎extensions/copilot/src/attempt.test.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -507,14 +507,14 @@ describe("runCopilotAttempt", () => {
507507
};
508508
});
509509
const createToolBridge = vi.fn(async (input: CopilotToolBridgeInput) => {
510-
input.attemptParams?.observeToolTerminal?.({
510+
input.observeToolTerminal?.({
511511
toolCallId: "send-1",
512512
toolName: "message",
513513
arguments: { action: "send", message: "hello", target: "room-1" },
514514
outcome: "failure",
515515
failure: { error: "delivery failed" },
516516
});
517-
input.attemptParams?.observeToolTerminal?.({
517+
input.observeToolTerminal?.({
518518
toolCallId: "heartbeat-1",
519519
toolName: "heartbeat_respond",
520520
arguments: { summary: "ok" },
@@ -596,14 +596,14 @@ describe("runCopilotAttempt", () => {
596596
});
597597
const createToolBridge = vi.fn(async (input: CopilotToolBridgeInput) => {
598598
const args = { action: "send", message: "hello", target: "room-1" };
599-
input.attemptParams?.observeToolTerminal?.({
599+
input.observeToolTerminal?.({
600600
toolCallId: "send-1",
601601
toolName: "message",
602602
arguments: args,
603603
outcome: "failure",
604604
failure: { error: "delivery failed" },
605605
});
606-
input.attemptParams?.observeToolTerminal?.({
606+
input.observeToolTerminal?.({
607607
toolCallId: "send-2",
608608
toolName: "message",
609609
arguments: args,
@@ -1676,9 +1676,11 @@ describe("runCopilotAttempt", () => {
16761676
// bridge can build PI-parity tool context and wire onYield to the
16771677
// live SDK session once it exists. See tool-bridge.ts.
16781678
const bridgeCall = (createToolBridge.mock.calls[0] as unknown[] | undefined)?.[0] as {
1679+
admittedAttempt?: unknown;
16791680
attemptParams?: unknown;
16801681
sessionRef?: { current?: unknown };
16811682
};
1683+
expect(bridgeCall.admittedAttempt).toBeDefined();
16821684
expect(bridgeCall.attemptParams).toBeDefined();
16831685
expect(bridgeCall.sessionRef).toBeDefined();
16841686
expect(
@@ -1792,11 +1794,13 @@ describe("runCopilotAttempt", () => {
17921794
it("F6: attemptParams carries the full input so the bridge can derive PI-parity tool context", async () => {
17931795
const sdk = makeFakeSdk();
17941796
const pool = makeFakePool(sdk);
1795-
let capturedParams: unknown;
1796-
const createToolBridge = vi.fn(async (input: { attemptParams?: unknown }) => {
1797-
capturedParams = input.attemptParams;
1798-
return { sdkTools: [], sourceTools: [] };
1799-
});
1797+
let capturedInput: { admittedAttempt?: unknown; attemptParams?: unknown } | undefined;
1798+
const createToolBridge = vi.fn(
1799+
async (input: { admittedAttempt?: unknown; attemptParams?: unknown }) => {
1800+
capturedInput = input;
1801+
return { sdkTools: [], sourceTools: [] };
1802+
},
1803+
);
18001804

18011805
const params = makeParams({
18021806
senderIsOwner: true,
@@ -1807,7 +1811,8 @@ describe("runCopilotAttempt", () => {
18071811

18081812
// The bridge receives the same params object so it can read every
18091813
// identity/policy/channel field the wrapped-tool layer needs.
1810-
expect(capturedParams).toBe(params);
1814+
expect(capturedInput?.attemptParams).toBe(params);
1815+
expect(capturedInput?.admittedAttempt).toBe(params);
18111816
});
18121817

18131818
it("F7: result.yieldDetected is true when the tool bridge fires onYieldDetected during the attempt", async () => {

0 commit comments

Comments
 (0)