Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
27 changes: 26 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 @@ -152,6 +152,7 @@
import io.agentscope.core.state.VersionedState;
import io.agentscope.core.tool.AgentTool;
import io.agentscope.core.tool.ToolBase;
import io.agentscope.core.tool.ToolCallOffload;
import io.agentscope.core.tool.ToolCallParam;
import io.agentscope.core.tool.ToolExecutionCallback;
import io.agentscope.core.tool.ToolExecutionContext;
Expand Down Expand Up @@ -4118,7 +4119,31 @@ private Mono<Msg> actingAtBoundary(int iter) {
actingStopRequested.compareAndSet(null, rs);
}
})
.then(Mono.defer(() -> Mono.just(resultHolder.get())));
.then(
Mono.fromSupplier(
() -> {
var results = resultHolder.get();
Set<ToolCallOffload.Key> placeholders =
rc.get(
ToolCallOffload
.PLACEHOLDER_CALLS_CONTEXT_KEY);
if (placeholders == null)
return results;
rc.put(
ToolCallOffload
.PLACEHOLDER_CALLS_CONTEXT_KEY,
null);
return results.stream()
.filter(
entry ->
!placeholders
.contains(
new ToolCallOffload
.Key(
entry
.getKey())))
.toList();
}));
})
.flatMap(
results -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright 2024-2026 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.agentscope.core.tool;

import io.agentscope.core.message.ToolResultBlock;
import io.agentscope.core.message.ToolUseBlock;
import reactor.core.publisher.Mono;

/** An application-owned handoff for one approved tool invocation in an acting batch. */
@FunctionalInterface
public interface ToolCallOffload {
/** RuntimeContext key for calls paired with an acting middleware's timeout placeholders. */
String PLACEHOLDER_CALLS_CONTEXT_KEY = "agentscope.tool.placeholderCalls";

/**
* Accept the prepared execution and return the result to put in this turn. The implementation
* owns its subscription once accepted. The execution retains toolkit validation, interceptors,
* scheduling, timeout and retry. Background chunks are not emitted into the original turn.
*/
Mono<ToolResultBlock> submit(Mono<ToolResultBlock> execution);

/** Identifies a tool use across argument normalization and permission evaluation. */
record Key(String id, String name) {
public Key(ToolUseBlock call) {
this(call.getId(), call.getName());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import io.agentscope.core.agent.Agent;
import io.agentscope.core.agent.CapabilitySurface;
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.agent.SubagentEventBus;
import io.agentscope.core.event.AgentEventEmitter;
import io.agentscope.core.journal.InvocationRecorder;
import io.agentscope.core.journal.JournalException;
import io.agentscope.core.message.ToolErrorKind;
Expand All @@ -27,6 +29,7 @@
import io.agentscope.core.model.ExecutionConfig;
import io.agentscope.core.observation.ActionObservationException;
import io.agentscope.core.observation.ActionObservations;
import io.agentscope.core.observation.ActionObserver;
import io.agentscope.core.shutdown.GracefulShutdownManager;
import io.agentscope.core.tracing.TracerRegistry;
import io.agentscope.core.util.ExceptionUtils;
Expand Down Expand Up @@ -671,13 +674,28 @@ Mono<List<ToolResultBlock>> executeAll(

Function<ToolUseBlock, Mono<ToolResultBlock>> execute =
toolCall ->
executeWithInfrastructure(
toolCall,
executionConfig,
agent,
agentRuntimeContext,
requestConfig,
executionCallback)
Mono.deferContextual(
context -> {
var key = new ToolCallOffload.Key(toolCall);
ToolCallOffload offload =
context.getOrDefault(key, null);
return offload == null
? executeWithInfrastructure(
toolCall,
executionConfig,
agent,
agentRuntimeContext,
requestConfig,
executionCallback)
: executeOffloaded(
toolCall,
executionConfig,
agent,
agentRuntimeContext,
requestConfig,
offload)
.contextWrite(c -> c.delete(key));
})
// Both hooks sit outside the retry wrapper inside
// executeWithInfrastructure, so one logical invocation fires
// onStart/onResult exactly once even across retries.
Expand All @@ -692,6 +710,37 @@ Mono<List<ToolResultBlock>> executeAll(
executionCallback.onResult(toolCall, result);
});

return Mono.deferContextual(
context -> {
var background = new ArrayList<ToolUseBlock>();
var foreground = new ArrayList<ToolUseBlock>();
for (var call : toolCalls) {
if (context.hasKey(new ToolCallOffload.Key(call))) background.add(call);
else foreground.add(call);
}
if (background.isEmpty())
return executeBatch(toolCalls, parallel, requestConfig, execute);
// Handoffs may overlap foreground calls. Keep the existing concurrency rules
// for
// foreground work and restore declaration order when returning the full batch.
return Flux.merge(
Flux.fromIterable(background).flatMap(execute),
executeBatch(foreground, parallel, requestConfig, execute)
.flatMapMany(Flux::fromIterable))
.collectMap(ToolResultBlock::getId)
.map(
results ->
toolCalls.stream()
.map(call -> results.get(call.getId()))
.toList());
});
}

private Mono<List<ToolResultBlock>> executeBatch(
List<ToolUseBlock> toolCalls,
boolean parallel,
ToolRequestConfig requestConfig,
Function<ToolUseBlock, Mono<ToolResultBlock>> execute) {
// Sequential mode: nothing to partition, run in declared order.
if (!parallel) {
List<Mono<ToolResultBlock>> monos = toolCalls.stream().map(execute).toList();
Expand Down Expand Up @@ -722,6 +771,33 @@ Mono<List<ToolResultBlock>> executeAll(
return Flux.concat(chunks).collectList();
}

private Mono<ToolResultBlock> executeOffloaded(
ToolUseBlock call,
ExecutionConfig config,
Agent agent,
RuntimeContext context,
ToolRequestConfig request,
ToolCallOffload offload) {
RuntimeContext detached = RuntimeContext.builder(context).build();
detached.put(InvocationRecorder.CONTEXT_KEY, null);
detached.put(ActionObserver.CONTEXT_KEY, null);
Mono<ToolResultBlock> execution =
executeWithInfrastructure(call, config, agent, detached, request, null)
.contextWrite(
c ->
c.delete(AgentEventEmitter.CONTEXT_KEY)
.delete(AgentEventEmitter.FORWARDING_CONTEXT_KEY)
.delete(SubagentEventBus.CONTEXT_KEY));
ToolCallParam receipt =
ToolCallParam.builder()
.toolUseBlock(call)
.agent(agent)
.runtimeContext(context)
.build();
return ActionObservations.observe(receipt, () -> offload.submit(execution))
.map(result -> result.withIdAndName(call.getId(), call.getName()));
}

/**
* Whether the tool backing {@code toolCall} can run in parallel with itself. Resolves the tool
* through {@link #resolveTool} so the safety classification matches the tool that will actually
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
import io.agentscope.durable.codec.agentscope.AgentScopeCheckpointCodec;
import io.agentscope.durable.codec.agentscope.DurableEventSchemas;
import io.agentscope.harness.agent.HarnessAgent;
import io.agentscope.harness.agent.middleware.BackgroundToolOptions;
import io.agentscope.harness.agent.middleware.MemoryFlushMiddleware;
import java.time.Duration;
import java.util.ArrayList;
Expand Down Expand Up @@ -202,8 +203,27 @@ public static AgentScopeAdapter forReAct(

public static AgentScopeAdapter forHarness(
Function<Binding, HarnessAgent.Builder> factory, Collection<ToolBinding> tools) {
return forHarness(factory, tools, Set.of(), false);
}

/**
* Exposes optional per-call background execution on the selected routed tools. Configure
* those routes with executors that atomically stage requests for independent delivery.
*/
public static AgentScopeAdapter forHarness(
Function<Binding, HarnessAgent.Builder> factory,
Collection<ToolBinding> tools,
Set<String> backgroundTools,
boolean allowBackgroundWakeups) {
var frozen = ToolBinding.catalog(tools);
return createHarness(factory, ToolBinding.routes(frozen.values()), frozen);
if (!frozen.keySet().containsAll(backgroundTools))
throw new IllegalArgumentException("Background tools must use frozen tool bindings");
return createHarness(
factory,
ToolBinding.routes(frozen.values()),
frozen,
Set.copyOf(backgroundTools),
allowBackgroundWakeups);
}

public static AgentScopeAdapter forReAct(
Expand Down Expand Up @@ -254,13 +274,15 @@ public void close() {

public static AgentScopeAdapter forHarness(
Function<Binding, HarnessAgent.Builder> factory, Map<String, String> executors) {
return createHarness(factory, executors, Map.of());
return createHarness(factory, executors, Map.of(), Set.of(), false);
}

private static AgentScopeAdapter createHarness(
Function<Binding, HarnessAgent.Builder> factory,
Map<String, String> executors,
Map<String, ToolBinding> bindings) {
Map<String, ToolBinding> bindings,
Set<String> backgroundTools,
boolean allowBackgroundWakeups) {
Objects.requireNonNull(factory);
return new AgentScopeAdapter(
invocation -> {
Expand All @@ -272,6 +294,9 @@ private static AgentScopeAdapter createHarness(
Objects.requireNonNull(
factory.apply(binding),
"Harness factory returned null builder");
if (!backgroundTools.isEmpty())
builder.middleware(
new RoutedBackgroundTools(backgroundTools, allowBackgroundWakeups));
var agent =
builder.journalEnabled(true)
.threadJournalStore(invocation.journalStore())
Expand All @@ -280,6 +305,14 @@ private static AgentScopeAdapter createHarness(
try {
AgentScopeToolExecutor.registerSchemas(
agent.getToolkit(), bindings.values());
for (String name : backgroundTools) {
var tool = agent.getToolkit().getTool(name);
if (tool.isReturnDirect() || tool.isSystem())
throw new IllegalArgumentException(
"Unsupported background tool: " + name);
BackgroundToolOptions.parameters(
tool.getParameters(), tool.getStrict());
}
route(agent.getToolkit(), executors.keySet());
} catch (RuntimeException error) {
agent.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,9 @@ private void applyInputs(RuntimeContext runtime, AgentState state, List<Signal>
Set.of(
"input:steer",
"input:inject",
BackgroundCompletion.SIGNAL_KEY)
BackgroundCompletion.SIGNAL_KEY,
TransactionalSessionBackend
.BACKGROUND_TOOL_INPUT)
.contains(signal.key()))
.toList();
if (pending.isEmpty()) return;
Expand All @@ -290,6 +292,14 @@ private void applyInputs(RuntimeContext runtime, AgentState state, List<Signal>
messageId,
DurableJson.convert(signal.value(), BackgroundCompletion.class))
: AgentScopeMessages.input(signal.value(), messageId);
if (TransactionalSessionBackend.BACKGROUND_TOOL_INPUT.equals(signal.key())) {
message =
UserMessage.builder()
.id(messageId)
.content(message.getContent())
.metadata(Map.of(Msg.METADATA_SYNTHETIC, true))
.build();
}
if (known.add(message.getId())) state.contextMutable().add(message);
ids.add(signal.id());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,8 @@ private Head commit(
var call =
JsonUtils.getJsonCodec().convertValue(data.get("call"), ToolUseBlock.class);
String executor = executors.get(call.getName());
if (executor != null)
if (executor != null) {
Object wake = call.getMetadata().get(RoutedBackgroundTools.WAKE_METADATA);
tools.add(
new ToolCall(
call.getId(),
Expand All @@ -431,7 +432,9 @@ private Head commit(
? bindings.get(call.getName()).digest()
: null,
new RunStepRef(
event.executionRunId(), (String) data.get("stepId"))));
event.executionRunId(), (String) data.get("stepId")),
wake instanceof Boolean value ? value : null));
}
}
if ("interaction/requested".equals(event.type())
|| "interaction/resolved".equals(event.type())) {
Expand Down
Loading
Loading