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
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,10 @@ private Maybe<TaskArtifactUpdateEvent> process(
}
ImmutableList<Part<?>> parts =
EventConverter.contentToParts(event.content(), event.partial().orElse(false));
// A2A Artifact rejects empty parts, so skip content-less events (e.g. state-only deltas).
if (parts.isEmpty()) {
return Maybe.empty();
}
Map<String, Object> metadata = new HashMap<>();
if (event.customMetadata().isPresent()) {
for (CustomMetadata cm : event.customMetadata().get()) {
Expand Down
121 changes: 121 additions & 0 deletions a2a/src/test/java/com/google/adk/a2a/executor/AgentExecutorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,28 @@
import com.google.adk.a2a.converters.PartConverter;
import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.InvocationContext;
import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.RunConfig;
import com.google.adk.apps.App;
import com.google.adk.artifacts.InMemoryArtifactService;
import com.google.adk.events.Event;
import com.google.adk.events.EventActions;
import com.google.adk.models.BaseLlm;
import com.google.adk.models.BaseLlmConnection;
import com.google.adk.models.LlmRequest;
import com.google.adk.models.LlmResponse;
import com.google.adk.sessions.BaseSessionService;
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.sessions.Session;
import com.google.adk.sessions.SessionException;
import com.google.adk.tools.BaseTool;
import com.google.adk.tools.ToolContext;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.genai.types.Content;
import com.google.genai.types.FunctionCall;
import com.google.genai.types.FunctionDeclaration;
import com.google.genai.types.Part;
import io.a2a.server.agentexecution.RequestContext;
import io.a2a.server.events.EventQueue;
Expand Down Expand Up @@ -1096,6 +1106,117 @@ public void execute_withDefaultArtifactPerRun_emitsMessageAndLastChunk() {
assertThat(finalMessage).isNull();
}

@Test
public void execute_withEmptyLongRunningToolStateDelta_skipsEmptyArtifactAndCompletes() {
BaseTool pendingTool =
new BaseTool("pending_tool", "Long-running tool.", /* isLongRunning= */ true) {
@Override
public Optional<FunctionDeclaration> declaration() {
return Optional.of(FunctionDeclaration.builder().name(name()).build());
}

@Override
public Single<Map<String, Object>> runAsync(
Map<String, Object> args, ToolContext toolContext) {
toolContext.state().put("lro_started", true);
return Single.just(ImmutableMap.of());
}
};
BaseLlm singleCallLlm =
new BaseLlm("test-model") {
@Override
public Flowable<LlmResponse> generateContent(LlmRequest llmRequest, boolean stream) {
return Flowable.just(
LlmResponse.builder()
.content(
Content.builder()
.role("model")
.parts(
Part.builder()
.functionCall(
FunctionCall.builder()
.id("lro-1")
.name("pending_tool")
.args(ImmutableMap.of())
.build())
.build())
.build())
.build());
}

@Override
public BaseLlmConnection connect(LlmRequest llmRequest) {
throw new UnsupportedOperationException();
}
};
LlmAgent lroAgent =
LlmAgent.builder()
.name("lro_agent")
.model(singleCallLlm)
.tools(ImmutableList.of(pendingTool))
.build();
InMemorySessionService sessionService = new InMemorySessionService();
AgentExecutor executor =
new AgentExecutor.Builder()
.app(App.builder().name(APP_NAME).rootAgent(lroAgent).build())
.sessionService(sessionService)
.artifactService(new InMemoryArtifactService())
.agentExecutorConfig(AgentExecutorConfig.builder().build())
.build();

RequestContext ctx = createRequestContext();
executor.execute(ctx, eventQueue);

ImmutableList<TaskArtifactUpdateEvent> artifactEvents =
enqueuedEvents.stream()
.filter(e -> e instanceof TaskArtifactUpdateEvent)
.map(e -> (TaskArtifactUpdateEvent) e)
.collect(toImmutableList());
assertThat(artifactEvents).hasSize(1);
assertThat(lastFinalState()).isEqualTo(TaskState.COMPLETED);
String contextId = ctx.getContextId();
Session stored =
sessionService
.getSession(APP_NAME, "A2A_USER_" + contextId, contextId, Optional.empty())
.blockingGet();
assertThat(stored.state()).containsEntry("lro_started", true);
ImmutableList<Event> deltaEvents =
stored.immutableEvents().stream()
.filter(e -> e.content().isEmpty())
.collect(toImmutableList());
assertThat(deltaEvents).hasSize(1);
assertThat(deltaEvents.get(0).actions().stateDelta()).containsEntry("lro_started", true);
}

@Test
public void execute_withLeadingContentlessEvent_preservesFirstArtifactAppendFalse() {
Event deltaOnlyEvent =
Event.builder()
.id("delta-1")
.author("agent")
.actions(EventActions.builder().stateDelta(ImmutableMap.of("k", "v")).build())
.build();
Event textEvent =
Event.builder()
.id("text-1")
.author("agent")
.content(Content.fromParts(Part.fromText("hello")))
.build();
testAgent.setEventsToEmit(Flowable.just(deltaOnlyEvent, textEvent));
AgentExecutor executor = executorWith(new InMemorySessionService());

executor.execute(createRequestContext(), eventQueue);

ImmutableList<TaskArtifactUpdateEvent> artifactEvents =
enqueuedEvents.stream()
.filter(e -> e instanceof TaskArtifactUpdateEvent)
.map(e -> (TaskArtifactUpdateEvent) e)
.collect(toImmutableList());
assertThat(artifactEvents).hasSize(1);
assertThat(artifactEvents.get(0).isAppend()).isFalse();
assertThat(lastFinalState()).isEqualTo(TaskState.COMPLETED);
}

private static final class TestAgent extends BaseAgent {
private Flowable<Event> eventsToEmit;
private volatile InvocationContext lastInvocationContext;
Expand Down
122 changes: 81 additions & 41 deletions core/src/main/java/com/google/adk/agents/InvocationContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -369,20 +369,27 @@ private boolean isOnCurrentBranch(
*/
private ImmutableSet<String> branchFunctionCallIds(
ImmutableList<Event> events, String scopeBranch) {
String descendantPrefix = scopeBranch + ".";
return events.stream()
.filter(
event -> {
@Nullable String eventBranch = event.branch().orElse(null);
return !isNullOrEmpty(eventBranch)
&& (eventBranch.equals(scopeBranch) || eventBranch.startsWith(descendantPrefix));
})
.filter(event -> isOnBranchOrDescendant(event.branch().orElse(null), scopeBranch))
.flatMap(event -> event.functionCalls().stream())
.map(FunctionCall::id)
.flatMap(Optional::stream)
.collect(toImmutableSet());
}

/**
* Returns whether {@code eventBranch} is on {@code scopeBranch} or a dot-separated descendant.
* When {@code scopeBranch} is null or empty, every branch counts.
*/
private static boolean isOnBranchOrDescendant(
@Nullable String eventBranch, @Nullable String scopeBranch) {
if (isNullOrEmpty(scopeBranch)) {
return true;
}
return !isNullOrEmpty(eventBranch)
&& (eventBranch.equals(scopeBranch) || eventBranch.startsWith(scopeBranch + "."));
}

/** Returns the user content that triggered this invocation, if any. */
public Optional<Content> userContent() {
return Optional.ofNullable(userContent);
Expand Down Expand Up @@ -645,27 +652,36 @@ private static boolean carriesLongRunningCall(Event event) {
}

/**
* Returns whether either of the last two events on this branch pauses the invocation, the
* condition Python uses to decide whether to withhold an agent's end-of-agent checkpoint.
* Returns whether a paused call on this branch or a descendant sub-branch in this invocation is
* still unanswered. Inside a workflow node, limits matches to this node's path or descendants so
* a paused sibling branch does not block a joined node.
*/
boolean lastEventsPauseInvocation() {
ImmutableList<Event> events = events(/* currentInvocation= */ true, /* currentBranch= */ true);
return events.subList(Math.max(0, events.size() - 2), events.size()).stream()
.anyMatch(this::shouldPauseInvocation);
boolean hasUnansweredLongRunningCallOnBranch() {
return hasUnansweredLongRunningCall(/* authors= */ null);
}

/**
* Returns whether {@code eventPath} belongs to {@code scopeNodePath} or a descendant workflow
* node. Outside a workflow node ({@code scopeNodePath} null or empty), every path counts.
*/
private static boolean isOnNodePathOrDescendant(
@Nullable String eventPath, @Nullable String scopeNodePath) {
if (isNullOrEmpty(scopeNodePath)) {
return true;
}
return !isNullOrEmpty(eventPath)
&& (eventPath.equals(scopeNodePath) || eventPath.startsWith(scopeNodePath + "/"));
}

/**
* Returns whether a long-running call made anywhere inside {@code agent}'s subtree is still
* unanswered. A workflow agent needs this because a sub-agent can pause without emitting an
* event, and because Java gives every sub-agent of a {@link ParallelAgent} that agent's own
* branch, which no branch filter can tell apart. Scoping by subtree keeps a paused parallel
* sibling from stalling an unrelated branch, as Python does.
* Returns whether a paused call made anywhere inside {@code agent}'s subtree on this branch and
* node path is still unanswered. Workflow agents use this to detect a sub-agent that paused
* without emitting an event, including across nested {@link ParallelAgent} branches.
*/
boolean hasUnansweredLongRunningCallIn(BaseAgent agent) {
Set<String> scope = new HashSet<>();
collectAgentNames(agent, scope);
return hasUnansweredLongRunningCall(
events(/* currentInvocation= */ true, /* currentBranch= */ false), scope);
return hasUnansweredLongRunningCall(scope);
}

private static void collectAgentNames(BaseAgent agent, Set<String> names) {
Expand All @@ -677,40 +693,64 @@ private static void collectAgentNames(BaseAgent agent, Set<String> names) {
}
}

private record AwaitedCall(String id, String branch, String nodePath) {}

/**
* Whether {@code events} hold a long-running call with no response. {@code scope} restricts which
* authors' calls count; responses always count whoever authored them, since a resumed answer is
* authored by the user.
* Whether any pausing call event in this invocation within this branch, node path, and optional
* {@code authors} set still has an unanswered call. An agent response must sit on the call's
* branch and node path; a user response must sit on the call's branch or a descendant.
*/
private static boolean hasUnansweredLongRunningCall(
ImmutableList<Event> events, Set<String> scope) {
private boolean hasUnansweredLongRunningCall(@Nullable Set<String> authors) {
if (!isResumable()) {
return false;
}
ImmutableList<Event> events = events(/* currentInvocation= */ true, /* currentBranch= */ false);
if (events.isEmpty()) {
return false;
}
Set<String> awaited = new HashSet<>();
@Nullable String scopeBranch = branch;
Set<AwaitedCall> unanswered = new HashSet<>();
for (Event event : events) {
if (!carriesLongRunningCall(event)) {
continue;
if (!unanswered.isEmpty()) {
Set<String> pendingConfirmations = event.actions().requestedToolConfirmations().keySet();
for (FunctionResponse response : event.functionResponses()) {
response
.id()
.filter(id -> !pendingConfirmations.contains(id))
.ifPresent(id -> removeAnsweredCalls(unanswered, event, id));
}
}
if (!scope.contains(event.author())) {
if (!carriesLongRunningCall(event)
|| (authors != null && !authors.contains(event.author()))
|| !isOnBranchOrDescendant(event.branch().orElse(null), scopeBranch)
|| !isOnNodePathOrDescendant(
event.nodeInfo().map(NodeInfo::path).orElse(null), nodePath)) {
continue;
}
// Only long-running calls count, as in Python: an ordinary call in the event runs inline.
Set<String> longRunningIds = event.longRunningToolIds().orElse(ImmutableSet.of());
String callBranch = event.branch().orElse("");
String callNodePath = event.nodeInfo().map(NodeInfo::path).orElse("");
// Match StepResume.pauseLeftCallsUnanswered: union calls and long-running ids.
for (FunctionCall call : event.functionCalls()) {
call.id().filter(longRunningIds::contains).ifPresent(awaited::add);
call.id().ifPresent(id -> unanswered.add(new AwaitedCall(id, callBranch, callNodePath)));
}
}
if (awaited.isEmpty()) {
return false;
}
Set<String> answered = new HashSet<>();
for (Event event : events) {
for (FunctionResponse response : event.functionResponses()) {
response.id().ifPresent(answered::add);
for (String id : event.longRunningToolIds().orElse(ImmutableSet.of())) {
unanswered.add(new AwaitedCall(id, callBranch, callNodePath));
}
}
return !answered.containsAll(awaited);
return !unanswered.isEmpty();
}

private static void removeAnsweredCalls(
Set<AwaitedCall> unanswered, Event responseEvent, String responseId) {
String eventBranch = responseEvent.branch().orElse("");
String eventPath = responseEvent.nodeInfo().map(NodeInfo::path).orElse("");
boolean isUser = Objects.equals(responseEvent.author(), Role.USER);
unanswered.removeIf(call ->
call.id().equals(responseId)
&& (isUser
? (eventBranch.isEmpty() || isOnBranchOrDescendant(eventBranch, call.branch()))
&& (eventPath.isEmpty() || isOnNodePathOrDescendant(eventPath, call.nodePath()))
: eventBranch.equals(call.branch()) && eventPath.equals(call.nodePath())));
}

/**
Expand Down
17 changes: 9 additions & 8 deletions core/src/main/java/com/google/adk/agents/LlmAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,9 @@ protected Flowable<Event> runAsyncImpl(InvocationContext invocationContext) {
})
.concatWith(
Flowable.defer(() -> {
if (resumePaused.get() || !invocationContext.isResumable()) {
if (resumePaused.get()
|| !invocationContext.isResumable()
|| invocationContext.hasUnansweredLongRunningCallOnBranch()) {
return Flowable.<Event>empty();
}
return endOfAgentAndRecord(invocationContext);
Expand All @@ -853,20 +855,19 @@ protected Flowable<Event> runAsyncImpl(InvocationContext invocationContext) {
}
// Normal path: emit an end-of-agent checkpoint so a later run can skip this agent.
AtomicBoolean paused = new AtomicBoolean(false);
return flow.doOnNext(
event -> {
if (invocationContext.shouldPauseInvocation(event)) {
paused.set(true);
}
})
return flow.doOnNext(event -> {
if (invocationContext.shouldPauseInvocation(event)) {
paused.set(true);
}
})
.concatWith(
Flowable.defer(() -> {
// Only the checkpoint is withheld, as in Python; the flow still runs. A
// transferring agent stays open so a resume re-enters it and reaches the
// sub-agent it handed off to.
// An open delegation leaves the agent unfinished too, so a resume re-enters it.
if (paused.get()
|| invocationContext.lastEventsPauseInvocation()
|| invocationContext.hasUnansweredLongRunningCallOnBranch()
|| Functions.leftADelegationUnanswered(invocationContext, delegationTools())) {
return Flowable.empty();
}
Expand Down
Loading
Loading