Skip to content

Commit 8dc8a31

Browse files
authored
perf(durable): batch Hands tool admission and result delivery (#4574)
1 parent 4abccdb commit 8dc8a31

82 files changed

Lines changed: 6880 additions & 2203 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/scripts/check-shade-and-bom-sync.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ get_packaging() {
7979

8080
# Scan agentscope-extensions directory for jar modules
8181
echo "Scanning agentscope-extensions/ for jar modules..."
82-
for pom in $(find "agentscope-extensions" -name "pom.xml" -type f); do
82+
for pom in $(find "agentscope-extensions" -type d -name target -prune -o -name "pom.xml" -type f -print); do
8383
packaging=$(get_packaging "$pom")
8484

8585
# Skip pom packaging (aggregator modules)

‎.licenserc.yaml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ header:
1616
See the License for the specific language governing permissions and
1717
limitations under the License.
1818
19+
language:
20+
Diff:
21+
extensions: [".patch"]
22+
comment_style_id: SlashAsterisk
23+
1924
paths-ignore:
2025
# Configuration files (including example configurations)
2126
- '**/.env'

‎agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,8 @@ private Mono<ToolResultBlock> executeCore(
370370
}
371371
final RuntimeContext effectiveRuntimeContext = runtimeContext;
372372

373-
// Create emitter for streaming
373+
// Preserve an emitter supplied for this call alongside the Toolkit callbacks.
374+
var callerEmitter = param.getEmitter();
374375
ToolEmitter toolEmitter =
375376
new DefaultToolEmitter(
376377
toolCall,
@@ -390,6 +391,12 @@ private Mono<ToolResultBlock> executeCore(
390391
if (executionCallback != null)
391392
invokeChunkCallback(
392393
"internal", executionCallback::onProgress, use, chunk);
394+
if (callerEmitter != NoOpToolEmitter.INSTANCE)
395+
invokeChunkCallback(
396+
"caller",
397+
(ignored, value) -> callerEmitter.emit(value),
398+
use,
399+
chunk);
393400
if (userChunkCallback != null)
394401
invokeChunkCallback("user", userChunkCallback, use, chunk);
395402
});

‎agentscope-durable/durable-adapters/durable-adapter-agui/src/main/java/io/agentscope/durable/agui/DurableAguiEventAdapter.java‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,18 @@ public List<AguiEvent> map(SessionStreamEvent event) {
5050
preview.threadId(), require(preview.runId(), "runId"), preview.data());
5151
}
5252
if (event instanceof SessionStreamEvent.EventDelta delta) {
53+
if (delta.deltaType() == EventDeltaType.TOOL_PROGRESS)
54+
return toolPreview(
55+
delta.threadId(),
56+
delta.runId(),
57+
"agentscope.tool_progress_delta",
58+
delta.data());
5359
if (delta.deltaType() == EventDeltaType.TOOL_OUTPUT)
54-
return toolOutput(delta.threadId(), delta.runId(), delta.data());
60+
return toolPreview(
61+
delta.threadId(),
62+
delta.runId(),
63+
"agentscope.tool_output_delta",
64+
delta.data());
5565
String runId = require(delta.runId(), "runId");
5666
if (delta.deltaType() == EventDeltaType.MESSAGE)
5767
return messageDelta(delta.threadId(), runId, delta.data());
@@ -113,7 +123,11 @@ List<AguiEvent> live(LiveEvent event) {
113123
Objects.requireNonNull(event);
114124
String threadId = event.threadId();
115125
if (ToolOutputDelta.TYPE.equals(event.type()))
116-
return toolOutput(threadId, event.runId(), event.data());
126+
return toolPreview(
127+
threadId, event.runId(), "agentscope.tool_output_delta", event.data());
128+
if ("tool.progress.delta".equals(event.type()))
129+
return toolPreview(
130+
threadId, event.runId(), "agentscope.tool_progress_delta", event.data());
117131
String runId = require(event.runId(), "runId");
118132
var data = event.data();
119133
return switch (event.type()) {
@@ -124,14 +138,12 @@ List<AguiEvent> live(LiveEvent event) {
124138
};
125139
}
126140

127-
private static List<AguiEvent> toolOutput(String threadId, String runId, JsonNode data) {
141+
private static List<AguiEvent> toolPreview(
142+
String threadId, String runId, String name, JsonNode data) {
128143
if (runId == null) return List.of();
129144
return List.of(
130145
new AguiEvent.Custom(
131-
threadId,
132-
runId,
133-
"agentscope.tool_output_delta",
134-
DurableJson.convert(data, Object.class)));
146+
threadId, runId, name, DurableJson.convert(data, Object.class)));
135147
}
136148

137149
private List<AguiEvent> runEnded(PublicEvent event) {

‎agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeToolEvents.java‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -222,13 +222,7 @@ LiveEventInput preview(Observation observation, long attempt) {
222222
? result
223223
: JsonUtils.getJsonCodec().convertValue(value, ToolResultBlock.class);
224224
if (chunk.getOutput() == null) return null;
225-
byte[] bytes =
226-
chunk.getOutput().stream()
227-
.filter(TextBlock.class::isInstance)
228-
.map(TextBlock.class::cast)
229-
.map(TextBlock::getText)
230-
.collect(Collectors.joining())
231-
.getBytes(StandardCharsets.UTF_8);
225+
byte[] bytes = textBytes(chunk);
232226
if (bytes.length == 0) return null;
233227
long offset = previewOffsets.getOrDefault(key, 0L);
234228
long next = Math.addExact(offset, bytes.length);
@@ -250,6 +244,15 @@ LiveEventInput preview(Observation observation, long attempt) {
250244
(String) source.get("stepId"));
251245
}
252246

247+
static byte[] textBytes(ToolResultBlock chunk) {
248+
return chunk.getOutput().stream()
249+
.filter(TextBlock.class::isInstance)
250+
.map(TextBlock.class::cast)
251+
.map(TextBlock::getText)
252+
.collect(Collectors.joining())
253+
.getBytes(StandardCharsets.UTF_8);
254+
}
255+
253256
private static ObjectNode outcome(ToolResultBlock result) {
254257
var value = update(result.getId(), status(result));
255258
value.set("content", content(result));

‎agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/main/java/io/agentscope/durable/agentscope/AgentScopeToolExecutor.java‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,13 @@
1919
import com.fasterxml.jackson.databind.JsonNode;
2020
import io.agentscope.core.agent.RuntimeContext;
2121
import io.agentscope.core.message.TextBlock;
22+
import io.agentscope.core.message.ToolResultBlock;
2223
import io.agentscope.core.message.ToolResultState;
2324
import io.agentscope.core.message.ToolUseBlock;
2425
import io.agentscope.core.model.ToolSchema;
2526
import io.agentscope.core.tool.AgentTool;
2627
import io.agentscope.core.tool.ToolCallParam;
28+
import io.agentscope.core.tool.ToolEmitter;
2729
import io.agentscope.core.tool.ToolValidator;
2830
import io.agentscope.core.tool.Toolkit;
2931
import io.agentscope.core.util.JsonUtils;
@@ -32,9 +34,11 @@
3234
import io.agentscope.durable.DurableTypes.ExecutionRequest;
3335
import io.agentscope.durable.DurableTypes.ExecutionResult;
3436
import io.agentscope.durable.DurableTypes.ExecutionState;
37+
import io.agentscope.durable.DurableTypes.OutputPage;
3538
import io.agentscope.durable.Executor;
3639
import io.agentscope.durable.ToolBinding;
3740
import java.time.Duration;
41+
import java.util.Base64;
3842
import java.util.Collection;
3943
import java.util.LinkedHashMap;
4044
import java.util.Map;
@@ -145,8 +149,13 @@ public void validateStart(ExecutionRequest request) {
145149
DurableException.Code.INVALID, "Invalid tool arguments: " + invalid);
146150
}
147151

148-
@SuppressWarnings("unchecked")
149152
public ExecutionResult startExecution(ExecutionRequest request) {
153+
return startExecution(request, null);
154+
}
155+
156+
@Override
157+
@SuppressWarnings("unchecked")
158+
public ExecutionResult startExecution(ExecutionRequest request, Preview preview) {
150159
validateStart(request);
151160
var binding = bindings.get(request.call().name());
152161
Map<String, Object> arguments = DurableJson.convert(request.call().arguments(), Map.class);
@@ -174,6 +183,7 @@ public ExecutionResult startExecution(ExecutionRequest request) {
174183
ToolCallParam.builder()
175184
.toolUseBlock(call)
176185
.input(arguments)
186+
.emitter(preview == null ? null : emitter(preview))
177187
.propagateErrors(true)
178188
.runtimeContext(context)
179189
.build())
@@ -209,6 +219,35 @@ public ExecutionResult startExecution(ExecutionRequest request) {
209219
null);
210220
}
211221

222+
private static ToolEmitter emitter(Preview preview) {
223+
return new ToolEmitter() {
224+
private long offset;
225+
226+
public synchronized void emit(ToolResultBlock chunk) {
227+
if (chunk.getOutput() == null) return;
228+
byte[] bytes = AgentScopeToolEvents.textBytes(chunk);
229+
if (bytes.length > 0) {
230+
long next = offset + bytes.length;
231+
preview.output(
232+
new OutputPage(
233+
offset,
234+
next,
235+
Base64.getEncoder().encodeToString(bytes),
236+
next,
237+
false,
238+
null));
239+
offset = next;
240+
}
241+
if (chunk.getOutput().stream().anyMatch(block -> !(block instanceof TextBlock))
242+
|| chunk.getMetadata() != null && !chunk.getMetadata().isEmpty()) {
243+
preview.progress(
244+
DurableJson.value(
245+
JsonUtils.getJsonCodec().convertValue(chunk, Map.class)));
246+
}
247+
}
248+
};
249+
}
250+
212251
public ExecutionResult query(ExecutionRequest request, String handle) {
213252
return ExecutionResult.unknown("Native tool has no external operation lookup");
214253
}

‎agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope/AgentScopeAdapterTest.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3085,8 +3085,12 @@ yield jobCall(
30853085
assertEquals(TurnStatus.WAITING, turn.status().status());
30863086
var pending = turn.getToolCall("await");
30873087
assertEquals(ToolExecutionStatus.RUNNING, pending.status());
3088-
assertEquals(jobId.get(), pending.progress().path("jobId").asText());
3089-
assertTrue(pending.progress().path("deadline").asLong() > pending.updatedAt());
3088+
var wait =
3089+
turn.progress().blockers().stream()
3090+
.filter(blocker -> jobId.get().equals(blocker.targetId()))
3091+
.findFirst()
3092+
.orElseThrow();
3093+
assertTrue(wait.readyAt() > pending.updatedAt());
30903094
assertEquals(3, calls.get());
30913095
assertTrue(childModel.inputs.isEmpty());
30923096
assertTrue(backend.pendingDispatch(thread).isEmpty());

‎agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope/AgentScopeToolExecutorTest.java‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import static org.junit.jupiter.api.Assertions.assertThrows;
2323
import static org.junit.jupiter.api.Assertions.assertTrue;
2424

25+
import com.fasterxml.jackson.databind.JsonNode;
2526
import io.agentscope.core.ReActAgent;
2627
import io.agentscope.core.message.TextBlock;
2728
import io.agentscope.core.message.ToolResultBlock;
@@ -35,17 +36,20 @@
3536
import io.agentscope.durable.DurableRuntime;
3637
import io.agentscope.durable.DurableTypes.ExecutionRequest;
3738
import io.agentscope.durable.DurableTypes.ExecutionState;
39+
import io.agentscope.durable.DurableTypes.OutputPage;
3840
import io.agentscope.durable.DurableTypes.RunStepRef;
3941
import io.agentscope.durable.DurableTypes.SessionKey;
4042
import io.agentscope.durable.DurableTypes.ThreadKey;
4143
import io.agentscope.durable.DurableTypes.TurnStatus;
44+
import io.agentscope.durable.Executor;
4245
import io.agentscope.durable.ToolBinding;
4346
import io.agentscope.durable.TransactionalSessionBackend;
4447
import io.agentscope.durable.worker.TransactionalExecutionStore;
4548
import io.agentscope.durable.worker.WorkerRuntime;
4649
import io.agentscope.extensions.durable.jdbc.JdbcRecordStore;
4750
import java.nio.file.Path;
4851
import java.time.Duration;
52+
import java.util.ArrayList;
4953
import java.util.List;
5054
import java.util.Map;
5155
import java.util.concurrent.atomic.AtomicInteger;
@@ -69,6 +73,7 @@ ToolBase tool(AtomicInteger calls, boolean uncertain) {
6973
Map.of("value", Map.of("type", "integer"))))) {
7074
public Mono<ToolResultBlock> callAsync(ToolCallParam param) {
7175
calls.incrementAndGet();
76+
param.getEmitter().emit(ToolResultBlock.text("abc"));
7277
assertEquals("tenant", param.getRuntimeContext().getUserId());
7378
assertEquals("session", param.getRuntimeContext().getSessionId());
7479
var origin = param.getRuntimeContext().get("durable.origin", RunStepRef.class);
@@ -137,7 +142,19 @@ void nativeResultRetainsStructuredMetadata() {
137142
"turn",
138143
binding.call("call", DurableJson.value(Map.of("value", 7)))
139144
.withOrigin(new RunStepRef("brain-run", "brain-step")));
140-
var result = executor.startExecution(request);
145+
var pages = new ArrayList<OutputPage>();
146+
var result =
147+
executor.startExecution(
148+
request,
149+
new Executor.Preview() {
150+
public void progress(JsonNode detail) {}
151+
152+
public void output(OutputPage page) {
153+
pages.add(page);
154+
}
155+
});
156+
assertEquals(List.of(new OutputPage(0, 3, "YWJj", 3, false, null)), pages);
157+
assertFalse(result.result().toString().contains("abc"));
141158
assertEquals(ExecutionState.SUCCEEDED, result.state());
142159
assertEquals(
143160
7,

‎agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableOperations.java‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ final class DurableOperations {
4545
"history",
4646
"submit",
4747
"getToolExecution",
48-
"toolOutput",
4948
"editQueuedInput",
5049
"convertQueuedToSteer",
5150
"getTurn",
@@ -112,12 +111,6 @@ JsonNode invoke(DurableProtocol.Request request) {
112111
backend.turns(thread, text(p, "cursor"), p.path("limit").asInt());
113112
case "history" ->
114113
backend.history(thread, text(p, "cursor"), p.path("limit").asInt());
115-
case "toolOutput" ->
116-
backend.toolOutput(
117-
thread,
118-
text(p, "turnId"),
119-
text(p, "executionId"),
120-
p.path("offset").asLong());
121114
case "getToolExecution" ->
122115
backend.toolExecution(
123116
thread,

0 commit comments

Comments
 (0)