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 dc669a9c29..c2f79b75a4 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java +++ b/agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java @@ -185,6 +185,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; @@ -6741,6 +6742,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; @@ -6887,6 +6889,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); @@ -7042,6 +7045,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. * @@ -7675,7 +7696,24 @@ 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)); + } else { + log.warn( + "Hook-contributed tool '{}' was rejected by hookToolFilter and" + + " will not be installed.", + toolName); + } + } + } if (enableMetaTool) { agentToolkit.registerMetaTool(); 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/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..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; @@ -180,4 +184,83 @@ public List tools() { assertNotNull(agent.getToolkit()); }); } + + @Test + @DisplayName("hookToolFilter drops rejected contributions before registration") + void hookToolFilterDropsRejectedContributions() { + 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() { + @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. + 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")); + assertFalse(agent.getToolkit().getToolNames().contains("hook_annotated_drop")); + } } 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 c6915f93d7..f1bd54eee1 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 @@ -1579,6 +1579,7 @@ public Builder contextPolicy(ContextPolicy policy) { String planFileDir = PlanModeManager.DEFAULT_PLAN_DIR; ToolsConfig toolsConfigOverride; + McpServerRegistrationListener mcpServerRegistrationListener; SandboxFilesystemSpec sandboxFilesystemSpec; @@ -3514,6 +3515,11 @@ && isLocalSession(effectiveSession)) { // ---- Build inner ReActAgent ---- inner.middleware(new HarnessToolBindings(Collections.unmodifiableMap(frameworkTools))); inner.toolkit(agentToolkit); + // 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 9505603889..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 @@ -464,6 +464,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; @@ -624,6 +625,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 ac318aae4d..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 @@ -16,13 +16,20 @@ package io.agentscope.harness.agent; 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.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -30,6 +37,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import reactor.core.publisher.Mono; class ManagedSubagentBoundaryTest { @TempDir Path workspace; @@ -147,4 +155,317 @@ void childCannotReenableParentDeniedTool() { .create(RuntimeContext.empty()); 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); + 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"); + } + + @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"); + } + + @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)) + .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"; + } + } } diff --git a/docs/dev/en/docs/harness/subagent.md b/docs/dev/en/docs/harness/subagent.md index 0d3fe4ee69..3cc66acd35 100644 --- a/docs/dev/en/docs/harness/subagent.md +++ b/docs/dev/en/docs/harness/subagent.md @@ -106,6 +106,14 @@ 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 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. ### Built-in `general-purpose` diff --git a/docs/dev/zh/docs/harness/subagent.md b/docs/dev/zh/docs/harness/subagent.md index 176485177a..cc040a17c7 100644 --- a/docs/dev/zh/docs/harness/subagent.md +++ b/docs/dev/zh/docs/harness/subagent.md @@ -104,6 +104,8 @@ HarnessAgent.builder() 也适用于从失败会话中重新加载的工具调用。等待人工审批的工具仍须提供审批结果;空输入恢复执行、 调用方补交工具结果的行为保持原有语义。远端 agent 和自定义工厂需自行配置恢复策略。 +框架自动构建的本地声明子 agent 还会继承父级显式配置的 `Hook` 实例,使用同一实例且优先级顺序不变。因此 hook 也会收到子 agent 的事件:实现需支持重入,并按 agent 或 session 身份隔离可变状态。hook 通过 `Hook.tools()` 贡献的工具始终会按 agent 生效的 `ToolsConfig` 过滤——根 agent、`general-purpose` 和声明子 agent 都是如此。对声明子 agent 而言,该生效配置同时包含声明的 `tools:` 白名单,因此 hook 无法重新启用父级禁用或声明排除的工具。 + 框架自动构建的本地子 Agent 也继承父级 `disableWebTools()` 配置。默认工厂和按声明构建的工厂都会应用该设置,`general-purpose` 也不例外,因此委派任务不会重新启用父级关闭的 Web 工具。若任务需要联网,应在已授权的父级配置中解决限制,而不是通过子 Agent 绕过。 ### 内置 `general-purpose`