diff --git a/bus/a2a_gettask_test.go b/bus/a2a_gettask_test.go new file mode 100644 index 0000000..41c53bf --- /dev/null +++ b/bus/a2a_gettask_test.go @@ -0,0 +1,266 @@ +package bus + +import ( + "context" + "errors" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/a2aproject/a2a-go/v2/a2a" +) + +func a2aHistoryText(t *testing.T, message *a2a.Message) string { + t.Helper() + if len(message.Parts) != 1 { + t.Fatalf("unexpected part count in %#v", message) + } + return message.Parts[0].Text() +} + +func TestA2AGetTaskPollsSubmitDeliverReply(t *testing.T) { + agents := setupAgents(t, ":memory:") + defer agents.runtime.Close() + ctx := context.Background() + publication, issued := setupA2APrincipal(t, agents) + server := httptest.NewServer(NewServer(agents.runtime, ServerOptions{})) + defer server.Close() + transport := a2aTestTransport(t, server, publication.ID) + defer transport.Destroy() + params := a2aTestParams(issued.Credential, string(a2a.Version)) + + message := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("Review this"), a2a.NewTextPart("Focus on security")) + message.ID = "remote-message-1" + result, err := transport.SendMessage(ctx, params, &a2a.SendMessageRequest{Message: message}) + requireNoError(t, err) + submitted := result.(*a2a.Task) + + polled, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: submitted.ID}) + requireNoError(t, err) + require(t, polled.ID == submitted.ID && polled.ContextID == submitted.ContextID, "poll lost task identity: %#v", polled) + require(t, polled.Status.State == a2a.TaskStateSubmitted && polled.Status.Timestamp != nil, "unexpected poll status: %#v", polled.Status) + require(t, len(polled.History) == 1, "unexpected poll history: %#v", polled.History) + first := polled.History[0] + require(t, first.ID == "remote-message-1" && first.Role == a2a.MessageRoleUser, "unexpected request message: %#v", first) + require(t, first.TaskID == submitted.ID && first.ContextID == submitted.ContextID, "history message lost task link: %#v", first) + require(t, a2aHistoryText(t, first) == "Review this\nFocus on security", "unexpected request body: %#v", first) + + reservation, err := agents.runtime.ReserveInbox(ctx, agents.reviewerToken, 10, 0) + require(t, err == nil && reservation != nil && len(reservation.Messages) == 1, "unexpected inbox: %#v, %v", reservation, err) + inbound := reservation.Messages[0] + if _, err := agents.runtime.CommitInbox(ctx, agents.reviewerToken, reservation.ID); err != nil { + t.Fatal(err) + } + working, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: submitted.ID}) + require(t, err == nil && working.Status.State == a2a.TaskStateWorking, "delivery did not advance poll: %#v, %v", working, err) + + reply, err := agents.runtime.SendMessage(ctx, agents.reviewerToken, SendMessageInput{ + To: issued.Principal.ID, Mode: MessageResponse, ResponseTo: inbound.ID, Body: "Found one issue", IdempotencyKey: "review-reply", + }) + requireNoError(t, err) + completed, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: submitted.ID}) + require(t, err == nil && completed.Status.State == a2a.TaskStateCompleted, "reply did not complete poll: %#v, %v", completed, err) + require(t, len(completed.History) == 2, "unexpected completed history: %#v", completed.History) + answer := completed.History[1] + require(t, answer.Role == a2a.MessageRoleAgent && answer.ID == reply.MessageID, "unexpected agent message: %#v", answer) + require(t, answer.TaskID == submitted.ID && answer.ContextID == submitted.ContextID, "agent message lost task link: %#v", answer) + require(t, a2aHistoryText(t, answer) == "Found one issue", "unexpected agent body: %#v", answer) + require(t, completed.Status.Message == nil, "status duplicated the reply: %#v", completed.Status) +} + +func TestA2AGetTaskSurvivesRestart(t *testing.T) { + database := filepath.Join(t.TempDir(), "bus.db") + agents := setupAgents(t, database) + ctx := context.Background() + publication, issued := setupA2APrincipal(t, agents) + server := httptest.NewServer(NewServer(agents.runtime, ServerOptions{})) + transport := a2aTestTransport(t, server, publication.ID) + params := a2aTestParams(issued.Credential, string(a2a.Version)) + + message := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("Review this")) + message.ID = "remote-message-1" + result, err := transport.SendMessage(ctx, params, &a2a.SendMessageRequest{Message: message}) + requireNoError(t, err) + taskID := result.(*a2a.Task).ID + reservation, err := agents.runtime.ReserveInbox(ctx, agents.reviewerToken, 10, 0) + requireNoError(t, err) + inbound := reservation.Messages[0] + if _, err := agents.runtime.CommitInbox(ctx, agents.reviewerToken, reservation.ID); err != nil { + t.Fatal(err) + } + if _, err := agents.runtime.SendMessage(ctx, agents.reviewerToken, SendMessageInput{ + To: issued.Principal.ID, Mode: MessageResponse, ResponseTo: inbound.ID, Body: "Done", IdempotencyKey: "restart-reply", + }); err != nil { + t.Fatal(err) + } + transport.Destroy() + server.Close() + requireNoError(t, agents.runtime.Close()) + + restarted, err := Open(database) + requireNoError(t, err) + defer restarted.Close() + server = httptest.NewServer(NewServer(restarted, ServerOptions{})) + defer server.Close() + transport = a2aTestTransport(t, server, publication.ID) + defer transport.Destroy() + + polled, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: taskID}) + require(t, err == nil && polled.Status.State == a2a.TaskStateCompleted, "restart lost poll state: %#v, %v", polled, err) + require(t, len(polled.History) == 2, "restart lost poll history: %#v", polled.History) + require(t, a2aHistoryText(t, polled.History[0]) == "Review this", "restart lost request body: %#v", polled.History[0]) + require(t, polled.History[1].Role == a2a.MessageRoleAgent && a2aHistoryText(t, polled.History[1]) == "Done", "restart lost agent reply: %#v", polled.History[1]) +} + +func TestA2AGetTaskHistoryLengthSelectsRecentMessages(t *testing.T) { + agents := setupAgents(t, ":memory:") + defer agents.runtime.Close() + ctx := context.Background() + publication, issued := setupA2APrincipal(t, agents) + server := httptest.NewServer(NewServer(agents.runtime, ServerOptions{})) + defer server.Close() + transport := a2aTestTransport(t, server, publication.ID) + defer transport.Destroy() + params := a2aTestParams(issued.Credential, string(a2a.Version)) + + first := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("Start")) + first.ID = "turn-1" + result, err := transport.SendMessage(ctx, params, &a2a.SendMessageRequest{Message: first}) + requireNoError(t, err) + taskID := result.(*a2a.Task).ID + principal, err := agents.runtime.AuthenticateA2APrincipal(ctx, issued.Credential, publication.ID) + requireNoError(t, err) + if _, err := sqliteStore(t, agents.runtime).SetA2ATaskState(ctx, principal, string(taskID), A2ATaskInputRequired); err != nil { + t.Fatal(err) + } + second := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("Here is the answer")) + second.ID = "turn-2" + second.TaskID = taskID + if _, err := transport.SendMessage(ctx, params, &a2a.SendMessageRequest{Message: second}); err != nil { + t.Fatal(err) + } + reservation, err := agents.runtime.ReserveInbox(ctx, agents.reviewerToken, 10, 0) + require(t, err == nil && reservation != nil && len(reservation.Messages) == 2, "unexpected inbox: %#v, %v", reservation, err) + if _, err := agents.runtime.CommitInbox(ctx, agents.reviewerToken, reservation.ID); err != nil { + t.Fatal(err) + } + if _, err := agents.runtime.SendMessage(ctx, agents.reviewerToken, SendMessageInput{ + To: issued.Principal.ID, Mode: MessageResponse, ResponseTo: reservation.Messages[1].ID, Body: "Thanks", IdempotencyKey: "turn-2-reply", + }); err != nil { + t.Fatal(err) + } + + full, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: taskID}) + require(t, err == nil && len(full.History) == 3, "omitted historyLength truncated history: %#v, %v", full, err) + zero := 0 + empty, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: taskID, HistoryLength: &zero}) + require(t, err == nil && len(empty.History) == 0, "zero historyLength kept messages: %#v, %v", empty, err) + one := 1 + latest, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: taskID, HistoryLength: &one}) + require(t, err == nil && len(latest.History) == 1, "historyLength=1 kept %#v, %v", latest, err) + require(t, latest.History[0].Role == a2a.MessageRoleAgent && a2aHistoryText(t, latest.History[0]) == "Thanks", "historyLength=1 missed the reply: %#v", latest.History[0]) + two := 2 + recent, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: taskID, HistoryLength: &two}) + require(t, err == nil && len(recent.History) == 2, "historyLength=2 kept %#v, %v", recent, err) + require(t, recent.History[0].ID == "turn-2" && recent.History[1].Role == a2a.MessageRoleAgent, "historyLength=2 selected wrong messages: %#v", recent.History) + many := 99 + all, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: taskID, HistoryLength: &many}) + require(t, err == nil && len(all.History) == 3, "oversized historyLength truncated history: %#v, %v", all, err) + negative := -1 + _, err = transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: taskID, HistoryLength: &negative}) + require(t, errors.Is(err, a2a.ErrInvalidParams), "negative historyLength error = %v", err) +} + +func TestA2AGetTaskReportsBusStates(t *testing.T) { + agents := setupAgents(t, ":memory:") + defer agents.runtime.Close() + ctx := context.Background() + publication, issued := setupA2APrincipal(t, agents) + server := httptest.NewServer(NewServer(agents.runtime, ServerOptions{})) + defer server.Close() + transport := a2aTestTransport(t, server, publication.ID) + defer transport.Destroy() + params := a2aTestParams(issued.Credential, string(a2a.Version)) + principal, err := agents.runtime.AuthenticateA2APrincipal(ctx, issued.Credential, publication.ID) + requireNoError(t, err) + + cases := []struct { + state A2ATaskState + want a2a.TaskState + }{ + {A2ATaskInputRequired, a2a.TaskStateInputRequired}, + {A2ATaskFailed, a2a.TaskStateFailed}, + {A2ATaskCanceled, a2a.TaskStateCanceled}, + {A2ATaskRejected, a2a.TaskStateRejected}, + } + for i, tc := range cases { + result, err := agents.runtime.AcceptA2AMessage(ctx, issued.Credential, publication.ID, AcceptA2AMessageInput{ + ClientMessageID: "state-message-" + string(rune('a'+i)), + Body: "case", + }) + requireNoError(t, err) + if _, err := sqliteStore(t, agents.runtime).SetA2ATaskState(ctx, principal, result.ID, tc.state); err != nil { + t.Fatal(err) + } + polled, err := transport.GetTask(ctx, params, &a2a.GetTaskRequest{ID: a2a.TaskID(result.ID)}) + require(t, err == nil && polled.Status.State == tc.want, "state %s polled as %#v, %v", tc.state, polled, err) + } +} + +func TestA2AGetTaskHidesForeignTasksAndEnforcesCredentialState(t *testing.T) { + agents := setupAgents(t, ":memory:") + defer agents.runtime.Close() + ctx := context.Background() + publication, owner := setupA2APrincipal(t, agents) + other, err := agents.runtime.CreateA2APrincipal(ctx, agents.scope.ScopeToken, CreateA2APrincipalInput{PublicationID: publication.ID, Label: "Other caller"}) + requireNoError(t, err) + server := httptest.NewServer(NewServer(agents.runtime, ServerOptions{})) + defer server.Close() + transport := a2aTestTransport(t, server, publication.ID) + defer transport.Destroy() + + message := a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("Private work")) + message.ID = "private-turn" + result, err := transport.SendMessage(ctx, a2aTestParams(owner.Credential, string(a2a.Version)), &a2a.SendMessageRequest{Message: message}) + requireNoError(t, err) + taskID := result.(*a2a.Task).ID + + // Another principal's poll is indistinguishable from an unknown task. + _, err = transport.GetTask(ctx, a2aTestParams(other.Credential, string(a2a.Version)), &a2a.GetTaskRequest{ID: taskID}) + require(t, errors.Is(err, a2a.ErrTaskNotFound), "foreign task lookup error = %v", err) + _, err = transport.GetTask(ctx, a2aTestParams(owner.Credential, string(a2a.Version)), &a2a.GetTaskRequest{ID: "a2at_does-not-exist"}) + require(t, errors.Is(err, a2a.ErrTaskNotFound), "unknown task lookup error = %v", err) + + // A rotated credential stops working immediately. + if _, err := agents.runtime.RotateA2APrincipal(ctx, agents.scope.ScopeToken, owner.Principal.ID); err != nil { + t.Fatal(err) + } + _, err = transport.GetTask(ctx, a2aTestParams(owner.Credential, string(a2a.Version)), &a2a.GetTaskRequest{ID: taskID}) + require(t, errors.Is(err, a2a.ErrUnauthenticated), "rotated credential lookup error = %v", err) + + // A disabled credential and a disabled publication stay denied. + rotated, err := agents.runtime.RotateA2APrincipal(ctx, agents.scope.ScopeToken, other.Principal.ID) + requireNoError(t, err) + if _, err := agents.runtime.SetA2APrincipalEnabled(ctx, agents.scope.ScopeToken, other.Principal.ID, false); err != nil { + t.Fatal(err) + } + _, err = transport.GetTask(ctx, a2aTestParams(rotated.Credential, string(a2a.Version)), &a2a.GetTaskRequest{ID: taskID}) + require(t, errors.Is(err, a2a.ErrUnauthenticated), "disabled credential lookup error = %v", err) + if _, err := agents.runtime.SetA2APrincipalEnabled(ctx, agents.scope.ScopeToken, other.Principal.ID, true); err != nil { + t.Fatal(err) + } + if _, err := agents.runtime.SetAgentCardPublicationEnabled(ctx, agents.scope.ScopeToken, publication.ID, false); err != nil { + t.Fatal(err) + } + _, err = transport.GetTask(ctx, a2aTestParams(rotated.Credential, string(a2a.Version)), &a2a.GetTaskRequest{ID: taskID}) + require(t, errors.Is(err, a2a.ErrUnauthenticated), "disabled publication lookup error = %v", err) + if _, err := agents.runtime.SetAgentCardPublicationEnabled(ctx, agents.scope.ScopeToken, publication.ID, true); err != nil { + t.Fatal(err) + } + + // Version and parameter checks still apply to task reads. + _, err = transport.GetTask(ctx, a2aTestParams(rotated.Credential, "broken"), &a2a.GetTaskRequest{ID: taskID}) + require(t, errors.Is(err, a2a.ErrVersionNotSupported), "bad version lookup error = %v", err) + _, err = transport.GetTask(ctx, a2aTestParams(rotated.Credential, string(a2a.Version)), &a2a.GetTaskRequest{ID: "!!! not an id !!!"}) + require(t, errors.Is(err, a2a.ErrInvalidParams), "invalid task ID lookup error = %v", err) +} diff --git a/bus/a2a_ingress.go b/bus/a2a_ingress.go index 7fef89f..50488d0 100644 --- a/bus/a2a_ingress.go +++ b/bus/a2a_ingress.go @@ -111,26 +111,59 @@ func acceptA2AInput(request *a2a.SendMessageRequest) (AcceptA2AMessageInput, err }, nil } -func taskToA2A(task A2ATaskCorrelation, message *a2a.Message) *a2a.Task { - state := a2a.TaskStateSubmitted - switch task.State { +func a2aTaskState(state A2ATaskState) a2a.TaskState { + switch state { case A2ATaskWorking: - state = a2a.TaskStateWorking + return a2a.TaskStateWorking case A2ATaskInputRequired: - state = a2a.TaskStateInputRequired + return a2a.TaskStateInputRequired case A2ATaskCompleted: - state = a2a.TaskStateCompleted + return a2a.TaskStateCompleted case A2ATaskFailed: - state = a2a.TaskStateFailed + return a2a.TaskStateFailed case A2ATaskCanceled: - state = a2a.TaskStateCanceled + return a2a.TaskStateCanceled case A2ATaskRejected: - state = a2a.TaskStateRejected + return a2a.TaskStateRejected + default: + return a2a.TaskStateSubmitted + } +} + +func taskToA2A(task A2ATaskCorrelation, message *a2a.Message) *a2a.Task { + timestamp, _ := time.Parse(time.RFC3339Nano, task.UpdatedAt) + return &a2a.Task{ + ID: a2a.TaskID(task.ID), ContextID: task.ContextID, + Status: a2a.TaskStatus{State: a2aTaskState(task.State), Timestamp: ×tamp}, History: []*a2a.Message{message}, } +} + +// taskHistoryToA2A renders one user message per correlated turn in acceptance +// order, each followed by its agent reply when one exists. A negative +// historyLength keeps the full history; otherwise only the most recent +// historyLength messages are returned. Agent replies surface in history only; +// status carries the state and timestamp without a duplicate message. +func taskHistoryToA2A(task A2ATaskCorrelation, history []A2ATaskHistoryEntry, historyLength int) *a2a.Task { timestamp, _ := time.Parse(time.RFC3339Nano, task.UpdatedAt) + messages := make([]*a2a.Message, 0, 2*len(history)) + for _, entry := range history { + messages = append(messages, &a2a.Message{ + ID: entry.ClientMessageID, ContextID: task.ContextID, TaskID: a2a.TaskID(task.ID), + Role: a2a.MessageRoleUser, Parts: a2a.ContentParts{a2a.NewTextPart(entry.RequestBody)}, + }) + if entry.ResponseMessageID != "" { + messages = append(messages, &a2a.Message{ + ID: entry.ResponseMessageID, ContextID: task.ContextID, TaskID: a2a.TaskID(task.ID), + Role: a2a.MessageRoleAgent, Parts: a2a.ContentParts{a2a.NewTextPart(entry.ResponseBody)}, + }) + } + } + if historyLength >= 0 && historyLength < len(messages) { + messages = messages[len(messages)-historyLength:] + } return &a2a.Task{ ID: a2a.TaskID(task.ID), ContextID: task.ContextID, - Status: a2a.TaskStatus{State: state, Timestamp: ×tamp}, History: []*a2a.Message{message}, + Status: a2a.TaskStatus{State: a2aTaskState(task.State), Timestamp: ×tamp}, History: messages, } } @@ -162,8 +195,25 @@ func (h *a2aRequestHandler) unsupported(ctx context.Context) error { return a2a.ErrUnsupportedOperation } -func (h *a2aRequestHandler) GetTask(ctx context.Context, _ *a2a.GetTaskRequest) (*a2a.Task, error) { - return nil, h.unsupported(ctx) +func (h *a2aRequestHandler) GetTask(ctx context.Context, request *a2a.GetTaskRequest) (*a2a.Task, error) { + if err := h.authorize(ctx); err != nil { + return nil, err + } + if request == nil || request.ID == "" { + return nil, a2a.NewError(a2a.ErrInvalidParams, "A task ID is required") + } + historyLength := -1 + if request.HistoryLength != nil { + if *request.HistoryLength < 0 { + return nil, a2a.NewError(a2a.ErrInvalidParams, "historyLength cannot be negative") + } + historyLength = *request.HistoryLength + } + task, history, err := h.runtime.A2ATaskHistory(ctx, h.credential, h.publicationID, string(request.ID)) + if err != nil { + return nil, mapBusA2AError(err) + } + return taskHistoryToA2A(task, history, historyLength), nil } func (h *a2aRequestHandler) ListTasks(ctx context.Context, _ *a2a.ListTasksRequest) (*a2a.ListTasksResponse, error) { diff --git a/bus/a2a_ingress_test.go b/bus/a2a_ingress_test.go index eca12fd..db236b9 100644 --- a/bus/a2a_ingress_test.go +++ b/bus/a2a_ingress_test.go @@ -75,7 +75,7 @@ func TestA2ASendMessageEnforcesAuthenticationVersionAndContent(t *testing.T) { _, err = transport.GetTask(ctx, a2aTestParams("invalid", string(a2a.Version)), &a2a.GetTaskRequest{ID: "hidden-task"}) require(t, errors.Is(err, a2a.ErrUnauthenticated), "unauthenticated task lookup error = %v", err) _, err = transport.GetTask(ctx, a2aTestParams(issued.Credential, string(a2a.Version)), &a2a.GetTaskRequest{ID: "hidden-task"}) - require(t, errors.Is(err, a2a.ErrUnsupportedOperation), "unsupported task lookup error = %v", err) + require(t, errors.Is(err, a2a.ErrTaskNotFound), "unknown task lookup error = %v", err) reservation, err := agents.runtime.ReserveInbox(ctx, agents.reviewerToken, 10, 0) require(t, err == nil && reservation == nil, "rejected requests created work: %#v, %v", reservation, err) diff --git a/bus/a2a_tasks.go b/bus/a2a_tasks.go index 37e6e44..e33a155 100644 --- a/bus/a2a_tasks.go +++ b/bus/a2a_tasks.go @@ -225,28 +225,6 @@ FROM messages WHERE scope_id=? AND from_kind='a2aPrincipal' AND state NOT IN ('a return task, nil } -func (s *Store) A2ATask(ctx context.Context, principal A2APrincipal, taskID string) (A2ATaskCorrelation, error) { - tx, err := s.beginTx(ctx, principal.ScopeID) - if err != nil { - return A2ATaskCorrelation{}, err - } - defer tx.Rollback() - if err := requireCurrentA2APrincipal(ctx, tx, principal); err != nil { - return A2ATaskCorrelation{}, err - } - if err := expireMessages(ctx, tx, principal.ScopeID, nowMillis()); err != nil { - return A2ATaskCorrelation{}, err - } - task, err := loadA2ATask(ctx, tx, principal.ID, taskID) - if err != nil { - return A2ATaskCorrelation{}, err - } - if err := tx.Commit(); err != nil { - return A2ATaskCorrelation{}, err - } - return task, nil -} - func a2aTaskTerminal(state A2ATaskState) bool { switch state { case A2ATaskCompleted, A2ATaskFailed, A2ATaskCanceled, A2ATaskRejected: @@ -344,13 +322,63 @@ func (r *Runtime) AcceptA2AMessage(ctx context.Context, credential, publicationI return task, err } -func (r *Runtime) A2ATask(ctx context.Context, credential, publicationID, taskID string) (A2ATaskCorrelation, error) { +// A2ATaskHistory loads a task with the request/response bodies of its +// correlated turns. Unknown and other-principal tasks report NotFound without +// revealing task existence, and revoked credentials or disabled publications +// stay denied through the same in-transaction fencing as acceptance. +func (s *Store) A2ATaskHistory(ctx context.Context, principal A2APrincipal, taskID string) (A2ATaskCorrelation, []A2ATaskHistoryEntry, error) { + tx, err := s.beginTx(ctx, principal.ScopeID) + if err != nil { + return A2ATaskCorrelation{}, nil, err + } + defer tx.Rollback() + if err := requireCurrentA2APrincipal(ctx, tx, principal); err != nil { + return A2ATaskCorrelation{}, nil, err + } + if err := expireMessages(ctx, tx, principal.ScopeID, nowMillis()); err != nil { + return A2ATaskCorrelation{}, nil, err + } + task, err := loadA2ATask(ctx, tx, principal.ID, taskID) + if err != nil { + return A2ATaskCorrelation{}, nil, err + } + history := make([]A2ATaskHistoryEntry, 0, len(task.Messages)) + for _, correlation := range task.Messages { + entry := A2ATaskHistoryEntry{ClientMessageID: correlation.ClientMessageID} + var body string + err := tx.QueryRowContext(ctx, `SELECT body FROM messages WHERE scope_id=? AND message_id=?`, principal.ScopeID, correlation.BusRequestMessageID).Scan(&body) + if errors.Is(err, sql.ErrNoRows) { + // Retention prunes a terminal task with its messages as one unit, + // so a missing row should not happen; skip rather than fail the poll. + continue + } + if err != nil { + return A2ATaskCorrelation{}, nil, err + } + entry.RequestBody = body + if correlation.BusResponseMessageID != "" { + err := tx.QueryRowContext(ctx, `SELECT body FROM messages WHERE scope_id=? AND message_id=?`, principal.ScopeID, correlation.BusResponseMessageID).Scan(&body) + if err == nil { + entry.ResponseMessageID, entry.ResponseBody = correlation.BusResponseMessageID, body + } else if !errors.Is(err, sql.ErrNoRows) { + return A2ATaskCorrelation{}, nil, err + } + } + history = append(history, entry) + } + if err := tx.Commit(); err != nil { + return A2ATaskCorrelation{}, nil, err + } + return task, history, nil +} + +func (r *Runtime) A2ATaskHistory(ctx context.Context, credential, publicationID, taskID string) (A2ATaskCorrelation, []A2ATaskHistoryEntry, error) { principal, err := r.AuthenticateA2APrincipal(ctx, credential, publicationID) if err != nil { - return A2ATaskCorrelation{}, err + return A2ATaskCorrelation{}, nil, err } if err := validateIdentity(taskID, "taskId", false); err != nil { - return A2ATaskCorrelation{}, err + return A2ATaskCorrelation{}, nil, err } - return r.store.A2ATask(ctx, principal, taskID) + return r.store.A2ATaskHistory(ctx, principal, taskID) } diff --git a/bus/a2a_tasks_test.go b/bus/a2a_tasks_test.go index 268f296..22fc643 100644 --- a/bus/a2a_tasks_test.go +++ b/bus/a2a_tasks_test.go @@ -40,7 +40,7 @@ func TestA2ATaskCorrelationIsDurableAndIdempotent(t *testing.T) { restarted, err := Open(database) requireNoError(t, err) defer restarted.Close() - stored, err := restarted.A2ATask(ctx, issued.Credential, publication.ID, task.ID) + stored, _, err := restarted.A2ATaskHistory(ctx, issued.Credential, publication.ID, task.ID) require(t, err == nil && stored.ID == task.ID && len(stored.Messages) == 1 && stored.Messages[0].BusRequestMessageID == correlation.BusRequestMessageID, "correlation did not survive restart: %#v, %v", stored, err) } @@ -58,14 +58,14 @@ func TestA2ATaskTracksBusDeliveryAndResponse(t *testing.T) { if _, err := agents.runtime.CommitInbox(ctx, agents.reviewerToken, reservation.ID); err != nil { t.Fatal(err) } - working, err := agents.runtime.A2ATask(ctx, issued.Credential, publication.ID, task.ID) + working, _, err := agents.runtime.A2ATaskHistory(ctx, issued.Credential, publication.ID, task.ID) require(t, err == nil && working.State == A2ATaskWorking, "delivery did not advance task: %#v, %v", working, err) reply, err := agents.runtime.SendMessage(ctx, agents.reviewerToken, SendMessageInput{ To: issued.Principal.ID, Mode: MessageResponse, ResponseTo: inbound.ID, Body: "Found one issue", IdempotencyKey: "review-reply", }) requireNoError(t, err) require(t, reply.State == DeliveryAcknowledged, "A2A response was not committed durably: %#v", reply) - completed, err := agents.runtime.A2ATask(ctx, issued.Credential, publication.ID, task.ID) + completed, _, err := agents.runtime.A2ATaskHistory(ctx, issued.Credential, publication.ID, task.ID) require(t, err == nil && completed.State == A2ATaskCompleted && completed.Messages[0].BusResponseMessageID == reply.MessageID, "response did not complete task: %#v, %v", completed, err) } @@ -103,7 +103,7 @@ func TestA2ATaskIsIsolatedByPrincipal(t *testing.T) { requireNoError(t, err) task, err := agents.runtime.AcceptA2AMessage(ctx, owner.Credential, publication.ID, AcceptA2AMessageInput{ClientMessageID: "private-turn", Body: "Private work"}) requireNoError(t, err) - _, err = agents.runtime.A2ATask(ctx, other.Credential, publication.ID, task.ID) + _, _, err = agents.runtime.A2ATaskHistory(ctx, other.Credential, publication.ID, task.ID) requireCode(t, err, CodeNotFound) otherPrincipal, err := agents.runtime.AuthenticateA2APrincipal(ctx, other.Credential, publication.ID) requireNoError(t, err) diff --git a/bus/hardening_test.go b/bus/hardening_test.go index b8fe8cc..8d400df 100644 --- a/bus/hardening_test.go +++ b/bus/hardening_test.go @@ -95,7 +95,7 @@ func TestA2ARotationFencesRetryReadAndStateChanges(t *testing.T) { } _, err = s.AcceptA2AMessage(ctx, p, a.runtime.a2aPrincipalLimits, input) requireCode(t, err, CodeUnauthenticated) - _, err = s.A2ATask(ctx, p, task.ID) + _, _, err = s.A2ATaskHistory(ctx, p, task.ID) requireCode(t, err, CodeUnauthenticated) _, err = s.SetA2ATaskState(ctx, p, task.ID, A2ATaskFailed) requireCode(t, err, CodeUnauthenticated) diff --git a/bus/protocol.go b/bus/protocol.go index e3da003..3fe54b2 100644 --- a/bus/protocol.go +++ b/bus/protocol.go @@ -124,6 +124,16 @@ type A2ATaskCorrelation struct { UpdatedAt string `json:"updatedAt"` } +// A2ATaskHistoryEntry pairs one correlated Bus request with its optional agent +// response body so A2A callers can poll task progress. It is principal-scoped: +// entries only ever carry the calling principal's own turns. +type A2ATaskHistoryEntry struct { + ClientMessageID string `json:"clientMessageId"` + RequestBody string `json:"requestBody"` + ResponseMessageID string `json:"responseMessageId,omitempty"` + ResponseBody string `json:"responseBody,omitempty"` +} + type AcceptA2AMessageInput struct { TaskID string `json:"taskId,omitempty"` ContextID string `json:"contextId,omitempty"` diff --git a/bus/storage_backend.go b/bus/storage_backend.go index a25ee38..934c168 100644 --- a/bus/storage_backend.go +++ b/bus/storage_backend.go @@ -92,7 +92,7 @@ type storageBackend interface { SetA2APrincipalEnabled(context.Context, string, string, bool) (A2APrincipal, error) AuthenticateA2APrincipal(context.Context, string, string) (A2APrincipal, error) AcceptA2AMessage(context.Context, A2APrincipal, A2APrincipalLimits, AcceptA2AMessageInput) (A2ATaskCorrelation, error) - A2ATask(context.Context, A2APrincipal, string) (A2ATaskCorrelation, error) + A2ATaskHistory(context.Context, A2APrincipal, string) (A2ATaskCorrelation, []A2ATaskHistoryEntry, error) CreateOutputStream(context.Context, string, CreateOutputStreamInput) (OutputStream, error) ListOutputStreams(context.Context, string) ([]OutputStream, error) diff --git a/docs/architecture/a2a-bridge.md b/docs/architecture/a2a-bridge.md index 6cc47cd..d4beffe 100644 --- a/docs/architecture/a2a-bridge.md +++ b/docs/architecture/a2a-bridge.md @@ -28,7 +28,18 @@ SDK versions and A2A protocol versions are independent. The bridge records both. - Remote principals are bound to one publication. Their credentials do not inherit scope, agent, MCP, or administrative authority. - Agent Intercom shared work items are a coordination pool. They are not A2A Tasks. A2A Tasks represent one delegated interaction and its result stream. -The reference daemon stores owner-controlled publications, scoped remote principals, and durable A2A task correlations. Each accepted A2A message maps to one Bus request and its optional linked response. The published interface accepts A2A `SendMessage` over HTTP+JSON and returns the durable A2A Task. Text parts are supported in the first write surface. Streaming, push notifications, task listing, task reads, and cancellation are not yet supported. +The reference daemon stores owner-controlled publications, scoped remote principals, and durable A2A task correlations. Each accepted A2A message maps to one Bus request and its optional linked response. The published interface accepts A2A `SendMessage` over HTTP+JSON and returns the durable A2A Task. Text parts are supported in the first write surface. Streaming, push notifications, task listing, and cancellation are not yet supported. + +Callers poll a returned task with A2A `GetTask` over the same publication URL and bearer credential. The lookup reuses publication authorization, the `A2A-Version` check, and the principal-scoped task read, so unknown and other-principal tasks report task-not-found without revealing task existence, and revoked credentials or disabled publications stay denied. + +`GetTask` returns the durable task identity and current state with this mapping: + +- Bus states map one-to-one onto the A2A task states (`submitted`, `working`, `input-required`, `completed`, `failed`, `canceled`, `rejected`); the status timestamp is the task's last update time. +- History holds one user message per correlated turn in acceptance order, each followed by its agent reply when the agent has responded. User messages reuse the caller's `messageId`; agent messages carry the durable Bus response identifier. Every history message sets the task and context IDs and holds a single plain-text part. +- `historyLength`, when present, limits the response to that many of the most recent history messages (`0` returns no history); an omitted value returns the full history. Negative values are rejected. +- Agent replies surface in history only; the status carries no duplicate message, and no artifacts are returned. + +Bounds: history covers only the polling principal's own turns on that task, each message body holds at most 64 KiB of text, and polls observe the same retention as the underlying Bus messages. Poll after delivery to observe `working`, and after the agent's correlated response to observe `completed` with the reply. Principal credentials are stored as one-way digests and shown only when created or rotated. Rotation invalidates the previous value immediately. Both the principal and its publication must be enabled for authentication to succeed. diff --git a/docs/clients.md b/docs/clients.md index 0c9c988..e5905f5 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -61,6 +61,13 @@ issued, err := owner.CreateA2APrincipal(ctx, bus.CreateA2APrincipalInput{ // Use an A2A 1.0 HTTP+JSON client against publication.InterfaceURL. // Send the issued credential as a bearer token. The first write surface // accepts text-only SendMessage requests and returns a durable A2A Task. +// Poll that task with GetTask until its state is terminal (completed, failed, canceled or rejected), then read the +// agent's reply from the task history: +// +// task, err := a2aClient.GetTask(ctx, &a2a.GetTaskRequest{ID: taskID}) // bearer credential, A2A-Version 1.0 +// // task.Status.State transitions submitted -> working -> completed; +// // task.History holds each user turn followed by its agent reply. +// // Pass historyLength to keep only the most recent history messages. principalUsage, err := owner.ListA2APrincipalUsage(ctx) diff --git a/spec/0.1/README.md b/spec/0.1/README.md index 47c7876..d3a49b7 100644 --- a/spec/0.1/README.md +++ b/spec/0.1/README.md @@ -205,7 +205,7 @@ A2A task states are `submitted`, `working`, `input-required`, `completed`, `fail Client message IDs are idempotent within one remote principal. Repeating an accepted message returns its existing task and Bus correlation. Reusing the ID with different content returns `CONFLICT`. A principal cannot read or change another principal's task records. -The reference HTTP+JSON binding accepts authenticated A2A `SendMessage` requests containing plain text parts. It joins multiple parts in order with a newline, creates a durable Bus request, and returns the correlated A2A Task. The first binding does not accept file, URL, data, extension, referenced-task, streaming, push-notification, task-read, task-list, or cancellation operations. Rejected requests do not create Bus work. If an `A2A-Version` header is present, it MUST contain exactly `1.0`. +The reference HTTP+JSON binding accepts authenticated A2A `SendMessage` requests containing plain text parts. It joins multiple parts in order with a newline, creates a durable Bus request, and returns the correlated A2A Task. It also accepts A2A `GetTask`, which returns the calling principal's task with its current state and its correlated request and response history as plain text messages. Unknown tasks and tasks of another principal return the same task-not-found error. The first binding does not accept file, URL, data, extension, referenced-task, streaming, push-notification, task-list, or cancellation operations. Rejected requests do not create Bus work. If an `A2A-Version` header is present, it MUST contain exactly `1.0`. The reference runtime limits unfinished inbound work independently for each A2A principal. The defaults are 1,000 messages and 16 MiB of text. A limit check and message acceptance occur in the same transaction. Terminal tasks and undelivered expired requests release their capacity. Scope authority can inspect each principal's counts, bytes, and effective limits without reading message content. diff --git a/spec/0.1/http.md b/spec/0.1/http.md index b09a592..651d3cb 100644 --- a/spec/0.1/http.md +++ b/spec/0.1/http.md @@ -109,6 +109,7 @@ The `health` object MAY include `features`, a unique array of feature identifier | `GET` | `/outputs/{streamId}/latest` | Scope or scoped read | Latest output value or `null` | | `GET` | `/a2a/agents/{publicationId}/.well-known/agent-card.json` | None | Enabled A2A Agent Card | | `POST` | `/a2a/agents/{publicationId}/message:send` | Scoped A2A | Durable A2A Task | +| `GET` | `/a2a/agents/{publicationId}/tasks/{taskId}` | Scoped A2A | Durable A2A Task with correlated history | | `POST` | `/mcp` | Agent | MCP Streamable HTTP endpoint | `/health/live` returns HTTP 200 while the server process can answer requests. `/health` and `/health/ready` return HTTP 200 only when the runtime can reach its storage backend. An unavailable backend returns HTTP 503 with `status: not_ready`. Health responses expose the backend name and availability, never its address or credentials. @@ -166,7 +167,7 @@ Agent Card publications are absent by default. A scope owner publishes one regis The reference runtime additionally limits the aggregate active A2A message backlog to 5,000 messages and 64 MiB of bodies per scope. Active means queued, reserved or delivered, not acknowledged or expired. Per-principal unfinished-task quotas apply independently. Already-accepted idempotent retries do not consume another slot and remain available at capacity. -`POST /a2a/agents/{publicationId}/message:send` implements A2A 1.0 HTTP+JSON `SendMessage`. It accepts user messages made only of plain text parts and returns a durable A2A Task. The bearer credential must belong to the requested publication. The optional `A2A-Version` header must contain exactly `1.0`. Other A2A operations and content types return A2A protocol errors. +`POST /a2a/agents/{publicationId}/message:send` implements A2A 1.0 HTTP+JSON `SendMessage`. It accepts user messages made only of plain text parts and returns a durable A2A Task. `GET /a2a/agents/{publicationId}/tasks/{taskId}` implements A2A 1.0 `GetTask` for the calling principal's own tasks. It returns the task state and a history of each accepted user message followed by the agent's response when one exists. The optional `historyLength` query parameter keeps only that many of the most recent messages; `0` returns none and a negative value is rejected. Unknown tasks and tasks owned by another principal return the same A2A task-not-found error. On both routes the bearer credential must belong to the requested publication and the optional `A2A-Version` header must contain exactly `1.0`. Other A2A operations and content types return A2A protocol errors. `POST /outputs/{streamId}/values` accepts `contentType`, `value`, and an optional URI reference. Agent credentials require an explicit publisher grant. Scoped output credentials require `publish` permission. `GET /outputs/{streamId}/values?after=0&limit=50` returns ordered values after the cursor. The limit is 1 through 100. Clients use `nextSequence` as their next cursor and rebuild from the latest value when `resyncRequired` is true.