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 @@ -1108,9 +1108,13 @@ public void testNonBlockingWithMultipleMessages() throws Exception {
CountDownLatch streamEventLatch = new CountDownLatch(2); // artifact-2 + completion
List<UpdateEvent_v0_3> streamReceivedEvents = new CopyOnWriteArrayList<>();
AtomicBoolean streamUnexpectedEvent = new AtomicBoolean(false);
AtomicBoolean streamReceivedInitialTask = new AtomicBoolean(false);

BiConsumer<ClientEvent_v0_3, AgentCard_v0_3> streamConsumer = (event, agentCard) -> {
if (event instanceof TaskUpdateEvent_v0_3 tue) {
// Per A2A spec 3.1.2, the stream begins with the Task, then its updates
if (event instanceof TaskEvent_v0_3 && !streamReceivedInitialTask.get() && streamReceivedEvents.isEmpty()) {
streamReceivedInitialTask.set(true);
} else if (event instanceof TaskUpdateEvent_v0_3 tue) {
streamReceivedEvents.add(tue.getUpdateEvent());
streamEventLatch.countDown();
} else {
Expand Down Expand Up @@ -1139,6 +1143,7 @@ public void testNonBlockingWithMultipleMessages() throws Exception {

assertFalse(resubUnexpectedEvent.get());
assertFalse(streamUnexpectedEvent.get());
assertTrue(streamReceivedInitialTask.get(), "The send stream must begin with the Task");
assertNull(resubErrorRef.get());

// Both should have received 2 events: artifact-2 and completion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ private record UpdateResult(boolean isFinal, @Nullable Task taskSnapshot) {}
*/
private final ConcurrentHashMap<String, Message> initialMessages = new ConcurrentHashMap<>();

/**
* Initial Tasks for new streaming tasks that have not emitted their first event yet. When that
* first event is a status or artifact update, this Task is what the TaskStore creates for the
* task, so the streaming response can begin with the same Task object.
*/
private final ConcurrentHashMap<String, Task> initialTasks = new ConcurrentHashMap<>();

private MainEventBus eventBus;

private TaskStore taskStore;
Expand Down Expand Up @@ -148,9 +155,24 @@ public void registerInitialMessage(String taskId, Message message) {
initialMessages.put(taskId, message);
}

/**
* Registers the Task that a new task's first event creates in the TaskStore when that event is a
* status or artifact update, until its first event is persisted. Without a registration, the
* TaskManager creates it.
*
* @param taskId the new task identifier
* @param initialTask the Task to create: SUBMITTED, with the opening message as its history
*/
public void registerInitialTask(String taskId, Task initialTask) {
initialTasks.put(taskId, initialTask);
}

/** Remove a registration after all events already submitted by the agent are processed. */
public void clearInitialMessageAfterEvents(String taskId) {
eventBus.submit(() -> initialMessages.remove(taskId));
eventBus.submit(() -> {
initialMessages.remove(taskId);
initialTasks.remove(taskId);
});
}

/**
Expand Down Expand Up @@ -258,10 +280,12 @@ private void processEvent(MainEventBusContext context) {

try {
Message initialMessage = initialMessages.get(taskId);
updateResult = updateTaskStore(taskId, event, isReplicated, initialMessage);
Task initialTask = initialTasks.get(taskId);
updateResult = updateTaskStore(taskId, event, isReplicated, initialMessage, initialTask);
if (event instanceof Task || event instanceof TaskStatusUpdateEvent
|| event instanceof TaskArtifactUpdateEvent || event instanceof A2AError) {
initialMessages.remove(taskId);
initialTasks.remove(taskId);
}
boolean isFinal = updateResult.isFinal();

Expand Down Expand Up @@ -365,8 +389,15 @@ private void processEvent(MainEventBusContext context) {
* @throws InternalError if persistence fails
*/
private UpdateResult updateTaskStore(String taskId, Event event, boolean isReplicated,
@Nullable Message initialMessage) throws InternalError {
@Nullable Message initialMessage, @Nullable Task initialTask) throws InternalError {
try {
// A new task opened by a status or artifact update: create it as registered (see
// registerInitialTask); TaskManager then finds it in the TaskStore and applies the update
if (initialTask != null && (event instanceof TaskStatusUpdateEvent
|| event instanceof TaskArtifactUpdateEvent) && taskStore.get(taskId) == null) {
taskStore.save(initialTask, false);
}

// Extract contextId from event (all relevant events have it)
String contextId = extractContextId(event);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;

import mutiny.zero.ZeroPublisher;

import org.a2aproject.sdk.jsonrpc.common.wrappers.ListTasksResult;
import org.a2aproject.sdk.server.EffectiveAgentCard;
import org.a2aproject.sdk.server.ServerCallContext;
Expand Down Expand Up @@ -76,6 +78,7 @@
import org.a2aproject.sdk.spec.TaskPushNotificationConfig;
import org.a2aproject.sdk.spec.TaskQueryParams;
import org.a2aproject.sdk.spec.TaskState;
import org.a2aproject.sdk.spec.TaskStatus;
import org.a2aproject.sdk.spec.TaskStatusUpdateEvent;
import org.a2aproject.sdk.spec.UnsupportedOperationError;
import org.a2aproject.sdk.util.Assert;
Expand Down Expand Up @@ -1056,13 +1059,24 @@ public Flow.Publisher<StreamingEventKind> onMessageSendStream(
mss.requestContext.getTaskId(), "TaskId must be non-null after RequestContext.build()");
final AtomicReference<@NonNull String> taskId = new AtomicReference<>(queueTaskId);

// The Task this stream begins with if the agent's first event is a status or artifact update
// (see prependTaskBeforeFirstUpdate). For an existing task it is the task as this request updated
// it; for a new task it is registered below as the Task that the first event creates.
Task initialTask = mss.task() != null ? mss.task() : Task.builder()
.id(queueTaskId)
.contextId(mss.requestContext.getContextId())
.status(new TaskStatus(TaskState.TASK_STATE_SUBMITTED))
.history(List.of(params.message()))
.build();

boolean agentStarted = false;
EventQueue queue;
ResultAggregator resultAggregator;
EventConsumer consumer;
try {
if (mss.task() == null) {
mainEventBusProcessor.registerInitialMessage(queueTaskId, params.message());
mainEventBusProcessor.registerInitialTask(queueTaskId, initialTask);
}
// Create queue with real taskId (no tempId parameter needed)
queue = queueManager.createOrTap(queueTaskId);
Expand Down Expand Up @@ -1125,6 +1139,8 @@ public Flow.Publisher<StreamingEventKind> onMessageSendStream(
// Then convert EventQueueItem -> Event
Flow.Publisher<Event> eventPublisher = convertingProcessor(processed, EventQueueItem::getEvent);

eventPublisher = prependTaskBeforeFirstUpdate(eventPublisher, initialTask);

Flow.Publisher<StreamingEventKind> finalPublisher = convertingProcessor(eventPublisher, event -> (StreamingEventKind) event);

// Wrap publisher to detect client disconnect and immediately close ChildQueue
Expand Down Expand Up @@ -1213,6 +1229,59 @@ public void onComplete() {
}
}

/**
* Per A2A Protocol Spec 3.1.2 (Send Streaming Message):
* "If the agent returns a Task, the stream MUST begin with the Task object."
* <p>
* An agent may begin with a status or artifact update (e.g. {@link AgentEmitter#startWork()}); the
* client would then receive an update of a Task it was never sent. This emits {@code initialTask}
* before such a first event. A first Task or Message passes unchanged.
* </p>
* <p>
* {@code initialTask} is fixed before the agent runs (the existing task as this request updated it, or
* the Task that a new task's first event creates), not read back from the TaskStore when the first
* event is relayed: by then the TaskStore may already hold later events, whose status and artifacts
* would reach the client ahead of, and again in, the updates that follow.
* </p>
*
* @param source the stream's events
* @param initialTask the Task to emit before a first status or artifact update
* @return the events, with {@code initialTask} before a first status or artifact update
*/
private static Flow.Publisher<Event> prependTaskBeforeFirstUpdate(Flow.Publisher<Event> source, Task initialTask) {
return ZeroPublisher.create(createTubeConfig(), tube -> {
source.subscribe(new Flow.Subscriber<Event>() {
private boolean firstEventSeen = false;

@Override
public void onSubscribe(Flow.Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}

@Override
public void onNext(Event event) {
if (!firstEventSeen) {
firstEventSeen = true;
if (event instanceof TaskStatusUpdateEvent || event instanceof TaskArtifactUpdateEvent) {
tube.send(initialTask);
}
}
tube.send(event);
}

@Override
public void onError(Throwable throwable) {
tube.fail(throwable);
}

@Override
public void onComplete() {
tube.complete();
}
});
});
}

@Override
public TaskPushNotificationConfig onCreateTaskPushNotificationConfig(
TaskPushNotificationConfig params, ServerCallContext context) throws A2AError {
Expand Down
Loading
Loading