Agent Executor (AX) is Google's open agentic orchestration runtime
Go
Feat: support A2A agent in AX. (#274)
Junjie Wang4b9de6aa680f
diff --git a/cmd/ax/exec.go b/cmd/ax/exec.goindex ba14e17..014dea6 100644--- a/cmd/ax/exec.go+++ b/cmd/ax/exec.go@@ -321,6 +321,8 @@ func displayContents(d *internal.Display, contents []*proto.Message) {d.DisplayOutput(fmt.Sprintf("Thinking: %s", textContent.Text))}}+ case *proto.Content_Image, *proto.Content_Audio, *proto.Content_Video, *proto.Content_Document:+ d.DisplayOutput(fmt.Sprintf("unsupported output type for display: %T", o))default:d.DisplayOutput(fmt.Sprintf("unknown output type: %v", o))}diff --git a/cmd/ax/trace.go b/cmd/ax/trace.goindex 13cc63a..1e368ff 100644--- a/cmd/ax/trace.go+++ b/cmd/ax/trace.go@@ -129,7 +129,7 @@ func loadTraceData(ctx context.Context, cfg *config.Config, convID string) (*TraConversationID: convID,RootExecID: rootExecID,Execs: buildExecTraces(execIDs, events),- }, nil+ }, nil}func fetch(ctx context.Context, cfg *config.Config, convID string) ([]*proto.ExecutionEvent, string, []string, error) {@@ -369,10 +369,18 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;backgrou.role-model .c-hdr{background:#dcfce7;color:#166534}.role-model .c-body{background:#f0fdf4}+.role-agent{border-color:#ccfbf1}+.role-agent .c-hdr{background:#ccfbf1;color:#0f766e}+.role-agent .c-body{background:#f0fdfa}+.role-assistant{border-color:#f3e8ff}.role-assistant .c-hdr{background:#f3e8ff;color:#7e22ce}.role-assistant .c-body{background:#faf5ff}+.role-unspecified{border-color:#e5e7eb}+.role-unspecified .c-hdr{background:#f3f4f6;color:#4b5563}+.role-unspecified .c-body{background:#f9fafb}+.role-unknown{border-color:#e5e7eb}.role-unknown .c-hdr{background:#f3f4f6;color:#4b5563}.role-unknown .c-body{background:#f9fafb}diff --git a/go.mod b/go.modindex 7101443..b6bd5af 100644--- a/go.mod+++ b/go.mod@@ -3,6 +3,7 @@ module github.com/google/axgo 1.26.1require (+ github.com/a2aproject/a2a-go/v2 v2.2.0github.com/ai-on-gke/SubstrATE v0.0.0-00010101000000-000000000000github.com/charmbracelet/huh v0.8.0github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834@@ -99,6 +100,7 @@ require (go.yaml.in/yaml/v2 v2.4.3 // indirectgo.yaml.in/yaml/v3 v3.0.4 // indirectgolang.org/x/crypto v0.49.0 // indirect+ golang.org/x/mod v0.33.0 // indirectgolang.org/x/oauth2 v0.36.0 // indirectgolang.org/x/sys v0.42.0 // indirectgolang.org/x/term v0.41.0 // indirectdiff --git a/go.sum b/go.sumindex dd9c4fe..e604da4 100644--- a/go.sum+++ b/go.sum@@ -8,6 +8,8 @@ github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQgithub.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=+github.com/a2aproject/a2a-go/v2 v2.2.0 h1:eayiNXYpyTOLVhhQrGmIHlcy8GnOdnwaNdYQPvS84Ik=+github.com/a2aproject/a2a-go/v2 v2.2.0/go.mod h1:htTxMwicNXXXEwwfjuB/Pd1g7UHDrswhSievncmTVcE=github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=diff --git a/internal/auth/auth.go b/internal/auth/auth.gonew file mode 100644index 0000000..2133360--- /dev/null+++ b/internal/auth/auth.go@@ -0,0 +1,99 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++// Package auth holds shared, transport-agnostic data types and helpers+// for describing how AX authenticates outbound calls to remote agents+// and what extra headers to attach.+package auth++import (+ "errors"+ "fmt"+ "maps"+ "os"+)++// Auth describes how AX authenticates to a remote agent. Two well-known+// schemes are supported, both sourcing their credential value from a+// single environment variable named in CredentialEnv:+// - "api_key": the credential is injected into a single HTTP header.+// For A2A consumers, the header name is determined at runtime from+// the agent's APIKeySecurityScheme on the AgentCard.+// - "bearer": the credential is injected as+// "Authorization: Bearer <value>".+type Auth struct {+ Type string `yaml:"type"` // "api_key" or "bearer"+ CredentialEnv string `yaml:"credential_env"` // env var holding credential value+}++// Headers is a reusable bundle of HTTP-style header values, with both+// literal and env-sourced sources.+type Headers struct {+ Literal map[string]string `yaml:"literal,omitempty"` // literal values (NOT secret-safe)+ Env map[string]string `yaml:"env,omitempty"` // header name -> env var name (secret-safe)+}++// resolveAuthHeader translates an Auth into a single (header name, value)+// tuple to inject.+func resolveAuthHeader(a Auth, apiKeyHeader string) (name, value string, err error) {+ if a.CredentialEnv == "" {+ return "", "", errors.New(`auth: credential_env is required`)+ }+ value = os.Getenv(a.CredentialEnv)+ if value == "" {+ return "", "", fmt.Errorf(`auth: env var %q is empty or unset`, a.CredentialEnv)+ }+ switch a.Type {+ case "bearer":+ return "Authorization", "Bearer " + value, nil+ case "api_key":+ if apiKeyHeader == "" {+ return "", "", errors.New(`auth.api_key: no header name provided by the transport`)+ }+ return apiKeyHeader, value, nil+ default:+ return "", "", fmt.Errorf(`auth.type: unsupported %q (want "api_key" or "bearer")`, a.Type)+ }+}++// MergeAllHeaders flattens user-supplied Headers and the auth-resolved+// header into a single map[string]string applied to every outgoing+// request. Returns (nil, nil) when no headers are produced.+func MergeAllHeaders(a Auth, h Headers, apiKeyHeader string) (map[string]string, error) {+ out := make(map[string]string, len(h.Literal)+len(h.Env)+1)+ maps.Copy(out, h.Literal)+ for k, envVar := range h.Env {+ v := os.Getenv(envVar)+ if v == "" {+ return nil, fmt.Errorf("headers.env[%q]: env var %q is empty or unset", k, envVar)+ }+ out[k] = v+ }+ if a.Type != "" {+ name, value, err := resolveAuthHeader(a, apiKeyHeader)+ if err != nil {+ return nil, err+ }+ if _, exists := out[name]; exists {+ return nil, fmt.Errorf(+ "auth resolves to header %q which is also set via headers; remove one source",+ name)+ }+ out[name] = value+ }+ if len(out) == 0 {+ return nil, nil+ }+ return out, nil+}diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.gonew file mode 100644index 0000000..7a214de--- /dev/null+++ b/internal/auth/auth_test.go@@ -0,0 +1,173 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package auth++import (+ "strings"+ "testing"+)++// ----- ResolveAuthHeader -----++func TestResolveAuthHeader_BearerSuccess(t *testing.T) {+ t.Setenv("MY_TOKEN", "abc123")+ name, value, err := resolveAuthHeader(Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"}, "")+ if err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if name != "Authorization" {+ t.Errorf("name=%q, want %q", name, "Authorization")+ }+ if value != "Bearer abc123" {+ t.Errorf("value=%q, want %q", value, "Bearer abc123")+ }+}++func TestResolveAuthHeader_MissingCredentialEnvFieldErrors(t *testing.T) {+ for _, scheme := range []string{"bearer", "api_key"} {+ t.Run(scheme, func(t *testing.T) {+ _, _, err := resolveAuthHeader(Auth{Type: scheme}, "")+ if err == nil {+ t.Fatal("got nil err, want non-nil for missing credential_env")+ }+ if !strings.Contains(err.Error(), "credential_env") {+ t.Errorf("err should mention credential_env field; got: %v", err)+ }+ })+ }+}++func TestResolveAuthHeader_EnvVarUnsetErrors(t *testing.T) {+ t.Setenv("MY_CRED", "")+ for _, scheme := range []string{"bearer", "api_key"} {+ t.Run(scheme, func(t *testing.T) {+ // apiKeyHeader is "", but the env-empty check fires before+ // the api_key path even consults it.+ _, _, err := resolveAuthHeader(Auth{Type: scheme, CredentialEnv: "MY_CRED"}, "")+ if err == nil {+ t.Fatal("got nil err, want non-nil for unset env")+ }+ if !strings.Contains(err.Error(), "MY_CRED") {+ t.Errorf("err should mention env var; got: %v", err)+ }+ })+ }+}++func TestResolveAuthHeader_UnknownTypeErrors(t *testing.T) {+ t.Setenv("MY_CRED", "value")+ _, _, err := resolveAuthHeader(Auth{Type: "oauth2", CredentialEnv: "MY_CRED"}, "")+ if err == nil {+ t.Fatal("got nil err, want non-nil for unknown type")+ }+ if !strings.Contains(err.Error(), "oauth2") {+ t.Errorf("err should mention the unknown type; got: %v", err)+ }+}++func TestResolveAuthHeader_ApiKeyEmptyHeaderErrors(t *testing.T) {+ t.Setenv("MY_KEY", "k-secret")+ _, _, err := resolveAuthHeader(Auth{Type: "api_key", CredentialEnv: "MY_KEY"}, "")+ if err == nil {+ t.Fatal("got nil err, want non-nil for empty apiKeyHeader")+ }+ if !strings.Contains(err.Error(), "no header name") {+ t.Errorf("err should mention missing header name; got: %v", err)+ }+}++// ----- MergeAllHeaders -----++func TestMergeAllHeaders_LiteralOnly(t *testing.T) {+ got, err := MergeAllHeaders(Auth{}, Headers{+ Literal: map[string]string{"X-Org": "acme", "X-Project": "demo"},+ }, "")+ if err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if got["X-Org"] != "acme" || got["X-Project"] != "demo" || len(got) != 2 {+ t.Errorf("got=%v, want X-Org=acme + X-Project=demo (2 entries)", got)+ }+}++func TestMergeAllHeaders_EnvResolvesValues(t *testing.T) {+ t.Setenv("MY_TOK", "secret123")+ got, err := MergeAllHeaders(Auth{}, Headers{+ Env: map[string]string{"X-Token": "MY_TOK"},+ }, "")+ if err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if got["X-Token"] != "secret123" {+ t.Errorf("X-Token=%q, want %q", got["X-Token"], "secret123")+ }+}++func TestMergeAllHeaders_EnvOverridesLiteralOnCollision(t *testing.T) {+ t.Setenv("OVERRIDE_VAL", "from-env")+ got, err := MergeAllHeaders(Auth{}, Headers{+ Literal: map[string]string{"X-Header": "from-yaml"},+ Env: map[string]string{"X-Header": "OVERRIDE_VAL"},+ }, "")+ if err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if got["X-Header"] != "from-env" {+ t.Errorf("collision: got %q, want %q (Env must override Literal)", got["X-Header"], "from-env")+ }+}++func TestMergeAllHeaders_EnvMissingErrors(t *testing.T) {+ t.Setenv("EMPTY_VAR", "")+ _, err := MergeAllHeaders(Auth{}, Headers{+ Env: map[string]string{"X-Missing": "EMPTY_VAR"},+ }, "")+ if err == nil {+ t.Fatal("got nil err, want non-nil for unset env")+ }+ if !strings.Contains(err.Error(), "EMPTY_VAR") || !strings.Contains(err.Error(), "X-Missing") {+ t.Errorf("err should mention env var and header name; got: %v", err)+ }+}++func TestMergeAllHeaders_AuthAndUserMerge(t *testing.T) {+ t.Setenv("MY_TOKEN", "abc123")+ got, err := MergeAllHeaders(+ Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"},+ Headers{Literal: map[string]string{"X-Org": "acme"}},+ "",+ )+ if err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if got["Authorization"] != "Bearer abc123" || got["X-Org"] != "acme" || len(got) != 2 {+ t.Errorf("got=%v, want Authorization+X-Org (2 entries)", got)+ }+}++func TestMergeAllHeaders_AuthCollidesWithUserHeaderErrors(t *testing.T) {+ t.Setenv("MY_TOKEN", "abc123")+ _, err := MergeAllHeaders(+ Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"},+ Headers{Literal: map[string]string{"Authorization": "Bearer manual"}},+ "",+ )+ if err == nil {+ t.Fatal("got nil err, want non-nil for header collision")+ }+ if !strings.Contains(err.Error(), "Authorization") {+ t.Errorf("err should mention the colliding header name; got: %v", err)+ }+}diff --git a/internal/cliutil/cliutil.go b/internal/cliutil/cliutil.goindex baddb90..68b8e2a 100644--- a/internal/cliutil/cliutil.go+++ b/internal/cliutil/cliutil.go@@ -23,8 +23,8 @@ import ("github.com/google/ax/internal/config""github.com/google/ax/internal/controller""github.com/google/ax/internal/controller/executor"- "github.com/google/ax/internal/gemini""github.com/google/ax/internal/experimental/antigravity"+ "github.com/google/ax/internal/gemini")// NewControllerFromConfig creates a new Controller instance based on the provided configuration.@@ -81,7 +81,7 @@ func NewControllerFromConfig(ctx context.Context, cfg *config.Config) (*controll}for _, agentCfg := range cfg.Registry.RemoteAgents {- if err := c.Registry().RegisterRemote(agentCfg); err != nil {+ if err := c.Registry().RegisterRemote(ctx, agentCfg); err != nil {return nil, fmt.Errorf("failed to register remote agent %s: %w", agentCfg.ID, err)}}diff --git a/internal/config/config.go b/internal/config/config.goindex 16226b8..e7f407b 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -21,6 +21,7 @@ import ("time""github.com/google/ax/internal/agent"+ "github.com/google/ax/internal/auth""gopkg.in/yaml.v3")@@ -126,11 +127,21 @@ type ATEAgentConfig struct {type RemoteAgentConfig struct {ID string `yaml:"id"` // Unique agent identifierName string `yaml:"name"` // Human-readable name- Description string `yaml:"description"` // Description of agent capabilities- Address string `yaml:"address"` // gRPC address (e.g., "localhost:50051")+ Description string `yaml:"description"` // Description+ Address string `yaml:"address"` // Remote agent address+ Protocol string `yaml:"protocol,omitempty"` // "axp" (default) or "a2a"+ Auth auth.Auth `yaml:"auth,omitempty"` // Optional auth (cross-protocol; today honored only for a2a)+ Headers auth.Headers `yaml:"headers,omitempty"` // Optional headers (cross-protocol; today honored only for a2a)+ A2A A2AConfig `yaml:"a2a,omitempty"` // A2A-protocol-specific optionsMetadata map[string]string `yaml:"metadata,omitempty"` // Optional metadata}+// A2AConfig holds A2A-protocol-specific options. Honored only when+// RemoteAgentConfig.Protocol is "a2a".+type A2AConfig struct {+ Stateless bool `yaml:"stateless,omitempty"` // Send full history each turn (default: stateful)+}+// SandboxAgentConfig configures a Kubernetes Sandbox agent to register on startup.type SandboxAgentConfig struct {ID string `yaml:"id"` // Unique agent identifierdiff --git a/internal/controller/registry.go b/internal/controller/registry.goindex 98dc093..1c5601d 100644--- a/internal/controller/registry.go+++ b/internal/controller/registry.go@@ -21,6 +21,7 @@ import ("github.com/google/ax/internal/agent""github.com/google/ax/internal/config"+ "github.com/google/ax/internal/experimental/a2abridge"expagent "github.com/google/ax/internal/experimental/agent")@@ -72,19 +73,31 @@ func (r *Registry) RegisterLocal(cfg config.LocalAgentConfig) error {}// RegisterRemote registers a remote agent by creating a remote agent client.-func (r *Registry) RegisterRemote(cfg config.RemoteAgentConfig) error {+// The protocol field determines what kind of remote agent to register:+// - axp/AXP (default): AX's proto.AgentService.+// - a2a/A2A: A2A protocol.+func (r *Registry) RegisterRemote(ctx context.Context, cfg config.RemoteAgentConfig) error {r.mu.Lock()defer r.mu.Unlock()if err := validateID(cfg.ID); err != nil {return err}-if _, ok := r.agents[cfg.ID]; ok {return fmt.Errorf("agent %s already registered", cfg.ID)}- // Create remote agent client+ switch cfg.Protocol {+ case "", "axp", "AXP":+ return r.registerRemote(cfg)+ case "a2a", "A2A":+ return r.registerA2A(ctx, cfg)+ default:+ return fmt.Errorf("remote agent %s: invalid protocol %q (want \"axp\" or \"a2a\")", cfg.ID, cfg.Protocol)+ }+}++func (r *Registry) registerRemote(cfg config.RemoteAgentConfig) error {remoteAgent, err := agent.NewRemoteAgent(agent.RemoteAgentConfig{Address: cfg.Address,Reconnect: true,@@ -93,7 +106,6 @@ func (r *Registry) RegisterRemote(cfg config.RemoteAgentConfig) error {if err != nil {return fmt.Errorf("failed to create remote agent: %w", err)}-r.agents[cfg.ID] = remoteAgentr.agentInfo[cfg.ID] = &agent.AgentInfo{ID: cfg.ID,@@ -101,7 +113,30 @@ func (r *Registry) RegisterRemote(cfg config.RemoteAgentConfig) error {Description: cfg.Description,Metadata: cfg.Metadata,}+ return nil+}+// Creates an A2A-protocol agent client. The agent's AgentCard is resolved at+// registration time and used to populate the agent's information.+func (r *Registry) registerA2A(ctx context.Context, cfg config.RemoteAgentConfig) error {+ a2aAgent, err := expagent.NewA2AAgent(ctx, expagent.A2AAgentConfig{+ ID: cfg.ID,+ Address: cfg.Address,+ Auth: cfg.Auth,+ Headers: cfg.Headers,+ Stateless: cfg.A2A.Stateless,+ })+ if err != nil {+ return fmt.Errorf("failed to create a2a agent: %w", err)+ }+ name, description := a2abridge.AgentMetadataFromCard(a2aAgent.Card(), cfg.Name, cfg.Description)+ r.agents[cfg.ID] = a2aAgent+ r.agentInfo[cfg.ID] = &agent.AgentInfo{+ ID: cfg.ID,+ Name: name,+ Description: description,+ Metadata: cfg.Metadata,+ }return nil}diff --git a/internal/controller/registry_test.go b/internal/controller/registry_test.goindex cdc7210..5723b4f 100644--- a/internal/controller/registry_test.go+++ b/internal/controller/registry_test.go@@ -17,6 +17,7 @@ package controller// TODO(lhuan): Setup a better automated testing frameworkimport (+ "context""fmt""net""testing"@@ -58,7 +59,7 @@ func TestRegistry_GracefulShutdown(t *testing.T) {// Register multiple agents to create workloadfor i := range 50 {- err := r.RegisterRemote(config.RemoteAgentConfig{+ err := r.RegisterRemote(context.Background(), config.RemoteAgentConfig{ID: fmt.Sprintf("remote-shutdown-test-%d", i),Name: "Shutdown Test Remote",Address: address,diff --git a/internal/experimental/a2abridge/a2a_converter.go b/internal/experimental/a2abridge/a2a_converter.gonew file mode 100644index 0000000..393f12c--- /dev/null+++ b/internal/experimental/a2abridge/a2a_converter.go@@ -0,0 +1,368 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "encoding/json"+ "fmt"+ "strings"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/google/ax/proto"+)++// ----- AX -> A2A direction -----++// MessagesToA2AParts converts AX message history into a flat list of A2A+// Parts. Internal-only AX content are skipped.+func MessagesToA2AParts(msgs []*proto.Message) []*a2a.Part {+ out := make([]*a2a.Part, 0, len(msgs))+ for _, msg := range msgs {+ if msg == nil || msg.Content == nil {+ continue+ }+ if isStateMarkerMessage(msg) {+ continue+ }+ if p := contentToA2APart(msg.Content); p != nil {+ out = append(out, p)+ }+ }+ return out+}++// LatestUserInputParts returns the most recent user-role input as a single+// A2A Part - i.e. what the AX user just typed. The walk goes backward+// from the end of msgs and returns as soon as it finds a user-role+// message with usable content (text/file/data).+func LatestUserInputParts(msgs []*proto.Message) []*a2a.Part {+ for i := len(msgs) - 1; i >= 0; i-- {+ msg := msgs[i]+ if msg == nil || msg.Role != "user" || msg.Content == nil {+ continue+ }+ if isStateMarkerMessage(msg) {+ continue+ }+ switch msg.Content.Type.(type) {+ case *proto.Content_Confirmation,+ *proto.Content_ToolCall,+ *proto.Content_ToolResult,+ *proto.Content_Thought:+ continue+ }+ if p := contentToA2APart(msg.Content); p != nil {+ return []*a2a.Part{p}+ }+ }+ return nil+}++// contentToA2APart converts a single AX Content variant into an A2A Part.+func contentToA2APart(content *proto.Content) *a2a.Part {+ if content == nil {+ return nil+ }+ switch t := content.Type.(type) {+ case *proto.Content_Text:+ if t.Text == nil || t.Text.Text == "" {+ return nil+ }+ return a2a.NewTextPart(t.Text.Text)+ case *proto.Content_Image:+ return imageContentToPart(t.Image)+ case *proto.Content_Audio:+ return audioContentToPart(t.Audio)+ case *proto.Content_Video:+ return videoContentToPart(t.Video)+ case *proto.Content_Document:+ return documentContentToPart(t.Document)+ }+ return nil+}++// rawOrURLPart builds an A2A Part from inline bytes (Raw variant) or a URI+// (URL variant), whichever is non-empty. Returns nil if both are empty.+func rawOrURLPart(data []byte, uri, mediaType string) *a2a.Part {+ if len(data) > 0 {+ return &a2a.Part{Content: a2a.Raw(data), MediaType: mediaType}+ }+ if uri != "" {+ return &a2a.Part{Content: a2a.URL(uri), MediaType: mediaType}+ }+ return nil+}++// mediaTypeOr returns table[enum] if present, otherwise fallback. Used by+// the typed-content converters to resolve the wire-mime string with a+// type-specific generic ("image/*", "audio/*", etc.) when the AX enum+// value isn't in our mapping table.+func mediaTypeOr[E comparable](table map[E]string, enum E, fallback string) string {+ if s := table[enum]; s != "" {+ return s+ }+ return fallback+}++func imageContentToPart(c *proto.ImageContent) *a2a.Part {+ if c == nil {+ return nil+ }+ return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(imageMimeToString, c.MimeType, "image/*"))+}++func audioContentToPart(c *proto.AudioContent) *a2a.Part {+ if c == nil {+ return nil+ }+ return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(audioMimeToString, c.MimeType, "audio/*"))+}++func videoContentToPart(c *proto.VideoContent) *a2a.Part {+ if c == nil {+ return nil+ }+ return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(videoMimeToString, c.MimeType, "video/*"))+}++func documentContentToPart(c *proto.DocumentContent) *a2a.Part {+ if c == nil {+ return nil+ }+ // DocumentContent with TYPE_JSON is the round-trip representation of+ // an A2A DataPart - convert it back. Falls through to raw bytes if+ // the JSON is malformed.+ if c.MimeType == proto.DocumentContent_TYPE_JSON {+ if data := c.GetData(); len(data) > 0 {+ var v any+ if err := json.Unmarshal(data, &v); err == nil {+ return &a2a.Part{+ Content: a2a.Data{Value: v},+ MediaType: "application/json",+ }+ }+ }+ }+ return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(documentMimeToString, c.MimeType, "application/octet-stream"))+}++// ----- A2A -> AX direction -----++// a2aPartsToMessages converts a list of A2A Parts into AX Messages. Each+// Part becomes one Message with the supplied role.+func a2aPartsToMessages(parts []*a2a.Part, role string) []*proto.Message {+ out := make([]*proto.Message, 0, len(parts))+ for _, part := range parts {+ if part == nil {+ continue+ }+ content := a2aPartToContent(part)+ if content == nil {+ continue+ }+ out = append(out, &proto.Message{Role: role, Content: content})+ }+ return out+}++// a2aPartToContent classifies an A2A Part by its Content variant and+// MediaType and produces the appropriate AX Content. Returns nil if the part+// is empty or unrecognised.+func a2aPartToContent(part *a2a.Part) *proto.Content {+ if part == nil {+ return nil+ }+ switch c := part.Content.(type) {+ case a2a.Text:+ text := string(c)+ if text == "" {+ return nil+ }+ return &proto.Content{+ Type: &proto.Content_Text{+ Text: &proto.TextContent{Text: text},+ },+ }+ case a2a.Raw:+ return classifyByMediaType([]byte(c), "", part.MediaType)+ case a2a.URL:+ return classifyByMediaType(nil, string(c), part.MediaType)+ case a2a.Data:+ return dataValueToContent(c.Value)+ }+ return nil+}++// classifyByMediaType builds an AX Content from inline bytes (data) OR a+// URL reference (uri); pass exactly one. The wire MIME string selects+// the typed Content variant (Image/Audio/Video/Document); unrecognised+// MIME types land in DocumentContent with TYPE_UNSPECIFIED.+func classifyByMediaType(data []byte, uri, mediaType string) *proto.Content {+ if e, ok := imageMimeFromString[mediaType]; ok {+ return newImageContent(e, data, uri)+ }+ if e, ok := audioMimeFromString[mediaType]; ok {+ return newAudioContent(e, data, uri)+ }+ if e, ok := videoMimeFromString[mediaType]; ok {+ return newVideoContent(e, data, uri)+ }+ if e, ok := documentMimeFromString[mediaType]; ok {+ return newDocumentContent(e, data, uri)+ }+ return newDocumentContent(proto.DocumentContent_TYPE_UNSPECIFIED, data, uri)+}++// newImageContent constructs an Image-typed proto.Content from inline+// bytes or a URI (whichever is non-empty); pass exactly one.+func newImageContent(mime proto.ImageContent_MimeType, data []byte, uri string) *proto.Content {+ img := &proto.ImageContent{MimeType: mime}+ if len(data) > 0 {+ img.DataOrUri = &proto.ImageContent_Data{Data: data}+ } else if uri != "" {+ img.DataOrUri = &proto.ImageContent_Uri{Uri: uri}+ }+ return &proto.Content{Type: &proto.Content_Image{Image: img}}+}++// newAudioContent constructs an Audio-typed proto.Content from inline+// bytes or a URI (whichever is non-empty); pass exactly one.+func newAudioContent(mime proto.AudioContent_MimeType, data []byte, uri string) *proto.Content {+ aud := &proto.AudioContent{MimeType: mime}+ if len(data) > 0 {+ aud.DataOrUri = &proto.AudioContent_Data{Data: data}+ } else if uri != "" {+ aud.DataOrUri = &proto.AudioContent_Uri{Uri: uri}+ }+ return &proto.Content{Type: &proto.Content_Audio{Audio: aud}}+}++// newVideoContent constructs a Video-typed proto.Content from inline+// bytes or a URI (whichever is non-empty); pass exactly one.+func newVideoContent(mime proto.VideoContent_MimeType, data []byte, uri string) *proto.Content {+ vid := &proto.VideoContent{MimeType: mime}+ if len(data) > 0 {+ vid.DataOrUri = &proto.VideoContent_Data{Data: data}+ } else if uri != "" {+ vid.DataOrUri = &proto.VideoContent_Uri{Uri: uri}+ }+ return &proto.Content{Type: &proto.Content_Video{Video: vid}}+}++// newDocumentContent constructs a Document-typed proto.Content from+// inline bytes or a URI (whichever is non-empty); pass exactly one.+func newDocumentContent(mime proto.DocumentContent_MimeType, data []byte, uri string) *proto.Content {+ doc := &proto.DocumentContent{MimeType: mime}+ if len(data) > 0 {+ doc.DataOrUri = &proto.DocumentContent_Data{Data: data}+ } else if uri != "" {+ doc.DataOrUri = &proto.DocumentContent_Uri{Uri: uri}+ }+ return &proto.Content{Type: &proto.Content_Document{Document: doc}}+}++// dataValueToContent serialises arbitrary structured data into JSON+// bytes stored as a DocumentContent with mime_type=TYPE_JSON.+func dataValueToContent(value any) *proto.Content {+ bytes, err := json.Marshal(value)+ if err != nil {+ // Fall back to a string representation so we never lose the data+ // entirely.+ bytes = fmt.Appendf(nil, "%v", value)+ }+ return &proto.Content{Type: &proto.Content_Document{+ Document: &proto.DocumentContent{+ MimeType: proto.DocumentContent_TYPE_JSON,+ DataOrUri: &proto.DocumentContent_Data{Data: bytes},+ },+ }}+}++// a2aArtifactToMessages converts an A2A Artifact into a list of AX Messages+// by flattening its Parts.+func a2aArtifactToMessages(artifact *a2a.Artifact, role string) []*proto.Message {+ if artifact == nil {+ return nil+ }+ out := make([]*proto.Message, 0, len(artifact.Parts))+ for _, part := range artifact.Parts {+ content := a2aPartToContent(part)+ if content == nil {+ continue+ }+ out = append(out, &proto.Message{Role: role, Content: content})+ }+ return out+}++// a2aRoleToRole maps A2A's MessageRole back to AX's role string.+func a2aRoleToRole(role a2a.MessageRole) string {+ if s, ok := a2aRoleToString[role]; ok {+ return s+ }+ return "unspecified"+}++// ----- card-derived metadata -----++// AgentMetadataFromCard composes the AX-side (Name, Description) for a+// registered A2A agent from its AgentCard plus optional config-supplied+// overrides.+func AgentMetadataFromCard(card *a2a.AgentCard, cfgName, cfgDescription string) (name, description string) {+ name = cfgName+ description = cfgDescription+ if card != nil {+ if name == "" {+ name = card.Name+ }+ if description == "" {+ description = card.Description+ }+ description = enrichDescriptionWithSkills(description, card)+ }+ return name, description+}++// enrichDescriptionWithSkills appends a structured summary of the agent's+// Skills (name, description, examples, tags) to the base description.+func enrichDescriptionWithSkills(base string, card *a2a.AgentCard) string {+ if card == nil || len(card.Skills) == 0 {+ return base+ }+ var b strings.Builder+ b.WriteString(strings.TrimRight(base, " \n"))+ if base != "" && !strings.HasSuffix(strings.TrimRight(base, " \n"), ".") {+ b.WriteString(".")+ }+ b.WriteString("\n\nSkills:\n")+ for _, s := range card.Skills {+ fmt.Fprintf(&b, "- %s: %s", s.Name, s.Description)+ if len(s.Tags) > 0 {+ fmt.Fprintf(&b, " (tags: %s)", strings.Join(s.Tags, ", "))+ }+ b.WriteString("\n")+ if len(s.Examples) > 0 {+ b.WriteString(" Examples: ")+ for i, ex := range s.Examples {+ if i > 0 {+ b.WriteString("; ")+ }+ fmt.Fprintf(&b, "%q", ex)+ }+ b.WriteString("\n")+ }+ }+ return b.String()+}diff --git a/internal/experimental/a2abridge/a2a_converter_test.go b/internal/experimental/a2abridge/a2a_converter_test.gonew file mode 100644index 0000000..cdce672--- /dev/null+++ b/internal/experimental/a2abridge/a2a_converter_test.go@@ -0,0 +1,423 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "strings"+ "testing"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/google/ax/proto"+)++// userTextMsg returns a user-role message wrapping the given text.+func userTextMsg(text string) *proto.Message {+ return &proto.Message{+ Role: "user",+ Content: &proto.Content{+ Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}},+ },+ }+}++// modelTextMsg returns a model-role message wrapping the given text.+func modelTextMsg(text string) *proto.Message {+ return &proto.Message{+ Role: "model",+ Content: &proto.Content{+ Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}},+ },+ }+}++// modelDocument returns a model-role message wrapping a DocumentContent+// for the supplied MIME string.+func modelDocument(data []byte, mime, name string) *proto.Message {+ _ = name+ e := documentMimeFromString[mime] // zero value = TYPE_UNSPECIFIED+ return &proto.Message{+ Role: "model",+ Content: &proto.Content{+ Type: &proto.Content_Document{+ Document: &proto.DocumentContent{+ MimeType: e,+ DataOrUri: &proto.DocumentContent_Data{Data: data},+ },+ },+ },+ }+}++// userConfirmation returns a user-role ConfirmationContent reply.+func userConfirmation(id string, approved bool) *proto.Message {+ conf := &proto.ConfirmationContent{Id: id}+ if approved {+ conf.Decision = &proto.ConfirmationContent_Approval{+ Approval: &proto.ApprovalDecision{Approved: true},+ }+ } else {+ conf.Decision = &proto.ConfirmationContent_Decline{+ Decline: &proto.DeclineDecision{Declined: true},+ }+ }+ return &proto.Message{+ Role: "user",+ Content: &proto.Content{Type: &proto.Content_Confirmation{Confirmation: conf}},+ }+}++// modelConfirmation returns a model-role ConfirmationContent question.+func modelConfirmation(id, question string) *proto.Message {+ return &proto.Message{+ Role: "model",+ Content: &proto.Content{+ Type: &proto.Content_Confirmation{+ Confirmation: &proto.ConfirmationContent{Id: id, Question: question},+ },+ },+ }+}++// modelToolCall returns a model-role ToolCall message.+func modelToolCall(id, name string) *proto.Message {+ return &proto.Message{+ Role: "model",+ Content: &proto.Content{+ Type: &proto.Content_ToolCall{+ ToolCall: &proto.ToolCallContent{+ Id: id,+ Type: &proto.ToolCallContent_FunctionCall{+ FunctionCall: &proto.FunctionCallContent{Name: name},+ },+ },+ },+ },+ }+}++// stateMarker returns the kind of internal_only marker the bridge+// persists during HITL. Delegates to buildStateMarker so a marshalA2AState+// failure aborts the test rather than silently producing nil.+func stateMarker(t *testing.T, conversationID, taskID string) *proto.Message {+ t.Helper()+ return buildStateMarker(t, conversationID, taskID, nil)+}++// partTexts extracts the Text() value of every Text-typed Part in order,+// for easy comparison in test assertions.+func partTexts(parts []*a2a.Part) []string {+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ if p == nil {+ continue+ }+ if t := p.Text(); t != "" {+ out = append(out, t)+ }+ }+ return out+}++func TestLatestUserInputParts_SingleUserMessage(t *testing.T) {+ got := LatestUserInputParts([]*proto.Message{+ userTextMsg("hello world"),+ })+ want := []string{"hello world"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)+ }+}++func TestLatestUserInputParts_StopsAtPriorModelTurn(t *testing.T) {+ // Only the trailing user-role messages after the last model turn+ // should be returned.+ got := LatestUserInputParts([]*proto.Message{+ userTextMsg("write me a flask server"), // exec 1 user input+ modelTextMsg("here is your flask server"), // exec 1 model reply+ userTextMsg("change port to 5050"), // exec 2 user input+ })+ want := []string{"change port to 5050"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)+ }+}++func TestLatestUserInputParts_StopsAtPriorModelDocument(t *testing.T) {+ // A DocumentContent emitted by the bridge (file artifact) is a+ // model-role content turn. The walk must stop there so we don't+ // re-send the prior text user message.+ got := LatestUserInputParts([]*proto.Message{+ userTextMsg("write me a flask server"),+ modelDocument([]byte("print('hi')"), "text/x-python", "hi.py"),+ userTextMsg("change port to 5050"),+ })+ want := []string{"change port to 5050"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)+ }+}++func TestLatestUserInputParts_SkipsStateMarkers(t *testing.T) {+ // State markers should be transparent - they don't break the+ // contiguous-user run, but they don't contribute parts either.+ got := LatestUserInputParts([]*proto.Message{+ modelTextMsg("prior agent reply"),+ stateMarker(t, "conv-1", ""),+ userTextMsg("new user message"),+ })+ want := []string{"new user message"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)+ }+}++func TestLatestUserInputParts_SkipsAXInternalContent(t *testing.T) {+ // Confirmation, ToolCall, ToolResult, Thought are AX-internal and+ // should not break the walk or contribute parts.+ got := LatestUserInputParts([]*proto.Message{+ modelTextMsg("prior turn"),+ modelConfirmation("task-x", "ok?"),+ userConfirmation("task-x", true),+ modelToolCall("call-1", "some-tool"),+ userTextMsg("the actual new request"),+ })+ want := []string{"the actual new request"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)+ }+}++func TestLatestUserInputParts_MultipleConsecutiveUserMessages(t *testing.T) {+ // AX is one-message-per-exec in practice, so the helper returns+ // only the most recent user-typed message. If multiple user+ // messages somehow appear in a row, only the last one is returned.+ got := LatestUserInputParts([]*proto.Message{+ modelTextMsg("prior agent reply"),+ userTextMsg("first follow-up"),+ userTextMsg("second follow-up"),+ })+ want := []string{"second follow-up"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)+ }+}++func TestLatestUserInputParts_SkipsPlannerOutputAfterUserInput(t *testing.T) {+ // AX's planner emits its own text reasoning and a ToolCall AFTER the+ // user's input but BEFORE the bridge is invoked. The helper must walk+ // past those model-role messages and still find the user's actual input+ // from earlier in the history.+ got := LatestUserInputParts([]*proto.Message{+ userTextMsg("write me a flask server"),+ modelTextMsg("here's a flask server"),+ modelDocument([]byte("..."), "text/x-python", "flask_app.py"),+ userTextMsg("change port to 5050"), // the actual new input+ modelTextMsg("I'll delegate to coding-agent"), // planner reasoning+ modelToolCall("call-1", "coding-agent"), // planner tool call+ })+ want := []string{"change port to 5050"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts (planner-after-user): got %v, want %v", gotTexts, want)+ }+}++func TestLatestUserInputParts_NoUserMessage(t *testing.T) {+ // History with only model content yields no parts.+ got := LatestUserInputParts([]*proto.Message{+ modelTextMsg("just an agent reply"),+ })+ if len(got) != 0 {+ t.Fatalf("LatestUserInputParts: got %d parts, want 0", len(got))+ }+}++func TestLatestUserInputParts_EmptyHistory(t *testing.T) {+ got := LatestUserInputParts(nil)+ if len(got) != 0 {+ t.Fatalf("LatestUserInputParts(nil): got %d parts, want 0", len(got))+ }+ got = LatestUserInputParts([]*proto.Message{})+ if len(got) != 0 {+ t.Fatalf("LatestUserInputParts(empty): got %d parts, want 0", len(got))+ }+}++func TestLatestUserInputParts_FollowupMessage(t *testing.T) {+ // End-to-end shape mimicking the user-reported bug: after exec 1+ // completes (HITL save approved + file artifact emitted), exec 2+ // kicks off with a new "change port" request. The bridge should+ // send only the new request to the A2A agent.+ got := LatestUserInputParts([]*proto.Message{+ userTextMsg("write me a flask server that listens on port 8080"),+ modelTextMsg("Here is the flask server: ..."),+ modelConfirmation("task-1", "I'd like to save this to ./flask_app.py"),+ stateMarker(t, "conv-1", "task-1"),+ userConfirmation("task-1", true),+ modelDocument([]byte("from flask import Flask\n..."), "text/x-python", "flask_app.py"),+ stateMarker(t, "conv-1", ""),+ userTextMsg("change port to 5050"),+ })+ want := []string{"change port to 5050"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, want) {+ t.Fatalf("LatestUserInputParts (exec 2 scenario): got %v, want %v", gotTexts, want)+ }+}++func TestAxMessagesToA2AParts_FullHistory(t *testing.T) {+ // Stateless mode: every text/file/data part across the whole+ // history (regardless of role) should be included.+ history := []*proto.Message{+ userTextMsg("write me a flask server"),+ modelTextMsg("here is your flask server"),+ modelDocument([]byte("print('hi')"), "text/x-python", "hi.py"),+ userTextMsg("change port to 5050"),+ }+ got := MessagesToA2AParts(history)+ wantTexts := []string{+ "write me a flask server",+ "here is your flask server",+ "change port to 5050",+ }+ if gotTexts := partTexts(got); !equalStrings(gotTexts, wantTexts) {+ t.Errorf("MessagesToA2AParts text parts: got %v, want %v", gotTexts, wantTexts)+ }+ // 3 text parts + 1 document part = 4 total.+ if len(got) != 4 {+ t.Errorf("MessagesToA2AParts total parts: got %d, want 4", len(got))+ }+}++func TestAxMessagesToA2AParts_SkipsAXInternalAndStateMarkers(t *testing.T) {+ // State markers and AX-internal types must be filtered out.+ got := MessagesToA2AParts([]*proto.Message{+ userTextMsg("hi"),+ stateMarker(t, "conv-1", "task-1"),+ modelConfirmation("task-1", "ok?"),+ userConfirmation("task-1", true),+ modelToolCall("call-1", "tool"),+ userTextMsg("bye"),+ })+ wantTexts := []string{"hi", "bye"}+ gotTexts := partTexts(got)+ if !equalStrings(gotTexts, wantTexts) {+ t.Fatalf("MessagesToA2AParts: got %v, want %v", gotTexts, wantTexts)+ }+}++func equalStrings(a, b []string) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}++// ----- AgentMetadataFromCard -----++// cardWithSkills returns a minimal AgentCard populated with the supplied+// fields and one Skill carrying name+description+tags+examples.+func cardWithSkills(name, description, skillName, skillDesc string, tags, examples []string) *a2a.AgentCard {+ return &a2a.AgentCard{+ Name: name,+ Description: description,+ Skills: []a2a.AgentSkill{+ {+ Name: skillName,+ Description: skillDesc,+ Tags: tags,+ Examples: examples,+ },+ },+ }+}++func TestAgentMetadataFromCard_NilCard(t *testing.T) {+ // Nil card: returns cfg values unchanged, no skills enrichment.+ name, desc := AgentMetadataFromCard(nil, "cfgName", "cfgDescription")+ if name != "cfgName" {+ t.Errorf("name: got %q, want %q", name, "cfgName")+ }+ if desc != "cfgDescription" {+ t.Errorf("description: got %q, want %q", desc, "cfgDescription")+ }+}++func TestAgentMetadataFromCard_CfgOverridesCard(t *testing.T) {+ // Both cfgName and cfgDescription are non-empty; they win over the+ // card values. (Description still gets skills enrichment though.)+ card := cardWithSkills("cardName", "cardDescription", "skill1", "Does X", nil, nil)+ name, desc := AgentMetadataFromCard(card, "cfgName", "cfgDescription")+ if name != "cfgName" {+ t.Errorf("name: got %q, want %q (cfg wins)", name, "cfgName")+ }+ if !strings.HasPrefix(desc, "cfgDescription.") {+ t.Errorf("description: got %q, want it to start with 'cfgDescription.' (cfg wins, then enriched)", desc)+ }+ if !strings.Contains(desc, "skill1: Does X") {+ t.Errorf("description: got %q, want it to contain skill metadata", desc)+ }+}++func TestAgentMetadataFromCard_FallsBackToCardWhenCfgEmpty(t *testing.T) {+ // Empty cfg -> falls back to card values.+ card := cardWithSkills("cardName", "cardDescription", "skill1", "Does X", nil, nil)+ name, desc := AgentMetadataFromCard(card, "", "")+ if name != "cardName" {+ t.Errorf("name: got %q, want %q (fallback to card)", name, "cardName")+ }+ if !strings.HasPrefix(desc, "cardDescription.") {+ t.Errorf("description: got %q, want it to start with 'cardDescription.' (fallback to card, then enriched)", desc)+ }+}++func TestAgentMetadataFromCard_NoSkillsLeavesDescriptionUnchanged(t *testing.T) {+ // Card with no Skills -> description NOT enriched (no Skills: header).+ card := &a2a.AgentCard{Name: "cardName", Description: "cardDescription"}+ _, desc := AgentMetadataFromCard(card, "", "")+ if desc != "cardDescription" {+ t.Errorf("description: got %q, want %q (no skills, no enrichment)", desc, "cardDescription")+ }+}++func TestAgentMetadataFromCard_FullEnrichmentFormat(t *testing.T) {+ // Card with skills + tags + examples produces the full markdown+ // format: terminating period normalized; skills bullet list with+ // "(tags: ...)" suffix and indented "Examples: ..." line.+ card := cardWithSkills(+ "agent",+ "A coding agent",+ "code",+ "Write Python",+ []string{"dev", "python"},+ []string{"fizzbuzz", "hello world"},+ )+ _, desc := AgentMetadataFromCard(card, "", "")+ expected := "A coding agent.\n\nSkills:\n- code: Write Python (tags: dev, python)\n Examples: \"fizzbuzz\"; \"hello world\"\n"+ if desc != expected {+ t.Errorf("description format mismatch\ngot:\n%s\nwant:\n%s", desc, expected)+ }+}diff --git a/internal/experimental/a2abridge/a2a_event_handler.go b/internal/experimental/a2abridge/a2a_event_handler.gonew file mode 100644index 0000000..89ea480--- /dev/null+++ b/internal/experimental/a2abridge/a2a_event_handler.go@@ -0,0 +1,471 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "context"+ "errors"+ "fmt"+ "iter"+ "strings"+ "time"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/google/ax/internal/agent"+ "github.com/google/ax/proto"+)++type streamState struct {+ conversationID string+ toolCallID string // planner's tool call ID+ agentID string // for AuthRequiredError+ o agent.OutputHandler+ activeTaskID a2a.TaskID+ terminal bool+ lastSeenTask *a2a.Task+ artifactBuffer map[a2a.ArtifactID]*a2a.Artifact+ emittedArtifact map[a2a.ArtifactID]bool+}++func newStreamState(conversationID, toolCallID, agentID string, o agent.OutputHandler) *streamState {+ return &streamState{+ conversationID: conversationID,+ toolCallID: toolCallID,+ agentID: agentID,+ o: o,+ artifactBuffer: make(map[a2a.ArtifactID]*a2a.Artifact),+ emittedArtifact: make(map[a2a.ArtifactID]bool),+ }+}++// handleEvent dispatches a single event from the A2A stream. Returns+// (stop, err): stop indicates the stream should end (e.g. HITL pause).+func (s *streamState) handleEvent(evt a2a.Event) (bool, error) {+ switch e := evt.(type) {+ case *a2a.Message:+ // Direct message response (no task).+ msgs := a2aPartsToMessages(e.Parts, a2aRoleToRole(e.Role))+ if len(msgs) > 0 {+ if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {+ return false, err+ }+ }+ return false, nil++ case *a2a.Task:+ // Snapshot of the task. Track it; emit any artifacts we haven't+ // seen yet. If the task is in INPUT_REQUIRED, treat it the same+ // way as the corresponding TaskStatusUpdateEvent: surface a+ // ConfirmationContent and persist the activeTaskID, then stop+ // the loop.+ s.lastSeenTask = e+ if e.ID != "" {+ s.activeTaskID = e.ID+ }+ for _, art := range e.Artifacts {+ if s.emittedArtifact[art.ID] {+ continue+ }+ s.emittedArtifact[art.ID] = true+ msgs := a2aArtifactToMessages(art, "agent")+ if len(msgs) > 0 {+ if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {+ return false, err+ }+ }+ }+ if e.Status.State == a2a.TaskStateAuthRequired {+ // Server is asking for refreshed credentials. The current static+ // credential model can't hot-reload, so mark terminal,+ // clear the marker, and return an actionable error.+ s.terminal = true+ _ = ClearStateMarker(s.conversationID, s.o)+ return false, AuthRequiredError(s.agentID, s.activeTaskID, e.Status.Message)+ }+ if e.Status.State == a2a.TaskStateInputRequired {+ if err := EmitConfirmation(s.conversationID, s.toolCallID, s.activeTaskID, e, emittedArtifactKeys(s.emittedArtifact), s.o); err != nil {+ return false, err+ }+ return true, nil+ }+ if e.Status.State.Terminal() {+ s.terminal = true+ }+ return false, nil++ case *a2a.TaskStatusUpdateEvent:+ if e.TaskID != "" {+ s.activeTaskID = e.TaskID+ }+ // Surface any human-readable status message to the client - EXCEPT+ // when the status is input_required (delivered as+ // ConfirmationContent.Question) or auth_required (delivered as+ // part of AuthRequiredError).+ if e.Status.Message != nil &&+ e.Status.State != a2a.TaskStateInputRequired &&+ e.Status.State != a2a.TaskStateAuthRequired {+ msgs := a2aPartsToMessages(e.Status.Message.Parts, a2aRoleToRole(e.Status.Message.Role))+ if len(msgs) > 0 {+ if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {+ return false, err+ }+ }+ }+ switch e.Status.State {+ case a2a.TaskStateInputRequired:+ // HITL pause: persist the active task ID and emit a+ // ConfirmationContent. Stop the stream loop.+ task := &a2a.Task{+ ID: s.activeTaskID,+ ContextID: s.conversationID,+ Status: e.Status,+ }+ if err := EmitConfirmation(s.conversationID, s.toolCallID, s.activeTaskID, task, emittedArtifactKeys(s.emittedArtifact), s.o); err != nil {+ return false, err+ }+ return true, nil+ case a2a.TaskStateAuthRequired:+ // Server is asking for refreshed credentials mid-stream.+ // Our static-credential model can't hot-reload, so mark+ // terminal, clear the marker, and return an actionable error.+ s.terminal = true+ _ = ClearStateMarker(s.conversationID, s.o)+ return false, AuthRequiredError(s.agentID, s.activeTaskID, e.Status.Message)+ case a2a.TaskStateCompleted:+ s.terminal = true+ if err := ClearStateMarker(s.conversationID, s.o); err != nil {+ return false, err+ }+ case a2a.TaskStateFailed, a2a.TaskStateCanceled, a2a.TaskStateRejected:+ s.terminal = true+ _ = ClearStateMarker(s.conversationID, s.o)+ return false, fmt.Errorf("a2a task %s ended with state %s", s.activeTaskID, e.Status.State)+ }+ return false, nil++ case *a2a.TaskArtifactUpdateEvent:+ if e.TaskID != "" {+ s.activeTaskID = e.TaskID+ }+ if e.Artifact == nil {+ return false, nil+ }+ // Buffer chunks by artifact ID; emit on LastChunk=true. We rely+ // on the A2A protocol's LastChunk contract and don't add a+ // per-artifact timeout.+ existing, ok := s.artifactBuffer[e.Artifact.ID]+ if !ok || !e.Append {+ // Start a new buffer entry (or replace if not appending).+ cp := *e.Artifact+ s.artifactBuffer[e.Artifact.ID] = &cp+ } else {+ existing.Parts = append(existing.Parts, e.Artifact.Parts...)+ }+ if e.LastChunk {+ full := s.artifactBuffer[e.Artifact.ID]+ delete(s.artifactBuffer, e.Artifact.ID)+ s.emittedArtifact[e.Artifact.ID] = true+ msgs := a2aArtifactToMessages(full, "agent")+ if len(msgs) > 0 {+ if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {+ return false, err+ }+ }+ }+ return false, nil+ }+ return false, nil+}++// IterateStream walks the SDK's iter.Seq2 stream of events, dispatches+// each to the appropriate handler, and returns once the stream ends or a+// fatal error is encountered. If the stream ends with the active task+// still in a non-terminal state, falls back to polling GetTask via+// PollUntilTerminal until the task reaches a terminal state.+//+// client and agentID are passed through to the polling fallback so it+// can issue GetTask calls and format error messages.+func IterateStream(+ ctx context.Context,+ client *a2aclient.Client,+ agentID string,+ conversationID string,+ toolCallID string,+ events iter.Seq2[a2a.Event, error],+ o agent.OutputHandler,+) error {+ state := newStreamState(conversationID, toolCallID, agentID, o)+ for evt, err := range events {+ if err != nil {+ return fmt.Errorf("a2a agent %s: stream error: %w", agentID, err)+ }+ stop, err := state.handleEvent(evt)+ if err != nil {+ return err+ }+ if stop {+ return nil+ }+ }+ // Stream ended. If we have an active task that's still non-terminal+ // the server expects us to poll for completion.+ if state.activeTaskID != "" && !state.terminal {+ return PollUntilTerminal(ctx, client, agentID, conversationID, toolCallID, state.activeTaskID, state.lastSeenTask, emittedArtifactKeys(state.emittedArtifact), o)+ }+ return nil+}++// PollUntilTerminal polls GetTask with exponential backoff until the task+// reaches a terminal state, the context is canceled, or an error occurs.+// Newly discovered artifacts and status changes are emitted to the client.+//+// client and agentID identify the SDK client and the bridge's registered+// agent ID for issuing GetTask and constructing user-facing errors.+//+// toolCallID is forwarded to EmitConfirmation if the task transitions to+// INPUT_REQUIRED while we are polling.+//+// alreadyEmitted seeds the dedup set with artifact IDs already emitted by+// the caller. It prevents re-emission across the streaming<->polling handoff+// and across invocation boundaries.+func PollUntilTerminal(+ ctx context.Context,+ client *a2aclient.Client,+ agentID string,+ conversationID string,+ toolCallID string,+ taskID a2a.TaskID,+ lastSeen *a2a.Task,+ alreadyEmitted []string,+ o agent.OutputHandler,+) error {+ emittedArtifactIDs := make(map[a2a.ArtifactID]bool)+ if lastSeen != nil {+ for _, art := range lastSeen.Artifacts {+ emittedArtifactIDs[art.ID] = true+ }+ }+ for _, id := range alreadyEmitted {+ emittedArtifactIDs[a2a.ArtifactID(id)] = true+ }++ const initialDelay = 250 * time.Millisecond+ const maxDelay = 60 * time.Second++ delay := initialDelay+ for {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(delay):+ }++ task, err := client.GetTask(ctx, &a2a.GetTaskRequest{ID: taskID})+ if err != nil {+ // If the server has dropped the task while we were polling,+ // the marker is stale: clear it and surface a clean error.+ if errors.Is(err, a2a.ErrTaskNotFound) {+ _ = ClearStateMarker(conversationID, o)+ return fmt.Errorf("a2a agent %s: task %s no longer exists on server (state marker cleared)", agentID, taskID)+ }+ return fmt.Errorf("a2a agent %s: poll GetTask(%s): %w", agentID, taskID, err)+ }++ // Emit newly observed artifacts. Track whether anything new+ // arrived this iteration.+ sawNewArtifact := false+ for _, art := range task.Artifacts {+ if emittedArtifactIDs[art.ID] {+ continue+ }+ emittedArtifactIDs[art.ID] = true+ sawNewArtifact = true+ msgs := a2aArtifactToMessages(art, "agent")+ if len(msgs) > 0 {+ if err := o(&proto.AgentOutputs{Messages: msgs}); err != nil {+ return err+ }+ }+ }++ switch task.Status.State {+ case a2a.TaskStateCompleted:+ return ClearStateMarker(conversationID, o)+ case a2a.TaskStateFailed, a2a.TaskStateCanceled, a2a.TaskStateRejected:+ _ = ClearStateMarker(conversationID, o)+ return fmt.Errorf("a2a agent %s: task %s ended with state %s", agentID, taskID, task.Status.State)+ case a2a.TaskStateAuthRequired:+ // Server is asking for refreshed credentials mid-poll.+ // Our static-credential model can't hot-reload, so clear+ // the marker and surface an actionable error.+ _ = ClearStateMarker(conversationID, o)+ return AuthRequiredError(agentID, taskID, task.Status.Message)+ case a2a.TaskStateInputRequired:+ // Convert to HITL pause; persist the current emitted set+ // so resume after the user's answer doesn't re-emit.+ return EmitConfirmation(conversationID, toolCallID, taskID, task, emittedArtifactKeys(emittedArtifactIDs), o)+ }++ // Reset poll delay on activity.+ if sawNewArtifact {+ delay = initialDelay+ } else {+ delay *= 2+ if delay > maxDelay {+ delay = maxDelay+ }+ }+ }+}++// EmitTaskArtifacts emits all artifacts from a completed task to the client.+func EmitTaskArtifacts(task *a2a.Task, o agent.OutputHandler) error {+ for _, art := range task.Artifacts {+ msgs := a2aArtifactToMessages(art, "agent")+ if len(msgs) > 0 {+ if err := o(&proto.AgentOutputs{Messages: msgs}); err != nil {+ return err+ }+ }+ }+ return nil+}++// EmitConfirmation surfaces a HITL prompt to the AX client and persists the+// state marker so the bridge can resume the same task on the user's reply.+//+// ConfirmationContentID is set to toolCallID so the planner can correlate+// the user's reply back to the call via a strict ID match.+// If toolCallID is empty (the bridge was invoked without a planner), we fall+// back to string(taskID).+func EmitConfirmation(conversationID, toolCallID string, taskID a2a.TaskID, task *a2a.Task, emittedArtifactIDs []string, o agent.OutputHandler) error {+ question := "The agent requires confirmation."+ if task != nil && task.Status.Message != nil {+ var b string+ for _, part := range task.Status.Message.Parts {+ if t := part.Text(); t != "" {+ if b != "" {+ b += "\n"+ }+ b += t+ }+ }+ if b != "" {+ question = b+ }+ }+ // Persist the (conversationID, taskID, emittedArtifactIDs) first so+ // resume can recover it.+ stateMsg, err := marshalA2AState(conversationID, string(taskID), emittedArtifactIDs)+ if err != nil {+ return err+ }+ if err := o(&proto.AgentOutputs{Messages: []*proto.Message{stateMsg}}); err != nil {+ return err+ }+ confID := toolCallID+ if confID == "" {+ confID = string(taskID)+ }+ // Emit the ConfirmationContent last so the executor sees it as the+ // final output and records the exec as PENDING.+ confirmMsg := &proto.Message{+ Role: "agent",+ Content: &proto.Content{+ Type: &proto.Content_Confirmation{+ Confirmation: &proto.ConfirmationContent{+ Id: confID,+ Question: question,+ },+ },+ },+ }+ return o(&proto.AgentOutputs{Messages: []*proto.Message{confirmMsg}})+}++// AuthRequiredError formats a user-facing error for TaskStateAuthRequired.+// Surfaces any hint the agent included in Status.Message. Temporary for now.+func AuthRequiredError(agentID string, taskID a2a.TaskID, statusMsg *a2a.Message) error {+ var b strings.Builder+ fmt.Fprintf(&b, "a2a agent %s: task %s requires updated auth credentials", agentID, taskID)+ if statusMsg != nil {+ var hint string+ for _, part := range statusMsg.Parts {+ if t := part.Text(); t != "" {+ if hint != "" {+ hint += "\n"+ }+ hint += t+ }+ }+ if hint != "" {+ fmt.Fprintf(&b, ": %s", hint)+ }+ }+ b.WriteString("; refresh credentials and restart AX")+ return errors.New(b.String())+}++// ClearStateMarker writes a final state marker indicating no active task.+func ClearStateMarker(conversationID string, o agent.OutputHandler) error {+ msg, err := marshalA2AState(conversationID, "", nil)+ if err != nil {+ return err+ }+ return o(&proto.AgentOutputs{Messages: []*proto.Message{msg}})+}++// FindConfirmationAnswer scans the history (most recent first) for a user+// reply to the ConfirmationContent we emitted with the given confID.+// Returns (true, approved) if a matching answer is found, (false, false)+// otherwise.+func FindConfirmationAnswer(history []*proto.Message, confID string) (answered, approved bool) {+ for i := len(history) - 1; i >= 0; i-- {+ conf := history[i].GetContent().GetConfirmation()+ if conf == nil {+ continue+ }+ if confID != "" && conf.Id != confID {+ continue+ }+ if conf.GetApproval() != nil {+ return true, true+ }+ if conf.GetDecline() != nil {+ return true, false+ }+ }+ return false, false+}++// FindToolCallID returns the ID of the most recent ToolCall in history+// whose function name matches agentID.+// Returns "" when no matching ToolCall is found - e.g. the bridge was+// invoked without a planner.+func FindToolCallID(agentID string, messages []*proto.Message) string {+ for i := len(messages) - 1; i >= 0; i-- {+ tc := messages[i].GetContent().GetToolCall()+ if tc == nil {+ continue+ }+ fc := tc.GetFunctionCall()+ if fc == nil || fc.Name != agentID {+ continue+ }+ return tc.Id+ }+ return ""+}diff --git a/internal/experimental/a2abridge/a2a_event_handler_test.go b/internal/experimental/a2abridge/a2a_event_handler_test.gonew file mode 100644index 0000000..9e776d9--- /dev/null+++ b/internal/experimental/a2abridge/a2a_event_handler_test.go@@ -0,0 +1,194 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "strings"+ "testing"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/google/ax/proto"+)++// captureHandler records every AgentOutputs emission for later inspection.+type captureHandler struct {+ emissions []*proto.AgentOutputs+}++func (c *captureHandler) handle(out *proto.AgentOutputs) error {+ c.emissions = append(c.emissions, out)+ return nil+}++// allMessages returns the flattened list of messages across every emission.+func (c *captureHandler) allMessages() []*proto.Message {+ var out []*proto.Message+ for _, e := range c.emissions {+ out = append(out, e.Messages...)+ }+ return out+}++// findConfirmation returns the first ConfirmationContent emitted, or nil.+func (c *captureHandler) findConfirmation() *proto.ConfirmationContent {+ for _, msg := range c.allMessages() {+ if conf := msg.GetContent().GetConfirmation(); conf != nil {+ return conf+ }+ }+ return nil+}++// findStateMarker returns the recovered state marker fields, if any was emitted.+func (c *captureHandler) findStateMarker() (conv string, taskID string, ok bool) {+ conv, taskID, _, ok = RecoverA2AState(c.allMessages())+ return+}++func TestStreamState_TaskWithInputRequiredEmitsConfirmation(t *testing.T) {+ cap := &captureHandler{}+ const toolCallID = "call-abc"+ state := newStreamState("conv-1", toolCallID, "", cap.handle)++ question := "Save flask_server.py to /tmp/flask_server.py?"+ task := &a2a.Task{+ ID: "task-2",+ ContextID: "conv-1",+ Status: a2a.TaskStatus{+ State: a2a.TaskStateInputRequired,+ Message: &a2a.Message{+ Role: a2a.MessageRoleAgent,+ Parts: []*a2a.Part{a2a.NewTextPart(question)},+ },+ },+ }++ stop, err := state.handleEvent(task)+ if err != nil {+ t.Fatalf("handleEvent returned error: %v", err)+ }+ if !stop {+ t.Fatal("handleEvent: expected stop=true for INPUT_REQUIRED, got false")+ }++ conf := cap.findConfirmation()+ if conf == nil {+ t.Fatal("expected a ConfirmationContent emission, got none")+ }+ if conf.Id != toolCallID {+ t.Errorf("ConfirmationContent.Id: got %q, want %q (planner's ToolCall.Id)", conf.Id, toolCallID)+ }+ if !strings.Contains(conf.Question, question) {+ t.Errorf("ConfirmationContent.Question: got %q, want it to contain %q", conf.Question, question)+ }++ convID, taskID, ok := cap.findStateMarker()+ if !ok {+ t.Fatal("expected a state marker emission, got none")+ }+ if convID != "conv-1" {+ t.Errorf("state marker conversationID: got %q, want %q", convID, "conv-1")+ }+ if taskID != "task-2" {+ t.Errorf("state marker activeTaskID: got %q, want %q", taskID, "task-2")+ }+}++func TestStreamState_TaskWithCompletedDoesNotEmitConfirmation(t *testing.T) {+ // A completed Task event should mark terminal=true and emit any+ // artifacts but NOT emit a ConfirmationContent or stop the loop.+ cap := &captureHandler{}+ state := newStreamState("conv-1", "call-abc", "", cap.handle)++ task := &a2a.Task{+ ID: "task-3",+ ContextID: "conv-1",+ Status: a2a.TaskStatus{State: a2a.TaskStateCompleted},+ Artifacts: []*a2a.Artifact{+ {+ ID: "a1",+ Name: "result",+ Parts: []*a2a.Part{a2a.NewTextPart("done")},+ },+ },+ }++ stop, err := state.handleEvent(task)+ if err != nil {+ t.Fatalf("handleEvent returned error: %v", err)+ }+ if stop {+ t.Fatal("handleEvent: expected stop=false for COMPLETED task event, got true")+ }+ if !state.terminal {+ t.Error("expected state.terminal=true after a completed Task event")+ }+ if cap.findConfirmation() != nil {+ t.Error("did not expect a ConfirmationContent emission for a completed task")+ }+ // Artifact should have been emitted.+ if len(cap.allMessages()) == 0 {+ t.Error("expected the artifact to be emitted to the client")+ }+}++func TestStreamState_TaskStatusUpdateInputRequiredEmitsConfirmation(t *testing.T) {+ // The streaming path: INPUT_REQUIRED arrives as a+ // TaskStatusUpdateEvent. The bridge should emit a single+ // ConfirmationContent.+ cap := &captureHandler{}+ state := newStreamState("conv-1", "call-xyz", "", cap.handle)++ question := "Save flask_server.py?"+ evt := &a2a.TaskStatusUpdateEvent{+ ContextID: "conv-1",+ TaskID: "task-2",+ Status: a2a.TaskStatus{+ State: a2a.TaskStateInputRequired,+ Message: &a2a.Message{+ Role: a2a.MessageRoleAgent,+ Parts: []*a2a.Part{a2a.NewTextPart(question)},+ },+ },+ }++ stop, err := state.handleEvent(evt)+ if err != nil {+ t.Fatalf("handleEvent returned error: %v", err)+ }+ if !stop {+ t.Fatal("handleEvent: expected stop=true for INPUT_REQUIRED, got false")+ }++ conf := cap.findConfirmation()+ if conf == nil {+ t.Fatal("expected a ConfirmationContent emission, got none")+ }+ if !strings.Contains(conf.Question, question) {+ t.Errorf("ConfirmationContent.Question: got %q, want it to contain %q", conf.Question, question)+ }++ // Verify the question text was NOT also emitted as a separate+ // TextContent (the de-duplication fix from a prior round).+ textOnlyEmissions := 0+ for _, msg := range cap.allMessages() {+ if msg.GetContent().GetText() != nil && strings.Contains(msg.GetContent().GetText().Text, question) {+ textOnlyEmissions+++ }+ }+ if textOnlyEmissions > 0 {+ t.Errorf("INPUT_REQUIRED status message should NOT be emitted as a standalone TextContent (got %d such emissions)", textOnlyEmissions)+ }+}diff --git a/internal/experimental/a2abridge/a2a_internal_state.go b/internal/experimental/a2abridge/a2a_internal_state.gonew file mode 100644index 0000000..2e0b674--- /dev/null+++ b/internal/experimental/a2abridge/a2a_internal_state.go@@ -0,0 +1,98 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "encoding/json"+ "fmt"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/google/ax/proto"+)++// The role used by the bridge as the source of internal_only state-marker messages.+const stateMarkerRole = "a2a_bridge"++// a2aStatePayload is the JSON shape of the internal_only state marker's+// TextContent payload. The marker is emitted as a Message with InternalOnly=true+// so it persists in the ExecutionEvents log (for the bridge to recover on resume)+// but is filtered out of the conversation log, the CLI display, and Gemini's view+// of conversation history.+type a2aStatePayload struct {+ ConversationID string `json:"conversation_id"`+ ActiveTaskID string `json:"active_task_id"`+ EmittedArtifactIDs []string `json:"emitted_artifact_ids,omitempty"`+}++func marshalA2AState(conversationID, activeTaskID string, emittedArtifactIDs []string) (*proto.Message, error) {+ payload := a2aStatePayload{+ ConversationID: conversationID,+ ActiveTaskID: activeTaskID,+ EmittedArtifactIDs: emittedArtifactIDs,+ }+ bytes, err := json.Marshal(payload)+ if err != nil {+ return nil, fmt.Errorf("marshal a2a state marker: %w", err)+ }+ return &proto.Message{+ Role: stateMarkerRole,+ InternalOnly: true,+ Content: &proto.Content{+ Type: &proto.Content_Text{+ Text: &proto.TextContent{Text: string(bytes)},+ },+ },+ }, nil+}++// RecoverA2AState scans the message history for the most recent A2A state+// marker and returns its conversation_id, active_task_id, and the list+// of artifact IDs already emitted by the prior bridge invocation. The+// most recent marker wins so successive resume cycles see the latest state.+func RecoverA2AState(msgs []*proto.Message) (conversationID, activeTaskID string, emittedArtifactIDs []string, found bool) {+ for i := len(msgs) - 1; i >= 0; i-- {+ if !isStateMarkerMessage(msgs[i]) {+ continue+ }+ t := msgs[i].GetContent().GetText()+ if t == nil {+ continue+ }+ var payload a2aStatePayload+ if err := json.Unmarshal([]byte(t.Text), &payload); err != nil {+ continue+ }+ return payload.ConversationID, payload.ActiveTaskID, payload.EmittedArtifactIDs, true+ }+ return "", "", nil, false+}++func emittedArtifactKeys(m map[a2a.ArtifactID]bool) []string {+ if len(m) == 0 {+ return nil+ }+ out := make([]string, 0, len(m))+ for id := range m {+ out = append(out, string(id))+ }+ return out+}++func isStateMarkerMessage(msg *proto.Message) bool {+ if msg == nil || !msg.GetInternalOnly() || msg.GetRole() != stateMarkerRole {+ return false+ }+ return msg.GetContent().GetText() != nil+}diff --git a/internal/experimental/a2abridge/a2a_internal_state_test.go b/internal/experimental/a2abridge/a2a_internal_state_test.gonew file mode 100644index 0000000..615bee9--- /dev/null+++ b/internal/experimental/a2abridge/a2a_internal_state_test.go@@ -0,0 +1,97 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "testing"++ "github.com/google/ax/proto"+)++// buildStateMarker wraps marshalA2AState for tests; the inputs used here are+// always JSON-marshalable (string + []string), so an error fails the test.+func buildStateMarker(t *testing.T, conversationID, activeTaskID string, emittedArtifactIDs []string) *proto.Message {+ t.Helper()+ m, err := marshalA2AState(conversationID, activeTaskID, emittedArtifactIDs)+ if err != nil {+ t.Fatalf("marshalA2AState: %v", err)+ }+ return m+}++func TestStateMarkerRoundTrip(t *testing.T) {+ msg := buildStateMarker(t, "conv-abc", "task-xyz", []string{"art-1", "art-2"})+ if !isStateMarkerMessage(msg) {+ t.Fatal("isStateMarkerMessage: expected marker to be recognised")+ }+ conv, task, emitted, found := RecoverA2AState([]*proto.Message{msg})+ if !found {+ t.Fatal("RecoverA2AState: not found")+ }+ if conv != "conv-abc" {+ t.Errorf("conversationID: got %q, want %q", conv, "conv-abc")+ }+ if task != "task-xyz" {+ t.Errorf("activeTaskID: got %q, want %q", task, "task-xyz")+ }+ if !equalStrings(emitted, []string{"art-1", "art-2"}) {+ t.Errorf("emittedArtifactIDs: got %v, want [art-1 art-2]", emitted)+ }+}++func TestStateMarkerRoundTrip_NilEmittedArtifactIDs(t *testing.T) {+ msg := buildStateMarker(t, "conv", "task", nil)+ _, _, emitted, found := RecoverA2AState([]*proto.Message{msg})+ if !found {+ t.Fatal("RecoverA2AState: not found")+ }+ if emitted != nil {+ t.Errorf("emittedArtifactIDs: got %v, want nil", emitted)+ }+}++func TestRecoverA2AState_ReturnsMostRecentMarker(t *testing.T) {+ got := []*proto.Message{+ buildStateMarker(t, "conv-1", "task-1", []string{"art-old"}), // older+ modelTextMsg("did some work"),+ buildStateMarker(t, "conv-1", "", nil), // newer (clears the marker)+ }+ conv, task, emitted, found := RecoverA2AState(got)+ if !found {+ t.Fatal("RecoverA2AState: not found")+ }+ if conv != "conv-1" {+ t.Errorf("conversationID: got %q, want %q", conv, "conv-1")+ }+ if task != "" {+ t.Errorf("activeTaskID: got %q, want empty (cleared)", task)+ }+ if emitted != nil {+ t.Errorf("emittedArtifactIDs: got %v, want nil (most recent marker is cleared)", emitted)+ }+}++func TestIsStateMarkerMessage_RejectsForeignInternalOnlyText(t *testing.T) {+ foreign := &proto.Message{+ Role: "future_subsystem",+ InternalOnly: true,+ Content: &proto.Content{+ Type: &proto.Content_Text{Text: &proto.TextContent{Text: "anything"}},+ },+ }+ if isStateMarkerMessage(foreign) {+ t.Error("expected isStateMarkerMessage to reject InternalOnly TextContent from non-bridge role")+ }+}diff --git a/internal/experimental/a2abridge/auth.go b/internal/experimental/a2abridge/auth.gonew file mode 100644index 0000000..76c392a--- /dev/null+++ b/internal/experimental/a2abridge/auth.go@@ -0,0 +1,95 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "context"+ "errors"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/google/ax/internal/auth"+)++// apiKeyHeaderFromCard looks up the api_key header name from an+// AgentCard's APIKeySecurityScheme.+// Returns ("", error) when the card declares no APIKeySecurityScheme+// with Location=header.+func apiKeyHeaderFromCard(card *a2a.AgentCard) (string, error) {+ if card != nil {+ for _, scheme := range card.SecuritySchemes {+ apiKey, ok := scheme.(a2a.APIKeySecurityScheme)+ if !ok {+ continue+ }+ if apiKey.Location == a2a.APIKeySecuritySchemeLocationHeader && apiKey.Name != "" {+ return apiKey.Name, nil+ }+ }+ }+ return "", errors.New(+ `auth.api_key: AgentCard does not declare an APIKeySecurityScheme ` ++ `with Location=header; specify the API key header via headers.env instead`)+}++// interceptor implements a2aclient.CallInterceptor and writes a fixed map+// of headers directly to req.ServiceParams on every outgoing request. The+// transport (HTTP / JSON-RPC / REST / gRPC) serialises ServiceParams into+// headers per its protocol binding.+type interceptor struct {+ headers map[string]string+}++// NewInterceptor builds an a2aclient.CallInterceptor that injects the+// merged auth + user headers on every outgoing call. Returns (nil, nil)+// when no headers are configured.+func NewInterceptor(card *a2a.AgentCard, a auth.Auth, h auth.Headers) (a2aclient.CallInterceptor, error) {+ apiKeyHeader := ""+ if a.Type == "api_key" {+ name, err := apiKeyHeaderFromCard(card)+ if err != nil {+ return nil, err+ }+ apiKeyHeader = name+ }+ headers, err := auth.MergeAllHeaders(a, h, apiKeyHeader)+ if err != nil {+ return nil, err+ }+ if len(headers) == 0 {+ return nil, nil+ }+ return &interceptor{headers: headers}, nil+}++// Before implements a2aclient.CallInterceptor.+func (i *interceptor) Before(ctx context.Context, req *a2aclient.Request) (context.Context, any, error) {+ if len(i.headers) == 0 {+ return ctx, nil, nil+ }+ if req.ServiceParams == nil {+ req.ServiceParams = make(a2aclient.ServiceParams)+ }+ for k, v := range i.headers {+ // Set semantics (overwrite existing entry for the same key).+ req.ServiceParams[k] = []string{v}+ }+ return ctx, nil, nil+}++// After implements a2aclient.CallInterceptor.+func (i *interceptor) After(_ context.Context, _ *a2aclient.Response) error {+ return nil+}diff --git a/internal/experimental/a2abridge/auth_test.go b/internal/experimental/a2abridge/auth_test.gonew file mode 100644index 0000000..914c83d--- /dev/null+++ b/internal/experimental/a2abridge/auth_test.go@@ -0,0 +1,130 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "context"+ "strings"+ "testing"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/google/ax/internal/auth"+)++// cardWithAPIKey returns an AgentCard declaring a single APIKeySecurityScheme+// at the given location.+func cardWithAPIKey(name string, location a2a.APIKeySecuritySchemeLocation) *a2a.AgentCard {+ return &a2a.AgentCard{+ SecuritySchemes: a2a.NamedSecuritySchemes{+ "apikey": a2a.APIKeySecurityScheme{Name: name, Location: location},+ },+ }+}++// ----- apiKeyHeaderFromCard -----++func TestApiKeyHeaderFromCard_Found(t *testing.T) {+ card := cardWithAPIKey("X-API-Key", a2a.APIKeySecuritySchemeLocationHeader)+ name, err := apiKeyHeaderFromCard(card)+ if err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if name != "X-API-Key" {+ t.Errorf("name=%q, want %q", name, "X-API-Key")+ }+}++func TestApiKeyHeaderFromCard_NoMatchingScheme(t *testing.T) {+ cases := map[string]*a2a.AgentCard{+ "nil": nil, // no card at all+ "empty": {}, // no SecuritySchemes+ "cookie": cardWithAPIKey("session", a2a.APIKeySecuritySchemeLocationCookie),+ "querystr": cardWithAPIKey("api_key", a2a.APIKeySecuritySchemeLocationQuery),+ }+ for label, card := range cases {+ t.Run(label, func(t *testing.T) {+ _, err := apiKeyHeaderFromCard(card)+ if err == nil {+ t.Fatal("got nil err, want non-nil")+ }+ if !strings.Contains(err.Error(), "APIKeySecurityScheme") {+ t.Errorf("err should mention APIKeySecurityScheme; got: %v", err)+ }+ })+ }+}++// ----- NewInterceptor -----++func TestNewInterceptor_NilWhenEmpty(t *testing.T) {+ got, err := NewInterceptor(nil, auth.Auth{}, auth.Headers{})+ if err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if got != nil {+ t.Errorf("got non-nil interceptor, want nil for empty config")+ }+}++func TestNewInterceptor_PropagatesError(t *testing.T) {+ t.Setenv("MY_TOKEN", "abc123")+ _, err := NewInterceptor(nil,+ auth.Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"},+ auth.Headers{Literal: map[string]string{"Authorization": "Bearer manual"}},+ )+ if err == nil {+ t.Fatal("got nil err, want non-nil for collision")+ }+}++// ----- interceptor (CallInterceptor implementation) -----++func TestInterceptor_BeforeWritesToRequestServiceParams(t *testing.T) {+ in := &interceptor{+ headers: map[string]string{+ "Authorization": "Bearer abc",+ "X-Organization-Id": "acme",+ },+ }+ req := &a2aclient.Request{ServiceParams: make(a2aclient.ServiceParams)}+ if _, _, err := in.Before(context.Background(), req); err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if got := req.ServiceParams["Authorization"]; len(got) != 1 || got[0] != "Bearer abc" {+ t.Errorf("Authorization=%v, want [Bearer abc]", got)+ }+ if got := req.ServiceParams["X-Organization-Id"]; len(got) != 1 || got[0] != "acme" {+ t.Errorf("X-Organization-Id=%v, want [acme]", got)+ }+}++func TestInterceptor_BeforeOverwritesExistingValue(t *testing.T) {+ in := &interceptor{headers: map[string]string{"Authorization": "Bearer correct"}}+ req := &a2aclient.Request{ServiceParams: a2aclient.ServiceParams{+ "Authorization": []string{"Bearer stale"},+ }}+ if _, _, err := in.Before(context.Background(), req); err != nil {+ t.Fatalf("got err=%v, want nil", err)+ }+ if got := req.ServiceParams["Authorization"]; len(got) != 1 || got[0] != "Bearer correct" {+ t.Errorf("Authorization=%v, want [Bearer correct] (overwrite)", got)+ }+}++// Ensure the unexported interceptor still implements the SDK's+// CallInterceptor interface. If the SDK changes its method set, this+// fails to compile rather than at runtime.+var _ a2aclient.CallInterceptor = (*interceptor)(nil)diff --git a/internal/experimental/a2abridge/mappings.go b/internal/experimental/a2abridge/mappings.gonew file mode 100644index 0000000..4d7133a--- /dev/null+++ b/internal/experimental/a2abridge/mappings.go@@ -0,0 +1,106 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/google/ax/proto"+)++// ----- enum <-> wire-string MIME mapping tables -----+//+// content.proto encodes canonical MIME wire strings (e.g. "image/png")+// as annotations on each enum value. We maintain the forward (string -> enum)+// tables here and derive the inverse (enum -> string) maps via invertMap.+//+// These tables are the single source of truth for the bridge's typed-+// content conversion in both directions. A test guards that they stay in sync+// with the content.proto annotations.++var imageMimeFromString = map[string]proto.ImageContent_MimeType{+ "image/png": proto.ImageContent_TYPE_PNG,+ "image/jpeg": proto.ImageContent_TYPE_JPEG,+ "image/webp": proto.ImageContent_TYPE_WEBP,+ "image/heic": proto.ImageContent_TYPE_HEIC,+ "image/heif": proto.ImageContent_TYPE_HEIF,+ "image/gif": proto.ImageContent_TYPE_GIF,+ "image/bmp": proto.ImageContent_TYPE_BMP,+ "image/tiff": proto.ImageContent_TYPE_TIFF,+}++var audioMimeFromString = map[string]proto.AudioContent_MimeType{+ "audio/wav": proto.AudioContent_TYPE_WAV,+ "audio/mp3": proto.AudioContent_TYPE_MP3,+ "audio/aiff": proto.AudioContent_TYPE_AIFF,+ "audio/aac": proto.AudioContent_TYPE_AAC,+ "audio/ogg": proto.AudioContent_TYPE_OGG,+ "audio/flac": proto.AudioContent_TYPE_FLAC,+ "audio/mpeg": proto.AudioContent_TYPE_MPEG,+ "audio/m4a": proto.AudioContent_TYPE_M4A,+ "audio/l16": proto.AudioContent_TYPE_L16,+ "audio/s16le": proto.AudioContent_TYPE_S16LE,+ "audio/opus": proto.AudioContent_TYPE_OPUS,+ "audio/alaw": proto.AudioContent_TYPE_ALAW,+ "audio/mulaw": proto.AudioContent_TYPE_MULAW,+}++var videoMimeFromString = map[string]proto.VideoContent_MimeType{+ "video/mp4": proto.VideoContent_TYPE_MP4,+ "video/mpeg": proto.VideoContent_TYPE_MPEG,+ "video/mpg": proto.VideoContent_TYPE_MPG,+ "video/mov": proto.VideoContent_TYPE_MOV,+ "video/avi": proto.VideoContent_TYPE_AVI,+ "video/x-flv": proto.VideoContent_TYPE_X_FLV,+ "video/webm": proto.VideoContent_TYPE_WEBM,+ "video/wmv": proto.VideoContent_TYPE_WMV,+ "video/3gpp": proto.VideoContent_TYPE_3GPP,+}++var documentMimeFromString = map[string]proto.DocumentContent_MimeType{+ "application/pdf": proto.DocumentContent_TYPE_PDF,+ "application/json": proto.DocumentContent_TYPE_JSON,+ "text/x-python": proto.DocumentContent_TYPE_PYTHON,+}++var (+ imageMimeToString = invertMap(imageMimeFromString)+ audioMimeToString = invertMap(audioMimeFromString)+ videoMimeToString = invertMap(videoMimeFromString)+ documentMimeToString = invertMap(documentMimeFromString)+)++// ----- role mapping -----+//+// stringToA2ARole is the strict source-of-truth map for role translation+// between AX (string) and A2A (typed enum). The inverse (a2aRoleToString)+// is derived via invertMap so adding an entry here automatically+// propagates to both directions.+var stringToA2ARole = map[string]a2a.MessageRole{+ "unspecified": a2a.MessageRoleUnspecified,+ "user": a2a.MessageRoleUser,+ "agent": a2a.MessageRoleAgent,+}++var a2aRoleToString = invertMap(stringToA2ARole)++// invertMap returns a new map with keys and values swapped. If two keys+// map to the same value, last write wins per Go map iteration order.+func invertMap[K, V comparable](in map[K]V) map[V]K {+ out := make(map[V]K, len(in))+ for k, v := range in {+ out[v] = k+ }+ return out+}diff --git a/internal/experimental/a2abridge/mappings_test.go b/internal/experimental/a2abridge/mappings_test.gonew file mode 100644index 0000000..8ec46d6--- /dev/null+++ b/internal/experimental/a2abridge/mappings_test.go@@ -0,0 +1,70 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package a2abridge++import (+ "testing"++ "github.com/google/ax/proto"+ "google.golang.org/protobuf/reflect/protoreflect"+)++// TestMimeTableCoverage verifies that every non-UNSPECIFIED MIME enum+// value declared in proto/content.proto has a corresponding wire-string+// entry in mime_map.go's forward table.+func TestMimeTableCoverage(t *testing.T) {+ t.Run("ImageContent_MimeType", func(t *testing.T) {+ assertMimeCoverage(t, proto.ImageContent_MimeType(0).Descriptor(), func(n int32) bool {+ _, ok := imageMimeToString[proto.ImageContent_MimeType(n)]+ return ok+ })+ })+ t.Run("AudioContent_MimeType", func(t *testing.T) {+ assertMimeCoverage(t, proto.AudioContent_MimeType(0).Descriptor(), func(n int32) bool {+ _, ok := audioMimeToString[proto.AudioContent_MimeType(n)]+ return ok+ })+ })+ t.Run("VideoContent_MimeType", func(t *testing.T) {+ assertMimeCoverage(t, proto.VideoContent_MimeType(0).Descriptor(), func(n int32) bool {+ _, ok := videoMimeToString[proto.VideoContent_MimeType(n)]+ return ok+ })+ })+ t.Run("DocumentContent_MimeType", func(t *testing.T) {+ assertMimeCoverage(t, proto.DocumentContent_MimeType(0).Descriptor(), func(n int32) bool {+ _, ok := documentMimeToString[proto.DocumentContent_MimeType(n)]+ return ok+ })+ })+}++func assertMimeCoverage(t *testing.T, desc protoreflect.EnumDescriptor, has func(int32) bool) {+ t.Helper()+ var missing []string+ values := desc.Values()+ for i := 0; i < values.Len(); i++ {+ v := values.Get(i)+ if int32(v.Number()) == 0 {+ continue // UNSPECIFIED; intentionally not mapped+ }+ if !has(int32(v.Number())) {+ missing = append(missing, string(v.Name()))+ }+ }+ if len(missing) > 0 {+ t.Errorf("mime_map missing wire-string entries for: %v (add the wire MIME string to the corresponding forward map in mime_map.go)", missing)+ }+}diff --git a/internal/experimental/agent/a2a.go b/internal/experimental/agent/a2a.gonew file mode 100644index 0000000..b887b69--- /dev/null+++ b/internal/experimental/agent/a2a.go@@ -0,0 +1,300 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package agent++import (+ "context"+ "errors"+ "fmt"++ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"+ "github.com/google/ax/internal/agent"+ "github.com/google/ax/internal/auth"+ "github.com/google/ax/internal/experimental/a2abridge"+ "github.com/google/ax/proto"+)++// A2AAgentConfig is the per-agent configuration needed to construct an+// A2AAgent.+//+// Stateless controls how the bridge composes outgoing A2A messages:+//+// - false (default, "stateful"): the bridge sends only the new user+// input each turn and relies on the agent server using contextId to+// load conversation history from its own session store. This matches+// the A2A protocol convention.+//+// - true: the bridge sends the full AX message history on every call.+// Use this when targeting an A2A agent that does not maintain its+// own per-context state.+type A2AAgentConfig struct {+ ID string+ Address string+ Auth auth.Auth+ Headers auth.Headers+ Stateless bool+}++// A2AAgent bridges AX's Agent interface to an A2A-protocol agent.+type A2AAgent struct {+ id string+ client *a2aclient.Client+ card *a2a.AgentCard+ stateless bool+}++func NewA2AAgent(ctx context.Context, config A2AAgentConfig) (*A2AAgent, error) {+ if config.Address == "" {+ return nil, errors.New("a2a agent: address is required")+ }++ card, err := agentcard.DefaultResolver.Resolve(ctx, config.Address)+ if err != nil {+ return nil, fmt.Errorf("a2a agent %s: resolve AgentCard: %w", config.ID, err)+ }++ interceptor, err := a2abridge.NewInterceptor(card, config.Auth, config.Headers)+ if err != nil {+ return nil, fmt.Errorf("a2a agent %s: %w", config.ID, err)+ }++ var opts []a2aclient.FactoryOption+ if interceptor != nil {+ opts = append(opts, a2aclient.WithCallInterceptors(interceptor))+ }++ client, err := a2aclient.NewFromCard(ctx, card, opts...)+ if err != nil {+ return nil, fmt.Errorf("a2a agent %s: create client: %w", config.ID, err)+ }++ return &A2AAgent{+ id: config.ID,+ client: client,+ card: card,+ stateless: config.Stateless,+ }, nil+}++// Card returns the resolved AgentCard for this agent.+func (a *A2AAgent) Card() *a2a.AgentCard {+ return a.card+}++// Connect bridges one AX execution to one A2A operation.+//+// Two paths:+//+// 1. Resume an existing in-flight task.+// This covers HITL continuation: the user has supplied an answer to a+// ConfirmationContent we previously emitted.+//+// 2. New A2A operation.+func (a *A2AAgent) Connect(+ ctx context.Context,+ conversationID string,+ execID string,+ start *proto.AgentStart,+ e agent.Executor,+ o agent.OutputHandler,+) error {+ // Compute the planner's ToolCallID for this delegation.+ // Empty when the A2A agent is invoked directly.+ toolCallID := a2abridge.FindToolCallID(a.id, start.Messages)++ // Recover any persisted state from prior calls on this exec_id.+ markerConv, activeTaskID, recoveredEmitted, found := a2abridge.RecoverA2AState(start.Messages)+ if found && markerConv != conversationID {+ found = false+ activeTaskID = ""+ recoveredEmitted = nil+ }++ if found && activeTaskID != "" {+ return a.resumeTask(ctx, conversationID, toolCallID, a2a.TaskID(activeTaskID), recoveredEmitted, start, o)+ }+ return a.newOperation(ctx, conversationID, toolCallID, start, o)+}++// Resumes an in-flight task. It checks the server-side state via GetTask+// and either continues a HITL flow, picks up completed artifacts, surfaces+// a failure, or resumes streaming for a still-active task.+func (a *A2AAgent) resumeTask(+ ctx context.Context,+ conversationID string,+ toolCallID string,+ taskID a2a.TaskID,+ recoveredEmitted []string,+ start *proto.AgentStart,+ o agent.OutputHandler,+) error {+ task, err := a.client.GetTask(ctx, &a2a.GetTaskRequest{ID: taskID})+ if err != nil {+ // If the server has dropped the task (TTL, admin action, etc.)+ // the marker is stale: clear it so the next exec starts fresh,+ // then surface the situation as an explicit error.+ if errors.Is(err, a2a.ErrTaskNotFound) {+ _ = a2abridge.ClearStateMarker(conversationID, o)+ return fmt.Errorf("a2a agent %s: task %s no longer exists on server (state marker cleared; retry to start a new operation)", a.id, taskID)+ }+ return fmt.Errorf("a2a agent %s: GetTask(%s): %w", a.id, taskID, err)+ }++ switch task.Status.State {+ case a2a.TaskStateCompleted:+ // Task already done on the server side; emit any artifacts the+ // client hasn't seen yet, then drop the now-stale marker.+ if err := a2abridge.EmitTaskArtifacts(task, o); err != nil {+ return err+ }+ return a2abridge.ClearStateMarker(conversationID, o)++ case a2a.TaskStateFailed, a2a.TaskStateCanceled, a2a.TaskStateRejected:+ _ = a2abridge.ClearStateMarker(conversationID, o)+ return fmt.Errorf("a2a agent %s: task %s ended with state %s", a.id, taskID, task.Status.State)++ case a2a.TaskStateAuthRequired:+ // Server is asking for refreshed credentials. Now returns an error.+ // TODO(wjjclaud): implement credential refresh.+ _ = a2abridge.ClearStateMarker(conversationID, o)+ return a2abridge.AuthRequiredError(a.id, taskID, task.Status.Message)++ case a2a.TaskStateInputRequired:+ // HITL: scan the resumed history for an answer to the+ // confirmation we previously emitted. If the user has answered,+ // forward to the same A2A task; if not, re-emit the confirmation+ // prompt so the client sees it again.+ matchID := toolCallID+ if matchID == "" {+ matchID = string(taskID)+ }+ answered, approved := a2abridge.FindConfirmationAnswer(start.Messages, matchID)+ if !answered {+ return a2abridge.EmitConfirmation(conversationID, toolCallID, taskID, task, recoveredEmitted, o)+ }+ return a.sendFollowUp(ctx, conversationID, toolCallID, taskID, approved, o)++ default:+ // Working / Submitted: subscribe back to the+ // task's event stream and process events normally.+ return a.subscribeAndProcess(ctx, conversationID, toolCallID, taskID, recoveredEmitted, o)+ }+}++// Handles a fresh A2A operation. It sends the AX messages to the agent and+// processes the resulting event stream.+//+// The outgoing message depends on the agent's mode:+//+// - Stateful (default): only the latest user-input parts are sent.+// The agent server is expected to reconstruct prior conversation+// context from contextId via its own session store.+//+// - Stateless: the full AX history is sent every turn. Necessary+// for agents that do not maintain their own per-context state.+func (a *A2AAgent) newOperation(+ ctx context.Context,+ conversationID string,+ toolCallID string,+ start *proto.AgentStart,+ o agent.OutputHandler,+) error {+ var parts []*a2a.Part+ if a.stateless {+ parts = a2abridge.MessagesToA2AParts(start.Messages)+ } else {+ parts = a2abridge.LatestUserInputParts(start.Messages)+ }+ if len(parts) == 0 {+ return fmt.Errorf("a2a agent %s: no user-input parts to send", a.id)+ }++ msg := &a2a.Message{+ ID: a2a.NewMessageID(),+ ContextID: conversationID,+ Role: a2a.MessageRoleUser,+ Parts: parts,+ }+ // SendStreamingMessage auto-falls-back to non-streaming SendMessage+ // when the agent does not support streaming. a2abridge.IterateStream+ // consumes both shapes uniformly.+ stream := a.client.SendStreamingMessage(ctx, &a2a.SendMessageRequest{Message: msg})+ return a2abridge.IterateStream(ctx, a.client, a.id, conversationID, toolCallID, stream, o)+}++// sendFollowUp sends the user's reply (yes/no) to a paused HITL task and+// processes the subsequent event stream.+func (a *A2AAgent) sendFollowUp(+ ctx context.Context,+ conversationID string,+ toolCallID string,+ taskID a2a.TaskID,+ approved bool,+ o agent.OutputHandler,+) error {+ answer := "yes"+ if !approved {+ answer = "no"+ }+ msg := &a2a.Message{+ ID: a2a.NewMessageID(),+ ContextID: conversationID,+ TaskID: taskID,+ Role: a2a.MessageRoleUser,+ Parts: []*a2a.Part{a2a.NewTextPart(answer)},+ }+ stream := a.client.SendStreamingMessage(ctx, &a2a.SendMessageRequest{Message: msg})+ return a2abridge.IterateStream(ctx, a.client, a.id, conversationID, toolCallID, stream, o)+}++// subscribeAndProcess re-subscribes to a task's event stream (for resuming a+// task that was still working when the bridge previously disconnected).+//+// toolCallID is passed through so that any HITL emitted via the resumed+// stream uses the planner's ToolCallID for ConfirmationContentID.+//+// alreadyEmitted is forwarded to a2abridge.PollUntilTerminal for dedup+// seeding when we fall back to polling.+func (a *A2AAgent) subscribeAndProcess(+ ctx context.Context,+ conversationID string,+ toolCallID string,+ taskID a2a.TaskID,+ alreadyEmitted []string,+ o agent.OutputHandler,+) error {+ if a.card != nil && a.card.Capabilities.Streaming {+ stream := a.client.SubscribeToTask(ctx, &a2a.SubscribeToTaskRequest{ID: taskID})+ return a2abridge.IterateStream(ctx, a.client, a.id, conversationID, toolCallID, stream, o)+ }+ return a2abridge.PollUntilTerminal(ctx, a.client, a.id, conversationID, toolCallID, taskID, nil, alreadyEmitted, o)+}++// HealthCheck performs a lightweight call to verify the agent is reachable.+// Uses GetExtendedAgentCard which is supported by all A2A-compliant agents.+func (a *A2AAgent) HealthCheck(ctx context.Context) error {+ _, err := a.client.GetExtendedAgentCard(ctx, &a2a.GetExtendedAgentCardRequest{})+ return err+}++// Close releases the underlying A2A client's resources.+func (a *A2AAgent) Close() error {+ if a.client == nil {+ return nil+ }+ return a.client.Destroy()+}diff --git a/internal/server/server.go b/internal/server/server.goindex 2bddfdf..9087295 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -78,7 +78,6 @@ func (s *Server) DeleteConversation(ctx context.Context, req *proto.DeleteRequesreturn &proto.DeleteResponse{}, nil}-// Serve starts the gRPC server on the specified address.func (s *Server) Serve(address string, opts ...grpc.ServerOption) error {lis, err := net.Listen("tcp", address)