a2a

package
v2.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 29, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package a2a provides types for the Agent-to-Agent (A2A) protocol.

Types are derived from the A2A protocol specification (a2a.proto) and use camelCase JSON tags matching the JSON-RPC binding convention.

Index

Examples

Constants

View Source
const (
	AgentCardPath       = "/.well-known/agent-card.json"
	LegacyAgentCardPath = "/.well-known/agent.json"
)

Agent card discovery paths. A2A 0.3 (§5.3) and 1.0 (§8.2) serve the card at AgentCardPath; 0.2 and earlier servers used LegacyAgentCardPath.

View Source
const (
	DefaultA2AMaxRetries   = 3
	DefaultA2AInitialDelay = 500 * time.Millisecond
	DefaultA2AMaxDelay     = 30 * time.Second

	// DefaultClientTTL is the default time-to-live for cached A2A clients.
	// Clients not used within this duration are evicted from the cache.
	DefaultClientTTL = 30 * time.Minute

	// DefaultMaxClients is the default maximum number of cached A2A clients.
	// When exceeded, the least recently used client is evicted.
	DefaultMaxClients = 100
)

Default retry constants for A2A executor.

View Source
const (
	MethodV1SendMessage          = "SendMessage"
	MethodV1SendStreamingMessage = "SendStreamingMessage"
	MethodV1GetTask              = "GetTask"
	MethodV1CancelTask           = "CancelTask"
	MethodV1ListTasks            = "ListTasks"
	MethodV1SubscribeToTask      = "SubscribeToTask"
	MethodV1GetExtendedAgentCard = "GetExtendedAgentCard"

	MethodV1CreateTaskPushNotificationConfig = "CreateTaskPushNotificationConfig"
	MethodV1GetTaskPushNotificationConfig    = "GetTaskPushNotificationConfig"
	MethodV1ListTaskPushNotificationConfigs  = "ListTaskPushNotificationConfigs"
	MethodV1DeleteTaskPushNotificationConfig = "DeleteTaskPushNotificationConfig"
)

A2A 1.0 JSON-RPC method names (A2A 1.0 §5.3).

View Source
const (
	MethodSendMessage          = "message/send"
	MethodSendStreamingMessage = "message/stream"
	MethodGetTask              = "tasks/get"
	MethodCancelTask           = "tasks/cancel"
	MethodListTasks            = "tasks/list"
	MethodTaskSubscribe        = "tasks/subscribe"
)

The method names PromptKit used before it spoke A2A 1.0 and 0.3 by version. They keep their values: a server still answers every one of them, and code comparing against them keeps working.

Deprecated: use the MethodV1* names for A2A 1.0 and MethodV03* for 0.3, or resolve a method with LookupMethod.

View Source
const (
	MethodV03SendMessage          = "message/send"
	MethodV03SendStreamingMessage = "message/stream"
	MethodV03GetTask              = "tasks/get"
	MethodV03CancelTask           = "tasks/cancel"
	MethodV03Resubscribe          = "tasks/resubscribe"
	MethodV03GetExtendedCard      = "agent/getAuthenticatedExtendedCard"

	MethodV03SetPushNotificationConfig    = "tasks/pushNotificationConfig/set"
	MethodV03GetPushNotificationConfig    = "tasks/pushNotificationConfig/get"
	MethodV03ListPushNotificationConfig   = "tasks/pushNotificationConfig/list"
	MethodV03DeletePushNotificationConfig = "tasks/pushNotificationConfig/delete"

	// MethodLegacyListTasks and MethodLegacySubscribe are the names PromptKit
	// servers before A2A 1.0 conformance answered to; they are in neither
	// 0.3 nor 1.0 and are accepted only so older PromptKit clients keep
	// working.
	MethodLegacyListTasks = MethodListTasks
	MethodLegacySubscribe = MethodTaskSubscribe
)

A2A 0.3 JSON-RPC method names. A 0.3 server knows only these.

View Source
const (
	ErrCodeTaskNotFound                   = -32001
	ErrCodeTaskNotCancelable              = -32002
	ErrCodePushNotificationNotSupported   = -32003
	ErrCodeUnsupportedOperation           = -32004
	ErrCodeContentTypeNotSupported        = -32005
	ErrCodeInvalidAgentResponse           = -32006
	ErrCodeExtendedAgentCardNotConfigured = -32007
	ErrCodeExtensionSupportRequired       = -32008
	ErrCodeVersionNotSupported            = -32009
)

A2A-specific JSON-RPC error codes (A2A 1.0 §5.4, identical in 0.3).

View Source
const (
	ErrCodeParse          = -32700
	ErrCodeInvalidRequest = -32600
	ErrCodeMethodNotFound = -32601
	ErrCodeInvalidParams  = -32602
	ErrCodeInternal       = -32603
)

Standard JSON-RPC 2.0 error codes.

View Source
const (

	// DefaultSSEIdleTimeout is the default idle timeout for SSE streams.
	// If no event is received within this duration, ReadSSE returns an error
	// so callers can reconnect.
	DefaultSSEIdleTimeout = 5 * time.Minute
)

HTTP client defaults for A2A communication.

View Source
const HeaderVersion = "A2A-Version"

HeaderVersion is the service parameter carrying the protocol version a request speaks. A request without it is 0.3 (A2A 1.0 §3.6.2).

View Source
const ProtocolBindingJSONRPC = "JSONRPC"

ProtocolBindingJSONRPC is the AgentInterface binding name of the JSON-RPC transport (0.3 calls the same field "transport").

Variables

View Source
var ErrSSEIdleTimeout = fmt.Errorf("a2a: SSE idle timeout exceeded")

ErrSSEIdleTimeout is returned when an SSE stream has not received any event within the configured idle timeout period.

Functions

func ExtractResponseParts

func ExtractResponseParts(task *Task) []types.ContentPart

ExtractResponseParts converts all A2A Parts from a completed task into PromptKit ContentParts. It collects parts from the status message (if present) and all artifacts. Parts that fail conversion (e.g., structured data) are silently skipped.

func ExtractResponseText

func ExtractResponseText(task *Task) string

ExtractResponseText extracts text from a completed A2A task. It checks the status message first, then artifacts.

func InferContentType

func InferContentType(mediaType string) string

InferContentType maps a MIME type to a PromptKit content type string.

func LookupMethod added in v2.8.0

func LookupMethod(method string) (op Operation, v ProtocolVersion, ok bool)

LookupMethod resolves a JSON-RPC method name to its operation and the version that names it that way. ok is false for an unknown method.

func MessageToMessage

func MessageToMessage(msg *Message) (*types.Message, error)

MessageToMessage converts an A2A Message to a PromptKit Message.

Example

ExampleMessageToMessage shows converting an A2A protocol Message into PromptKit's internal types.Message. This is a pure conversion — no network call or running A2A server required. The "agent" role maps to PromptKit's "assistant" role.

package main

import (
	"fmt"

	"github.com/AltairaLabs/PromptKit/runtime/v2/a2a"
)

func main() {
	text := "hello from agent"
	msg := &a2a.Message{
		MessageID: "m1",
		Role:      a2a.RoleAgent,
		Parts:     []a2a.Part{{Text: &text}},
	}

	out, err := a2a.MessageToMessage(msg)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(out.Role, "->", out.GetContent())
}
Output:
assistant -> hello from agent

func PartToContentPart

func PartToContentPart(part *Part) (types.ContentPart, error)

PartToContentPart converts an A2A Part to a PromptKit ContentPart.

func ReadSSE

func ReadSSE(ctx context.Context, r io.Reader, ch chan<- StreamEvent)

ReadSSE reads SSE events from r and sends parsed StreamEvents to ch. It has no idle timeout; use ReadSSEWithIdleTimeout for timeout support.

func ReadSSEWithIdleTimeout

func ReadSSEWithIdleTimeout(ctx context.Context, r io.Reader, ch chan<- StreamEvent, idleTimeout time.Duration)

ReadSSEWithIdleTimeout reads SSE events from r and sends parsed StreamEvents to ch. If idleTimeout is positive and no line is received within that duration, reading stops (callers should reconnect). A zero or negative idleTimeout disables idle detection.

Types

type APIKeySecurityScheme added in v2.8.0

type APIKeySecurityScheme struct {
	Description string `json:"description,omitempty"`
	// Location is "header", "query" or "cookie".
	Location string `json:"location"`
	Name     string `json:"name"`
}

APIKeySecurityScheme is an API key sent in a header, query parameter or cookie.

type AgentCapabilities

type AgentCapabilities struct {
	Streaming         bool             `json:"streaming,omitempty"`
	PushNotifications bool             `json:"pushNotifications,omitempty"`
	ExtendedAgentCard bool             `json:"extendedAgentCard,omitempty"`
	Extensions        []AgentExtension `json:"extensions,omitempty"`
}

AgentCapabilities describes what the agent supports.

type AgentCard

type AgentCard struct {
	Name                string            `json:"name"`
	Description         string            `json:"description,omitempty"`
	Version             string            `json:"version,omitempty"`
	Provider            *AgentProvider    `json:"provider,omitempty"`
	Capabilities        AgentCapabilities `json:"capabilities,omitzero"`
	Skills              []AgentSkill      `json:"skills,omitempty"`
	DefaultInputModes   []string          `json:"defaultInputModes,omitempty"`
	DefaultOutputModes  []string          `json:"defaultOutputModes,omitempty"`
	SupportedInterfaces []AgentInterface  `json:"supportedInterfaces,omitempty"`
	IconURL             string            `json:"iconUrl,omitempty"`
	DocumentationURL    string            `json:"documentationUrl,omitempty"`

	// SecuritySchemes declares the authentication schemes the agent accepts,
	// keyed by a name SecurityRequirements refer to (A2A 1.0 §7.3).
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
	// SecurityRequirements lists the scheme combinations a caller must
	// satisfy; any one requirement suffices.
	SecurityRequirements []SecurityRequirement `json:"securityRequirements,omitempty"`
}

AgentCard describes an agent's capabilities and endpoints.

func (*AgentCard) PreferredVersion added in v2.8.0

func (card *AgentCard) PreferredVersion() ProtocolVersion

PreferredVersion picks the protocol version to speak to the agent that published card: 1.0 when any JSON-RPC interface declares it (or the card declares nothing), otherwise 0.3.

func (*AgentCard) UnmarshalJSON added in v2.8.0

func (card *AgentCard) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. A 0.3 card declares its endpoint in url/preferredTransport/additionalInterfaces rather than supportedInterfaces, and its requirements in "security"; both are folded into the 1.0 fields when the card does not carry them itself.

type AgentExtension

type AgentExtension struct {
	URI         string `json:"uri"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

AgentExtension describes an optional protocol extension.

type AgentInterface

type AgentInterface struct {
	URL string `json:"url"`
	// ProtocolBinding is the transport: [ProtocolBindingJSONRPC], "GRPC" or
	// "HTTP+JSON".
	ProtocolBinding string `json:"protocolBinding,omitempty"`
	// ProtocolVersion is the A2A Major.Minor version served at URL.
	ProtocolVersion string `json:"protocolVersion,omitempty"`
	Tenant          string `json:"tenant,omitempty"`
}

AgentInterface describes a protocol endpoint.

type AgentProvider

type AgentProvider struct {
	Organization string `json:"organization"`
	URL          string `json:"url,omitempty"`
}

AgentProvider identifies the organization behind an agent.

type AgentSkill

type AgentSkill struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	Examples    []string `json:"examples,omitempty"`
	InputModes  []string `json:"inputModes,omitempty"`
	OutputModes []string `json:"outputModes,omitempty"`

	SecurityRequirements []SecurityRequirement `json:"securityRequirements,omitempty"`
}

AgentSkill describes a specific skill an agent can perform.

type Artifact

type Artifact struct {
	ArtifactID  string         `json:"artifactId"`
	Name        string         `json:"name,omitempty"`
	Description string         `json:"description,omitempty"`
	Parts       []Part         `json:"parts"`
	Extensions  []string       `json:"extensions,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

Artifact is a named output generated by an agent.

func ContentPartsToArtifacts

func ContentPartsToArtifacts(parts []types.ContentPart) ([]Artifact, error)

ContentPartsToArtifacts converts PromptKit ContentParts into A2A Artifacts. It creates a single Artifact containing all non-empty parts. Returns nil if parts is empty or all parts fail to convert.

type CancelTaskRequest

type CancelTaskRequest struct {
	Tenant string `json:"tenant,omitempty"`
	ID     string `json:"id"`
}

CancelTaskRequest is the params for CancelTask (0.3: tasks/cancel).

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an HTTP client for discovering and calling external A2A agents.

func NewClient

func NewClient(baseURL string, opts ...ClientOption) *Client

NewClient creates a Client targeting baseURL.

func (*Client) CancelTask

func (c *Client) CancelTask(ctx context.Context, taskID string) error

CancelTask cancels a task by ID (CancelTask; 0.3: tasks/cancel).

func (*Client) Discover

func (c *Client) Discover(ctx context.Context) (*AgentCard, error)

Discover fetches the agent card, trying AgentCardPath first and falling back to LegacyAgentCardPath when the agent does not serve it (404/405). The card is cached after the first successful call.

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, taskID string) (*Task, error)

GetTask retrieves a task by ID (GetTask; 0.3: tasks/get).

func (*Client) ListTasks

func (c *Client) ListTasks(ctx context.Context, params *ListTasksRequest) ([]*Task, error)

ListTasks lists tasks (ListTasks, which A2A 1.0 added; to a 0.3 agent the client sends the legacy PromptKit tasks/list, which only PromptKit servers answer).

func (*Client) ProtocolVersion added in v2.8.0

func (c *Client) ProtocolVersion() ProtocolVersion

ProtocolVersion returns the protocol version the client currently speaks.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, params *SendMessageRequest) (*Task, error)

SendMessage sends a message (SendMessage; 0.3: message/send) and returns the resulting task.

An agent that answers with a Message rather than a Task gets a completed task synthesized around it, the message as its status message, so callers have one shape to read.

func (*Client) SendMessageStream

func (c *Client) SendMessageStream(ctx context.Context, params *SendMessageRequest) (<-chan StreamEvent, error)

SendMessageStream sends a streaming message (SendStreamingMessage; 0.3: message/stream) and returns a channel of streaming events. The channel is closed when the stream ends or the context is canceled.

func (*Client) WaitForTask added in v2.8.0

func (c *Client) WaitForTask(ctx context.Context, task *Task) (*Task, error)

WaitForTask polls task until it finishes or needs the caller (a terminal or interrupted state), and returns it as it then stands. A task that is already there is returned as is. ctx bounds the wait; when it ends, the last state seen is returned with ctx's error.

A SendMessage can come back before its task is done: with returnImmediately, from a 0.3 agent that does not block, or from a server that caps how long it holds a request.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client.

func WithAuth

func WithAuth(scheme, token string) ClientOption

WithAuth sets the Authorization header on all requests.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) ClientOption

WithHTTPClient sets the underlying HTTP client.

func WithHeaders

func WithHeaders(headers map[string]string) ClientOption

WithHeaders sets custom headers that are sent on all requests.

func WithProtocolVersion added in v2.8.0

func WithProtocolVersion(v ProtocolVersion) ClientOption

WithProtocolVersion pins the A2A protocol version the client speaks, disabling negotiation. Without it the client speaks 1.0, or what a discovered agent card prefers, and falls back to 0.3 when the agent rejects a 1.0 method.

func WithRequestTimeout added in v2.8.0

func WithRequestTimeout(d time.Duration) ClientOption

WithRequestTimeout sets the timeout for non-streaming requests (agent card discovery and message/send, tasks/get, ...). The default is 60s. It does not affect SSE streams, which are bounded by the SSE idle timeout instead. A zero or negative value leaves the default in place.

func WithSSEIdleTimeout

func WithSSEIdleTimeout(d time.Duration) ClientOption

WithSSEIdleTimeout sets the idle timeout for SSE streams. If no event is received within this duration, the stream is considered stale and ReadSSE returns ErrSSEIdleTimeout so callers can reconnect. A zero or negative value disables the idle timeout.

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor implements tools.Executor and tools.MultimodalExecutor for A2A agent tools. It dispatches tool calls to remote A2A agents via the A2A client. The executor maintains a cache of A2A clients with TTL-based eviction. Call Close when the executor is no longer needed to release resources.

func NewExecutor

func NewExecutor(opts ...ExecutorOption) *Executor

NewExecutor creates a new A2A executor with optional configuration. The executor starts a background goroutine for cache cleanup. Call Close when the executor is no longer needed.

func (*Executor) Close

func (e *Executor) Close() error

Close stops the background cleanup goroutine and clears the client cache.

func (*Executor) Execute

func (e *Executor) Execute(
	ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage,
) (json.RawMessage, error)

Execute calls a remote A2A agent with the tool arguments and returns the response.

func (*Executor) ExecuteMultimodal

func (e *Executor) ExecuteMultimodal(
	ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage,
) (json.RawMessage, []types.ContentPart, error)

ExecuteMultimodal calls a remote A2A agent and returns both JSON result and multimodal content parts. It implements tools.MultimodalExecutor.

func (*Executor) Name

func (e *Executor) Name() string

Name returns "a2a" to match the Mode on A2A tool descriptors.

type ExecutorOption

type ExecutorOption func(*Executor)

ExecutorOption configures an Executor.

func WithClientTTL

func WithClientTTL(d time.Duration) ExecutorOption

WithClientTTL sets the time-to-live for cached A2A clients. Clients not used within this duration are evicted from the cache.

func WithMaxClients

func WithMaxClients(n int) ExecutorOption

WithMaxClients sets the maximum number of cached A2A clients. When exceeded, the least recently used client is evicted.

func WithNoRetry

func WithNoRetry() ExecutorOption

WithNoRetry disables retry for the A2A executor.

func WithRetryPolicy

func WithRetryPolicy(policy RetryPolicy) ExecutorOption

WithRetryPolicy sets the retry policy for the A2A executor.

type GetTaskRequest

type GetTaskRequest struct {
	Tenant        string `json:"tenant,omitempty"`
	ID            string `json:"id"`
	HistoryLength *int   `json:"historyLength,omitempty"`
}

GetTaskRequest is the params for GetTask (0.3: tasks/get).

type HTTPAuthSecurityScheme added in v2.8.0

type HTTPAuthSecurityScheme struct {
	Description  string `json:"description,omitempty"`
	Scheme       string `json:"scheme"`
	BearerFormat string `json:"bearerFormat,omitempty"`
}

HTTPAuthSecurityScheme is an HTTP Authorization scheme such as Bearer.

type HTTPStatusError

type HTTPStatusError struct {
	StatusCode int
	Method     string
}

HTTPStatusError is returned when an A2A HTTP request receives a non-200 status code.

func (*HTTPStatusError) Error

func (e *HTTPStatusError) Error() string

type JSONRPCError

type JSONRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

JSONRPCError is a JSON-RPC 2.0 error object.

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

JSONRPCRequest is a JSON-RPC 2.0 request.

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *JSONRPCError   `json:"error,omitempty"`
}

JSONRPCResponse is a JSON-RPC 2.0 response.

type ListTasksRequest

type ListTasksRequest struct {
	Tenant               string     `json:"tenant,omitempty"`
	ContextID            string     `json:"contextId,omitempty"`
	Status               *TaskState `json:"status,omitempty"`
	PageSize             int        `json:"pageSize,omitempty"`
	PageToken            string     `json:"pageToken,omitempty"`
	HistoryLength        *int       `json:"historyLength,omitempty"`
	StatusTimestampAfter *time.Time `json:"statusTimestampAfter,omitempty"`
	// IncludeArtifacts asks for each task's artifacts; they are omitted by
	// default.
	IncludeArtifacts bool `json:"includeArtifacts,omitempty"`
}

ListTasksRequest is the params for ListTasks (1.0 only).

type ListTasksResponse

type ListTasksResponse struct {
	Tasks         []Task `json:"tasks"`
	NextPageToken string `json:"nextPageToken"`
	PageSize      int    `json:"pageSize"`
	TotalSize     int    `json:"totalSize"`
}

ListTasksResponse is the result for ListTasks. NextPageToken is empty on the last page.

type Message

type Message struct {
	MessageID        string         `json:"messageId"`
	ContextID        string         `json:"contextId,omitempty"`
	TaskID           string         `json:"taskId,omitempty"`
	Role             Role           `json:"role"`
	Parts            []Part         `json:"parts"`
	ReferenceTaskIDs []string       `json:"referenceTaskIds,omitempty"`
	Extensions       []string       `json:"extensions,omitempty"`
	Metadata         map[string]any `json:"metadata,omitempty"`
}

Message is a communication unit in the A2A protocol.

type MutualTLSSecurityScheme added in v2.8.0

type MutualTLSSecurityScheme struct {
	Description string `json:"description,omitempty"`
}

MutualTLSSecurityScheme is mutual TLS.

type OAuth2SecurityScheme added in v2.8.0

type OAuth2SecurityScheme struct {
	Description       string     `json:"description,omitempty"`
	Flows             OAuthFlows `json:"flows"`
	OAuth2MetadataURL string     `json:"oauth2MetadataUrl,omitempty"`
}

OAuth2SecurityScheme is OAuth 2.0.

type OAuthFlow added in v2.8.0

type OAuthFlow struct {
	AuthorizationURL       string            `json:"authorizationUrl,omitempty"`
	DeviceAuthorizationURL string            `json:"deviceAuthorizationUrl,omitempty"`
	TokenURL               string            `json:"tokenUrl,omitempty"`
	RefreshURL             string            `json:"refreshUrl,omitempty"`
	Scopes                 map[string]string `json:"scopes"`
	PKCERequired           bool              `json:"pkceRequired,omitempty"`
}

OAuthFlow is one OAuth 2.0 flow; which URLs apply depends on the flow.

type OAuthFlows added in v2.8.0

type OAuthFlows struct {
	AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
	ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
	DeviceCode        *OAuthFlow `json:"deviceCode,omitempty"`
	Implicit          *OAuthFlow `json:"implicit,omitempty"`
	Password          *OAuthFlow `json:"password,omitempty"`
}

OAuthFlows lists the OAuth 2.0 flows the agent supports.

type OpenIDConnectSecurityScheme added in v2.8.0

type OpenIDConnectSecurityScheme struct {
	Description      string `json:"description,omitempty"`
	OpenIDConnectURL string `json:"openIdConnectUrl"`
}

OpenIDConnectSecurityScheme is OpenID Connect discovery.

type Operation added in v2.8.0

type Operation int

Operation is a protocol operation, independent of any version's name for it.

const (
	OpUnknown Operation = iota
	OpSendMessage
	OpSendStreamingMessage
	OpGetTask
	OpCancelTask
	OpListTasks
	OpSubscribeToTask
	OpPushNotificationConfig
	OpGetExtendedAgentCard
)

Protocol operations.

type Part

type Part struct {
	Text *string        `json:"text,omitempty"`
	Raw  []byte         `json:"raw,omitempty"`
	URL  *string        `json:"url,omitempty"`
	Data map[string]any `json:"data,omitempty"`

	Metadata  map[string]any `json:"metadata,omitempty"`
	Filename  string         `json:"filename,omitempty"`
	MediaType string         `json:"mediaType,omitempty"`
}

Part represents a piece of content within a message or artifact. Exactly one of Text, Raw, URL, or Data should be set.

func ContentPartToA2APart

func ContentPartToA2APart(part types.ContentPart) (Part, error)

ContentPartToA2APart converts a PromptKit ContentPart to an A2A Part.

func (*Part) UnmarshalJSON added in v2.8.0

func (p *Part) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. Besides the A2A 1.0 shape it accepts 0.3's kind-tagged parts: {"kind":"text"}, {"kind":"data"} and {"kind":"file","file":{"bytes"|"uri",...}}.

type ProtocolVersion added in v2.8.0

type ProtocolVersion string

ProtocolVersion is an A2A protocol version, as Major.Minor (A2A 1.0 §3.6).

const (
	ProtocolVersion10 ProtocolVersion = "1.0"
	ProtocolVersion03 ProtocolVersion = "0.3"
)

Supported protocol versions.

func ParseProtocolVersion added in v2.8.0

func ParseProtocolVersion(s string) (ProtocolVersion, error)

ParseProtocolVersion resolves an A2A-Version value to a supported version. Patch numbers are ignored, as the spec requires. An empty value returns ("", nil): the caller decides what an unversioned request means.

func (ProtocolVersion) Method added in v2.8.0

func (v ProtocolVersion) Method(op Operation) string

Method returns version v's JSON-RPC method name for op (1.0's for any version other than 0.3). 0.3 has no ListTasks; the legacy PromptKit name is returned for it.

func (ProtocolVersion) WireAgentCard added in v2.8.0

func (v ProtocolVersion) WireAgentCard(card *AgentCard) any

WireAgentCard returns card in version v's shape.

For 1.0 the card is returned as is. For 0.3 (and for a request that names no version, which the spec reads as 0.3) it is the 0.3 card — url, preferredTransport, protocolVersion, additionalInterfaces, 0.3-style security — with supportedInterfaces kept as well, so a 1.0 client reading the same document still finds its interface.

func (ProtocolVersion) WireSendParams added in v2.8.0

func (v ProtocolVersion) WireSendParams(req *SendMessageRequest) any

WireSendParams returns SendMessage params in version v's shape (0.3 parts are kind-tagged).

func (ProtocolVersion) WireSendResult added in v2.8.0

func (v ProtocolVersion) WireSendResult(task *Task) any

WireSendResult returns the SendMessage result for task in version v's shape: 1.0 wraps it as {"task": ...}, 0.3 sends the kind-tagged task bare.

func (ProtocolVersion) WireStreamEvent added in v2.8.0

func (v ProtocolVersion) WireStreamEvent(event any) (any, error)

WireStreamEvent returns one streaming result in version v's shape. event is a *Task, *Message, *TaskStatusUpdateEvent or *TaskArtifactUpdateEvent. 1.0 wraps it in a StreamResponse; 0.3 sends it bare with its "kind" and, on a status update, "final" set when the state ends the stream.

func (ProtocolVersion) WireTask added in v2.8.0

func (v ProtocolVersion) WireTask(task *Task) any

WireTask returns task in version v's shape (the result of GetTask and CancelTask).

type RPCError

type RPCError struct {
	Code    int
	Message string
}

RPCError represents a JSON-RPC error returned by an A2A agent.

func (*RPCError) Error

func (e *RPCError) Error() string

type RetryPolicy

type RetryPolicy struct {
	MaxRetries   int
	InitialDelay time.Duration
	MaxDelay     time.Duration
}

RetryPolicy configures retry behavior for the A2A executor.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the default retry policy for A2A calls.

type Role

type Role string

Role identifies the sender of a message.

Like TaskState, a Role marshals to its A2A 1.0 name (ROLE_USER) and unmarshals from either version's spelling.

const (
	RoleUser  Role = "user"
	RoleAgent Role = "agent"
)

Role constants for message senders.

func (Role) MarshalJSON added in v2.8.0

func (r Role) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, writing the A2A 1.0 name.

func (*Role) UnmarshalJSON added in v2.8.0

func (r *Role) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, accepting either version's spelling. An unrecognized role is kept verbatim.

func (Role) V1Name added in v2.8.0

func (r Role) V1Name() string

V1Name returns the role's A2A 1.0 wire name.

type SecurityRequirement added in v2.8.0

type SecurityRequirement struct {
	Schemes map[string][]string
}

SecurityRequirement names the schemes (and their scopes) a caller must satisfy together. It marshals in the 1.0 shape ({"schemes": {"bearer": {"list": []}}}) and unmarshals from that or 0.3's {"bearer": []}.

func RequireScheme added in v2.8.0

func RequireScheme(name string, scopes ...string) SecurityRequirement

RequireScheme returns a requirement for a single scheme with optional scopes.

func (SecurityRequirement) MarshalJSON added in v2.8.0

func (r SecurityRequirement) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler in the A2A 1.0 shape.

func (*SecurityRequirement) UnmarshalJSON added in v2.8.0

func (r *SecurityRequirement) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for both versions' shapes.

type SecurityScheme added in v2.8.0

type SecurityScheme struct {
	APIKey        *APIKeySecurityScheme        `json:"apiKeySecurityScheme,omitempty"`
	HTTPAuth      *HTTPAuthSecurityScheme      `json:"httpAuthSecurityScheme,omitempty"`
	OAuth2        *OAuth2SecurityScheme        `json:"oauth2SecurityScheme,omitempty"`
	OpenIDConnect *OpenIDConnectSecurityScheme `json:"openIdConnectSecurityScheme,omitempty"`
	MutualTLS     *MutualTLSSecurityScheme     `json:"mtlsSecurityScheme,omitempty"`
}

SecurityScheme declares one way a caller can authenticate (A2A 1.0 §4.5). Exactly one field is set. It marshals in the 1.0 shape ({"httpAuthSecurityScheme": {...}}) and unmarshals from either that or 0.3's OpenAPI-style {"type": "http", ...}.

func (*SecurityScheme) UnmarshalJSON added in v2.8.0

func (s *SecurityScheme) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for both versions' shapes.

type SendMessageConfiguration

type SendMessageConfiguration struct {
	AcceptedOutputModes []string `json:"acceptedOutputModes,omitempty"`
	HistoryLength       *int     `json:"historyLength,omitempty"`
	// Blocking is A2A 0.3's switch.
	Blocking bool `json:"blocking,omitempty"`
	// ReturnImmediately is A2A 1.0's switch.
	ReturnImmediately bool `json:"returnImmediately,omitempty"`
}

SendMessageConfiguration controls message handling.

Blocking and ReturnImmediately are the same switch in two versions: A2A 0.3 sends blocking (default false), 1.0 sends returnImmediately (default false, so 1.0 blocks by default). A server reads the one its caller's version defines; see SendMessageConfiguration.WaitsForCompletion.

func (*SendMessageConfiguration) WaitsForCompletion added in v2.8.0

func (c *SendMessageConfiguration) WaitsForCompletion(v ProtocolVersion) bool

WaitsForCompletion reports whether a SendMessage under version v should wait for the task to finish or be interrupted before answering. A nil configuration takes the version's default.

type SendMessageRequest

type SendMessageRequest struct {
	Tenant        string                    `json:"tenant,omitempty"`
	Message       Message                   `json:"message"`
	Configuration *SendMessageConfiguration `json:"configuration,omitempty"`
	Metadata      map[string]any            `json:"metadata,omitempty"`
}

SendMessageRequest is the params for SendMessage and SendStreamingMessage (0.3: message/send, message/stream).

type SendMessageResponse added in v2.8.0

type SendMessageResponse struct {
	Task    *Task    `json:"task,omitempty"`
	Message *Message `json:"message,omitempty"`
}

SendMessageResponse is the A2A 1.0 result of SendMessage: exactly one of Task or Message is set. (0.3 returns the Task or Message bare.)

type StreamEvent

type StreamEvent struct {
	Task           *Task
	Message        *Message
	StatusUpdate   *TaskStatusUpdateEvent
	ArtifactUpdate *TaskArtifactUpdateEvent
}

StreamEvent represents a single event received during message streaming. Exactly one field will be non-nil. A conforming agent opens a task stream with the Task itself, or answers with a single Message.

type StreamResponse added in v2.8.0

type StreamResponse struct {
	Task           *Task                    `json:"task,omitempty"`
	Message        *Message                 `json:"message,omitempty"`
	StatusUpdate   *TaskStatusUpdateEvent   `json:"statusUpdate,omitempty"`
	ArtifactUpdate *TaskArtifactUpdateEvent `json:"artifactUpdate,omitempty"`
}

StreamResponse is one A2A 1.0 streaming result: exactly one field is set. (0.3 sends each object bare, discriminated by its "kind".)

type SubscribeTaskRequest

type SubscribeTaskRequest struct {
	Tenant string `json:"tenant,omitempty"`
	ID     string `json:"id"`
}

SubscribeTaskRequest is the params for SubscribeToTask (0.3: tasks/resubscribe).

type Task

type Task struct {
	ID        string         `json:"id"`
	ContextID string         `json:"contextId"`
	Status    TaskStatus     `json:"status"`
	Artifacts []Artifact     `json:"artifacts,omitempty"`
	History   []Message      `json:"history,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Task is the top-level unit of work in the A2A protocol.

type TaskArtifactUpdateEvent

type TaskArtifactUpdateEvent struct {
	TaskID    string         `json:"taskId"`
	ContextID string         `json:"contextId"`
	Artifact  Artifact       `json:"artifact"`
	Append    bool           `json:"append,omitempty"`
	LastChunk bool           `json:"lastChunk,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

TaskArtifactUpdateEvent is sent during streaming when an artifact is produced.

type TaskState

type TaskState string

TaskState represents the state of an A2A task.

The Go values are PromptKit's own and never appear on the wire: a TaskState marshals to its A2A 1.0 name (TASK_STATE_COMPLETED, ...) and unmarshals from the 1.0, 0.3 (input-required) and legacy (input_required) spellings alike.

const (
	TaskStateSubmitted     TaskState = "submitted"
	TaskStateWorking       TaskState = "working"
	TaskStateCompleted     TaskState = "completed"
	TaskStateFailed        TaskState = "failed"
	TaskStateCanceled      TaskState = "canceled"
	TaskStateInputRequired TaskState = "input_required"
	TaskStateRejected      TaskState = "rejected"
	TaskStateAuthRequired  TaskState = "auth_required"
	// TaskStateUnknown is 1.0's TASK_STATE_UNSPECIFIED and 0.3's "unknown".
	TaskStateUnknown TaskState = "unknown"
)

TaskState constants for the A2A protocol.

func ParseTaskState added in v2.8.0

func ParseTaskState(str string) (TaskState, error)

ParseTaskState resolves a wire spelling (1.0, 0.3 or legacy PromptKit) to a TaskState.

func (TaskState) IsInterrupted added in v2.8.0

func (s TaskState) IsInterrupted() bool

IsInterrupted reports whether s pauses the task for the client (input-required or auth-required). A stream ends at an interrupted state.

func (TaskState) IsTerminal added in v2.8.0

func (s TaskState) IsTerminal() bool

IsTerminal reports whether no further transitions are possible from s.

func (TaskState) MarshalJSON

func (s TaskState) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, writing the A2A 1.0 name.

func (*TaskState) UnmarshalJSON

func (s *TaskState) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, accepting any version's spelling.

func (TaskState) V1Name added in v2.8.0

func (s TaskState) V1Name() string

V1Name returns the state's A2A 1.0 wire name, e.g. TASK_STATE_COMPLETED.

func (TaskState) V03Name added in v2.8.0

func (s TaskState) V03Name() string

V03Name returns the state's A2A 0.3 wire name, e.g. input-required.

type TaskStatus

type TaskStatus struct {
	State     TaskState  `json:"state"`
	Message   *Message   `json:"message,omitempty"`
	Timestamp *time.Time `json:"timestamp,omitempty"`
}

TaskStatus describes the current status of a task.

type TaskStatusUpdateEvent

type TaskStatusUpdateEvent struct {
	TaskID    string         `json:"taskId"`
	ContextID string         `json:"contextId"`
	Status    TaskStatus     `json:"status"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

TaskStatusUpdateEvent is sent during streaming when a task's status changes.

type ToolBridge

type ToolBridge struct {
	// contains filtered or unexported fields
}

ToolBridge discovers an A2A agent and creates ToolDescriptor entries for each of the agent's skills so they can be invoked through the standard tool registry.

func NewToolBridge

func NewToolBridge(client *Client) *ToolBridge

NewToolBridge creates a ToolBridge backed by the given A2A client.

func NewToolBridgeWithConfig

func NewToolBridgeWithConfig(client *Client, cfg *tools.A2AConfig) *ToolBridge

NewToolBridgeWithConfig creates a ToolBridge that applies the given A2AConfig (headers, auth, retry, skill filter) to all generated tool descriptors.

func (*ToolBridge) GetToolDescriptors

func (b *ToolBridge) GetToolDescriptors() []*tools.ToolDescriptor

GetToolDescriptors returns all tool descriptors accumulated via RegisterAgent calls.

func (*ToolBridge) RegisterAgent

func (b *ToolBridge) RegisterAgent(ctx context.Context) ([]*tools.ToolDescriptor, error)

RegisterAgent discovers the agent card and creates a ToolDescriptor for each skill. The descriptors are appended to the bridge's internal list (supporting multi-agent composition via GetToolDescriptors). Skills excluded by the skill filter are skipped.

Directories

Path Synopsis
Package mock provides a configurable mock A2A server for use in tests.
Package mock provides a configurable mock A2A server for use in tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL