Skip to content

Commit aad014c

Browse files
committed
fix: harden subagent control boundaries
1 parent 68c674d commit aad014c

26 files changed

Lines changed: 1386 additions & 876 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ Docs: https://docs.openclaw.ai
7878
- Secrets/SecretRef: reject exec SecretRef traversal ids across schema, runtime, and gateway. (#42370) Thanks @joshavant.
7979
- Telegram/docs: clarify that `channels.telegram.groups` allowlists chats while `groupAllowFrom` allowlists users inside those chats, and point invalid negative chat IDs at the right config key. (#42451) Thanks @altaywtf.
8080
- Models/Alibaba Cloud Model Studio: wire `MODELSTUDIO_API_KEY` through shared env auth, implicit provider discovery, and shell-env fallback so onboarding works outside the wizard too. (#40634) Thanks @pomelo-nwu.
81+
- Subagents/authority: persist leaf vs orchestrator control scope at spawn time and route tool plus slash-command control through shared ownership checks, so leaf sessions cannot regain orchestration privileges after restore or flat-key lookups. Thanks @tdjackey.
8182
- ACP/sessions_spawn: implicitly stream `mode="run"` ACP spawns to parent only for eligible subagent orchestrator sessions (heartbeat `target: "last"` with a usable session-local route), restoring parent progress relays without thread binding. (#42404) Thanks @davidguttman.
8283
- Sessions/reset model recompute: clear stale runtime model, context-token, and system-prompt metadata before session resets recompute the replacement session, so resets pick up current defaults and explicit overrides instead of reusing old runtime model state. (#41173) thanks @PonyX-lab.
8384
- Browser/Browserbase 429 handling: surface stable no-retry rate-limit guidance without buffering discarded HTTP 429 response bodies from remote browser services. (#40491) thanks @mvanhorn.

‎docs/tools/subagents.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ Each level only sees announces from its direct children.
182182

183183
### Tool policy by depth
184184

185+
- Role and control scope are written into session metadata at spawn time. That keeps flat or restored session keys from accidentally regaining orchestrator privileges.
185186
- **Depth 1 (orchestrator, when `maxSpawnDepth >= 2`)**: Gets `sessions_spawn`, `subagents`, `sessions_list`, `sessions_history` so it can manage its children. Other session/system tools remain denied.
186187
- **Depth 1 (leaf, when `maxSpawnDepth == 1`)**: No session tools (current default behavior).
187188
- **Depth 2 (leaf worker)**: No session tools — `sessions_spawn` is always denied at depth 2. Cannot spawn further children.

‎src/agents/openclaw-tools.subagents.scope.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,4 +149,97 @@ describe("openclaw-tools: subagents scope isolation", () => {
149149
}),
150150
]);
151151
});
152+
153+
it("leaf subagents cannot kill even explicitly-owned child sessions", async () => {
154+
const leafKey = "agent:main:subagent:leaf";
155+
const childKey = `${leafKey}:subagent:child`;
156+
157+
writeStore(storePath, {
158+
[leafKey]: {
159+
sessionId: "leaf-session",
160+
updatedAt: Date.now(),
161+
spawnedBy: "agent:main:main",
162+
subagentRole: "leaf",
163+
subagentControlScope: "none",
164+
},
165+
[childKey]: {
166+
sessionId: "child-session",
167+
updatedAt: Date.now(),
168+
spawnedBy: leafKey,
169+
subagentRole: "leaf",
170+
subagentControlScope: "none",
171+
},
172+
});
173+
174+
addSubagentRunForTests({
175+
runId: "run-child",
176+
childSessionKey: childKey,
177+
controllerSessionKey: leafKey,
178+
requesterSessionKey: leafKey,
179+
requesterDisplayKey: leafKey,
180+
task: "impossible child",
181+
cleanup: "keep",
182+
createdAt: Date.now() - 30_000,
183+
startedAt: Date.now() - 30_000,
184+
});
185+
186+
const tool = createSubagentsTool({ agentSessionKey: leafKey });
187+
const result = await tool.execute("call-leaf-kill", {
188+
action: "kill",
189+
target: childKey,
190+
});
191+
192+
expect(result.details).toMatchObject({
193+
status: "forbidden",
194+
error: "Leaf subagents cannot control other sessions.",
195+
});
196+
expect(callGatewayMock).not.toHaveBeenCalled();
197+
});
198+
199+
it("leaf subagents cannot steer even explicitly-owned child sessions", async () => {
200+
const leafKey = "agent:main:subagent:leaf";
201+
const childKey = `${leafKey}:subagent:child`;
202+
203+
writeStore(storePath, {
204+
[leafKey]: {
205+
sessionId: "leaf-session",
206+
updatedAt: Date.now(),
207+
spawnedBy: "agent:main:main",
208+
subagentRole: "leaf",
209+
subagentControlScope: "none",
210+
},
211+
[childKey]: {
212+
sessionId: "child-session",
213+
updatedAt: Date.now(),
214+
spawnedBy: leafKey,
215+
subagentRole: "leaf",
216+
subagentControlScope: "none",
217+
},
218+
});
219+
220+
addSubagentRunForTests({
221+
runId: "run-child",
222+
childSessionKey: childKey,
223+
controllerSessionKey: leafKey,
224+
requesterSessionKey: leafKey,
225+
requesterDisplayKey: leafKey,
226+
task: "impossible child",
227+
cleanup: "keep",
228+
createdAt: Date.now() - 30_000,
229+
startedAt: Date.now() - 30_000,
230+
});
231+
232+
const tool = createSubagentsTool({ agentSessionKey: leafKey });
233+
const result = await tool.execute("call-leaf-steer", {
234+
action: "steer",
235+
target: childKey,
236+
message: "continue",
237+
});
238+
239+
expect(result.details).toMatchObject({
240+
status: "forbidden",
241+
error: "Leaf subagents cannot control other sessions.",
242+
});
243+
expect(callGatewayMock).not.toHaveBeenCalled();
244+
});
152245
});

‎src/agents/openclaw-tools.subagents.sessions-spawn-depth-limits.test.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,6 @@ import { addSubagentRunForTests, resetSubagentRegistryForTests } from "./subagen
66
import { createPerSenderSessionConfig } from "./test-helpers/session-config.js";
77
import { createSessionsSpawnTool } from "./tools/sessions-spawn-tool.js";
88

9-
vi.mock("@mariozechner/pi-ai/oauth", () => ({
10-
getOAuthApiKey: () => undefined,
11-
getOAuthProviders: () => [],
12-
}));
13-
149
const callGatewayMock = vi.fn();
1510

1611
vi.mock("../gateway/call.js", () => ({
@@ -121,6 +116,8 @@ describe("sessions_spawn depth + child limits", () => {
121116
(entry) => entry.method === "sessions.patch" && entry.params?.spawnDepth === 2,
122117
);
123118
expect(spawnDepthPatch?.params?.key).toMatch(/^agent:main:subagent:/);
119+
expect(spawnDepthPatch?.params?.subagentRole).toBe("leaf");
120+
expect(spawnDepthPatch?.params?.subagentControlScope).toBe("none");
124121
});
125122

126123
it("rejects depth-2 callers when maxSpawnDepth is 2 (using stored spawnDepth on flat keys)", async () => {

‎src/agents/openclaw-tools.subagents.test-harness.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,6 @@ export type LoadedConfig = ReturnType<(typeof import("../config/config.js"))["lo
55

66
export const callGatewayMock: MockFn = vi.fn();
77

8-
vi.mock("@mariozechner/pi-ai/oauth", () => ({
9-
getOAuthApiKey: () => undefined,
10-
getOAuthProviders: () => [],
11-
}));
12-
138
const defaultConfig: LoadedConfig = {
149
session: {
1510
mainKey: "main",

‎src/agents/pi-tools.policy.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
14
import { describe, expect, it } from "vitest";
25
import type { OpenClawConfig } from "../config/config.js";
36
import {
47
filterToolsByPolicy,
58
isToolAllowedByPolicyName,
69
resolveEffectiveToolPolicy,
710
resolveSubagentToolPolicy,
11+
resolveSubagentToolPolicyForSession,
812
} from "./pi-tools.policy.js";
913
import { createStubTool } from "./test-helpers/pi-tool-stubs.js";
1014

@@ -165,6 +169,41 @@ describe("resolveSubagentToolPolicy depth awareness", () => {
165169
expect(isToolAllowedByPolicyName("sessions_list", policy)).toBe(false);
166170
});
167171

172+
it("uses stored leaf role for flat depth-1 session keys", () => {
173+
const storePath = path.join(
174+
os.tmpdir(),
175+
`openclaw-subagent-policy-${Date.now()}-${Math.random().toString(16).slice(2)}.json`,
176+
);
177+
fs.mkdirSync(path.dirname(storePath), { recursive: true });
178+
fs.writeFileSync(
179+
storePath,
180+
JSON.stringify(
181+
{
182+
"agent:main:subagent:flat-leaf": {
183+
sessionId: "flat-leaf",
184+
updatedAt: Date.now(),
185+
spawnDepth: 1,
186+
subagentRole: "leaf",
187+
subagentControlScope: "none",
188+
},
189+
},
190+
null,
191+
2,
192+
),
193+
"utf-8",
194+
);
195+
const cfg = {
196+
...baseCfg,
197+
session: {
198+
store: storePath,
199+
},
200+
} as unknown as OpenClawConfig;
201+
202+
const policy = resolveSubagentToolPolicyForSession(cfg, "agent:main:subagent:flat-leaf");
203+
expect(isToolAllowedByPolicyName("sessions_spawn", policy)).toBe(false);
204+
expect(isToolAllowedByPolicyName("subagents", policy)).toBe(false);
205+
});
206+
168207
it("defaults to leaf behavior when no depth is provided", () => {
169208
const policy = resolveSubagentToolPolicy(baseCfg);
170209
// Default depth=1, maxSpawnDepth=2 → orchestrator

‎src/agents/pi-tools.policy.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ import { compileGlobPatterns, matchesAnyGlobPattern } from "./glob-pattern.js";
1111
import type { AnyAgentTool } from "./pi-tools.types.js";
1212
import { pickSandboxToolPolicy } from "./sandbox-tool-policy.js";
1313
import type { SandboxToolPolicy } from "./sandbox.js";
14+
import {
15+
resolveStoredSubagentCapabilities,
16+
type SubagentSessionRole,
17+
} from "./subagent-capabilities.js";
1418
import { expandToolGroups, normalizeToolName } from "./tool-policy.js";
1519

1620
function makeToolPolicyMatcher(policy: SandboxToolPolicy) {
@@ -89,6 +93,13 @@ function resolveSubagentDenyList(depth: number, maxSpawnDepth: number): string[]
8993
return [...SUBAGENT_TOOL_DENY_ALWAYS];
9094
}
9195

96+
function resolveSubagentDenyListForRole(role: SubagentSessionRole): string[] {
97+
if (role === "leaf") {
98+
return [...SUBAGENT_TOOL_DENY_ALWAYS, ...SUBAGENT_TOOL_DENY_LEAF];
99+
}
100+
return [...SUBAGENT_TOOL_DENY_ALWAYS];
101+
}
102+
92103
export function resolveSubagentToolPolicy(cfg?: OpenClawConfig, depth?: number): SandboxToolPolicy {
93104
const configured = cfg?.tools?.subagents?.tools;
94105
const maxSpawnDepth =
@@ -108,6 +119,27 @@ export function resolveSubagentToolPolicy(cfg?: OpenClawConfig, depth?: number):
108119
return { allow: mergedAllow, deny };
109120
}
110121

122+
export function resolveSubagentToolPolicyForSession(
123+
cfg: OpenClawConfig | undefined,
124+
sessionKey: string,
125+
): SandboxToolPolicy {
126+
const configured = cfg?.tools?.subagents?.tools;
127+
const capabilities = resolveStoredSubagentCapabilities(sessionKey, { cfg });
128+
const allow = Array.isArray(configured?.allow) ? configured.allow : undefined;
129+
const alsoAllow = Array.isArray(configured?.alsoAllow) ? configured.alsoAllow : undefined;
130+
const explicitAllow = new Set(
131+
[...(allow ?? []), ...(alsoAllow ?? [])].map((toolName) => normalizeToolName(toolName)),
132+
);
133+
const deny = [
134+
...resolveSubagentDenyListForRole(capabilities.role).filter(
135+
(toolName) => !explicitAllow.has(normalizeToolName(toolName)),
136+
),
137+
...(Array.isArray(configured?.deny) ? configured.deny : []),
138+
];
139+
const mergedAllow = allow && alsoAllow ? Array.from(new Set([...allow, ...alsoAllow])) : allow;
140+
return { allow: mergedAllow, deny };
141+
}
142+
111143
export function isToolAllowedByPolicyName(name: string, policy?: SandboxToolPolicy): boolean {
112144
if (!policy) {
113145
return true;

‎src/agents/pi-tools.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
isToolAllowedByPolicies,
2525
resolveEffectiveToolPolicy,
2626
resolveGroupToolPolicy,
27-
resolveSubagentToolPolicy,
27+
resolveSubagentToolPolicyForSession,
2828
} from "./pi-tools.policy.js";
2929
import {
3030
assertRequiredParams,
@@ -45,7 +45,6 @@ import { cleanToolSchemaForGemini, normalizeToolParameters } from "./pi-tools.sc
4545
import type { AnyAgentTool } from "./pi-tools.types.js";
4646
import type { SandboxContext } from "./sandbox.js";
4747
import { isXaiProvider } from "./schema/clean-for-xai.js";
48-
import { getSubagentDepthFromSessionStore } from "./subagent-depth.js";
4948
import { createToolFsPolicy, resolveToolFsConfig } from "./tool-fs-policy.js";
5049
import {
5150
applyToolPolicyPipeline,
@@ -321,10 +320,7 @@ export function createOpenClawCodingTools(options?: {
321320
options?.exec?.scopeKey ?? options?.sessionKey ?? (agentId ? `agent:${agentId}` : undefined);
322321
const subagentPolicy =
323322
isSubagentSessionKey(options?.sessionKey) && options?.sessionKey
324-
? resolveSubagentToolPolicy(
325-
options.config,
326-
getSubagentDepthFromSessionStore(options.sessionKey, { cfg: options.config }),
327-
)
323+
? resolveSubagentToolPolicyForSession(options.config, options.sessionKey)
328324
: undefined;
329325
const allowBackground = isToolAllowedByPolicies("process", [
330326
profilePolicyWithAlsoAllow,

0 commit comments

Comments
 (0)