From a716f68c691e7b080e1eea7988b09a4256046134 Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Tue, 24 Nov 2026 22:14:16 +0800 Subject: [PATCH 1/8] fix(harness): inherit parent hooks for declared subagents Declared subagents (workspace subagents/*.md and programmatic SubagentDeclaration) are built through buildDeclaredFactory, which forwarded the parent's middlewares but not its hooks. The general-purpose subagent factory already propagates b.hooks, so the two paths were inconsistent: hooks configured on the parent for tool governance, human-in-the-loop approval, audit, or budget were silently dropped for declared subagents. Capture b.hooks in buildDeclaredFactory and apply them to the child builder alongside the middlewares, mirroring buildGeneralPurposeFactory. Fixes #1578 --- .../agent/HarnessAgentBuilderSupport.java | 2 ++ .../agent/ManagedSubagentBoundaryTest.java | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java index 0cf2321e3b..d6a29624dc 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java @@ -455,6 +455,7 @@ static SubagentFactory buildDeclaredFactory( b.toolkit != null ? b.toolkit.copy() : HarnessAgent.Builder.newDefaultToolkit(); final Function capturedResolver = b.modelResolver; final List capturedMiddlewares = List.copyOf(b.middlewares); + final List capturedHooks = List.copyOf(b.hooks); final AbstractFilesystem capturedSharedBackend = sandboxFs != null ? sandboxFs : b.abstractFilesystem; final MemoryConfig capturedMemoryConfig = b.memoryConfig; @@ -609,6 +610,7 @@ static SubagentFactory buildDeclaredFactory( } sub.middlewares(capturedMiddlewares); + sub.hooks(capturedHooks); return sub.build(); }; } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java index 4c261dd9f2..fb071ba51a 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java @@ -16,6 +16,7 @@ package io.agentscope.harness.agent; import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.hook.Hook; import io.agentscope.core.model.Model; import io.agentscope.harness.agent.filesystem.spec.LocalFilesystemSpec; import io.agentscope.harness.agent.subagent.SubagentDeclaration; @@ -80,4 +81,29 @@ void childCannotReenableParentDeniedTool() { .create(RuntimeContext.empty()); Assertions.assertTrue(child.getToolkit().getToolNames().isEmpty()); } + + @Test + void declaredSubagentInheritsParentHooks() { + Hook hook = Mockito.mock(Hook.class); + var parent = + HarnessAgent.builder() + .model(Mockito.mock(Model.class)) + .workspace(workspace) + .filesystem(new LocalFilesystemSpec()) + .hook(hook); + var declaration = + SubagentDeclaration.builder() + .name("reader") + .description("read only") + .inlineAgentsBody("read only") + .build(); + var child = + (HarnessAgent) + HarnessAgentBuilderSupport.buildDeclaredFactory( + parent, declaration, workspace, null) + .create(RuntimeContext.empty()); + Assertions.assertTrue( + child.getDelegate().getHooks().contains(hook), + "declared subagent should inherit the parent agent's hooks"); + } } From 644fbeb9b0ade16b8e06c7253bacea6edce67114 Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Sun, 29 Nov 2026 20:39:02 +0800 Subject: [PATCH 2/8] feat(core): add build-time filter for hook-contributed tools Hook.tools() contributions are installed while the agent is built, after callers have assembled the toolkit, so there is no way to keep a specific contribution out before registration. Add ReActAgent.Builder.hookToolFilter(Predicate). When set, hook contributions are resolved into a throwaway toolkit first and only the accepted names are registered on the agent toolkit. A rejected contribution never registers, so it cannot displace an existing tool with the same name. HookToolsRegistrationTest covers AgentTool and annotated @Tool contributions, rejected names, and same-name preservation. --- .../java/io/agentscope/core/ReActAgent.java | 35 +++++++- .../hook/HookToolsRegistrationTest.java | 81 +++++++++++++++++++ 2 files changed, 115 insertions(+), 1 deletion(-) diff --git a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java index 6001cf8373..02ee8a4d3e 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java +++ b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java @@ -182,6 +182,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.slf4j.Logger; @@ -6583,6 +6584,7 @@ public Builder threadJournalStore(ThreadJournalStore store) { GenerateOptions generateOptions; private boolean validateStructuredOutput = true; final Set hooks = new LinkedHashSet<>(); + private Predicate hookToolFilter; private final List middlewares = new ArrayList<>(); private ModelRequestPreparer modelRequestPreparer; private ActionObserver actionObserver; @@ -6729,6 +6731,7 @@ public synchronized Builder copy() { copy.skillCodeExecutionEnabled = this.skillCodeExecutionEnabled; copy.skillWorkDir = this.skillWorkDir; copy.hooks.addAll(this.hooks); + copy.hookToolFilter = this.hookToolFilter; copy.middlewares.addAll(this.middlewares); copy.knowledgeBases.addAll(this.knowledgeBases); copy.skillRepositories.addAll(this.skillRepositories); @@ -6884,6 +6887,24 @@ public Builder hooks(List hooks) { return this; } + /** + * Sets a construction-time filter for tools contributed by hooks. + * + *

The predicate receives the resolved public name of each {@link Hook#tools()} + * contribution. Returning {@code true} installs the tool; {@code false} drops it before + * registration. Only hook contributions are tested — tools already on the toolkit and + * tools installed separately by the builder are unaffected. A dropped contribution leaves + * an existing same-name tool untouched. By default no filter is applied. + * + * @param hookToolFilter non-null predicate selecting hook-contributed tool names + * @return this builder instance for method chaining + * @throws NullPointerException if the predicate is null + */ + public Builder hookToolFilter(Predicate hookToolFilter) { + this.hookToolFilter = Objects.requireNonNull(hookToolFilter, "hookToolFilter"); + return this; + } + /** * Adds a middleware for intercepting agent execution. * @@ -7517,7 +7538,19 @@ private ReActAgent buildInstance() { // Request-specific visibility is composed at execution time, without copying. Toolkit agentToolkit = this.toolkit.copy(); - registerToolsFromHooks(agentToolkit); + if (hookToolFilter == null) { + registerToolsFromHooks(agentToolkit); + } else { + // Resolve contributions in a throwaway toolkit so rejected names are never + // registered; a rejected contribution cannot displace an existing tool. + Toolkit hookTools = new Toolkit(); + registerToolsFromHooks(hookTools); + for (String toolName : hookTools.getToolNames().stream().sorted().toList()) { + if (hookToolFilter.test(toolName)) { + agentToolkit.registerAgentTool(hookTools.getTool(toolName)); + } + } + } if (enableMetaTool) { agentToolkit.registerMetaTool(); diff --git a/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java b/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java index 8ccc1b6874..aeddad51d1 100644 --- a/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java +++ b/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java @@ -180,4 +180,85 @@ public List tools() { assertNotNull(agent.getToolkit()); }); } + + @Test + @DisplayName("hookToolFilter drops rejected contributions before registration") + void hookToolFilterDropsRejectedContributions() { + AgentTool keep = org.mockito.Mockito.mock(AgentTool.class); + org.mockito.Mockito.when(keep.getName()).thenReturn("hook_keep"); + AgentTool drop = org.mockito.Mockito.mock(AgentTool.class); + org.mockito.Mockito.when(drop.getName()).thenReturn("hook_drop"); + AgentTool existing = org.mockito.Mockito.mock(AgentTool.class); + org.mockito.Mockito.when(existing.getName()).thenReturn("hook_drop"); + + Hook hook = + new Hook() { + @Override + public Mono onEvent(T event) { + return Mono.just(event); + } + + @Override + public List tools() { + return List.of(keep, drop); + } + }; + + Toolkit builderToolkit = new Toolkit(); + builderToolkit.registerAgentTool(existing); + ReActAgent agent = + ReActAgent.builder() + .name("a") + .model(model) + .toolkit(builderToolkit) + .hook(hook) + .hookToolFilter(name -> name.equals("hook_keep")) + .build(); + + assertNotNull(agent.getToolkit().getTool("hook_keep")); + // A rejected contribution must not displace an existing same-name tool. + org.junit.jupiter.api.Assertions.assertSame( + existing, agent.getToolkit().getTool("hook_drop")); + } + + @Test + @DisplayName("hookToolFilter receives resolved @Tool annotation names") + void hookToolFilterUsesAnnotatedToolName() { + class Pojo { + @Tool(name = "hook_annotated_keep") + public String keep() { + return "ok"; + } + + @Tool(name = "hook_annotated_drop") + public String drop() { + return "ok"; + } + } + + Hook hook = + new Hook() { + @Override + public Mono onEvent(T event) { + return Mono.just(event); + } + + @Override + public List tools() { + return List.of(new Pojo()); + } + }; + + ReActAgent agent = + ReActAgent.builder() + .name("a") + .model(model) + .hook(hook) + .hookToolFilter(name -> name.equals("hook_annotated_keep")) + .build(); + + assertTrue(agent.getToolkit().getToolNames().contains("hook_annotated_keep")); + org.junit.jupiter.api.Assertions.assertFalse( + agent.getToolkit().getToolNames().contains("hook_annotated_drop")); + } } From 20498b2d3ba24e053a92d2967dac42aed25396ae Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Sun, 29 Nov 2026 20:39:02 +0800 Subject: [PATCH 3/8] fix(harness): constrain inherited hook tools in declared subagents Declared subagents inherit the parent's hooks, but their Hook.tools() contributions were installed after ToolFilter.apply had narrowed the toolkit, so an inherited hook could re-enable a tool the parent denied or the declaration excluded. Set a hook tool filter on declared children that requires both the declaration allowlist and the effective child ToolsConfig. Add regression coverage for the denied-tool probe, allowlist boundaries, a parent deny without a declaration allowlist, a declared-but-denied tool, the no-policy case, annotated @Tool contributions, multiple hooks, and the unchanged general-purpose path. --- .../harness/agent/HarnessAgent.java | 29 ++ .../agent/HarnessAgentBuilderSupport.java | 3 + .../agent/ManagedSubagentBoundaryTest.java | 265 ++++++++++++++++++ 3 files changed, 297 insertions(+) diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java index ab8157ef6c..fb6f9715e9 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java @@ -1675,6 +1675,14 @@ public Builder contextPolicy(ContextPolicy policy) { String planFileDir = PlanModeManager.DEFAULT_PLAN_DIR; ToolsConfig toolsConfigOverride; + + /** + * Declaration tool allowlist for an automatically constructed declared child. When + * non-null, hook-contributed tools must also satisfy the child's effective tool policy; + * without it hook contributions register normally. + */ + List inheritedHookToolAllowlist; + McpServerRegistrationListener mcpServerRegistrationListener; SandboxFilesystemSpec sandboxFilesystemSpec; @@ -2040,6 +2048,16 @@ public Builder hooks(List hooks) { return this; } + /** + * Restricts inherited hook-contributed tools to {@code allowlist} and the child's + * effective tool policy. Internal: used by {@code buildDeclaredFactory} so inherited hooks + * cannot re-enable tools the declaration or the parent's config removed. + */ + Builder inheritedHookToolAllowlist(List allowlist) { + this.inheritedHookToolAllowlist = allowlist; + return this; + } + public Builder middleware(MiddlewareBase middleware) { if (middleware != null) { middlewares.add(middleware); @@ -3548,6 +3566,17 @@ && isLocalSession(effectiveSession)) { // ---- Build inner ReActAgent ---- inner.middleware(new HarnessToolBindings(Collections.unmodifiableMap(frameworkTools))); inner.toolkit(agentToolkit); + if (inheritedHookToolAllowlist != null) { + List hookToolAllowlist = inheritedHookToolAllowlist; + ToolsConfig hookToolPolicy = resolvedToolsConfig; + // Filter before installation so inherited hooks cannot re-enable tools that the + // declaration allowlist or the child's effective tool policy removed. + inner.hookToolFilter( + toolName -> + (hookToolAllowlist.isEmpty() + || hookToolAllowlist.contains(toolName)) + && ToolFilter.isAllowed(toolName, hookToolPolicy)); + } ReActAgent delegate = inner.build(); // Core adds tools during build; finish ownership before exposing the agent. captureFrameworkTools(delegate.getToolkit(), coreInheritedNames, frameworkTools); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java index d6a29624dc..86edfbe22c 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java @@ -611,6 +611,9 @@ static SubagentFactory buildDeclaredFactory( sub.middlewares(capturedMiddlewares); sub.hooks(capturedHooks); + // Inherited hooks may contribute tools; keep them inside the declaration allowlist + // and the child's effective tool policy instead of letting them bypass it. + sub.inheritedHookToolAllowlist(decl.getTools()); return sub.build(); }; } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java index fb071ba51a..0c853cf43d 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java @@ -17,16 +17,24 @@ import io.agentscope.core.agent.RuntimeContext; import io.agentscope.core.hook.Hook; +import io.agentscope.core.hook.HookEvent; +import io.agentscope.core.message.ToolResultBlock; import io.agentscope.core.model.Model; +import io.agentscope.core.tool.AgentTool; +import io.agentscope.core.tool.Tool; +import io.agentscope.core.tool.ToolCallParam; import io.agentscope.harness.agent.filesystem.spec.LocalFilesystemSpec; import io.agentscope.harness.agent.subagent.SubagentDeclaration; import io.agentscope.harness.agent.tools.ToolsConfig; import java.nio.file.Path; import java.util.List; +import java.util.Map; +import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; +import reactor.core.publisher.Mono; class ManagedSubagentBoundaryTest { @TempDir Path workspace; @@ -82,6 +90,73 @@ void childCannotReenableParentDeniedTool() { Assertions.assertTrue(child.getToolkit().getToolNames().isEmpty()); } + @Test + void declaredSubagentDoesNotInstallRejectedHookTools() { + var cfg = new ToolsConfig(); + cfg.setDeny(List.of("execute")); + AgentTool executeTool = + new AgentTool() { + @Override + public String getName() { + return "execute"; + } + + @Override + public String getDescription() { + return "parent-denied tool contributed by a hook"; + } + + @Override + public Map getParameters() { + return Map.of( + "type", "object", + "properties", Map.of(), + "required", List.of()); + } + + @Override + public Mono callAsync(ToolCallParam param) { + return Mono.just(ToolResultBlock.text("ok")); + } + }; + Hook hook = + new Hook() { + @Override + public Mono onEvent(T event) { + return Mono.just(event); + } + + @Override + public List tools() { + return List.of(executeTool); + } + }; + var parent = + HarnessAgent.builder() + .model(Mockito.mock(Model.class)) + .workspace(workspace) + .filesystem(new LocalFilesystemSpec()) + .toolsConfig(cfg) + .hook(hook); + var declaration = + SubagentDeclaration.builder() + .name("reader") + .description("read only") + .inlineAgentsBody("read only") + .tools(List.of("read_file")) + .build(); + var child = + (HarnessAgent) + HarnessAgentBuilderSupport.buildDeclaredFactory( + parent, declaration, workspace, null) + .create(RuntimeContext.empty()); + Set names = child.getToolkit().getToolNames(); + Assertions.assertFalse( + names.contains("execute"), + "declared child must not install hook tools outside the declaration policy"); + Assertions.assertTrue(names.contains("read_file")); + } + @Test void declaredSubagentInheritsParentHooks() { Hook hook = Mockito.mock(Hook.class); @@ -106,4 +181,194 @@ void declaredSubagentInheritsParentHooks() { child.getDelegate().getHooks().contains(hook), "declared subagent should inherit the parent agent's hooks"); } + + @Test + void declaredSubagentInstallsHookToolInsideDeclarationAllowlist() { + Hook hook = hookContributing(tool("hook_extra")); + var parent = parentBuilder().hook(hook); + var declaration = declaration("reader").tools(List.of("read_file", "hook_extra")).build(); + + HarnessAgent child = buildDeclared(parent, declaration); + + Set names = child.getToolkit().getToolNames(); + Assertions.assertTrue( + names.contains("hook_extra"), + "a hook tool inside the declaration allowlist must be installed"); + Assertions.assertTrue(names.contains("read_file")); + } + + @Test + void declaredSubagentDropsHookToolOutsideDeclarationAllowlist() { + Hook hook = hookContributing(tool("hook_extra")); + var parent = parentBuilder().hook(hook); + var declaration = declaration("reader").tools(List.of("read_file")).build(); + + HarnessAgent child = buildDeclared(parent, declaration); + + Assertions.assertFalse( + child.getToolkit().getToolNames().contains("hook_extra"), + "a hook tool outside the declaration allowlist must be dropped"); + Assertions.assertTrue(child.getToolkit().getToolNames().contains("read_file")); + } + + @Test + void declaredSubagentAppliesParentDenyWithoutDeclarationAllowlist() { + var cfg = new ToolsConfig(); + cfg.setDeny(List.of("hook_extra")); + Hook hook = hookContributing(tool("hook_extra")); + var parent = parentBuilder().toolsConfig(cfg).hook(hook); + var declaration = declaration("reader").build(); + + HarnessAgent child = buildDeclared(parent, declaration); + + Assertions.assertFalse( + child.getToolkit().getToolNames().contains("hook_extra"), + "parent deny must apply to hook tools even without a declaration allowlist"); + } + + @Test + void declaredSubagentDropsHookToolDeniedByParentEvenWhenDeclared() { + var cfg = new ToolsConfig(); + cfg.setDeny(List.of("hook_extra")); + Hook hook = hookContributing(tool("hook_extra")); + var parent = parentBuilder().toolsConfig(cfg).hook(hook); + var declaration = declaration("reader").tools(List.of("read_file", "hook_extra")).build(); + + HarnessAgent child = buildDeclared(parent, declaration); + + Assertions.assertFalse( + child.getToolkit().getToolNames().contains("hook_extra"), + "the declaration allowlist must not override the parent's deny list"); + } + + @Test + void declaredSubagentInstallsHookToolsWhenNoToolPolicy() { + Hook hook = hookContributing(tool("hook_extra")); + var parent = parentBuilder().hook(hook); + var declaration = declaration("reader").build(); + + HarnessAgent child = buildDeclared(parent, declaration); + + Assertions.assertTrue( + child.getToolkit().getToolNames().contains("hook_extra"), + "hook tools register normally when no tool policy applies"); + } + + @Test + void declaredSubagentFiltersAnnotatedHookToolsByResolvedName() { + Hook hook = hookContributing(new AnnotatedHookTools()); + var parent = parentBuilder().hook(hook); + var declaration = + declaration("reader").tools(List.of("read_file", "hook_pojo_allowed")).build(); + + HarnessAgent child = buildDeclared(parent, declaration); + + Set names = child.getToolkit().getToolNames(); + Assertions.assertTrue(names.contains("hook_pojo_allowed")); + Assertions.assertFalse( + names.contains("hook_pojo_denied"), + "annotated hook tools must be filtered by their resolved @Tool name"); + } + + @Test + void declaredSubagentFiltersEachHookIndependently() { + Hook keep = hookContributing(tool("hook_keep")); + Hook drop = hookContributing(tool("hook_drop")); + var parent = parentBuilder().hook(keep).hook(drop); + var declaration = declaration("reader").tools(List.of("read_file", "hook_keep")).build(); + + HarnessAgent child = buildDeclared(parent, declaration); + + Set names = child.getToolkit().getToolNames(); + Assertions.assertTrue(names.contains("hook_keep")); + Assertions.assertFalse(names.contains("hook_drop")); + } + + @Test + void generalPurposeSubagentStillInstallsHookTools() { + Hook hook = hookContributing(tool("hook_extra")); + var parent = parentBuilder().hook(hook); + + HarnessAgent child = + (HarnessAgent) + HarnessAgentBuilderSupport.buildGeneralPurposeFactory( + parent, workspace, null) + .create(RuntimeContext.empty()); + + Assertions.assertTrue( + child.getToolkit().getToolNames().contains("hook_extra"), + "hook tool filtering must not change the general-purpose subagent path"); + } + + private HarnessAgent.Builder parentBuilder() { + return HarnessAgent.builder() + .model(Mockito.mock(Model.class)) + .workspace(workspace) + .filesystem(new LocalFilesystemSpec()); + } + + private HarnessAgent buildDeclared( + HarnessAgent.Builder parent, SubagentDeclaration declaration) { + return (HarnessAgent) + HarnessAgentBuilderSupport.buildDeclaredFactory( + parent, declaration, workspace, null) + .create(RuntimeContext.empty()); + } + + private static SubagentDeclaration.Builder declaration(String name) { + return SubagentDeclaration.builder() + .name(name) + .description(name + " subagent") + .inlineAgentsBody(name + " body"); + } + + private static Hook hookContributing(Object... contributions) { + return new Hook() { + @Override + public Mono onEvent(T event) { + return Mono.just(event); + } + + @Override + public List tools() { + return List.of(contributions); + } + }; + } + + private static AgentTool tool(String name) { + return new AgentTool() { + @Override + public String getName() { + return name; + } + + @Override + public String getDescription() { + return name + " tool"; + } + + @Override + public Map getParameters() { + return Map.of("type", "object", "properties", Map.of(), "required", List.of()); + } + + @Override + public Mono callAsync(ToolCallParam param) { + return Mono.just(ToolResultBlock.text("ok")); + } + }; + } + + static class AnnotatedHookTools { + @Tool(name = "hook_pojo_allowed") + public String allowed() { + return "ok"; + } + + @Tool(name = "hook_pojo_denied") + public String denied() { + return "ok"; + } + } } From ab91a21819ab702218e0d46de891c613485b57d5 Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Sun, 29 Nov 2026 20:39:02 +0800 Subject: [PATCH 4/8] docs: document declared subagent hook inheritance - Hook: document that automatically constructed subagents share the same instances, the resulting reentrancy and agent-scoped state requirements, and that tools() may be resolved more than once. - harness subagent pages (EN/ZH): note hook inheritance and that hook-contributed tools remain bounded by the declaration allowlist and the child's effective ToolsConfig. --- .../src/main/java/io/agentscope/core/hook/Hook.java | 10 ++++++++++ docs/dev/en/docs/harness/subagent.md | 7 +++++++ docs/dev/zh/docs/harness/subagent.md | 5 +++++ 3 files changed, 22 insertions(+) diff --git a/agentscope-core/src/main/java/io/agentscope/core/hook/Hook.java b/agentscope-core/src/main/java/io/agentscope/core/hook/Hook.java index 5cad598a63..2ee77258b7 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/hook/Hook.java +++ b/agentscope-core/src/main/java/io/agentscope/core/hook/Hook.java @@ -31,6 +31,12 @@ *

Hook Priority: Hooks are executed in priority order (lower value = higher priority). * Default priority is 100. Hooks with the same priority execute in registration order. * + *

Shared instances: Harness automatically constructed subagents inherit the parent's + * explicitly configured Hook instances, so one instance can receive concurrent events from the + * parent and its children. Implementations must be reentrant, scope mutable state by agent or + * session identity, and resolve the emitting agent from {@link HookEvent#getAgent()} rather than + * capture a single owner. A parent-only hook should skip events from other agent IDs. + * *

Event Modifiability: Whether an event is modifiable is indicated by the presence of * setter methods: *

    @@ -161,6 +167,10 @@ public interface Hook { *

    Return {@link AgentTool} instances and/or objects that declare {@code @Tool} methods. * The default implementation returns an empty list so existing hooks need no change. * + *

    Contributions may be resolved more than once, for example when a subagent filters them + * during construction. Return plain value objects with no registration-time resource + * ownership or one-shot binding to a toolkit; manage external resources separately. + * *

    If this method returns {@code null}, it is treated as an empty list. * * @return tool instances to register for this hook (may be immutable) diff --git a/docs/dev/en/docs/harness/subagent.md b/docs/dev/en/docs/harness/subagent.md index 4f13770f21..0cec2dc16b 100644 --- a/docs/dev/en/docs/harness/subagent.md +++ b/docs/dev/en/docs/harness/subagent.md @@ -104,6 +104,13 @@ results, including calls loaded from a failed session. Pending permission confir require confirmation; empty-input resume and caller-supplied tool results retain their existing behavior. Remote agents and custom factories configure recovery themselves. +Automatically built local declared subagents also inherit the parent's explicitly configured +`Hook` instances, using the same instances and priority ordering. Hooks therefore receive child +events: implement them reentrantly and scope mutable state by agent or session identity. Tools +contributed by an inherited hook (`Hook.tools()`) remain constrained by the declaration's `tools:` +allowlist and the child's effective `ToolsConfig`, so a hook cannot re-enable a tool the parent +denied or the declaration excluded. + ### Built-in `general-purpose` No spec file needed; always available. Its role is "generic fallback" — it mirrors the parent's capability (same model, tools, skills) and shares the parent's workspace. Useful when the parent wants to isolate context for a sub-task without writing a dedicated spec. diff --git a/docs/dev/zh/docs/harness/subagent.md b/docs/dev/zh/docs/harness/subagent.md index 565554c5c4..ce056da1c7 100644 --- a/docs/dev/zh/docs/harness/subagent.md +++ b/docs/dev/zh/docs/harness/subagent.md @@ -102,6 +102,11 @@ HarnessAgent.builder() 也适用于从失败会话中重新加载的工具调用。等待人工审批的工具仍须提供审批结果;空输入恢复执行、 调用方补交工具结果的行为保持原有语义。远端 agent 和自定义工厂需自行配置恢复策略。 +框架自动构建的本地声明子 agent 还会继承父级显式配置的 `Hook` 实例,使用同一实例且优先级顺序 +不变。因此 hook 也会收到子 agent 的事件:实现需支持重入,并按 agent 或 session 身份隔离可变 +状态。继承 hook 通过 `Hook.tools()` 贡献的工具仍受声明的 `tools:` 白名单和子 agent 生效的 +`ToolsConfig` 约束,hook 无法重新启用父级禁用或声明排除的工具。 + ### 内置 `general-purpose` 不需要写声明文件,总是可用。它的角色是"通用兜底"——能力和主 agent 一致(同样的模型、工具、技能),共享主工作区。适合"主 agent 想隔离上下文跑一个子任务但又懒得专门写 spec"。 From 923f6e81e5ca2146d355cff8e6b18a41181834ed Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Mon, 30 Nov 2026 13:43:30 +0800 Subject: [PATCH 5/8] refactor(core): log dropped hook-contributed tools When hookToolFilter rejects a contribution, the tool is silently absent from the built agent. Log the dropped name at WARN, matching the diagnostics ToolFilter.warnUnknown provides for unmatched tools.json entries. --- .../src/main/java/io/agentscope/core/ReActAgent.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java index 8abfc6cc82..8b1624275b 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java +++ b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java @@ -7665,6 +7665,11 @@ private ReActAgent buildInstance() { for (String toolName : hookTools.getToolNames().stream().sorted().toList()) { if (hookToolFilter.test(toolName)) { agentToolkit.registerAgentTool(hookTools.getTool(toolName)); + } else { + log.warn( + "Hook-contributed tool '{}' was rejected by hookToolFilter and" + + " will not be installed.", + toolName); } } } From bb508e2e7a1ee5fa98d266bb0796f878071a8bce Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Mon, 30 Nov 2026 13:43:30 +0800 Subject: [PATCH 6/8] test(core): use static imports in hook tool filter tests Match the existing static imports in HookToolsRegistrationTest instead of fully-qualified Mockito and Assertions references. --- .../hook/HookToolsRegistrationTest.java | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java b/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java index aeddad51d1..0761eb6f9a 100644 --- a/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java +++ b/agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java @@ -16,8 +16,12 @@ package io.agentscope.core.legacy.hook; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import io.agentscope.core.ReActAgent; import io.agentscope.core.agent.test.MockModel; @@ -184,12 +188,12 @@ public List tools() { @Test @DisplayName("hookToolFilter drops rejected contributions before registration") void hookToolFilterDropsRejectedContributions() { - AgentTool keep = org.mockito.Mockito.mock(AgentTool.class); - org.mockito.Mockito.when(keep.getName()).thenReturn("hook_keep"); - AgentTool drop = org.mockito.Mockito.mock(AgentTool.class); - org.mockito.Mockito.when(drop.getName()).thenReturn("hook_drop"); - AgentTool existing = org.mockito.Mockito.mock(AgentTool.class); - org.mockito.Mockito.when(existing.getName()).thenReturn("hook_drop"); + AgentTool keep = mock(AgentTool.class); + when(keep.getName()).thenReturn("hook_keep"); + AgentTool drop = mock(AgentTool.class); + when(drop.getName()).thenReturn("hook_drop"); + AgentTool existing = mock(AgentTool.class); + when(existing.getName()).thenReturn("hook_drop"); Hook hook = new Hook() { @@ -217,8 +221,7 @@ public List tools() { assertNotNull(agent.getToolkit().getTool("hook_keep")); // A rejected contribution must not displace an existing same-name tool. - org.junit.jupiter.api.Assertions.assertSame( - existing, agent.getToolkit().getTool("hook_drop")); + assertSame(existing, agent.getToolkit().getTool("hook_drop")); } @Test @@ -258,7 +261,6 @@ public List tools() { .build(); assertTrue(agent.getToolkit().getToolNames().contains("hook_annotated_keep")); - org.junit.jupiter.api.Assertions.assertFalse( - agent.getToolkit().getToolNames().contains("hook_annotated_drop")); + assertFalse(agent.getToolkit().getToolNames().contains("hook_annotated_drop")); } } From bfaecdf0f15bd611be3f047bbe04f57c5d5513ea Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Mon, 30 Nov 2026 13:43:30 +0800 Subject: [PATCH 7/8] fix(harness): apply hook tool policy to all agents Hook.tools() contributions were filtered only for declared children, so the general-purpose subagent and the root agent could still install a tool the effective ToolsConfig denied. They register after ToolFilter.apply, so the deny list never saw them. childToolsConfig already folds the declaration allowlist into the child's strict ToolsConfig, so the extra allowlist condition was redundant. Apply one predicate in HarnessAgent.buildInstance for every build: toolName -> ToolFilter.isAllowed(toolName, resolvedToolsConfig) A null config allows every contribution, preserving configs that define no tool policy. Remove the per-call-site inheritedHookToolAllowlist field, setter, and factory call. Regression coverage: general-purpose and root agents now drop a denied hook tool; the no-policy general-purpose case still installs it. --- .../harness/agent/HarnessAgent.java | 33 +++---------------- .../agent/HarnessAgentBuilderSupport.java | 3 -- .../agent/ManagedSubagentBoundaryTest.java | 31 +++++++++++++++++ 3 files changed, 36 insertions(+), 31 deletions(-) diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java index 121944d4b5..fe21d930d4 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java @@ -1580,13 +1580,6 @@ public Builder contextPolicy(ContextPolicy policy) { ToolsConfig toolsConfigOverride; - /** - * Declaration tool allowlist for an automatically constructed declared child. When - * non-null, hook-contributed tools must also satisfy the child's effective tool policy; - * without it hook contributions register normally. - */ - List inheritedHookToolAllowlist; - McpServerRegistrationListener mcpServerRegistrationListener; SandboxFilesystemSpec sandboxFilesystemSpec; @@ -1955,16 +1948,6 @@ public Builder hooks(List hooks) { return this; } - /** - * Restricts inherited hook-contributed tools to {@code allowlist} and the child's - * effective tool policy. Internal: used by {@code buildDeclaredFactory} so inherited hooks - * cannot re-enable tools the declaration or the parent's config removed. - */ - Builder inheritedHookToolAllowlist(List allowlist) { - this.inheritedHookToolAllowlist = allowlist; - return this; - } - public Builder middleware(MiddlewareBase middleware) { if (middleware != null) { middlewares.add(middleware); @@ -3496,17 +3479,11 @@ && isLocalSession(effectiveSession)) { // ---- Build inner ReActAgent ---- inner.middleware(new HarnessToolBindings(Collections.unmodifiableMap(frameworkTools))); inner.toolkit(agentToolkit); - if (inheritedHookToolAllowlist != null) { - List hookToolAllowlist = inheritedHookToolAllowlist; - ToolsConfig hookToolPolicy = resolvedToolsConfig; - // Filter before installation so inherited hooks cannot re-enable tools that the - // declaration allowlist or the child's effective tool policy removed. - inner.hookToolFilter( - toolName -> - (hookToolAllowlist.isEmpty() - || hookToolAllowlist.contains(toolName)) - && ToolFilter.isAllowed(toolName, hookToolPolicy)); - } + // Filter hook contributions before installation so no agent path can re-enable a + // tool the effective policy removed: root agent, general-purpose, and declared + // children all share one predicate. A null config allows every contribution. + ToolsConfig hookToolPolicy = resolvedToolsConfig; + inner.hookToolFilter(toolName -> ToolFilter.isAllowed(toolName, hookToolPolicy)); ReActAgent delegate = inner.build(); // Core adds tools during build; finish ownership before exposing the agent. captureFrameworkTools(delegate.getToolkit(), coreInheritedNames, frameworkTools); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java index e5765128c4..73066013a4 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java @@ -626,9 +626,6 @@ static SubagentFactory buildDeclaredFactory( sub.middlewares(capturedMiddlewares); sub.hooks(capturedHooks); - // Inherited hooks may contribute tools; keep them inside the declaration allowlist - // and the child's effective tool policy instead of letting them bypass it. - sub.inheritedHookToolAllowlist(decl.getTools()); return sub.build(); }; } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java index 5700f25803..5c84c72e32 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/ManagedSubagentBoundaryTest.java @@ -366,6 +366,37 @@ void generalPurposeSubagentStillInstallsHookTools() { "hook tool filtering must not change the general-purpose subagent path"); } + @Test + void generalPurposeSubagentDropsDeniedHookTool() { + var cfg = new ToolsConfig(); + cfg.setDeny(List.of("hook_extra")); + Hook hook = hookContributing(tool("hook_extra")); + var parent = parentBuilder().toolsConfig(cfg).hook(hook); + + HarnessAgent child = + (HarnessAgent) + HarnessAgentBuilderSupport.buildGeneralPurposeFactory( + parent, workspace, null) + .create(RuntimeContext.empty()); + + Assertions.assertFalse( + child.getToolkit().getToolNames().contains("hook_extra"), + "general-purpose must not re-enable a parent-denied hook tool"); + } + + @Test + void rootAgentDropsDeniedHookTool() { + var cfg = new ToolsConfig(); + cfg.setDeny(List.of("hook_extra")); + Hook hook = hookContributing(tool("hook_extra")); + + HarnessAgent root = parentBuilder().toolsConfig(cfg).hook(hook).build(); + + Assertions.assertFalse( + root.getToolkit().getToolNames().contains("hook_extra"), + "the root agent must not install a hook tool the effective policy denies"); + } + private HarnessAgent.Builder parentBuilder() { return HarnessAgent.builder() .model(Mockito.mock(Model.class)) From a1b9590aeee32077782220869732521f2b52cb35 Mon Sep 17 00:00:00 2001 From: ZhangHaonan <1481929167@qq.com> Date: Mon, 30 Nov 2026 13:43:30 +0800 Subject: [PATCH 8/8] docs: generalize hook tool policy wording Hook-contributed tools are now filtered for the root agent and general-purpose as well, not only declared children. Describe the behavior by the effective ToolsConfig and note that declared children also encode the declaration allowlist in it. --- docs/dev/en/docs/harness/subagent.md | 7 ++++--- docs/dev/zh/docs/harness/subagent.md | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/dev/en/docs/harness/subagent.md b/docs/dev/en/docs/harness/subagent.md index a185b63bb6..ad673dbc1a 100644 --- a/docs/dev/en/docs/harness/subagent.md +++ b/docs/dev/en/docs/harness/subagent.md @@ -109,9 +109,10 @@ behavior. Remote agents and custom factories configure recovery themselves. Automatically built local declared subagents also inherit the parent's explicitly configured `Hook` instances, using the same instances and priority ordering. Hooks therefore receive child events: implement them reentrantly and scope mutable state by agent or session identity. Tools -contributed by an inherited hook (`Hook.tools()`) remain constrained by the declaration's `tools:` -allowlist and the child's effective `ToolsConfig`, so a hook cannot re-enable a tool the parent -denied or the declaration excluded. +contributed by a hook (`Hook.tools()`) are always filtered against the agent's effective +`ToolsConfig` — for the root agent, `general-purpose`, and declared children alike. For declared +children that effective config also encodes the declaration's `tools:` allowlist, so a hook cannot +re-enable a tool the parent denied or the declaration excluded. Automatically built local children also inherit the parent's `disableWebTools()` setting. Both the default factory and the declaration-aware factory apply it, including for `general-purpose`, so delegating a task does not restore web tools disabled on the parent. If the task needs web access, resolve that restriction in the authorized parent configuration instead of using a child as a workaround. diff --git a/docs/dev/zh/docs/harness/subagent.md b/docs/dev/zh/docs/harness/subagent.md index a3f4aba510..3375dfcdcc 100644 --- a/docs/dev/zh/docs/harness/subagent.md +++ b/docs/dev/zh/docs/harness/subagent.md @@ -104,7 +104,7 @@ HarnessAgent.builder() 也适用于从失败会话中重新加载的工具调用。等待人工审批的工具仍须提供审批结果;空输入恢复执行、 调用方补交工具结果的行为保持原有语义。远端 agent 和自定义工厂需自行配置恢复策略。 -框架自动构建的本地声明子 agent 还会继承父级显式配置的 `Hook` 实例,使用同一实例且优先级顺序不变。因此 hook 也会收到子 agent 的事件:实现需支持重入,并按 agent 或 session 身份隔离可变状态。继承 hook 通过 `Hook.tools()` 贡献的工具仍受声明的 `tools:` 白名单和子 agent 生效的 `ToolsConfig` 约束,hook 无法重新启用父级禁用或声明排除的工具。 +框架自动构建的本地声明子 agent 还会继承父级显式配置的 `Hook` 实例,使用同一实例且优先级顺序不变。因此 hook 也会收到子 agent 的事件:实现需支持重入,并按 agent 或 session 身份隔离可变状态。hook 通过 `Hook.tools()` 贡献的工具始终会按 agent 生效的 `ToolsConfig` 过滤——根 agent、`general-purpose` 和声明子 agent 都是如此。对声明子 agent 而言,该生效配置同时包含声明的 `tools:` 白名单,因此 hook 无法重新启用父级禁用或声明排除的工具。 框架自动构建的本地子 Agent 也继承父级 `disableWebTools()` 配置。默认工厂和按声明构建的工厂都会应用该设置,`general-purpose` 也不例外,因此委派任务不会重新启用父级关闭的 Web 工具。若任务需要联网,应在已授权的父级配置中解决限制,而不是通过子 Agent 绕过。