Skip to content

Commit 386d56a

Browse files
steipeteMertBasar0
andcommitted
fix(agents): block fallback completion delegation
Co-authored-by: Mert Başar <[email protected]>
1 parent 2256387 commit 386d56a

15 files changed

Lines changed: 344 additions & 2 deletions

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1325,6 +1325,25 @@ describe("Codex app-server dynamic tool build", () => {
13251325
expect(toolOptions.exec?.mode).toBeUndefined();
13261326
});
13271327

1328+
it("passes the delegation capability into shared OpenClaw tool construction", async () => {
1329+
const sessionFile = path.join(tempDir, "session.jsonl");
1330+
const workspaceDir = path.join(tempDir, "workspace");
1331+
const params = createParams(sessionFile, workspaceDir);
1332+
params.disableTools = false;
1333+
params.delegationCapability = "report_only";
1334+
params.runtimePlan = createCodexRuntimePlanFixture();
1335+
const factoryOptions: unknown[] = [];
1336+
setOpenClawCodingToolsFactoryForTests((options) => {
1337+
factoryOptions.push(options);
1338+
return [];
1339+
});
1340+
1341+
await buildDynamicToolsForTest(params, workspaceDir, { sandbox: null as never });
1342+
1343+
expect(factoryOptions).toHaveLength(1);
1344+
expect(factoryOptions[0]).toMatchObject({ delegationCapability: "report_only" });
1345+
});
1346+
13281347
it("uses the tool auth profile store for Codex dynamic tool construction", async () => {
13291348
const sessionFile = path.join(tempDir, "session.jsonl");
13301349
const workspaceDir = path.join(tempDir, "workspace");

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
293293
: undefined,
294294
modelApi: params.model.api,
295295
modelContextWindowTokens: params.model.contextWindow,
296+
delegationCapability: params.delegationCapability,
296297
modelAuthMode: resolveModelAuthMode(
297298
params.model.provider,
298299
params.config,

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,8 +350,12 @@ export async function startOrResumeThread(
350350
const startModelProvider = startModelSelection.modelProvider;
351351
// Capability read failures use managed search for this turn but must not
352352
// create a binding that later looks like a confirmed provider-policy change.
353+
const transientDelegationRestriction = params.params.delegationCapability === "report_only";
353354
let preserveExistingBinding =
354-
!ringZeroActive && params.nativeProviderWebSearchSupport === "unknown" && !binding?.threadId;
355+
transientDelegationRestriction ||
356+
(!ringZeroActive &&
357+
params.nativeProviderWebSearchSupport === "unknown" &&
358+
!binding?.threadId);
355359
let rotatedContextEngineBinding = false;
356360
let prebuiltPluginThreadConfig: CodexPluginThreadConfig | undefined;
357361
const webSearchBindingChanged =
@@ -439,6 +443,16 @@ export async function startOrResumeThread(
439443
preserveExistingBinding = true;
440444
binding = undefined;
441445
}
446+
if (binding?.threadId && transientDelegationRestriction) {
447+
assertCodexBindingMayBeReplaced(binding, "starting a delegation-restricted turn");
448+
// Loaded Codex threads ignore resume config overrides. Keep the normal
449+
// binding intact and start a transient thread with collaboration disabled.
450+
embeddedAgentLog.debug(
451+
"codex app-server delegation restricted for turn; starting transient thread",
452+
{ threadId: binding.threadId },
453+
);
454+
binding = undefined;
455+
}
442456
if (binding?.threadId && (binding.contextEngine || contextEngineBinding)) {
443457
if (
444458
!contextEngineBinding ||

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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,6 +1155,64 @@ describe("Codex app-server thread lifecycle bindings", () => {
11551155
});
11561156
});
11571157

1158+
it("uses a transient Codex thread for report-only fallback completion", async () => {
1159+
const sessionFile = path.join(tempDir, "session.jsonl");
1160+
const workspaceDir = path.join(tempDir, "workspace");
1161+
const params = createParams(sessionFile, workspaceDir);
1162+
const appServer = createThreadLifecycleAppServerOptions();
1163+
let starts = 0;
1164+
const request = vi.fn(async (method: string, requestParams?: unknown) => {
1165+
if (method === "thread/start") {
1166+
starts += 1;
1167+
return threadStartResult(`thread-${starts}`);
1168+
}
1169+
if (method === "thread/resume") {
1170+
return threadStartResult((requestParams as { threadId: string }).threadId);
1171+
}
1172+
throw new Error(`unexpected method: ${method}`);
1173+
});
1174+
1175+
await startOrResumeThread({
1176+
client: { request } as never,
1177+
params,
1178+
cwd: workspaceDir,
1179+
dynamicTools: [],
1180+
appServer,
1181+
});
1182+
params.delegationCapability = "report_only";
1183+
const restrictedBinding = await startOrResumeThread({
1184+
client: { request } as never,
1185+
params,
1186+
cwd: workspaceDir,
1187+
dynamicTools: [],
1188+
appServer,
1189+
});
1190+
const savedAfterRestriction = await readCodexAppServerBinding(sessionFile);
1191+
params.delegationCapability = "full";
1192+
const resumedBinding = await startOrResumeThread({
1193+
client: { request } as never,
1194+
params,
1195+
cwd: workspaceDir,
1196+
dynamicTools: [],
1197+
appServer,
1198+
});
1199+
1200+
expect(restrictedBinding.threadId).toBe("thread-2");
1201+
expect(savedAfterRestriction?.threadId).toBe("thread-1");
1202+
expect(resumedBinding.threadId).toBe("thread-1");
1203+
expect(request.mock.calls.map(([method]) => method)).toEqual([
1204+
"thread/start",
1205+
"thread/start",
1206+
"thread/resume",
1207+
]);
1208+
expect(request.mock.calls[1]?.[1]).toMatchObject({
1209+
config: {
1210+
"features.multi_agent": false,
1211+
"features.multi_agent_v2": false,
1212+
},
1213+
});
1214+
});
1215+
11581216
it("preserves the native-search binding when provider capability support is unknown", async () => {
11591217
const sessionFile = path.join(tempDir, "session.jsonl");
11601218
const workspaceDir = path.join(tempDir, "workspace");

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,37 @@ describe("Codex ring-zero thread config", () => {
8484
});
8585
});
8686

87+
describe("Codex delegation capability", () => {
88+
it("disables native delegation on start and resume without disabling other tools", () => {
89+
const params = createAttemptParams({ provider: "openai" });
90+
params.delegationCapability = "report_only";
91+
const appServer = createAppServerOptions() as never;
92+
const config = {
93+
"features.multi_agent": true,
94+
"features.multi_agent_v2": true,
95+
"features.goals": true,
96+
};
97+
const start = buildThreadStartParams(params, {
98+
appServer,
99+
cwd: "/repo",
100+
dynamicTools: [],
101+
config,
102+
});
103+
const resume = buildThreadResumeParams(params, {
104+
appServer,
105+
dynamicTools: [],
106+
threadId: "thread-1",
107+
config,
108+
});
109+
110+
for (const request of [start, resume]) {
111+
expect(request.config?.["features.multi_agent"]).toBe(false);
112+
expect(request.config?.["features.multi_agent_v2"]).toBe(false);
113+
expect(request.config?.["features.goals"]).toBe(true);
114+
}
115+
});
116+
});
117+
87118
function startOrResumeThread(
88119
params: Omit<Parameters<typeof startOrResumeThreadImpl>[0], "bindingStore">,
89120
) {

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ const CODEX_TOOL_SEARCH_UNSUPPORTED_THREAD_CONFIG: JsonObject = {
5151
"features.multi_agent": false,
5252
};
5353

54+
const CODEX_DELEGATION_DISABLED_THREAD_CONFIG: JsonObject = {
55+
"features.multi_agent": false,
56+
"features.multi_agent_v2": false,
57+
};
58+
5459
const CODEX_RING_ZERO_THREAD_CONFIG: JsonObject = {
5560
"features.apps": false,
5661
"features.current_time_reminder": false,
@@ -362,6 +367,9 @@ export function buildCodexRuntimeThreadConfigForRun(
362367
shouldDisableCodexToolSearchForModel(params.modelId)
363368
? CODEX_TOOL_SEARCH_UNSUPPORTED_THREAD_CONFIG
364369
: undefined,
370+
params.delegationCapability === "report_only"
371+
? CODEX_DELEGATION_DISABLED_THREAD_CONFIG
372+
: undefined,
365373
buildCodexRingZeroThreadConfigPatch(
366374
params,
367375
options.hostSystemAgentActive,

‎extensions/copilot/src/tool-bridge.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,7 @@ describe("createCopilotToolBridge", () => {
500500
forceMessageTool: true,
501501
enableHeartbeatTool: true,
502502
forceHeartbeatTool: false,
503+
delegationCapability: "report_only",
503504
} as never,
504505
createOpenClawCodingTools,
505506
modelId: "gpt-4o",
@@ -532,6 +533,7 @@ describe("createCopilotToolBridge", () => {
532533
requireExplicitMessageTarget: true,
533534
forceMessageTool: true,
534535
enableHeartbeatTool: true,
536+
delegationCapability: "report_only",
535537
});
536538
});
537539

‎extensions/copilot/src/tool-bridge.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,7 @@ function buildOpenClawCodingToolsOptions(
407407
modelCompat,
408408
modelApi: model?.api,
409409
modelContextWindowTokens: model?.contextWindow,
410+
delegationCapability: a.delegationCapability,
410411
modelAuthMode: resolveModelAuthMode(input.modelProvider, a.config, undefined, {
411412
workspaceDir,
412413
}),

‎src/agents/agent-tools.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import {
6666
type ResolvedConversationCapabilityProfile,
6767
} from "./conversation-capability-profile.js";
6868
import type { OpenClawCodingToolConstructionPlan } from "./core-tool-factory-descriptors.js";
69+
import { applyDelegationCapability, type DelegationCapability } from "./delegation-capability.js";
6970
import { resolveImageSanitizationLimits } from "./image-sanitization.js";
7071
import { createLazyExecTool, resolveExecToolConfig } from "./lazy-exec-tool.js";
7172
import {
@@ -342,6 +343,8 @@ type OpenClawCodingToolsOptions = {
342343
modelId?: string;
343344
/** Internal review-run restrictions and proposal provenance. */
344345
skillWorkshop?: SkillWorkshopRunOptions;
346+
/** Attempt-local authority to start or redirect delegated work. */
347+
delegationCapability?: DelegationCapability;
345348
/** Model API for the current provider (used for provider-native tool arbitration). */
346349
modelApi?: string;
347350
/** Model context window in tokens (used to scale read-tool output budget). */
@@ -1102,7 +1105,10 @@ function createOpenClawCodingToolsInternal(options?: OpenClawCodingToolsOptions)
11021105
});
11031106
// Host-bound ring-zero tools carry their own authority checks. Agent policy
11041107
// must not deadlock setup, but the tools still receive schema/hook wrappers.
1105-
const authorizedTools = mergeAgentRingZeroTools(ringZeroTools, subagentFiltered);
1108+
const authorizedTools = applyDelegationCapability(
1109+
mergeAgentRingZeroTools(ringZeroTools, subagentFiltered),
1110+
options?.delegationCapability,
1111+
);
11061112
if (shouldInheritEffectiveToolAllowlist) {
11071113
replaceWithEffectiveToolAllowlist(inheritedToolAllowlist, authorizedTools);
11081114
}
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { applyDelegationCapability, resolveDelegationCapability } from "./delegation-capability.js";
3+
import type { AnyAgentTool } from "./tools/common.js";
4+
5+
function createTool(
6+
name: string,
7+
execute = vi.fn(async () => ({ content: [], details: {} })),
8+
): AnyAgentTool {
9+
return {
10+
name,
11+
label: name,
12+
description: name,
13+
parameters: {} as never,
14+
execute,
15+
} as unknown as AnyAgentTool;
16+
}
17+
18+
describe("delegation capability", () => {
19+
it("enters report-only mode only for fallback completion reports", () => {
20+
expect(
21+
resolveDelegationCapability({
22+
fallbackActive: true,
23+
inputProvenance: { kind: "inter_session", sourceTool: "subagent_announce" },
24+
}),
25+
).toBe("report_only");
26+
expect(
27+
resolveDelegationCapability({
28+
fallbackActive: true,
29+
inputProvenance: { kind: "inter_session", sourceTool: "agent_harness_task" },
30+
}),
31+
).toBe("report_only");
32+
expect(
33+
resolveDelegationCapability({
34+
fallbackActive: false,
35+
inputProvenance: { kind: "inter_session", sourceTool: "subagent_announce" },
36+
}),
37+
).toBe("full");
38+
expect(
39+
resolveDelegationCapability({
40+
fallbackActive: true,
41+
inputProvenance: { kind: "external_user" },
42+
}),
43+
).toBe("full");
44+
});
45+
46+
it("removes delegation tools but retains ordinary reporting tools", () => {
47+
const tools = [
48+
createTool("sessions_spawn"),
49+
createTool("sessions_send"),
50+
createTool("openclaw"),
51+
createTool("llm-task"),
52+
createTool("codex_session_send"),
53+
createTool("message"),
54+
createTool("gateway"),
55+
createTool("sessions_history"),
56+
];
57+
58+
expect(applyDelegationCapability(tools, "report_only").map((tool) => tool.name)).toEqual([
59+
"message",
60+
"gateway",
61+
"sessions_history",
62+
]);
63+
expect(applyDelegationCapability(tools, "full")).toBe(tools);
64+
});
65+
66+
it("keeps status and cleanup actions while rejecting new background work", async () => {
67+
const cronExecute = vi.fn(async () => ({ content: [], details: {} }));
68+
const imageExecute = vi.fn(async () => ({ content: [], details: {} }));
69+
const [cron, image] = applyDelegationCapability(
70+
[createTool("cron", cronExecute), createTool("image_generate", imageExecute)],
71+
"report_only",
72+
);
73+
74+
await expect(cron?.execute("cron-status", { action: "status" })).resolves.toEqual({
75+
content: [],
76+
details: {},
77+
});
78+
await expect(cron?.execute("cron-remove", { action: "remove" })).resolves.toEqual({
79+
content: [],
80+
details: {},
81+
});
82+
await expect(cron?.execute("cron-add", { action: "add" })).rejects.toThrow(
83+
"New delegation is unavailable",
84+
);
85+
await expect(image?.execute("image-status", { action: "status" })).resolves.toEqual({
86+
content: [],
87+
details: {},
88+
});
89+
await expect(image?.execute("image-generate", {})).rejects.toThrow(
90+
"New delegation is unavailable",
91+
);
92+
expect(cronExecute).toHaveBeenCalledTimes(2);
93+
expect(imageExecute).toHaveBeenCalledTimes(1);
94+
});
95+
});

0 commit comments

Comments
 (0)