Skip to content

Commit 16e0dc5

Browse files
authored
fix(agents): apply fallback delegation gate to CLI runs (#115405)
1 parent 03ff561 commit 16e0dc5

17 files changed

Lines changed: 452 additions & 6 deletions

‎src/agents/cli-runner/mcp-grant-context.test.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
import { describe, expect, it } from "vitest";
22
import type { OpenClawConfig } from "../../config/types.openclaw.js";
3-
import { buildCliMcpGrantContext } from "./mcp-grant-context.js";
3+
import {
4+
buildCliMcpDelegationCapabilityBinding,
5+
buildCliMcpGrantContext,
6+
} from "./mcp-grant-context.js";
47
import type { RunCliAgentParams } from "./types.js";
58

6-
function buildGrant(overrides: Partial<RunCliAgentParams> = {}) {
9+
function buildGrant(
10+
overrides: Partial<RunCliAgentParams> = {},
11+
delegationCapability?: "full" | "report_only",
12+
) {
713
const run = {
814
sessionKey: "agent:main:telegram:group:chat123",
915
workspaceDir: "/workspace",
@@ -16,6 +22,7 @@ function buildGrant(overrides: Partial<RunCliAgentParams> = {}) {
1622
currentChannelId: "telegram:chat123",
1723
cliToolAvailability: { native: [], openClaw: ["message"] },
1824
...overrides,
25+
...(delegationCapability ? buildCliMcpDelegationCapabilityBinding(delegationCapability) : {}),
1926
} as RunCliAgentParams;
2027

2128
return buildCliMcpGrantContext({
@@ -151,3 +158,18 @@ describe("buildCliMcpGrantContext source-reply authority", () => {
151158
expect(buildGrant(overrides as Partial<RunCliAgentParams>).sourceReplyOnly).toBeUndefined();
152159
});
153160
});
161+
162+
describe("buildCliMcpGrantContext delegationCapability", () => {
163+
it("stamps a report-only capability into the minted grant", () => {
164+
expect(buildGrant({}, "report_only")).toMatchObject({
165+
delegationCapability: "report_only",
166+
});
167+
});
168+
169+
it("leaves the grant shape untouched for ordinary runs", () => {
170+
// Primary attempts must produce byte-identical grant contexts, so the key
171+
// is absent rather than explicitly "full".
172+
expect(buildGrant()).not.toHaveProperty("delegationCapability");
173+
expect(buildGrant({}, "full")).not.toHaveProperty("delegationCapability");
174+
});
175+
});

‎src/agents/cli-runner/mcp-grant-context.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,24 @@ import { canonicalizeMainSessionAlias } from "../../config/sessions/main-session
33
import type { OpenClawConfig } from "../../config/types.openclaw.js";
44
import type { McpLoopbackRequestContext } from "../../gateway/mcp-grant-store.js";
55
import { resolveGatewayMessageChannel } from "../../utils/message-channel.js";
6+
import type { DelegationCapability } from "../delegation-capability.js";
67
import { SESSION_PERMISSION_BY_EXEC_MODE } from "../session-permission-exec-mode.js";
78
import type { RunCliAgentParams } from "./types.js";
89

10+
const cliMcpDelegationCapability = Symbol("cliMcpDelegationCapability");
11+
12+
export function buildCliMcpDelegationCapabilityBinding(capability: DelegationCapability): object {
13+
return capability === "report_only" ? { [cliMcpDelegationCapability]: capability } : {};
14+
}
15+
16+
function readCliMcpDelegationCapability(run: object): DelegationCapability | undefined {
17+
if (!(cliMcpDelegationCapability in run)) {
18+
return undefined;
19+
}
20+
const capability = run[cliMcpDelegationCapability];
21+
return capability === "full" || capability === "report_only" ? capability : undefined;
22+
}
23+
924
export function normalizeOptionalMcpContextValue(value: string | undefined): string | undefined {
1025
return value?.trim() || undefined;
1126
}
@@ -124,6 +139,7 @@ export function buildCliMcpGrantContext(params: {
124139
);
125140
const currentChannelId = normalizeOptionalMcpContextValue(params.run.currentChannelId);
126141
const grantedToolsAllow = params.run.cliToolAvailability?.openClaw ?? params.toolsAllow;
142+
const delegationCapability = readCliMcpDelegationCapability(params.run);
127143
// Trusted message-only completions stay restricted even when source routing
128144
// is missing; the message tool must fail closed instead of widening authority.
129145
const sourceReplyOnly =
@@ -147,6 +163,9 @@ export function buildCliMcpGrantContext(params: {
147163
...(params.run.skillWorkshopProposalRevision
148164
? { skillWorkshop: { proposalRevision: params.run.skillWorkshopProposalRevision } }
149165
: {}),
166+
// Same enforcement point for the fallback delegation gate, so an
167+
// unrestricted run keeps its exact prior grant shape.
168+
...(delegationCapability ? { delegationCapability } : {}),
150169
...(params.run.scheduledToolPolicy
151170
? { scheduledToolPolicy: { ...params.run.scheduledToolPolicy } }
152171
: {}),

‎src/agents/command/attempt-execution.cli.test.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import { createTestPreparedRunAdmission } from "../admitted-run-context.test-sup
3434
import { clearRuntimeAuthProfileStoreSnapshots } from "../auth-profiles/runtime-snapshots.js";
3535
import { saveAuthProfileStore } from "../auth-profiles/store.js";
3636
import { testing as cliBackendsTesting } from "../cli-backends.test-support.js";
37+
import { buildCliMcpGrantContext } from "../cli-runner/mcp-grant-context.js";
3738
import { createCronCreatorAuthorityCapability } from "../cron-creator-authority-context.js";
3839
import type { RunEmbeddedAgentInternalParams } from "../embedded-agent-runner/run/internal-params.js";
3940
import type { EmbeddedAgentRunResult } from "../embedded-agent.js";
@@ -2952,6 +2953,97 @@ describe("CLI attempt execution", () => {
29522953
});
29532954
});
29542955

2956+
it.each([
2957+
{
2958+
label: "a fallback completion report",
2959+
isFallbackRetry: true,
2960+
inputProvenance: { kind: "inter_session", sourceTool: "subagent_announce" },
2961+
expected: "report_only",
2962+
},
2963+
{
2964+
label: "a fallback answering ordinary user input",
2965+
isFallbackRetry: true,
2966+
inputProvenance: { kind: "external_user" },
2967+
expected: undefined,
2968+
},
2969+
{
2970+
label: "a primary completion report",
2971+
isFallbackRetry: false,
2972+
inputProvenance: { kind: "inter_session", sourceTool: "subagent_announce" },
2973+
expected: undefined,
2974+
},
2975+
])(
2976+
"stamps the command-fallback CLI grant delegation capability for $label",
2977+
async ({ isFallbackRetry, inputProvenance, expected }) => {
2978+
const runId = `run-command-fallback-delegation-${String(isFallbackRetry)}-${expected}`;
2979+
const sessionKey = `agent:main:direct:${runId}`;
2980+
const sessionEntry: SessionEntry = {
2981+
sessionId: `session-${runId}`,
2982+
updatedAt: Date.now(),
2983+
};
2984+
const cfg = {
2985+
session: { store: storePath },
2986+
agents: {
2987+
defaults: {
2988+
models: {
2989+
"anthropic/claude-opus-4-7": { agentRuntime: { id: "claude-cli" } },
2990+
},
2991+
},
2992+
},
2993+
} as OpenClawConfig;
2994+
await writeSessionStoreSeed({ [sessionKey]: sessionEntry });
2995+
runCliAgentMock.mockResolvedValueOnce(makeCliResult("delegation gate"));
2996+
2997+
await runAgentAttempt({
2998+
providerOverride: "anthropic",
2999+
originalProvider: "anthropic",
3000+
modelOverride: "claude-opus-4-7",
3001+
cfg,
3002+
sessionEntry,
3003+
sessionId: sessionEntry.sessionId,
3004+
sessionKey,
3005+
sessionAgentId: "main",
3006+
sessionFile: path.join(tmpDir, `${runId}.jsonl`),
3007+
workspaceDir: tmpDir,
3008+
body: "report the completion",
3009+
isFallbackRetry,
3010+
resolvedThinkLevel: "medium",
3011+
timeoutMs: 1_000,
3012+
runId,
3013+
opts: {
3014+
message: "report the completion",
3015+
inputProvenance,
3016+
} as RunAgentAttemptParams["opts"],
3017+
runContext: {} as RunAgentAttemptParams["runContext"],
3018+
spawnedBy: undefined,
3019+
messageChannel: "telegram",
3020+
skillsSnapshot: undefined,
3021+
resolvedVerboseLevel: undefined,
3022+
agentDir,
3023+
onAgentEvent: vi.fn(),
3024+
authProfileProvider: "anthropic",
3025+
sessionStore: { [sessionKey]: sessionEntry },
3026+
storePath,
3027+
sessionHasHistory: false,
3028+
});
3029+
3030+
// The command loop is a second fallback entry point; its CLI grant must
3031+
// carry the same gate as the auto-reply candidate or the loopback surface
3032+
// resolves to full.
3033+
const grantContext = buildCliMcpGrantContext({
3034+
run: firstRunCliAgentArg() as unknown as Parameters<
3035+
typeof buildCliMcpGrantContext
3036+
>[0]["run"],
3037+
config: cfg,
3038+
requireExplicitMessageTarget: false,
3039+
agentId: "main",
3040+
modelProvider: "anthropic",
3041+
modelId: "claude-opus-4-7",
3042+
});
3043+
expect(grantContext.delegationCapability).toBe(expected);
3044+
},
3045+
);
3046+
29553047
it("routes canonical Anthropic models through the configured Claude CLI runtime", async () => {
29563048
const sessionKey = "agent:main:direct:canonical-claude-cli";
29573049
const sessionEntry = makeSessionEntry("openclaw-session-canonical-cli");

‎src/agents/command/attempt-execution.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ import {
7373
} from "../cli-execution-auth.js";
7474
import { runCliAgent } from "../cli-runner.js";
7575
import { hasCliLiveSession } from "../cli-runner/cli-live-session-registry.js";
76+
import { buildCliMcpDelegationCapabilityBinding } from "../cli-runner/mcp-grant-context.js";
7677
import { resolveCliRuntimeToolsAllow } from "../cli-runner/tool-policy.js";
7778
import {
7879
getCliSessionBinding,
@@ -81,6 +82,7 @@ import {
8182
} from "../cli-session.js";
8283
import { resolveConversationCapabilityProfile } from "../conversation-capability-profile.js";
8384
import { resolveConversationToolPolicies } from "../conversation-tool-policy-pipeline.js";
85+
import { resolveDelegationCapability } from "../delegation-capability.js";
8486
import type { DeferredEmbeddedRunLifecycleManager } from "../embedded-agent-runner/run/deferred-lifecycle-owner.js";
8587
import type { RunEmbeddedAgentInternalParams } from "../embedded-agent-runner/run/internal-params.js";
8688
import { runEmbeddedAgent, type EmbeddedAgentRunResult } from "../embedded-agent.js";
@@ -1095,6 +1097,17 @@ export function runAgentAttempt(params: {
10951097
runtimeToolsAllow,
10961098
params.opts.toolsAllowIsDefault,
10971099
),
1100+
// This loop is the command-origin sibling of the auto-reply fallback
1101+
// candidate, so its CLI grant needs the same delegation gate; the
1102+
// inputs match the tool state this invocation actually runs with.
1103+
...buildCliMcpDelegationCapabilityBinding(
1104+
resolveDelegationCapability({
1105+
fallbackActive: params.isFallbackRetry,
1106+
inputProvenance: params.opts.inputProvenance,
1107+
disableTools,
1108+
toolsAllow: runtimeToolsAllow,
1109+
}),
1110+
),
10981111
scheduledToolPolicy: params.opts.scheduledToolPolicy,
10991112
cleanupBundleMcpOnRunEnd: params.opts.cleanupBundleMcpOnRunEnd,
11001113
cleanupCliLiveSessionOnRunEnd: params.opts.cleanupCliLiveSessionOnRunEnd,

‎src/agents/delegation-capability.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { describe, expect, it, vi } from "vitest";
2+
import { getPluginToolMeta, setPluginToolMeta } from "../plugins/tool-metadata.js";
23
import { applyDelegationCapability, resolveDelegationCapability } from "./delegation-capability.js";
34
import { attachToolAllowlistIntersection } from "./tool-policy.js";
45
import type { AnyAgentTool } from "./tools/common.js";
@@ -158,4 +159,16 @@ describe("delegation capability", () => {
158159
expect(cronExecute).toHaveBeenCalledTimes(2);
159160
expect(imageExecute).toHaveBeenCalledTimes(1);
160161
});
162+
163+
it("preserves plugin ownership metadata through the report-only wrapper", () => {
164+
const cron = createTool("cron");
165+
setPluginToolMeta(cron, { pluginId: "scheduler" } as never);
166+
167+
const [wrapped] = applyDelegationCapability([cron], "report_only");
168+
169+
// The effective cron-creator allowlist reads meta off the returned tool, so
170+
// a wrapper that drops it would silently unown the plugin's tool.
171+
expect(wrapped).not.toBe(cron);
172+
expect(getPluginToolMeta(wrapped as AnyAgentTool)).toEqual({ pluginId: "scheduler" });
173+
});
161174
});

‎src/agents/delegation-capability.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1+
import { createSubsystemLogger } from "../logging/subsystem.js";
2+
import { copyPluginToolMeta } from "../plugins/tool-metadata.js";
13
import { isCompletionReportInputProvenance } from "../sessions/input-provenance.js";
24
import { createRuntimeToolMatcher } from "./tool-policy-match.js";
35
import { normalizeToolPolicyName } from "./tool-policy.js";
46
import { AUTOMATIONS_TOOL_NAME } from "./tools/automations-tool-name.js";
57
import type { AnyAgentTool } from "./tools/common.js";
68
import { ToolAuthorizationError } from "./tools/common.js";
79

10+
const log = createSubsystemLogger("agents/delegation-capability");
11+
812
export type DelegationCapability = "full" | "report_only";
913

1014
const NEW_DELEGATION_TOOL_NAMES = new Set([
@@ -58,7 +62,7 @@ function readToolAction(params: unknown): string {
5862
}
5963

6064
function wrapReportOnlyTool(tool: AnyAgentTool, allowedActions: ReadonlySet<string>): AnyAgentTool {
61-
return new Proxy(tool, {
65+
const wrapped = new Proxy(tool, {
6266
get(target, property, receiver) {
6367
if (property !== "execute") {
6468
return Reflect.get(target, property, receiver);
@@ -76,6 +80,11 @@ function wrapReportOnlyTool(tool: AnyAgentTool, allowedActions: ReadonlySet<stri
7680
};
7781
},
7882
});
83+
// Plugin ownership lives in a WeakMap keyed by tool identity, so the proxy
84+
// needs its own entry; otherwise plugin-owned report-only tools drop out of
85+
// the effective cron-creator allowlist for the rest of the run.
86+
copyPluginToolMeta(tool, wrapped);
87+
return wrapped;
7988
}
8089

8190
/**
@@ -90,12 +99,29 @@ export function applyDelegationCapability(
9099
if (capability !== "report_only") {
91100
return tools;
92101
}
93-
return tools.flatMap((tool) => {
102+
const removed: string[] = [];
103+
const narrowed: string[] = [];
104+
const gated = tools.flatMap((tool) => {
94105
const name = normalizeToolPolicyName(tool.name);
95106
if (NEW_DELEGATION_TOOL_NAMES.has(name)) {
107+
removed.push(name);
96108
return [];
97109
}
98110
const allowedActions = REPORT_ONLY_TOOL_ACTIONS.get(name);
99-
return allowedActions ? [wrapReportOnlyTool(tool, allowedActions)] : [tool];
111+
if (!allowedActions) {
112+
return [tool];
113+
}
114+
narrowed.push(name);
115+
return [wrapReportOnlyTool(tool, allowedActions)];
100116
});
117+
if (removed.length > 0 || narrowed.length > 0) {
118+
// Removal is otherwise invisible: the model simply never sees the tool and
119+
// no error is raised. Record it so a fallback completion turn stays
120+
// auditable after the fact.
121+
log.debug("delegation capability restricted run tools", {
122+
removed,
123+
narrowed,
124+
});
125+
}
126+
return gated;
101127
}

‎src/auto-reply/reply/agent-runner-cli-candidate.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { resolveBootstrapWarningSignaturesSeen } from "../../agents/bootstrap-budget.js";
2+
import { buildCliMcpDelegationCapabilityBinding } from "../../agents/cli-runner/mcp-grant-context.js";
23
import {
34
getCliSessionBinding,
45
shouldClearFailedCliSessionBinding,
56
} from "../../agents/cli-session.js";
7+
import { resolveDelegationCapability } from "../../agents/delegation-capability.js";
68
import { findModelInCatalog } from "../../agents/model-catalog-lookup.js";
79
import { withLocalSessionPlacementTurnAdmission } from "../../agents/session-placement-admission.js";
810
import { normalizeChatType } from "../../channels/chat-type.js";
@@ -332,6 +334,17 @@ export async function runCliFallbackCandidate(
332334
currentInboundEventKind: turn.followupRun.currentInboundEventKind,
333335
currentInboundContext: turn.followupRun.currentInboundContext,
334336
inputProvenance: turn.followupRun.run.inputProvenance,
337+
// Candidate zero is the primary attempt; later candidates are
338+
// fallbacks. Carry the runner-owned fact instead of inferring from
339+
// this shared dispatch path, or primary CLI runs lose delegation.
340+
...buildCliMcpDelegationCapabilityBinding(
341+
resolveDelegationCapability({
342+
fallbackActive: params.isFallbackRetry,
343+
inputProvenance: turn.followupRun.run.inputProvenance,
344+
disableTools: turn.opts?.disableTools,
345+
toolsAllow: turn.opts?.toolsAllow,
346+
}),
347+
),
335348
modelProvider: params.provider,
336349
modelHasVision,
337350
modelContextWindow: selectedModelEntry?.contextWindow,

0 commit comments

Comments
 (0)