Skip to content
Merged
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
9 changes: 6 additions & 3 deletions internal/a2a/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,15 +353,18 @@ func (e *piExecutor) Execute(ctx context.Context, execCtx *a2asrv.ExecutorContex
if res.err != nil {
e.logger.Log(ctx, slog.LevelError, "a2a-server: prompt failed",
"task", execCtx.TaskID, "err", res.err)
yield(a2a.NewStatusUpdateEvent(execCtx, a2a.TaskStateFailed,
a2a.NewMessage(a2a.MessageRoleAgent, a2a.NewTextPart(res.err.Error()))), nil)
msg := a2a.NewMessage(a2a.MessageRoleAgent, a2a.NewTextPart(res.err.Error()))
setTimelinePosition(msg, updater.nextPosition())
yield(a2a.NewStatusUpdateEvent(execCtx, a2a.TaskStateFailed, msg), nil)
return
}
// The reply was already streamed as chunks; a final
// artifact would duplicate it. Emit one only when the
// turn produced text without streaming it.
if !updater.streamedText() && strings.TrimSpace(res.result.FinalText) != "" {
if !yield(a2a.NewArtifactEvent(execCtx, a2a.NewTextPart(res.result.FinalText)), nil) {
final := a2a.NewArtifactEvent(execCtx, a2a.NewTextPart(res.result.FinalText))
setTimelinePosition(final.Artifact, updater.nextPosition())
if !yield(final, nil) {
return
}
}
Expand Down
8 changes: 4 additions & 4 deletions internal/a2a/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func TestServeStreamingEvents(t *testing.T) {
continue
}
if text := part.Text(); text != "" {
if part.Meta()[adkMetaThoughtKey] == true {
if part.Meta()[kagentThoughtKey] == true {
sawThought = true
}
if text == "done" {
Expand All @@ -249,11 +249,11 @@ func TestServeStreamingEvents(t *testing.T) {
continue
}
if data, ok := part.Data().(map[string]any); ok {
switch part.Meta()[adkMetaTypeKey] {
switch part.Meta()[kagentPartTypeKey] {
case "function_call":
sawToolCall = data["name"] == "git status -s" && data["args"] != nil
sawToolCall = data["name"] == "bash" && data["args"] != nil
case "function_response":
sawToolResult = data["name"] == "git status -s" && data["response"] != nil
sawToolResult = data["name"] == "bash" && data["response"] != nil
}
}
}
Expand Down
192 changes: 159 additions & 33 deletions internal/a2a/server/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,51 @@ package server

import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"time"

"github.com/a2aproject/a2a-go/v2/a2a"
"github.com/a2aproject/a2a-go/v2/a2asrv"
acp "github.com/coder/acp-go-sdk"

"github.com/dimetron/pi-go/internal/acp/server/adapter"
)

// kagent's shared A2A metadata keys (kagent go/api/a2a/metadata.go). The
// kagent UI classifies a data part as a tool call or result by
// kagentPartTypeKey alone — a part without it renders as unrecognized data,
// not as a tool card — and orders a reloaded task by kagentTimelineKey when
// every entry carries one.
const (
kagentPartTypeKey = "kagent.dev/a2a/part-type"
kagentThoughtKey = "kagent.dev/a2a/thought"
kagentTimelineKey = "kagent.dev/a2a/timeline-position"
)

// ADK metadata keys, matching what kagent's ADK executor writes on A2A parts
// (google.golang.org/adk/v2/server/adka2a/v2). The kagent UI classifies data
// parts by shape ({name,args} vs {name,response}) rather than by these keys,
// but keeping them lets ADK-based clients round-trip the parts.
// (google.golang.org/adk/v2/server/adka2a/v2). kagent no longer reads them;
// they are kept so ADK-based clients can still round-trip the parts.
const (
adkMetaTypeKey = "adk_type"
adkMetaThoughtKey = "adk_thought"
)

const (
partTypeFunctionCall = "function_call"
partTypeFunctionResponse = "function_response"
)

// a2aUpdater implements acpserver.SessionUpdater by translating ACP session
// updates into A2A TaskArtifactUpdateEvents, mirroring how kagent's ADK
// executor converts ADK session events to A2A artifacts:
// updates into A2A TaskArtifactUpdateEvents, mirroring the artifacts kagent's
// Claude and Codex harnesses emit (kagent go/harness/runtime/a2a/executor.go):
//
// - agent_message_chunk → text artifact (append to one artifact per turn)
// - agent_thought_chunk → text artifact marked adk_thought (append)
// - tool_call start → data part {name, args, id} adk_type=function_call
// - tool_call update → data part {name, response} adk_type=function_response
// - agent_message_chunk → text artifact (append to one artifact per run)
// - agent_thought_chunk → text artifact marked thought (append)
// - tool_call start → data part {id, name, args} part-type=function_call
// - tool_call terminal → data part {id, name, response} part-type=function_response
//
// Events are pushed to a channel that piExecutor.Execute drains and yields to
// the A2A client, so streaming reaches the UI as it happens rather than in one
Expand All @@ -39,10 +59,13 @@ type a2aUpdater struct {
mu sync.Mutex
textArtifactID a2a.ArtifactID
thoughtArtifactID a2a.ArtifactID
textPosition time.Time // timeline position of the open text artifact
thoughtPosition time.Time // timeline position of the open thinking artifact
textBuf strings.Builder // accumulated assistant text for the open artifact
thoughtBuf strings.Builder // accumulated thinking for the open artifact
streamedAnyText bool
toolNames map[string]string // ACP call ID → tool name
lastPosition time.Time
}

func newA2AUpdater(ctx context.Context, execCtx *a2asrv.ExecutorContext) *a2aUpdater {
Expand Down Expand Up @@ -112,17 +135,19 @@ func (u *a2aUpdater) emitText(ctx context.Context, content acp.ContentBlock, tho
var ev *a2a.TaskArtifactUpdateEvent
if id == "" {
ev = a2a.NewArtifactEvent(u.execCtx, a2a.NewTextPart(text))
position := u.nextPositionLocked()
setTimelinePosition(ev.Artifact, position)
if thought {
u.thoughtArtifactID = ev.Artifact.ID
u.thoughtArtifactID, u.thoughtPosition = ev.Artifact.ID, position
} else {
u.textArtifactID = ev.Artifact.ID
u.textArtifactID, u.textPosition = ev.Artifact.ID, position
u.streamedAnyText = true
}
} else {
ev = a2a.NewArtifactUpdateEvent(u.execCtx, id, a2a.NewTextPart(text))
}
if thought {
ev.Artifact.Parts[0].SetMeta(adkMetaThoughtKey, true)
markThought(ev.Artifact.Parts[0])
}
u.mu.Unlock()

Expand All @@ -140,16 +165,17 @@ func (u *a2aUpdater) emitText(ctx context.Context, content acp.ContentBlock, tho
func (u *a2aUpdater) closeTextArtifacts(ctx context.Context) error {
u.mu.Lock()
type pending struct {
id a2a.ArtifactID
text string
thought bool
id a2a.ArtifactID
text string
thought bool
position time.Time
}
var closing []pending
if u.textArtifactID != "" {
closing = append(closing, pending{u.textArtifactID, u.textBuf.String(), false})
closing = append(closing, pending{u.textArtifactID, u.textBuf.String(), false, u.textPosition})
}
if u.thoughtArtifactID != "" {
closing = append(closing, pending{u.thoughtArtifactID, u.thoughtBuf.String(), true})
closing = append(closing, pending{u.thoughtArtifactID, u.thoughtBuf.String(), true, u.thoughtPosition})
}
u.textArtifactID, u.thoughtArtifactID = "", ""
u.textBuf.Reset()
Expand All @@ -164,8 +190,11 @@ func (u *a2aUpdater) closeTextArtifacts(ctx context.Context) error {
// Replace rather than append: this frame carries the whole text.
ev.Append = false
ev.LastChunk = true
// A replacement replaces the stored artifact's metadata too, so the
// position the first frame set has to be carried again.
setTimelinePosition(ev.Artifact, c.position)
if c.thought {
ev.Artifact.Parts[0].SetMeta(adkMetaThoughtKey, true)
markThought(ev.Artifact.Parts[0])
}
if err := u.emit(ctx, ev); err != nil {
return err
Expand All @@ -174,13 +203,16 @@ func (u *a2aUpdater) closeTextArtifacts(ctx context.Context) error {
return nil
}

// emitToolStart streams a tool invocation as a function_call data part. The
// ACP update carries the human-readable title (e.g. "bash git status -s"),
// which is what the kagent UI shows as the card header; the raw args ride in
// RawInput. The title is remembered so the matching result carries the same
// name.
// emitToolStart streams a tool invocation as a function_call data part,
// named by the registered tool name as kagent's Claude and Codex harnesses
// name theirs. The ACP title folds the main argument into a display string
// ("git status -s" for a bash call); it is only the fallback for a start that
// does not carry the name, since the card already shows the arguments.
func (u *a2aUpdater) emitToolStart(ctx context.Context, tc *acp.SessionUpdateToolCall) error {
name := tc.Title
name, _ := tc.Meta[adapter.ToolNameMetaKey].(string)
if name == "" {
name = tc.Title
}
if name == "" {
name = "tool"
}
Expand All @@ -189,21 +221,37 @@ func (u *a2aUpdater) emitToolStart(ctx context.Context, tc *acp.SessionUpdateToo
return err
}

args, err := jsonValue(tc.RawInput)
if err != nil {
return fmt.Errorf("a2a: encode tool %q args: %w", name, err)
}
if args == nil {
args = map[string]any{}
}

u.mu.Lock()
u.toolNames[string(tc.ToolCallId)] = name
u.mu.Unlock()

part := a2a.NewDataPart(map[string]any{
"name": name,
"args": tc.RawInput,
return u.emitToolArtifact(ctx, partTypeFunctionCall, map[string]any{
"id": string(tc.ToolCallId),
"name": name,
"args": args,
})
part.SetMeta(adkMetaTypeKey, "function_call")
return u.emit(ctx, a2a.NewArtifactEvent(u.execCtx, part))
}

// emitToolEnd streams a tool result as a function_response data part.
//
// Only a terminal update is a result. ACP also sends non-terminal updates for
// a running call — a subagent's card is re-sent with each nested call it
// makes — and treating those as results rendered a nameless result card per
// nested call and orphaned the real one.
func (u *a2aUpdater) emitToolEnd(ctx context.Context, tu *acp.SessionToolCallUpdate) error {
if tu.Status == nil ||
(*tu.Status != acp.ToolCallStatusCompleted && *tu.Status != acp.ToolCallStatusFailed) {
return nil
}

if err := u.closeTextArtifacts(ctx); err != nil {
return err
}
Expand All @@ -216,12 +264,90 @@ func (u *a2aUpdater) emitToolEnd(ctx context.Context, tu *acp.SessionToolCallUpd
name = "tool"
}

part := a2a.NewDataPart(map[string]any{
result, err := jsonValue(tu.RawOutput)
if err != nil {
return fmt.Errorf("a2a: encode tool %q result: %w", name, err)
}
// The shape kagent's harness writes and its tool card reads.
response := map[string]any{"result": result}
if *tu.Status == acp.ToolCallStatusFailed {
response["isError"] = true
}
return u.emitToolArtifact(ctx, partTypeFunctionResponse, map[string]any{
"id": string(tu.ToolCallId),
"name": name,
"response": tu.RawOutput,
"response": response,
})
part.SetMeta(adkMetaTypeKey, "function_response")
return u.emit(ctx, a2a.NewArtifactEvent(u.execCtx, part))
}

// emitToolArtifact emits one tool part as a complete artifact of its own,
// tagged with both kagent's part-type key and the legacy ADK one.
func (u *a2aUpdater) emitToolArtifact(ctx context.Context, partType string, data map[string]any) error {
part := a2a.NewDataPart(data)
part.SetMeta(kagentPartTypeKey, partType)
part.SetMeta(adkMetaTypeKey, partType)

ev := a2a.NewArtifactEvent(u.execCtx, part)
ev.LastChunk = true
u.mu.Lock()
setTimelinePosition(ev.Artifact, u.nextPositionLocked())
u.mu.Unlock()
return u.emit(ctx, ev)
}

// nextPositionLocked returns a strictly increasing timeline position, so two
// artifacts emitted within one clock tick still sort in emission order.
// Caller must hold mu.
func (u *a2aUpdater) nextPositionLocked() time.Time {
position := time.Now().UTC()
if !position.After(u.lastPosition) {
position = u.lastPosition.Add(time.Nanosecond)
}
u.lastPosition = position
return position
}

// nextPosition is nextPositionLocked for a caller that does not hold mu.
func (u *a2aUpdater) nextPosition() time.Time {
u.mu.Lock()
defer u.mu.Unlock()
return u.nextPositionLocked()
}

// timelineLayout is RFC 3339 with a fixed nine-digit fraction. The kagent UI
// orders positions by string comparison, and time.RFC3339Nano trims trailing
// zeros — ".33171Z" would sort before ".331709Z". Fixed width keeps string
// order equal to time order, and the value still parses as RFC3339Nano.
const timelineLayout = "2006-01-02T15:04:05.000000000Z07:00"

// setTimelinePosition records kagent's task-timeline ordering key.
func setTimelinePosition(carrier a2a.MetadataCarrier, position time.Time) {
carrier.SetMeta(kagentTimelineKey, position.UTC().Format(timelineLayout))
}

// markThought tags a text part as reasoning rather than the answer, under
// kagent's key and the legacy ADK one.
func markThought(part *a2a.Part) {
part.SetMeta(kagentThoughtKey, true)
part.SetMeta(adkMetaThoughtKey, true)
}

// jsonValue converts v to plain JSON values. Tool inputs and results can be Go
// structs, and an A2A data part is converted to a protobuf Struct on the gRPC
// path, which accepts only maps, slices and scalars.
func jsonValue(v any) (any, error) {
if v == nil {
return nil, nil
}
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
var out any
if err := json.Unmarshal(data, &out); err != nil {
return nil, err
}
return out, nil
}

// emit pushes one event to the executor's drain channel, aborting when the
Expand Down
Loading
Loading