Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,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;
Expand Down Expand Up @@ -6700,6 +6701,7 @@ public Builder threadJournalStore(ThreadJournalStore store) {
GenerateOptions generateOptions;
private boolean validateStructuredOutput = true;
final Set<Hook> hooks = new LinkedHashSet<>();
private Predicate<String> hookToolFilter;
private final List<MiddlewareBase> middlewares = new ArrayList<>();
private ModelRequestPreparer modelRequestPreparer;
private ActionObserver actionObserver;
Expand Down Expand Up @@ -6846,6 +6848,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);
Expand Down Expand Up @@ -7001,6 +7004,24 @@ public Builder hooks(List<Hook> hooks) {
return this;
}

/**
* Sets a construction-time filter for tools contributed by hooks.
*
* <p>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<String> hookToolFilter) {
this.hookToolFilter = Objects.requireNonNull(hookToolFilter, "hookToolFilter");
return this;
}

/**
* Adds a middleware for intercepting agent execution.
*
Expand Down Expand Up @@ -7634,7 +7655,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();
Expand Down
10 changes: 10 additions & 0 deletions agentscope-core/src/main/java/io/agentscope/core/hook/Hook.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@
* <p><b>Hook Priority:</b> Hooks are executed in priority order (lower value = higher priority).
* Default priority is 100. Hooks with the same priority execute in registration order.
*
* <p><b>Shared instances:</b> 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.
*
* <p><b>Event Modifiability:</b> Whether an event is modifiable is indicated by the presence of
* setter methods:
* <ul>
Expand Down Expand Up @@ -161,6 +167,10 @@ public interface Hook {
* <p>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.
*
* <p>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.
*
* <p>If this method returns {@code null}, it is treated as an empty list.
*
* @return tool instances to register for this hook (may be immutable)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,85 @@ public List<Object> 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 <T extends HookEvent> Mono<T> onEvent(T event) {
return Mono.just(event);
}

@Override
public List<Object> 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 <T extends HookEvent> Mono<T> onEvent(T event) {
return Mono.just(event);
}

@Override
public List<Object> 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"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1579,6 +1579,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<String> inheritedHookToolAllowlist;

McpServerRegistrationListener mcpServerRegistrationListener;

SandboxFilesystemSpec sandboxFilesystemSpec;
Expand Down Expand Up @@ -1947,6 +1955,16 @@ public Builder hooks(List<Hook> 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<String> allowlist) {
this.inheritedHookToolAllowlist = allowlist;
return this;
}

public Builder middleware(MiddlewareBase middleware) {
if (middleware != null) {
middlewares.add(middleware);
Expand Down Expand Up @@ -3478,6 +3496,17 @@ && isLocalSession(effectiveSession)) {
// ---- Build inner ReActAgent ----
inner.middleware(new HarnessToolBindings(Collections.unmodifiableMap(frameworkTools)));
inner.toolkit(agentToolkit);
if (inheritedHookToolAllowlist != null) {
List<String> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,7 @@ static SubagentFactory buildDeclaredFactory(
b.toolkit != null ? b.toolkit.copy() : HarnessAgent.Builder.newDefaultToolkit();
final Function<String, Model> capturedResolver = b.modelResolver;
final List<MiddlewareBase> capturedMiddlewares = List.copyOf(b.middlewares);
final List<Hook> capturedHooks = List.copyOf(b.hooks);
final AbstractFilesystem capturedSharedBackend =
sandboxFs != null ? sandboxFs : b.abstractFilesystem;
final MemoryConfig capturedMemoryConfig = b.memoryConfig;
Expand Down Expand Up @@ -624,6 +625,10 @@ 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();
};
}
Expand Down
Loading
Loading