Skip to content

Commit da2bc9c

Browse files
authored
feat(durable): support async subagent jobs across threads and deployments (#4572)
1 parent 9dc3efb commit da2bc9c

37 files changed

Lines changed: 4516 additions & 182 deletions

File tree

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,28 @@ List<AguiEvent> committed(PublicEvent event) {
8383
require(event.stepId(), "stepId")));
8484
case "message.completed" -> message(event);
8585
case "tool.call.updated" -> tool(event);
86+
case "turn.delegated",
87+
"tool.delegated",
88+
"turn.waiting",
89+
"turn.resumed",
90+
"turn.cancel_requested",
91+
"turn.cancelled",
92+
"turn.succeeded",
93+
"turn.failed",
94+
"interaction.requested",
95+
"interaction.resolved",
96+
"x.remote-subagent.admitted",
97+
"x.remote-subagent.progress",
98+
"x.remote-subagent.control",
99+
"x.remote-subagent.outcome" ->
100+
List.of(
101+
new AguiEvent.Custom(
102+
threadId,
103+
runId == null ? require(event.turnId(), "turnId") : runId,
104+
"agentscope." + event.type(),
105+
DurableJson.convert(DurableJson.value(event), Object.class),
106+
event.occurredAt(),
107+
null));
86108
default -> List.of();
87109
};
88110
}

‎agentscope-durable/durable-adapters/durable-adapter-agui/src/test/java/io/agentscope/durable/agui/DurableAguiEventAdapterTest.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,31 @@ void committedResultApplicationDoesNotRepeatTheToolResult() {
7676
assertEquals(List.of(), adapter.committed(applied));
7777
}
7878

79+
@Test
80+
void childApprovalKeepsDurableIdentityWithoutAnInvocation() {
81+
var approval =
82+
new PublicEvent(
83+
"1",
84+
"approval",
85+
session,
86+
"child",
87+
"child-turn",
88+
null,
89+
null,
90+
"3",
91+
"approval-cursor",
92+
0,
93+
"interaction.requested",
94+
DurableJson.value(Map.of("id", "confirm", "kind", "confirmation")));
95+
var mapped = assertInstanceOf(AguiEvent.Custom.class, adapter.committed(approval).get(0));
96+
assertEquals("agentscope.interaction.requested", mapped.name());
97+
assertEquals("child", mapped.threadId());
98+
assertEquals("child-turn", mapped.runId());
99+
var payload = DurableJson.value(mapped.value());
100+
assertEquals("approval-cursor", payload.path("cursor").asText());
101+
assertEquals("confirm", payload.path("data").path("id").asText());
102+
}
103+
79104
@Test
80105
void toolOutputPreviewDoesNotBecomeAnAguiToolResult() {
81106
var data = new ToolOutputDelta("call", "execution", 1, 0, 0, 3, "YWJj");

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ public record Binding(
9292
private record InvocationBinding(Binding binding, ThreadJournalStore journalStore) {}
9393

9494
private interface NativeAgent extends AutoCloseable {
95+
Toolkit toolkit();
96+
9597
ThreadJournal log(RuntimeContext context);
9698

9799
Flux<AgentEvent> stream(List<Msg> input, RuntimeContext context);
@@ -100,6 +102,11 @@ private interface NativeAgent extends AutoCloseable {
100102
void close();
101103
}
102104

105+
@Override
106+
public boolean supportsDelegationPolicy() {
107+
return true;
108+
}
109+
103110
/** Visibility of middleware-produced thinking previews and completed public messages. */
104111
public record ThinkingPolicy(boolean preview, boolean save) {
105112
static final ThinkingPolicy DISABLED = new ThinkingPolicy(false, false);
@@ -235,6 +242,10 @@ private static AgentScopeAdapter createReAct(
235242
throw error;
236243
}
237244
return new NativeAgent() {
245+
public Toolkit toolkit() {
246+
return agent.getToolkit();
247+
}
248+
238249
public ThreadJournal log(RuntimeContext context) {
239250
return agent.threadJournal(context);
240251
}
@@ -286,6 +297,10 @@ private static AgentScopeAdapter createHarness(
286297
throw error;
287298
}
288299
return new NativeAgent() {
300+
public Toolkit toolkit() {
301+
return agent.getToolkit();
302+
}
303+
289304
public ThreadJournal log(RuntimeContext context) {
290305
return agent.threadJournal(context);
291306
}
@@ -512,6 +527,7 @@ && resolveNativeToolOutcomes(context, log, JournalProjection.read(log)) == null)
512527
throw new DurableException(
513528
DurableException.Code.INCOMPATIBLE,
514529
"Adapter did not install the invocation journal");
530+
host.toolkit(agent.toolkit());
515531
// A view fixed by the claim can recover without a separate native start commit.
516532
host.deferInvocationStart(workspace.pinInvocationWorkspace());
517533
agent.stream(List.copyOf(input), runtimeContext).blockLast();

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

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,13 @@
3535
import io.agentscope.core.model.ModelRequestObserver;
3636
import io.agentscope.core.model.ToolSchema;
3737
import io.agentscope.core.state.AgentState;
38+
import io.agentscope.core.tool.ToolBase;
39+
import io.agentscope.core.tool.Toolkit;
3840
import io.agentscope.core.util.JsonUtils;
3941
import io.agentscope.durable.DurableException;
4042
import io.agentscope.durable.DurableJson;
4143
import io.agentscope.durable.DurableTypes.BackgroundCompletion;
44+
import io.agentscope.durable.DurableTypes.DelegationPolicy;
4245
import io.agentscope.durable.DurableTypes.Signal;
4346
import io.agentscope.durable.DurableTypes.TurnInputs;
4447
import io.agentscope.durable.DurableTypes.TurnStatus;
@@ -113,6 +116,7 @@ WaitCondition waitingForModel() {
113116
private boolean waitingForNativeReconciliation;
114117
private volatile boolean active;
115118
private RuntimeContext context;
119+
private Toolkit toolkit;
116120
private final AtomicInteger slot = new AtomicInteger();
117121
private final AtomicInteger storageSlot = new AtomicInteger();
118122

@@ -131,6 +135,7 @@ public boolean defersInvocationStart() {
131135
@Override
132136
public Mono<Void> startInvocation(
133137
InvocationRecorder recorder, List<Msg> input, AgentState state) {
138+
restrict(state);
134139
return recorder.start(input, state, deferInvocationStart, PreparationScheduler::onWorker)
135140
.doOnSuccess(ignored -> startupRecorder = recorder);
136141
}
@@ -330,6 +335,29 @@ void workspace(DurableWorkspaceStore workspace) {
330335
this.workspace = workspace;
331336
}
332337

338+
void toolkit(Toolkit toolkit) {
339+
this.toolkit = toolkit;
340+
}
341+
342+
private void restrict(AgentState state) {
343+
var policy = durable.initialFrame().delegationPolicy();
344+
if (policy != null && policy.readOnly()) state.getPlanModeContext().setPlanActive(true);
345+
}
346+
347+
private boolean deniedByDelegation(DelegationPolicy policy, ToolUseBlock call) {
348+
var tool = toolkit == null ? null : toolkit.getTool(call.getName());
349+
if (policy.readOnly() && (tool == null || !tool.isReadOnly())) return true;
350+
for (var rule : policy.denyRules()) {
351+
if (!rule.toolName().equals(call.getName())) continue;
352+
if (rule.pattern() == null
353+
|| rule.pattern().isEmpty()
354+
|| !(tool instanceof ToolBase base)
355+
|| toolkit.isExternalTool(call.getName())
356+
|| base.matchRule(rule.pattern(), call.getInput())) return true;
357+
}
358+
return false;
359+
}
360+
333361
String resourceTimestamp() {
334362
return active ? Instant.ofEpochMilli(frame.startedAt()).toString() : null;
335363
}
@@ -343,7 +371,21 @@ String resourceIdentity() {
343371
@Override
344372
public Mono<ToolPlan> prepareTools(
345373
RuntimeContext runtime, AgentState state, List<ToolUseBlock> calls) {
346-
return toolHooks.prepare(runtime, state, calls);
374+
restrict(state);
375+
return toolHooks
376+
.prepare(runtime, state, calls)
377+
.map(
378+
plan -> {
379+
var policy = durable.initialFrame().delegationPolicy();
380+
var denied = new HashSet<>(plan.denied());
381+
for (var call : plan.calls()) {
382+
if (policy != null && deniedByDelegation(policy, call))
383+
denied.add(call.getId());
384+
if (!denied.contains(call.getId()))
385+
log.captureDelegationContext(call, state);
386+
}
387+
return new ToolPlan(plan.calls(), plan.confirm(), denied);
388+
});
347389
}
348390

349391
@Override

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

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,22 @@
2323
import io.agentscope.core.journal.JournalEventTypes;
2424
import io.agentscope.core.journal.ThreadJournal;
2525
import io.agentscope.core.message.Msg;
26+
import io.agentscope.core.message.MsgRole;
2627
import io.agentscope.core.message.ToolResultBlock;
2728
import io.agentscope.core.message.ToolUseBlock;
2829
import io.agentscope.core.model.ChatResponse;
2930
import io.agentscope.core.state.AgentState;
3031
import io.agentscope.core.state.TaskVerification;
3132
import io.agentscope.core.util.JsonUtils;
33+
import io.agentscope.durable.DelegatedJobExecutor;
3234
import io.agentscope.durable.DurableException;
3335
import io.agentscope.durable.DurableJson;
3436
import io.agentscope.durable.DurableMessages.Input;
3537
import io.agentscope.durable.DurableMessages.Message;
3638
import io.agentscope.durable.DurableTypes.AppliedResult;
3739
import io.agentscope.durable.DurableTypes.Commit;
40+
import io.agentscope.durable.DurableTypes.DelegationDeny;
41+
import io.agentscope.durable.DurableTypes.DelegationPolicy;
3842
import io.agentscope.durable.DurableTypes.EventInput;
3943
import io.agentscope.durable.DurableTypes.JournalAppend;
4044
import io.agentscope.durable.DurableTypes.LiveEventInput;
@@ -55,9 +59,11 @@
5559
import io.agentscope.durable.codec.agentscope.AgentScopeCheckpointCodec;
5660
import io.agentscope.durable.codec.agentscope.DurableEventSchemas;
5761
import java.time.Duration;
62+
import java.util.ArrayDeque;
5863
import java.util.ArrayList;
5964
import java.util.HashSet;
6065
import java.util.LinkedHashMap;
66+
import java.util.LinkedHashSet;
6167
import java.util.List;
6268
import java.util.Locale;
6369
import java.util.Map;
@@ -69,6 +75,7 @@ final class BackendThreadJournal implements ThreadJournal {
6975
private final HarnessContext context;
7076
private final Map<String, String> executors;
7177
private final Map<String, ToolBinding> bindings;
78+
private final Map<String, JsonNode> delegationContexts = new LinkedHashMap<>();
7279
private final String initialInputId;
7380
private final JsonNode initialInput;
7481
private final Set<String> sealed = new HashSet<>();
@@ -179,6 +186,65 @@ synchronized SessionResources.Version workspaceVersion() {
179186
return workspaceVersion;
180187
}
181188

189+
synchronized void captureDelegationContext(ToolUseBlock call, AgentState state) {
190+
var binding = bindings.get(call.getName());
191+
if (!DelegatedJobExecutor.START.equals(call.getName()) || binding == null) return;
192+
Object name = call.getInput().get("agent");
193+
if (!(name instanceof String child)) return;
194+
var registered = binding.target().path("children").path(child);
195+
if (registered.isMissingNode()) return;
196+
var inherited = context.initialFrame().delegationPolicy();
197+
var deny = new LinkedHashSet<DelegationDeny>();
198+
if (inherited != null) deny.addAll(inherited.denyRules());
199+
if (registered.path("inheritPermissions").asBoolean())
200+
state.getPermissionContext()
201+
.getDenyRules()
202+
.values()
203+
.forEach(
204+
rules ->
205+
rules.forEach(
206+
rule ->
207+
deny.add(
208+
new DelegationDeny(
209+
rule.toolName(),
210+
rule.ruleContent()))));
211+
boolean readOnly =
212+
state.getPlanModeContext().isPlanActive()
213+
|| inherited != null && inherited.readOnly();
214+
var policy =
215+
readOnly || !deny.isEmpty()
216+
? new DelegationPolicy(readOnly, List.copyOf(deny))
217+
: null;
218+
var history =
219+
registered.path("includeParentContext").asBoolean()
220+
? excerpt(state)
221+
: List.<String>of();
222+
if (policy != null || !history.isEmpty())
223+
delegationContexts.put(
224+
call.getId(),
225+
DurableJson.value(new DurableSubagentTools.Context(history, policy)));
226+
}
227+
228+
private static List<String> excerpt(AgentState state) {
229+
var messages = state.getContext();
230+
var text = new ArrayDeque<String>();
231+
for (int i = messages.size() - 1; i >= 0 && text.size() < 12; i--) {
232+
var message = messages.get(i);
233+
if (message.getRole() != MsgRole.USER && message.getRole() != MsgRole.ASSISTANT)
234+
continue;
235+
String value = message.getTextContent();
236+
if (value.isBlank()) continue;
237+
int end =
238+
value.offsetByCodePoints(
239+
0, Math.min(1000, value.codePointCount(0, value.length())));
240+
text.addFirst(
241+
message.getRole().name().toLowerCase(Locale.ROOT)
242+
+ ": "
243+
+ value.substring(0, end));
244+
}
245+
return List.copyOf(text);
246+
}
247+
182248
synchronized void pinWorkspace(SessionResources.Version version) {
183249
if (workspaceVersion != null && !workspaceVersion.equals(version))
184250
throw new DurableException(
@@ -431,7 +497,8 @@ private Head commit(
431497
? bindings.get(call.getName()).digest()
432498
: null,
433499
new RunStepRef(
434-
event.executionRunId(), (String) data.get("stepId"))));
500+
event.executionRunId(), (String) data.get("stepId")),
501+
delegationContexts.get(call.getId())));
435502
}
436503
if ("interaction/requested".equals(event.type())
437504
|| "interaction/resolved".equals(event.type())) {

0 commit comments

Comments
 (0)