Skip to content

Commit 45224e1

Browse files
committed
fix(agent): honor interceptor tool selection and dynamic registries in standalone ReAct (issue #268)
1 parent b348353 commit 45224e1

2 files changed

Lines changed: 265 additions & 9 deletions

File tree

‎argi-agent/argi-agent-core/src/main/java/io/github/agentic/ai/agent/react/ReActAgent.java‎

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,8 @@ private void run() {
317317
for (int turn = 0; turn < maxTurns; turn++) {
318318
context.control().assertActive();
319319
ToolRegistry availableTools = resolveTools(state);
320-
ChatResponse response = modelTurn(messages, state, usage, availableTools);
320+
AtomicReference<ToolRegistry> effectiveTools = new AtomicReference<>(availableTools);
321+
ChatResponse response = modelTurn(messages, state, usage, availableTools, effectiveTools);
321322
if (response.messages().isEmpty()) {
322323
throw new IllegalStateException("Model response did not contain an assistant message");
323324
}
@@ -330,7 +331,7 @@ private void run() {
330331
return;
331332
}
332333
for (ToolCall call : response.toolCalls()) {
333-
ToolStep step = executeTool(call, messages, state, availableTools);
334+
ToolStep step = executeTool(call, messages, state, effectiveTools.get());
334335
if (step.suspension() != null) {
335336
AgentOutcome outcome = new AgentOutcome(AgentOutcome.Status.SUSPENDED, messages, state,
336337
usage.value(), step.suspension());
@@ -352,17 +353,29 @@ private ToolRegistry resolveTools(Map<String, Object> state) {
352353
}
353354
ToolRegistry dynamic = Objects.requireNonNull(dynamicToolProvider.apply(Map.copyOf(state)),
354355
"dynamic tool provider returned no registry");
355-
List<Tool> combined = new ArrayList<>(tools.tools());
356-
combined.addAll(dynamic.tools());
357-
return new ToolRegistry(combined);
356+
// Static bindings shadow same-named dynamic disclosures instead of failing the
357+
// merge (issue #268: a testable duplicate-name policy, consistent with
358+
// ModelRequest.getTools()'s distinct order).
359+
Map<String, Tool> combined = new LinkedHashMap<>();
360+
for (Tool tool : tools.tools()) {
361+
combined.put(tool.definition().name(), tool);
362+
}
363+
for (Tool tool : dynamic.tools()) {
364+
combined.putIfAbsent(tool.definition().name(), tool);
365+
}
366+
return new ToolRegistry(List.copyOf(combined.values()));
358367
}
359368

360369
private ChatResponse modelTurn(List<ChatMessage> messages, Map<String, Object> state,
361-
UsageAccumulator usage, ToolRegistry availableTools) {
370+
UsageAccumulator usage, ToolRegistry availableTools,
371+
AtomicReference<ToolRegistry> effectiveTools) {
362372
context.control().assertActive();
363373
ModelRequest request = ModelRequest.builder().messages(messages).toolRegistry(availableTools)
364374
.trustedExecutionContext(context.trusted()).context(state).attributes(state).build();
365-
ModelCallHandler handler = modelRequest -> invokeModel(modelRequest, usage);
375+
// The effective tool set is only known at the end of the interceptor chain,
376+
// where selection semantics are resolved; execution in the same turn must use
377+
// exactly the set the model was shown (issue #268: declared and executed agree).
378+
ModelCallHandler handler = modelRequest -> invokeModel(modelRequest, usage, effectiveTools);
366379
for (int index = interceptors.size() - 1; index >= 0; index--) {
367380
ModelInterceptor interceptor = interceptors.get(index);
368381
ModelCallHandler next = handler;
@@ -375,8 +388,37 @@ private ChatResponse modelTurn(List<ChatMessage> messages, Map<String, Object> s
375388
return response.getChatResponse();
376389
}
377390

378-
private ModelResponse invokeModel(ModelRequest request, UsageAccumulator usage) {
379-
ChatRequest chatRequest = new ChatRequest(request.getMessages(), request.getToolRegistry().definitions(),
391+
/**
392+
* Resolves the effective tool set at the end of the interceptor chain: static
393+
* bindings and the invocation-local dynamic registry merged (static shadows
394+
* dynamic on name conflicts, matching {@link ModelRequest#getTools()}), narrowed
395+
* by the explicit selection when one is specified. An explicit empty selection
396+
* disables all tool disclosure and execution; an absent selection uses every
397+
* binding.
398+
*/
399+
private ToolRegistry effectiveToolSet(ModelRequest request) {
400+
List<String> selection = request.hasToolSelection() ? request.getTools() : null;
401+
if (selection == null && request.getDynamicToolRegistry().tools().isEmpty()) {
402+
return request.getToolRegistry();
403+
}
404+
Map<String, Tool> effective = new LinkedHashMap<>();
405+
for (Tool tool : request.getToolRegistry().tools()) {
406+
effective.put(tool.definition().name(), tool);
407+
}
408+
for (Tool tool : request.getDynamicToolRegistry().tools()) {
409+
effective.putIfAbsent(tool.definition().name(), tool);
410+
}
411+
if (selection != null) {
412+
effective.keySet().retainAll(selection);
413+
}
414+
return new ToolRegistry(List.copyOf(effective.values()));
415+
}
416+
417+
private ModelResponse invokeModel(ModelRequest request, UsageAccumulator usage,
418+
AtomicReference<ToolRegistry> effectiveTools) {
419+
ToolRegistry effective = effectiveToolSet(request);
420+
effectiveTools.set(effective);
421+
ChatRequest chatRequest = new ChatRequest(request.getMessages(), effective.definitions(),
380422
request.getOptions(), request.getAttributes());
381423
if (streamModel) {
382424
return ModelResponse.of(collectModelStream(chatRequest, usage));

‎argi-agent/argi-agent-core/src/test/java/io/github/agentic/ai/agent/react/ReActAgentTest.java‎

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,220 @@ public void onComplete() {
165165
assertTrue(events.stream().anyMatch(event -> event instanceof AgentEvent.MessageDelta));
166166
}
167167

168+
// ------------------------------------------------------------------
169+
// issue #268: interceptor tool selection must gate disclosure AND execution
170+
// ------------------------------------------------------------------
171+
172+
@Test
173+
void unfilteredRunDisclosesStaticAndDynamicTools() throws Exception {
174+
Tool staticTool = tool("chosen", "{}", (ignored, context) ->
175+
CompletableFuture.completedFuture(ToolResult.text("static")));
176+
Tool dynamicTool = tool("dyn", "{}", (ignored, context) ->
177+
CompletableFuture.completedFuture(ToolResult.text("dynamic")));
178+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("answer"), List.of(), 1)));
179+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(staticTool)))
180+
.dynamicTools(state -> new ToolRegistry(List.of(dynamicTool))).build();
181+
182+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
183+
184+
List<String> disclosed = client.requests.get(0).tools().stream()
185+
.map(ToolDefinition::name).toList();
186+
assertEquals(List.of("chosen", "dyn"), disclosed);
187+
}
188+
189+
@Test
190+
void explicitEmptySelectionDisablesDisclosureAndExecution() throws Exception {
191+
ToolCall call = new ToolCall("call-1", "secret", "{}");
192+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("try", List.of(call)),
193+
List.of(call), 1), response(ChatMessage.assistant("blocked"), List.of(), 1)));
194+
ModelInterceptor interceptor = new ModelInterceptor() {
195+
public String getName() {
196+
return "disable-tools";
197+
}
198+
199+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
200+
return next.call(ModelRequest.builder(request).tools(List.of()).build());
201+
}
202+
};
203+
Tool secret = tool("secret", "{}", (ignored, context) ->
204+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
205+
AgentOutcome outcome = ReActAgent.builder(client).tools(new ToolRegistry(List.of(secret)))
206+
.interceptors(List.of(interceptor)).build().invoke(request(), context()).get(3, TimeUnit.SECONDS);
207+
208+
// The model sees no tools at all.
209+
assertTrue(client.requests.get(0).tools().isEmpty());
210+
// A tool call for a filtered-out tool surfaces via the unknown-tool error path.
211+
assertEquals("blocked", outcome.messages().get(outcome.messages().size() - 1).text());
212+
assertTrue(outcome.messages().stream()
213+
.anyMatch(message -> message.text().contains("Unknown tool: secret")));
214+
}
215+
216+
@Test
217+
void subsetSelectionDisclosesAndExecutesOnlyChosenTools() throws Exception {
218+
ToolCall call = new ToolCall("call-1", "chosen", "{}");
219+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("use", List.of(call)),
220+
List.of(call), 1), response(ChatMessage.assistant("done"), List.of(), 1)));
221+
ModelInterceptor interceptor = new ModelInterceptor() {
222+
public String getName() {
223+
return "subset";
224+
}
225+
226+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
227+
return next.call(ModelRequest.builder(request).tools(List.of("chosen")).build());
228+
}
229+
};
230+
Tool chosen = tool("chosen", "{}", (ignored, context) ->
231+
CompletableFuture.completedFuture(ToolResult.text("chosen result")));
232+
Tool secret = tool("secret", "{}", (ignored, context) ->
233+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
234+
AgentOutcome outcome = ReActAgent.builder(client).tools(new ToolRegistry(List.of(chosen, secret)))
235+
.interceptors(List.of(interceptor)).build().invoke(request(), context()).get(3, TimeUnit.SECONDS);
236+
237+
List<String> disclosed = client.requests.get(0).tools().stream()
238+
.map(ToolDefinition::name).toList();
239+
assertEquals(List.of("chosen"), disclosed);
240+
assertTrue(outcome.messages().stream().anyMatch(message -> "chosen result".equals(message.text())));
241+
assertTrue(outcome.messages().stream().noneMatch(message -> "leaked".equals(message.text())));
242+
}
243+
244+
@Test
245+
void dynamicToolsParticipateInSelection() throws Exception {
246+
Tool dynamic = tool("dyn", "{}", (ignored, context) ->
247+
CompletableFuture.completedFuture(ToolResult.text("dynamic result")));
248+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("answer"), List.of(), 1)));
249+
ModelInterceptor interceptor = new ModelInterceptor() {
250+
public String getName() {
251+
return "dynamic-only";
252+
}
253+
254+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
255+
return next.call(ModelRequest.builder(request).tools(List.of("dyn")).build());
256+
}
257+
};
258+
ReActAgent agent = ReActAgent.builder(client).dynamicTools(state -> new ToolRegistry(List.of(dynamic)))
259+
.interceptors(List.of(interceptor)).build();
260+
261+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
262+
263+
List<String> disclosed = client.requests.get(0).tools().stream()
264+
.map(ToolDefinition::name).toList();
265+
assertEquals(List.of("dyn"), disclosed);
266+
}
267+
268+
@Test
269+
void staticToolShadowsDynamicToolOnNameConflict() throws Exception {
270+
AtomicInteger staticExecutions = new AtomicInteger();
271+
AtomicInteger dynamicExecutions = new AtomicInteger();
272+
Tool staticTool = tool("lookup", "{}", (ignored, context) -> {
273+
staticExecutions.incrementAndGet();
274+
return CompletableFuture.completedFuture(ToolResult.text("original"));
275+
});
276+
Tool dynamicTool = tool("lookup", "{}", (ignored, context) -> {
277+
dynamicExecutions.incrementAndGet();
278+
return CompletableFuture.completedFuture(ToolResult.text("replacement"));
279+
});
280+
ToolCall call = new ToolCall("call-1", "lookup", "{}");
281+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("use", List.of(call)),
282+
List.of(call), 1), response(ChatMessage.assistant("done"), List.of(), 1)));
283+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(staticTool)))
284+
.dynamicTools(state -> new ToolRegistry(List.of(dynamicTool))).build();
285+
286+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
287+
288+
// Static bindings shadow same-named dynamic disclosures (getTools() semantics).
289+
assertEquals(1, staticExecutions.get());
290+
assertEquals(0, dynamicExecutions.get());
291+
}
292+
293+
@Test
294+
void streamingRunDisclosesTheSameFilteredSetAsNonStreaming() throws Exception {
295+
Tool secret = tool("secret", "{}", (ignored, context) ->
296+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
297+
StreamingClient client = new StreamingClient();
298+
ModelInterceptor interceptor = new ModelInterceptor() {
299+
public String getName() {
300+
return "disable-tools";
301+
}
302+
303+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
304+
return next.call(ModelRequest.builder(request).tools(List.of()).build());
305+
}
306+
};
307+
ReActAgent agent = ReActAgent.builder(client).streamModel(true).tools(new ToolRegistry(List.of(secret)))
308+
.interceptors(List.of(interceptor)).build();
309+
310+
try (AgentExecutionContext context = context()) {
311+
CompletableFuture<AgentOutcome> outcome = new CompletableFuture<>();
312+
agent.stream(request(), context).subscribe(new Flow.Subscriber<>() {
313+
public void onSubscribe(Flow.Subscription subscription) {
314+
subscription.request(Long.MAX_VALUE);
315+
}
316+
317+
public void onNext(AgentEvent event) {
318+
if (event instanceof AgentEvent.Finished finished) {
319+
outcome.complete(finished.outcome());
320+
}
321+
}
322+
323+
public void onError(Throwable error) {
324+
outcome.completeExceptionally(error);
325+
}
326+
327+
public void onComplete() {
328+
}
329+
});
330+
outcome.get(3, TimeUnit.SECONDS);
331+
}
332+
assertTrue(client.requests.get(0).tools().isEmpty());
333+
}
334+
335+
@Test
336+
void selectionDoesNotLeakAcrossSequentialRuns() throws Exception {
337+
ToolCall chosenCall = new ToolCall("call-1", "chosen", "{}");
338+
ScriptedClient client = new ScriptedClient(List.of(
339+
response(ChatMessage.assistant("use", List.of(chosenCall)), List.of(chosenCall), 1),
340+
response(ChatMessage.assistant("done"), List.of(), 1),
341+
response(ChatMessage.assistant("use", List.of(chosenCall)), List.of(chosenCall), 1),
342+
response(ChatMessage.assistant("done"), List.of(), 1)));
343+
ModelInterceptor interceptor = new ModelInterceptor() {
344+
public String getName() {
345+
return "subset";
346+
}
347+
348+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
349+
return next.call(ModelRequest.builder(request).tools(List.of("chosen")).build());
350+
}
351+
};
352+
Tool chosen = tool("chosen", "{}", (ignored, context) ->
353+
CompletableFuture.completedFuture(ToolResult.text("chosen result")));
354+
Tool secret = tool("secret", "{}", (ignored, context) ->
355+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
356+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(chosen, secret)))
357+
.interceptors(List.of(interceptor)).build();
358+
359+
AgentOutcome first = agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
360+
AgentOutcome second = agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
361+
362+
for (AgentOutcome outcome : List.of(first, second)) {
363+
assertTrue(outcome.messages().stream().anyMatch(message -> "chosen result".equals(message.text())));
364+
assertTrue(outcome.messages().stream().noneMatch(message -> "leaked".equals(message.text())));
365+
}
366+
}
367+
368+
@Test
369+
void unfilteredRunWithNoDynamicToolsKeepsRegistryFastPath() throws Exception {
370+
Tool staticTool = tool("only", "{}", (ignored, context) ->
371+
CompletableFuture.completedFuture(ToolResult.text("ok")));
372+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("answer"), List.of(), 1)));
373+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(staticTool))).build();
374+
375+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
376+
377+
List<String> disclosed = client.requests.get(0).tools().stream()
378+
.map(ToolDefinition::name).toList();
379+
assertEquals(List.of("only"), disclosed);
380+
}
381+
168382
@Test
169383
void deniedToolCanSuspendForHumanApproval() throws Exception {
170384
ToolCall call = new ToolCall("call-1", "danger", "{}");

0 commit comments

Comments
 (0)