a2a

package
v0.32.3 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package a2a is a hand-rolled codec for the Agent2Agent (A2A) protocol: an open standard for agent-to-agent communication built around a Task lifecycle, Messages composed of Parts, and Artifacts carrying task output.

This package is codec-only. It contains the canonical A2A data model, the operation parameter/response objects, the JSON-RPC 2.0 binding, the HTTP+JSON/REST binding route shapes, the Server-Sent Events streaming transport in both framings, the Agent Card discovery types, the A2A service parameters (A2A-Version / A2A-Extensions), the Nexus protocol extension, and the protocol error model with its per-binding mappings. It has no dependency on the Nexus engine or event bus so that both a serve plugin and an outbound client can reuse it.

Targeted spec version

This implementation targets A2A specification 1.0.x. The wire facts were taken from https://raw.githubusercontent.com/a2aproject/A2A/main/docs/specification.md and the canonical Protocol Buffer definition at https://raw.githubusercontent.com/a2aproject/A2A/main/specification/a2a.proto, both fetched 2026-08-18.

1.0 is a breaking revision of 0.3.x. Two differences bite hardest and are implemented here deliberately:

  • JSON-RPC method names are PascalCase operation names ("SendMessage", "GetTask"), not the 0.3-era dotted forms ("message/send", "tasks/get"). See specification section 9.4.
  • Part is flattened. There are no separate TextPart/FilePart/DataPart types; a Part is a single struct with a content oneof (text, raw, url, data) plus mediaType, filename and metadata that apply to every kind.

JSON conventions

All JSON field names are camelCase (specification section 5.5), even though the proto uses snake_case. Enums serialize as their SCREAMING_SNAKE_CASE proto names ("TASK_STATE_WORKING", "ROLE_USER") per ProtoJSON. Timestamps serialize as ISO 8601 UTC strings with millisecond precision (section 5.6.1); see Timestamp.

Streaming

SSEWriter and SSEReader implement the streaming transport for SendStreamingMessage and SubscribeToTask. Both enforce the stream contract of specification section 11.7 rather than merely serializing frames: a stream opens with a Task or a Message, carries only update events afterwards, keeps task and context identity stable across frames, follows the task state transition graph, and closes the moment a frame reports a terminal state. Terminal means COMPLETED, FAILED, CANCELED and REJECTED alike — a failed run closes its stream exactly as a successful one does.

Status and artifact updates may interleave after the opening frame. A stricter reading of the section 11.7 ordering ("all status updates, then all artifact updates") is not implementable, since the COMPLETED status frame that closes a stream necessarily follows the artifact frames carrying the output it completes.

Streams parked on INPUT_REQUIRED

TASK_STATE_INPUT_REQUIRED (and TASK_STATE_AUTH_REQUIRED with it) is an interruption, not a termination: the task is still live and the client is expected to resume it by sending a new message carrying the same taskId and contextId. The specification's close rule keys off terminal states, so it does not fire here, and this package deliberately does not invent an extra close.

The chosen behavior, and the reasoning for it:

  • The INPUT_REQUIRED status frame is written and flushed like any other, carrying the agent's question in Status.Message, and the stream stays open. Closing on a non-terminal state would be indistinguishable, client-side, from a dropped connection: the client cannot tell whether to answer the question, retry, or re-subscribe. Keeping the stream open keeps that signal unambiguous, and lets the answer's effects (the WORKING transition and everything after) arrive on the connection the client is already reading.
  • Because a parked stream would otherwise leave a client waiting forever, SSEWriter.Interrupted reports the parked condition explicitly. It exists so a serving layer must make a policy decision rather than inherit an indefinite wait by accident: apply an input deadline, and on expiry drive the task to a real terminal state (FAILED or CANCELED) and let the ordinary terminal-close rule end the stream. Ending a wait through a state transition keeps the task store, any concurrent subscriber, and the client's own view in agreement; a silent hangup would not.
  • SSEWriter.WriteComment and SSEWriter.Ping emit SSE comment records so a parked stream can be kept alive through proxies with idle read timeouts without emitting a protocol frame that says nothing happened.

Discovery

AgentCard and its subordinate types model the manifest served at AgentCardPath. Use EncodeAgentCard to serve it and ValidateAgentCard to check it. AgentCapabilities serializes its three booleans unconditionally, so a card always states a capability rather than leaving a client to infer it from an absent key; its zero value is the honest card for an agent supporting none of them.

Specification section 4.4 defers the card's field list entirely to a2a.proto, which is the authority here. Three of its choices are easy to get wrong by analogy with other manifest formats, so they are called out: the card is FLAT (no nested identity object), there is NO card-level protocol version (the A2A version is declared per AgentInterface), and the transport is an OPEN-FORM STRING — "JSONRPC", "GRPC", "HTTP+JSON" — not a ProtoJSON enum. See ProtocolBinding.

Version negotiation policy

ParseServiceParams implements section 3.6.2 literally: an absent A2A-Version means 0.3, which this codec does not speak and therefore rejects. Because that reading refuses well-behaved 1.0 clients whose HTTP layer merely omitted a header, ParseServiceParamsAssuming lets a serving host choose the fallback explicitly. The choice belongs to the host, which knows whether it ever served 0.3; it is not a codec-level default to be inherited by accident.

The Nexus extension

NexusExtensionURI names the one extension this codebase defines. It carries the Nexus telemetry that has no canonical A2A representation — thinking steps, tool calls and results, subagent progress, token usage — as the typed NexusEvent union. See extension.go for the two carriers and the rationale.

Scope

The push-notification operations are out of scope: the TaskPushNotificationConfig data type exists because SendMessageConfiguration references it, but no push operation is implemented, and DecodeCall reports the push-config methods as unsupported. Agent cards built by NewAgentCard therefore declare both capabilities.pushNotifications and capabilities.extendedAgentCard as false. The gRPC binding is likewise not implemented; only the two HTTP bindings are.

No third-party A2A SDK is used; this is pure standard-library Go.

Index

Constants

View Source
const (
	CodeJSONParse      = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternal       = -32603
)

Standard JSON-RPC 2.0 error codes (specification section 9.5).

View Source
const (
	CodeTaskNotFound                 = -32001
	CodeTaskNotCancelable            = -32002
	CodePushNotificationNotSupported = -32003
	CodeUnsupportedOperation         = -32004
	CodeContentTypeNotSupported      = -32005
	CodeInvalidAgentResponse         = -32006
	CodeExtendedAgentCardNotConfig   = -32007
	CodeExtensionSupportRequired     = -32008
	CodeVersionNotSupported          = -32009
)

A2A-specific JSON-RPC error codes (specification section 5.4). A2A reserves the -32001..-32099 range.

View Source
const (
	TypeErrorInfo  = "type.googleapis.com/google.rpc.ErrorInfo"
	TypeBadRequest = "type.googleapis.com/google.rpc.BadRequest"
)

Well-known ProtoJSON Any type URLs used in error detail objects.

View Source
const (
	MethodSendMessage          = "SendMessage"
	MethodSendStreamingMessage = "SendStreamingMessage"
	MethodGetTask              = "GetTask"
	MethodListTasks            = "ListTasks"
	MethodCancelTask           = "CancelTask"
	MethodSubscribeToTask      = "SubscribeToTask"

	MethodCreateTaskPushNotificationConfig = "CreateTaskPushNotificationConfig"
	MethodGetTaskPushNotificationConfig    = "GetTaskPushNotificationConfig"
	MethodListTaskPushNotificationConfigs  = "ListTaskPushNotificationConfigs"
	MethodDeleteTaskPushNotificationConfig = "DeleteTaskPushNotificationConfig"

	MethodGetExtendedAgentCard = "GetExtendedAgentCard"
)

A2A operation names. In A2A 1.0 the JSON-RPC method string is the PascalCase operation name, matching the gRPC method (specification sections 5.3 and 9.4). This is a breaking change from the 0.3-era dotted forms ("message/send", "tasks/get"), which this codec deliberately does not accept.

View Source
const (
	// ContentTypeJSON is the media type A2A prefers for REST requests and
	// responses.
	ContentTypeJSON = "application/a2a+json"
	// ContentTypeSSE is the media type of a streaming response body.
	ContentTypeSSE = "text/event-stream"
)

Content types for the HTTP+JSON/REST binding (specification section 11.1).

View Source
const (
	PathSendMessage   = "/message:send"
	PathStreamMessage = "/message:stream"
	PathGetTask       = "/tasks/{id}"
	PathListTasks     = "/tasks"
	PathCancelTask    = "/tasks/{id}:cancel"
	PathSubscribeTask = "/tasks/{id}:subscribe"

	PathCreatePushNotificationConfig = "/tasks/{id}/pushNotificationConfigs"
	PathGetPushNotificationConfig    = "/tasks/{id}/pushNotificationConfigs/{configId}"
	PathListPushNotificationConfigs  = "/tasks/{id}/pushNotificationConfigs"
	PathDeletePushNotificationConfig = "/tasks/{id}/pushNotificationConfigs/{configId}"

	PathExtendedAgentCard = "/extendedAgentCard"
)

REST path templates (specification section 11.3). The {id} placeholder is the task id; note that the cancel and subscribe operations are custom verbs appended to the resource path with a colon, so a task id itself may not contain a colon.

View Source
const (
	// HeaderVersion carries the Major.Minor protocol version the client speaks.
	HeaderVersion = "A2A-Version"
	// HeaderExtensions carries a comma-separated list of extension URIs the
	// client wants to use.
	HeaderExtensions = "A2A-Extensions"
)

A2A service parameter names (specification section 3.2.6). Over HTTP bindings these travel as request headers; header names are case-insensitive, and http.Header canonicalization handles that for us.

View Source
const (
	// DefaultListPageSize is the page size a server applies when the client
	// leaves PageSize unset.
	DefaultListPageSize = 50
	// MinListPageSize is the smallest page size a client may request.
	MinListPageSize = 1
	// MaxListPageSize is the largest page size a client may request.
	MaxListPageSize = 100
)

Pagination bounds for ListTasks, from specification section 3.2 / ListTasksRequest.page_size.

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

AgentCardPath is the well-known location of an agent's public Agent Card (specification section 8.2). The card types themselves are defined elsewhere.

View Source
const ContentTypeAgentCard = "application/json"

ContentTypeAgentCard is the media type of a served Agent Card.

View Source
const DefaultVersion = "0.3"

DefaultVersion is the version an agent must assume when the A2A-Version service parameter is absent or empty. The specification pins this to 0.3 for backwards compatibility with pre-1.0 clients (section 3.6.2).

View Source
const ErrorDomain = "a2a-protocol.org"

ErrorDomain is the google.rpc.ErrorInfo domain A2A stamps on its errors.

View Source
const JSONRPCVersion = "2.0"

JSONRPCVersion is the only value the "jsonrpc" field may carry.

View Source
const NexusExtensionDescription = "Nexus agent telemetry: thinking steps, tool calls and results, " +
	"subagent progress, and token usage that have no canonical A2A representation."

NexusExtensionDescription is the human-readable summary published in the agent card.

View Source
const NexusExtensionURI = "https://github.com/frankbardon/nexus/a2a/extensions/agent-events/v1"

NexusExtensionURI uniquely identifies the Nexus A2A extension. It is the value clients send in the A2A-Extensions service parameter to opt in, and the key under which extension payloads travel in metadata maps.

View Source
const NexusExtensionVersion = "1.0"

NexusExtensionVersion is the extension's own version, independent of the A2A protocol version.

It is NOT published as a separate card field: AgentExtension has no version key, because specification section 4.6.3 requires the version to live inside the URI and requires a NEW URI for any breaking change. The "/v1" suffix on NexusExtensionURI is the wire-visible version; this constant exists so the two cannot drift silently and so the value is available to code that reports it (logs, the params block below).

View Source
const ProtocolVersion = "1.0"

ProtocolVersion is the Major.Minor A2A protocol version this codec speaks. It is the value sent and expected in the A2A-Version service parameter. Patch versions are never used on the wire (specification section 3.6).

View Source
const SpecVersion = "1.0.x (a2aproject/A2A specification.md + a2a.proto, 2026-08-18)"

SpecVersion identifies the A2A specification revision this codec was written against, including the fetch date of the source documents.

Variables

View Source
var (
	// ErrStreamClosed is returned by SSEWriter.Write once the stream has
	// terminated, whether because the task reached a terminal state, because an
	// error frame was written, or because Close was called.
	ErrStreamClosed = errors.New("a2a: stream is closed")
	// ErrStreamOrder is returned when a frame would violate the ordering rules
	// of specification section 11.7. It is wrapped with the offending detail.
	ErrStreamOrder = errors.New("a2a: stream frame out of order")
)

Stream sentinel errors. These report misuse or termination of the local stream object; protocol-shaped failures are reported as *Error instead.

Functions

func BuildPath

func BuildPath(template string, vars map[string]string) (string, error)

BuildPath renders a route template with the supplied placeholder values, URL-escaping each one.

func CanTransition

func CanTransition(from, to TaskState) bool

CanTransition reports whether a task may move from state from to state to.

func DecodeCall

func DecodeCall(data []byte) (*Call, *Error)

DecodeCall parses a JSON-RPC request and decodes its parameters into the typed struct for the operation. Parameters are validated for required fields.

The error returned distinguishes the failure modes the specification calls out: malformed JSON is a JSONParseError (-32700), a bad envelope is an InvalidRequestError (-32600), an unrecognized method is a MethodNotFoundError (-32601), a method the spec defines but this codec does not implement is PushNotificationNotSupportedError (-32003) or UnsupportedOperationError (-32004) per section 3.3.4, and bad parameters are an InvalidParamsError (-32602).

func DecodeCancelTaskRequest

func DecodeCancelTaskRequest(taskID string, body []byte) (*CancelTaskRequest, *Error)

DecodeCancelTaskRequest parses the REST body of POST /tasks/{id}:cancel. The body is optional; an empty body yields a request carrying only the path id.

func DecodeRequest

func DecodeRequest(data []byte) (*Request, *Error)

DecodeRequest parses a JSON-RPC request envelope without touching params. It validates the JSON-RPC version and the presence of a method, and returns the envelope even on validation failure so the caller can echo the id.

func DecodeSendMessageRequest

func DecodeSendMessageRequest(data []byte) (*SendMessageRequest, *Error)

DecodeSendMessageRequest parses a SendMessageRequest, the REST body of POST /message:send and POST /message:stream.

func DecodeSubscribeToTaskRequest

func DecodeSubscribeToTaskRequest(taskID string, body []byte) (*SubscribeToTaskRequest, *Error)

DecodeSubscribeToTaskRequest parses the REST body of POST /tasks/{id}:subscribe. The body is optional.

func Encode

func Encode(v any) ([]byte, error)

Encode serializes any A2A wire object to JSON. It exists so that call sites get uniform "a2a: ..." error wrapping rather than bare encoding/json errors.

func EncodeAgentCard

func EncodeAgentCard(c *AgentCard) ([]byte, error)

EncodeAgentCard serializes a card for serving at AgentCardPath, using indented JSON since cards are read by humans as often as by clients.

It normalizes the required repeated fields from nil to an empty array first. Section 8.4.1 requires a REQUIRED field to be present even at its default value, and a nil Go slice would marshal to null — which is a different JSON value from [], and would change the canonical form a signature is computed over. The card argument is not mutated.

func HistoryLength

func HistoryLength(n int) *int

HistoryLength returns a pointer to a history length, for the optional history-length fields. Zero means "omit history entirely", which is distinct from leaving the field unset.

func IsStreamingMethod

func IsStreamingMethod(method string) bool

IsStreamingMethod reports whether an operation responds with an SSE stream rather than a single JSON-RPC response.

func IsVersionSupported

func IsVersionSupported(version string) bool

IsVersionSupported reports whether a normalized Major.Minor version is one this codec speaks.

func Methods

func Methods() []string

Methods returns the operation names this codec decodes, in a stable order.

func NexusEventMetadata

func NexusEventMetadata(e NexusEvent) (map[string]any, error)

NexusEventMetadata builds the metadata map entry carrying the event, keyed by the extension URI. Merge it into a status or artifact update's metadata.

func NormalizeVersion

func NormalizeVersion(raw string) (string, error)

NormalizeVersion parses a protocol version and returns its Major.Minor form. A patch component is accepted and dropped: the specification says patch versions must not be considered when negotiating (section 3.6).

func PageSize

func PageSize(n int) *int

PageSize returns a pointer to a page size, for the optional ListTasksRequest field.

func ParseExtensions

func ParseExtensions(values ...string) []string

ParseExtensions splits one or more A2A-Extensions header values into a deduplicated, order-preserving list of extension URIs. Empty entries are dropped.

func ParseGetTaskQuery

func ParseGetTaskQuery(taskID string, q url.Values) (*GetTaskRequest, *Error)

ParseGetTaskQuery builds a GetTaskRequest from a path task id and the request query parameters.

func ParseListTasksQuery

func ParseListTasksQuery(q url.Values) (*ListTasksRequest, *Error)

ParseListTasksQuery builds a ListTasksRequest from request query parameters.

func ParseServiceParams

func ParseServiceParams(h http.Header, q url.Values) (ServiceParams, *Error)

ParseServiceParams reads the A2A service parameters from request headers, falling back to query parameters for the version, which the specification permits clients to supply either way (section 3.6.1). Pass a nil query when there is none.

It returns a VersionNotSupportedError when the requested version is not one this codec speaks, and an InvalidRequestError when the version is malformed.

func ParseServiceParamsAssuming

func ParseServiceParamsAssuming(h http.Header, q url.Values, assumeVersion string) (ServiceParams, *Error)

ParseServiceParamsAssuming is ParseServiceParams with the absent-parameter fallback supplied by the caller instead of pinned to DefaultVersion.

It exists because "what does an absent A2A-Version mean" is a DEPLOYMENT policy, not a codec fact, and the codec should not force one on every host. Section 3.6.2 says agents MUST read an empty value as 0.3, which this codec then rejects as unsupported — spec-faithful, and correct for an agent that ever served 0.3. An agent that has only ever served 1.0 has no such client to protect and may prefer to read an absent parameter as 1.0 rather than refuse a caller whose HTTP layer simply omitted a header. Both readings are reachable through this function; neither is inherited silently.

An empty assumeVersion falls back to DefaultVersion, so the strict reading is what a caller that does not think about it gets.

func ParseStreamFrame

func ParseStreamFrame(payload []byte) (*StreamResponse, *Error)

ParseStreamFrame decodes one SSE data payload into a StreamResponse, accepting either the bare REST framing or the JSON-RPC Response envelope. A server-sent error, in either framing, is returned as the *Error it encodes.

func SupportedVersions

func SupportedVersions() []string

SupportedVersions returns the Major.Minor versions this codec accepts. The returned slice is a fresh copy.

func TaskPath

func TaskPath(template, taskID string) (string, error)

TaskPath renders a task-scoped route template for a specific task id.

func ValidateTransition

func ValidateTransition(from, to TaskState) error

ValidateTransition checks a task state transition and returns a protocol error describing why it is illegal, or nil when it is legal.

The rules enforced are:

  • Both states must be recognized enum values.
  • The destination may not be TASK_STATE_UNSPECIFIED; a live task always has a concrete state.
  • No transition may leave a terminal state, including back to itself.
  • Active states may re-enter themselves, since an agent may re-emit a state carrying a new status message.

func ValidateTransitionSequence

func ValidateTransitionSequence(states []TaskState) error

ValidateTransitionSequence walks a full sequence of states, starting from TaskStateUnspecified, and returns the first illegal transition it finds. It is a convenience for tests and conformance checks.

func WriteSSEHeaders

func WriteSSEHeaders(h http.Header)

WriteSSEHeaders sets the response headers for an A2A SSE stream. Buffering is disabled explicitly because intermediaries otherwise coalesce records and defeat incremental delivery.

Types

type APIKeyLocation

type APIKeyLocation string

APIKeyLocation names where an API key credential travels.

const (
	APIKeyInQuery  APIKeyLocation = "query"
	APIKeyInHeader APIKeyLocation = "header"
	APIKeyInCookie APIKeyLocation = "cookie"
)

API key locations.

func (APIKeyLocation) Valid

func (l APIKeyLocation) Valid() bool

Valid reports whether the location is one of the three defined placements.

type APIKeySecurityScheme

type APIKeySecurityScheme struct {
	// Description is a human-readable note about the scheme.
	Description string `json:"description,omitempty"`
	// Location is where the credential travels. Required.
	Location APIKeyLocation `json:"location"`
	// Name is the header, parameter or cookie name. Required.
	Name string `json:"name"`
}

APIKeySecurityScheme carries a credential in a named header, query parameter or cookie.

The placement field is named "location", not the OpenAPI-familiar "in": the proto calls it location and section 5.5 derives the JSON names from the proto.

type AgentCapabilities

type AgentCapabilities struct {
	// Streaming reports support for SendStreamingMessage and SubscribeToTask.
	Streaming bool `json:"streaming"`
	// PushNotifications reports support for the push-notification config
	// operations and webhook delivery.
	PushNotifications bool `json:"pushNotifications"`
	// ExtendedAgentCard reports support for GetExtendedAgentCard.
	ExtendedAgentCard bool `json:"extendedAgentCard"`
	// Extensions declares the protocol extensions the agent speaks.
	Extensions []AgentExtension `json:"extensions,omitempty"`
}

AgentCapabilities declares the optional protocol features an agent supports.

The three booleans are serialized unconditionally rather than with omitempty. The proto marks them `optional bool`, and section 8.4.1's canonicalization rules say an optional field that was explicitly set must be present in the JSON even when its value equals the default — which is exactly the position this codec takes: a discovery document should state a capability as false rather than leave a client to infer it from an absent key. The zero value is therefore the correct, honest card for an agent supporting none of them.

type AgentCard

type AgentCard struct {
	// Name is the human-readable agent name. Required.
	Name string `json:"name"`
	// Description is a human-readable summary of what the agent does. Required
	// by the proto, so it is serialized even when empty.
	Description string `json:"description"`
	// SupportedInterfaces are the protocol endpoints the agent exposes, in
	// preference order: the first entry is the preferred one (section 8.3.1).
	// Required, and must be non-empty.
	SupportedInterfaces []AgentInterface `json:"supportedInterfaces"`
	// Provider identifies the organization operating the agent.
	Provider *AgentProvider `json:"provider,omitempty"`
	// Version is the agent's own version, independent of any protocol version.
	// Required.
	Version string `json:"version"`
	// DocumentationURL points at human-readable documentation.
	DocumentationURL string `json:"documentationUrl,omitempty"`
	// Capabilities are the optional protocol features the agent supports.
	// Required, and always serialized in full so a client never has to infer a
	// capability from an absent field.
	Capabilities AgentCapabilities `json:"capabilities"`
	// SecuritySchemes declares, by name, every authentication scheme the agent
	// accepts. Names are referenced from SecurityRequirements and from
	// AgentSkill.SecurityRequirements.
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
	// SecurityRequirements lists the scheme requirement sets that apply
	// agent-wide. Each entry is one alternative: satisfying any entry suffices,
	// and within an entry every named scheme must be satisfied.
	SecurityRequirements []SecurityRequirement `json:"securityRequirements,omitempty"`
	// DefaultInputModes are the media types the agent accepts in message parts
	// when a skill does not narrow them. Required.
	DefaultInputModes []string `json:"defaultInputModes"`
	// DefaultOutputModes are the media types the agent produces when a skill
	// does not narrow them. Required.
	DefaultOutputModes []string `json:"defaultOutputModes"`
	// Skills describe what the agent can do. Required, and must be non-empty.
	Skills []AgentSkill `json:"skills"`
	// Signatures carry JWS detached signatures over the card, for clients that
	// verify card provenance.
	Signatures []AgentCardSignature `json:"signatures,omitempty"`
	// IconURL points at an icon representing the agent.
	IconURL string `json:"iconUrl,omitempty"`
}

AgentCard is the agent's public manifest, served at AgentCardPath.

Field order follows a2a.proto field numbers so a reader can diff the two side by side.

func DecodeAgentCard

func DecodeAgentCard(data []byte) (*AgentCard, error)

DecodeAgentCard parses an Agent Card.

func NewAgentCard

func NewAgentCard(name, description, version string) AgentCard

NewAgentCard builds a card with the capability booleans explicitly at their conservative defaults: streaming on, push notifications and extended card off. The three required identity fields are taken as arguments because a card without them cannot be served at all.

func (AgentCard) DeclaresExtension

func (c AgentCard) DeclaresExtension(uri string) bool

DeclaresExtension reports whether the card declares the given extension URI.

func (AgentCard) Extension

func (c AgentCard) Extension(uri string) (AgentExtension, bool)

Extension returns the declared extension with the given URI.

func (AgentCard) InterfaceFor

func (c AgentCard) InterfaceFor(binding ProtocolBinding) (string, bool)

InterfaceFor returns the first endpoint URL the agent exposes for a binding. Interfaces are ordered by preference, so "first" is "preferred".

func (AgentCard) RequiredExtensions

func (c AgentCard) RequiredExtensions() []string

RequiredExtensions returns the URIs of every extension a client must support to interact with this agent.

func (AgentCard) Skill

func (c AgentCard) Skill(id string) (AgentSkill, bool)

Skill returns the declared skill with the given id.

func (AgentCard) WithExtension

func (c AgentCard) WithExtension(e AgentExtension) AgentCard

WithExtension appends an extension declaration and returns the card, for chaining.

func (AgentCard) WithInterface

func (c AgentCard) WithInterface(binding ProtocolBinding, url string) AgentCard

WithInterface appends a protocol endpoint speaking this codec's protocol version and returns the card, for chaining.

func (AgentCard) WithSecurityRequirement

func (c AgentCard) WithSecurityRequirement(name string, scopes ...string) AgentCard

WithSecurityRequirement appends an agent-wide security requirement naming one scheme and its scopes, and returns the card for chaining.

func (AgentCard) WithSecurityScheme

func (c AgentCard) WithSecurityScheme(name string, scheme SecurityScheme) AgentCard

WithSecurityScheme registers a named security scheme and returns the card, for chaining.

func (AgentCard) WithSkill

func (c AgentCard) WithSkill(s AgentSkill) AgentCard

WithSkill appends a skill and returns the card, for chaining.

type AgentCardSignature

type AgentCardSignature struct {
	// Protected is the base64url-encoded JWS protected header. Required.
	Protected string `json:"protected"`
	// Signature is the base64url-encoded signature. Required.
	Signature string `json:"signature"`
	// Header is the unprotected JWS header.
	Header map[string]any `json:"header,omitempty"`
}

AgentCardSignature is a JWS detached signature over the card.

type AgentExtension

type AgentExtension struct {
	// URI uniquely identifies the extension, version included. Required.
	URI string `json:"uri"`
	// Description is a human-readable summary of how this agent uses the
	// extension.
	Description string `json:"description,omitempty"`
	// Required reports whether a client must support the extension to interact
	// with this agent at all. Optional extensions are the norm; a required one
	// lets an agent refuse clients that would misread its output.
	Required bool `json:"required,omitempty"`
	// Params is extension-defined configuration data, whose shape the extension
	// itself specifies (google.protobuf.Struct in the proto).
	Params map[string]any `json:"params,omitempty"`
}

AgentExtension declares one protocol extension in an agent card (specification section 4.6.1). Clients opt in per request via the A2A-Extensions service parameter.

There is deliberately no version field: section 4.6.3 requires extensions to carry their version inside the URI and requires a NEW URI for any breaking change, so a separate version field would be a second, disagreeable source of truth. See NexusExtensionURI for how this codebase applies that rule.

func NexusExtension

func NexusExtension() AgentExtension

NexusExtension returns the agent card declaration for the Nexus extension. It is never Required: everything it carries is supplementary, so a client that ignores it still receives a complete canonical stream.

The declaration's params publish the event kinds and the two carriers, so a client can tell from the card alone what to expect and where to look for it without fetching an out-of-band schema.

type AgentInterface

type AgentInterface struct {
	// URL is the endpoint address. For HTTP bindings it is the base URL that
	// operation paths are appended to (REST) or POSTed to directly (JSON-RPC);
	// for gRPC it is "hostname:port". Required.
	URL string `json:"url"`
	// ProtocolBinding is the binding spoken at this URL. Required.
	ProtocolBinding ProtocolBinding `json:"protocolBinding"`
	// Tenant is an opaque routing identifier for deployments serving several
	// agents or tenants behind one A2A endpoint. When set, a client MUST echo
	// it in the tenant field of every request to this interface (section
	// 8.3.2). The protocol does not define its format or semantics.
	Tenant string `json:"tenant,omitempty"`
	// ProtocolVersion is the Major.Minor A2A version this interface exposes.
	// Required.
	ProtocolVersion string `json:"protocolVersion"`
}

AgentInterface binds one protocol binding, at one A2A protocol version, to one endpoint URL. An agent exposing both the JSON-RPC and REST bindings declares two interfaces; an agent serving 0.3 and 1.0 declares one per version.

type AgentProvider

type AgentProvider struct {
	// URL is the provider's website or relevant documentation. Required when a
	// provider is given.
	URL string `json:"url"`
	// Organization is the provider's name. Required when a provider is given.
	Organization string `json:"organization"`
}

AgentProvider identifies the organization behind an agent.

type AgentSkill

type AgentSkill struct {
	// ID uniquely identifies the skill within the card. Required.
	ID string `json:"id"`
	// Name is the human-readable skill name. Required.
	Name string `json:"name"`
	// Description explains what the skill does. Required.
	Description string `json:"description"`
	// Tags are keywords describing the skill's capabilities. Required by the
	// proto, so the key is always present.
	Tags []string `json:"tags"`
	// Examples are sample prompts that exercise the skill.
	Examples []string `json:"examples,omitempty"`
	// InputModes narrows the card's default input media types for this skill.
	InputModes []string `json:"inputModes,omitempty"`
	// OutputModes narrows the card's default output media types for this skill.
	OutputModes []string `json:"outputModes,omitempty"`
	// SecurityRequirements narrows the card's agent-wide security requirements
	// for this skill, for skills needing stronger credentials than the agent as
	// a whole.
	SecurityRequirements []SecurityRequirement `json:"securityRequirements,omitempty"`
}

AgentSkill describes one capability the agent advertises.

type Artifact

type Artifact struct {
	// ArtifactID is unique within the owning task. Required.
	ArtifactID string `json:"artifactId"`
	// Name is a human-readable label.
	Name string `json:"name,omitempty"`
	// Description is a human-readable description.
	Description string `json:"description,omitempty"`
	// Parts is the artifact content. Required, and must be non-empty.
	Parts []Part `json:"parts"`
	// Metadata is free-form custom data attached to the artifact.
	Metadata map[string]any `json:"metadata,omitempty"`
	// Extensions lists the URIs of extensions contributing to this artifact.
	Extensions []string `json:"extensions,omitempty"`
}

Artifact is a set of Parts produced as task output. Outputs travel as artifacts, not as messages (specification section 3.7).

func DecodeArtifact

func DecodeArtifact(data []byte) (*Artifact, error)

DecodeArtifact parses an Artifact.

func NewArtifact

func NewArtifact(artifactID string, parts ...Part) Artifact

NewArtifact builds an Artifact with the required artifactId and parts.

func NewTextArtifact

func NewTextArtifact(artifactID, name, text string) Artifact

NewTextArtifact builds a named Artifact holding a single text part.

type AuthenticationInfo

type AuthenticationInfo struct {
	// Scheme is an HTTP authentication scheme name (Bearer, Basic, ...). Required.
	Scheme string `json:"scheme"`
	// Credentials is the scheme-dependent credential material.
	Credentials string `json:"credentials,omitempty"`
}

AuthenticationInfo describes the credentials a server uses when POSTing to a push notification webhook.

type AuthorizationCodeOAuthFlow

type AuthorizationCodeOAuthFlow struct {
	// AuthorizationURL is the authorization endpoint. Required.
	AuthorizationURL string `json:"authorizationUrl"`
	// TokenURL is the token endpoint. Required.
	TokenURL string `json:"tokenUrl"`
	// RefreshURL is the refresh endpoint, when it differs from TokenURL.
	RefreshURL string `json:"refreshUrl,omitempty"`
	// Scopes maps scope name to human-readable description. Required.
	Scopes map[string]string `json:"scopes,omitempty"`
	// PKCERequired reports whether RFC 7636 PKCE is required for this flow. It
	// should always be set for public clients and is recommended for all.
	PKCERequired bool `json:"pkceRequired,omitempty"`
}

AuthorizationCodeOAuthFlow is the authorization code grant.

type Call

type Call struct {
	// Request is the raw envelope, retained so callers can echo the id.
	Request *Request
	// Method is the A2A operation name.
	Method string
	// Params is the typed parameter object: one of *SendMessageRequest,
	// *GetTaskRequest, *ListTasksRequest, *CancelTaskRequest or
	// *SubscribeToTaskRequest. SendMessage and SendStreamingMessage share
	// *SendMessageRequest.
	Params any
}

Call is a decoded JSON-RPC request with its parameters decoded into the typed struct for the operation.

func (*Call) ID

func (c *Call) ID() json.RawMessage

ID returns the raw JSON-RPC id, for echoing into the response.

func (*Call) Streaming

func (c *Call) Streaming() bool

Streaming reports whether the call's response is an SSE stream.

type CancelTaskRequest

type CancelTaskRequest struct {
	// Tenant is an opaque routing identifier.
	Tenant string `json:"tenant,omitempty"`
	// ID is the task to cancel. Required.
	ID string `json:"id"`
	// Metadata is free-form custom data attached to the call.
	Metadata map[string]any `json:"metadata,omitempty"`
}

CancelTaskRequest is the parameter object for CancelTask.

type ClientCredentialsOAuthFlow

type ClientCredentialsOAuthFlow struct {
	// TokenURL is the token endpoint. Required.
	TokenURL string `json:"tokenUrl"`
	// RefreshURL is the refresh endpoint, when it differs from TokenURL.
	RefreshURL string `json:"refreshUrl,omitempty"`
	// Scopes maps scope name to human-readable description. Required.
	Scopes map[string]string `json:"scopes,omitempty"`
}

ClientCredentialsOAuthFlow is the machine-to-machine grant.

type DeviceCodeOAuthFlow

type DeviceCodeOAuthFlow struct {
	// DeviceAuthorizationURL is the device authorization endpoint. Required.
	DeviceAuthorizationURL string `json:"deviceAuthorizationUrl"`
	// TokenURL is the token endpoint. Required.
	TokenURL string `json:"tokenUrl"`
	// RefreshURL is the refresh endpoint, when it differs from TokenURL.
	RefreshURL string `json:"refreshUrl,omitempty"`
	// Scopes maps scope name to human-readable description. Required.
	Scopes map[string]string `json:"scopes,omitempty"`
}

DeviceCodeOAuthFlow is the device authorization grant, for input-constrained clients.

type Error

type Error struct {
	// Type is the A2A error taxonomy entry.
	Type ErrorType
	// Message is the human-readable description.
	Message string
	// Details are structured detail objects. The ErrorInfo detail for
	// A2A-specific errors is added automatically by the binding renderers, so
	// callers only add supplementary details here.
	Details []ErrorDetail
	// Metadata is attached to the auto-generated ErrorInfo detail, carrying
	// context such as the offending task ID.
	Metadata map[string]string
}

Error is a protocol-level A2A error. It carries everything needed to render itself into any binding: the JSON-RPC code, the HTTP status, the gRPC status name, and the structured detail objects.

Error implements the error interface, so protocol failures flow through ordinary Go error handling and can be recovered with errors.As.

func ErrInvalidParams

func ErrInvalidParams(violations ...FieldViolation) *Error

ErrInvalidParams builds an InvalidParamsError carrying field violations.

func ErrInvalidRequest

func ErrInvalidRequest(field, description string) *Error

ErrInvalidRequest builds an InvalidRequestError naming the offending envelope field.

func ErrTaskNotCancelable

func ErrTaskNotCancelable(taskID string, state TaskState) *Error

ErrTaskNotCancelable builds a TaskNotCancelableError for a task already in a terminal state.

func ErrTaskNotFound

func ErrTaskNotFound(taskID string) *Error

ErrTaskNotFound builds a TaskNotFoundError naming the task.

func ErrUnsupportedOperation

func ErrUnsupportedOperation(operation string) *Error

ErrUnsupportedOperation builds an UnsupportedOperationError naming the operation.

func Errorf

func Errorf(t ErrorType, format string, args ...any) *Error

Errorf builds an A2A error with a formatted message.

func NewError

func NewError(t ErrorType, message string) *Error

NewError builds an A2A error of the given type. An empty message falls back to the spec's standard message for that type.

func ValidateAgentCard

func ValidateAgentCard(c *AgentCard) *Error

ValidateAgentCard checks a card's required fields and internal consistency: declared interfaces and skills are non-empty and well-formed, every security scheme sets exactly one arm, and every security requirement names a declared scheme.

func ValidateArtifact

func ValidateArtifact(a *Artifact, field string) *Error

ValidateArtifact checks an Artifact's required fields: artifactId and at least one well-formed part.

func ValidateArtifactUpdate

func ValidateArtifactUpdate(e *TaskArtifactUpdateEvent) *Error

ValidateArtifactUpdate checks a TaskArtifactUpdateEvent's required fields.

func ValidateListTasksRequest

func ValidateListTasksRequest(r *ListTasksRequest) *Error

ValidateListTasksRequest checks the parameter object for ListTasks, including the specification's page-size bounds and status filter.

func ValidateMessage

func ValidateMessage(m *Message, field string) *Error

ValidateMessage checks a Message's required fields: messageId, a valid role, and at least one well-formed part.

func ValidatePart

func ValidatePart(p Part, field string) *Error

ValidatePart checks a Part: exactly one content arm must be set.

func ValidateParts

func ValidateParts(parts []Part, field string) *Error

ValidateParts checks a required, non-empty slice of parts.

func ValidateSecurityScheme

func ValidateSecurityScheme(s SecurityScheme, field string) *Error

ValidateSecurityScheme checks that a scheme sets exactly one arm and that the arm's required fields are present.

func ValidateSendMessageRequest

func ValidateSendMessageRequest(r *SendMessageRequest) *Error

ValidateSendMessageRequest checks the parameter object for SendMessage and SendStreamingMessage.

func ValidateSendMessageResponse

func ValidateSendMessageResponse(r *SendMessageResponse) *Error

ValidateSendMessageResponse checks that exactly one payload arm is set and that it is well-formed.

func ValidateStatusUpdate

func ValidateStatusUpdate(e *TaskStatusUpdateEvent) *Error

ValidateStatusUpdate checks a TaskStatusUpdateEvent's required fields.

func ValidateStreamResponse

func ValidateStreamResponse(s *StreamResponse) *Error

ValidateStreamResponse checks that exactly one payload arm is set and that it is well-formed.

func ValidateTask

func ValidateTask(t *Task) *Error

ValidateTask checks a Task's required fields: id, a valid status, and well-formed artifacts and history.

func ValidateTaskStatus

func ValidateTaskStatus(s TaskStatus, field string) *Error

ValidateTaskStatus checks that a status carries a valid, specified state and that any attached message is well-formed.

func (*Error) Code

func (e *Error) Code() int

Code returns the JSON-RPC error code for this error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) GRPCStatus

func (e *Error) GRPCStatus() string

GRPCStatus returns the canonical gRPC status name for this error, which is also the value of the REST error body's "status" field.

func (*Error) HTTPStatus

func (e *Error) HTTPStatus() int

HTTPStatus returns the HTTP status code for this error.

func (*Error) RESTError

func (e *Error) RESTError() (int, RESTError)

RESTError renders the A2A error as a REST error body plus its HTTP status.

func (*Error) RPCError

func (e *Error) RPCError() *RPCError

RPCError renders the A2A error as a JSON-RPC error object, including the auto-generated ErrorInfo detail for A2A-specific error types.

func (*Error) Reason

func (e *Error) Reason() string

Reason returns the google.rpc.ErrorInfo reason for this error, or the empty string for transport-level errors, which carry no ErrorInfo.

func (*Error) WithDetail

func (e *Error) WithDetail(d ErrorDetail) *Error

WithDetail appends a structured detail object and returns the error for chaining.

func (*Error) WithMetadata

func (e *Error) WithMetadata(key, value string) *Error

WithMetadata attaches ErrorInfo metadata and returns the error for chaining.

type ErrorDetail

type ErrorDetail map[string]any

ErrorDetail is one entry in an error's details array. Every detail object must carry an "@type" key identifying it, using ProtoJSON Any representation (specification section 3.3.2).

func NewBadRequest

func NewBadRequest(violations ...FieldViolation) ErrorDetail

NewBadRequest builds a google.rpc.BadRequest detail object carrying field violations.

func NewErrorInfo

func NewErrorInfo(reason string, metadata map[string]string) ErrorDetail

NewErrorInfo builds a google.rpc.ErrorInfo detail object for an A2A error reason. The metadata map is optional and is omitted when empty.

type ErrorType

type ErrorType string

ErrorType is the A2A error taxonomy from specification section 3.3.2. The values are the spec's error names verbatim.

const (
	// A2A-specific errors (specification section 3.3.2).
	ErrorTypeTaskNotFound                 ErrorType = "TaskNotFoundError"
	ErrorTypeTaskNotCancelable            ErrorType = "TaskNotCancelableError"
	ErrorTypePushNotificationNotSupported ErrorType = "PushNotificationNotSupportedError"
	ErrorTypeUnsupportedOperation         ErrorType = "UnsupportedOperationError"
	ErrorTypeContentTypeNotSupported      ErrorType = "ContentTypeNotSupportedError"
	ErrorTypeInvalidAgentResponse         ErrorType = "InvalidAgentResponseError"
	ErrorTypeExtendedAgentCardNotConfig   ErrorType = "ExtendedAgentCardNotConfiguredError"
	ErrorTypeExtensionSupportRequired     ErrorType = "ExtensionSupportRequiredError"
	ErrorTypeVersionNotSupported          ErrorType = "VersionNotSupportedError"

	// Transport-level errors (specification section 9.5).
	ErrorTypeJSONParse      ErrorType = "JSONParseError"
	ErrorTypeInvalidRequest ErrorType = "InvalidRequestError"
	ErrorTypeMethodNotFound ErrorType = "MethodNotFoundError"
	ErrorTypeInvalidParams  ErrorType = "InvalidParamsError"
	ErrorTypeInternal       ErrorType = "InternalError"
)

A2A error types, plus the four JSON-RPC transport-level conditions modeled as error types so that one constructor covers every failure this codec reports.

type FieldViolation

type FieldViolation struct {
	Field       string `json:"field"`
	Description string `json:"description"`
}

FieldViolation names a request field that failed validation, along with why.

type GetTaskRequest

type GetTaskRequest struct {
	// Tenant is an opaque routing identifier.
	Tenant string `json:"tenant,omitempty"`
	// ID is the task to retrieve. Required.
	ID string `json:"id"`
	// HistoryLength caps how many recent history messages the response carries.
	HistoryLength *int `json:"historyLength,omitempty"`
}

GetTaskRequest is the parameter object for GetTask.

func (*GetTaskRequest) Query

func (r *GetTaskRequest) Query() url.Values

Query renders a GetTaskRequest's non-path parameters as query parameters.

type HTTPAuthSecurityScheme

type HTTPAuthSecurityScheme struct {
	// Description is a human-readable note about the scheme.
	Description string `json:"description,omitempty"`
	// Scheme is the HTTP auth scheme name as registered with IANA, e.g.
	// "Bearer" or "Basic". Required.
	Scheme string `json:"scheme"`
	// BearerFormat hints at the bearer token's format, e.g. "JWT".
	BearerFormat string `json:"bearerFormat,omitempty"`
}

HTTPAuthSecurityScheme is an HTTP Authorization scheme.

type ListTasksRequest

type ListTasksRequest struct {
	// Tenant is an opaque routing identifier.
	Tenant string `json:"tenant,omitempty"`
	// ContextID restricts the listing to one conversational context.
	ContextID string `json:"contextId,omitempty"`
	// Status restricts the listing to tasks in one state.
	Status TaskState `json:"status,omitempty"`
	// PageSize caps the page length. Unset means the server default of
	// DefaultListPageSize; the accepted range is 1..MaxListPageSize.
	PageSize *int `json:"pageSize,omitempty"`
	// PageToken is the cursor from a previous response's nextPageToken.
	PageToken string `json:"pageToken,omitempty"`
	// HistoryLength caps how many history messages each listed task carries.
	HistoryLength *int `json:"historyLength,omitempty"`
	// StatusTimestampAfter restricts the listing to tasks whose status changed at
	// or after this instant.
	StatusTimestampAfter *Timestamp `json:"statusTimestampAfter,omitempty"`
	// IncludeArtifacts requests artifacts in the listed tasks. Defaults to false
	// to keep payloads small.
	IncludeArtifacts *bool `json:"includeArtifacts,omitempty"`
}

ListTasksRequest is the parameter object for ListTasks.

func (*ListTasksRequest) Query

func (r *ListTasksRequest) Query() url.Values

Query renders a ListTasksRequest as query parameters.

type ListTasksResponse

type ListTasksResponse struct {
	// Tasks are the matching tasks. Required, though it may be empty.
	Tasks []Task `json:"tasks"`
	// NextPageToken is the cursor for the following page, empty when exhausted.
	NextPageToken string `json:"nextPageToken"`
	// PageSize is the page size actually applied.
	PageSize int `json:"pageSize"`
	// TotalSize is the total number of matching tasks before pagination.
	TotalSize int `json:"totalSize"`
}

ListTasksResponse is the result object for ListTasks.

func DecodeListTasksResponse

func DecodeListTasksResponse(data []byte) (*ListTasksResponse, error)

DecodeListTasksResponse parses a ListTasksResponse.

type Message

type Message struct {
	// MessageID is the creator-assigned unique identifier. Required.
	MessageID string `json:"messageId"`
	// ContextID associates the message with a conversational context.
	ContextID string `json:"contextId,omitempty"`
	// TaskID associates the message with a task. Resuming an interrupted task
	// means sending a new message carrying the same taskId and contextId.
	TaskID string `json:"taskId,omitempty"`
	// Role identifies the sender. Required.
	Role Role `json:"role"`
	// Parts is the message content. Required, and must be non-empty.
	Parts []Part `json:"parts"`
	// Metadata is free-form custom data attached to the message.
	Metadata map[string]any `json:"metadata,omitempty"`
	// Extensions lists the URIs of extensions contributing to this message.
	Extensions []string `json:"extensions,omitempty"`
	// ReferenceTaskIDs lists other tasks this message refers to for context.
	ReferenceTaskIDs []string `json:"referenceTaskIds,omitempty"`
}

Message is one unit of communication between client and server.

func DecodeMessage

func DecodeMessage(data []byte) (*Message, error)

DecodeMessage parses a Message.

func NewAgentMessage

func NewAgentMessage(messageID, text string) Message

NewAgentMessage builds an agent-role text message.

func NewMessage

func NewMessage(messageID string, role Role, parts ...Part) Message

NewMessage builds a Message with the required messageId, role and parts.

func NewUserMessage

func NewUserMessage(messageID, text string) Message

NewUserMessage builds a user-role text message.

func (Message) ForTask

func (m Message) ForTask(taskID string) Message

ForTask stamps a task id onto the message and returns it, for chaining. This is how a client resumes an interrupted task: a new message carrying the same taskId and contextId (specification section 3.4).

func (Message) InContext

func (m Message) InContext(contextID string) Message

InContext stamps a context id onto the message and returns it, for chaining.

type MutualTlsSecurityScheme

type MutualTlsSecurityScheme struct {
	// Description is a human-readable note about the scheme.
	Description string `json:"description,omitempty"`
}

MutualTlsSecurityScheme is client-certificate authentication.

type NexusEvent

type NexusEvent struct {
	// Kind selects the payload arm. Required.
	Kind NexusEventKind `json:"kind"`
	// TaskID is the A2A task the telemetry belongs to.
	TaskID string `json:"taskId,omitempty"`
	// ContextID is the A2A context the telemetry belongs to.
	ContextID string `json:"contextId,omitempty"`
	// Sequence orders events within a task. It is monotonic per task and lets a
	// client reassemble ordering across the two carriers, since a part and a
	// metadata entry do not share a delivery channel.
	Sequence int `json:"sequence,omitempty"`
	// Timestamp records when the event was observed.
	Timestamp *Timestamp `json:"timestamp,omitempty"`
	// Source names the originating Nexus bus event type, e.g. "tool.result".
	// It is informational: clients must key behavior off Kind, not Source.
	Source string `json:"source,omitempty"`

	// Thinking is set when Kind is NexusEventKindThinking.
	Thinking *NexusThinking `json:"thinking,omitempty"`
	// ToolCall is set when Kind is NexusEventKindToolCall.
	ToolCall *NexusToolCall `json:"toolCall,omitempty"`
	// ToolResult is set when Kind is NexusEventKindToolResult.
	ToolResult *NexusToolResult `json:"toolResult,omitempty"`
	// Subagent is set when Kind is NexusEventKindSubagent.
	Subagent *NexusSubagentProgress `json:"subagent,omitempty"`
	// Usage is set when Kind is NexusEventKindUsage.
	Usage *NexusTokenUsage `json:"usage,omitempty"`
	// OutputGate is set when Kind is NexusEventKindOutputGate.
	OutputGate *NexusOutputGate `json:"outputGate,omitempty"`
}

NexusEvent is the typed payload of the Nexus A2A extension. Kind selects exactly one payload arm; the remaining envelope fields apply to every kind.

func DecodeNexusEvent

func DecodeNexusEvent(data []byte) (*NexusEvent, error)

DecodeNexusEvent parses and validates a Nexus extension event payload.

func NewNexusEvent

func NewNexusEvent(kind NexusEventKind, taskID, contextID string) NexusEvent

NewNexusEvent builds an event of the given kind stamped with the current time. Callers set the matching payload arm on the returned value.

func NexusEventFromMetadata

func NexusEventFromMetadata(md map[string]any) (*NexusEvent, bool, error)

NexusEventFromMetadata decodes a Nexus extension event out of a metadata map. The second return value reports whether the map carried one.

func NexusEventFromPart

func NexusEventFromPart(p Part) (*NexusEvent, bool, error)

NexusEventFromPart decodes a Part carrying a Nexus extension event. The second return value reports whether the part is tagged with this extension at all; a part belonging to another extension yields (nil, false, nil).

func OutputGateEvent

func OutputGateEvent(taskID, contextID string, gate NexusOutputGate) NexusEvent

OutputGateEvent builds an output-gate event.

func SubagentEvent

func SubagentEvent(taskID, contextID string, progress NexusSubagentProgress) NexusEvent

SubagentEvent builds a subagent-progress event.

func ThinkingEvent

func ThinkingEvent(taskID, contextID string, step NexusThinking) NexusEvent

ThinkingEvent builds a thinking-step event.

func ToolCallEvent

func ToolCallEvent(taskID, contextID string, call NexusToolCall) NexusEvent

ToolCallEvent builds a tool-invocation event.

func ToolResultEvent

func ToolResultEvent(taskID, contextID string, result NexusToolResult) NexusEvent

ToolResultEvent builds a tool-result event.

func UsageEvent

func UsageEvent(taskID, contextID string, usage NexusTokenUsage) NexusEvent

UsageEvent builds a token-usage event.

func (NexusEvent) At

func (e NexusEvent) At(t time.Time) NexusEvent

At stamps a specific observation time onto the event and returns it, for deterministic tests and replayed histories.

func (NexusEvent) From

func (e NexusEvent) From(busEventType string) NexusEvent

From stamps the originating Nexus bus event type onto the event and returns it, for chaining.

func (NexusEvent) Seq

func (e NexusEvent) Seq(n int) NexusEvent

Seq stamps a sequence number onto the event and returns it, for chaining.

func (NexusEvent) Validate

func (e NexusEvent) Validate() *Error

Validate checks that the event's kind is known and that exactly the matching payload arm is set.

type NexusEventKind

type NexusEventKind string

NexusEventKind names the kind of telemetry a NexusEvent carries, and selects which payload arm is set.

const (
	NexusEventKindUnset      NexusEventKind = ""
	NexusEventKindThinking   NexusEventKind = "thinking"
	NexusEventKindToolCall   NexusEventKind = "tool_call"
	NexusEventKindToolResult NexusEventKind = "tool_result"
	NexusEventKindSubagent   NexusEventKind = "subagent"
	NexusEventKindUsage      NexusEventKind = "usage"
	// NexusEventKindOutputGate reports that a Nexus output gate suspended or
	// blocked the model's stream. A2A publishes one post-gate artifact at turn
	// end rather than streaming text deltas, so a blocked turn is already safe
	// here — but without this a client sees only the refusal that replaced the
	// answer, with nothing to distinguish it from a model that chose to
	// refuse. This says policy intervened, and why.
	NexusEventKindOutputGate NexusEventKind = "output_gate"
)

Nexus extension event kinds.

func NexusEventKinds

func NexusEventKinds() []NexusEventKind

NexusEventKinds returns the event kinds the extension defines. The returned slice is a fresh copy.

func (NexusEventKind) Valid

func (k NexusEventKind) Valid() bool

Valid reports whether the kind is one the extension defines.

type NexusOutputGate

type NexusOutputGate struct {
	// State is what the gate did. Required.
	State NexusOutputGateState `json:"state"`
	// Held is the number of bytes currently withheld. Meaningful when State is
	// held.
	Held int `json:"held,omitempty"`
	// ReleasedLen is how much text had already been published when a block
	// landed. Meaningful when State is blocked.
	ReleasedLen int `json:"releasedLen,omitempty"`
	// Reason is the gate's explanation. It never quotes the text the gate
	// withheld — routing blocked content through a reason string would defeat
	// the gate that produced it.
	Reason string `json:"reason,omitempty"`
}

NexusOutputGate reports a Nexus output gate acting on the model's stream.

type NexusOutputGateState

type NexusOutputGateState string

NexusOutputGateState names what an output gate did to the model's stream.

const (
	// NexusOutputGateHeld reports that the gate is withholding text while it
	// decides — a deliberate pause, not a stall.
	NexusOutputGateHeld NexusOutputGateState = "held"
	// NexusOutputGateReleased reports that withheld text was cleared and sent.
	NexusOutputGateReleased NexusOutputGateState = "released"
	// NexusOutputGateBlocked reports that the gate ended the stream. The task's
	// answer is the substitute the gate authored, not the model's text.
	NexusOutputGateBlocked NexusOutputGateState = "blocked"
)

Output-gate states.

type NexusSubagentPhase

type NexusSubagentPhase string

NexusSubagentPhase names a point in a subagent's lifecycle.

const (
	NexusSubagentStarted   NexusSubagentPhase = "started"
	NexusSubagentIteration NexusSubagentPhase = "iteration"
	NexusSubagentComplete  NexusSubagentPhase = "complete"
	NexusSubagentFailed    NexusSubagentPhase = "failed"
)

Subagent lifecycle phases.

func (NexusSubagentPhase) Valid

func (p NexusSubagentPhase) Valid() bool

Valid reports whether the phase is one the extension defines.

type NexusSubagentProgress

type NexusSubagentProgress struct {
	// SubagentID uniquely identifies the delegated run. Required.
	SubagentID string `json:"subagentId"`
	// Name is the human-readable subagent or posture name.
	Name string `json:"name,omitempty"`
	// Phase is the lifecycle point being reported. Required.
	Phase NexusSubagentPhase `json:"phase"`
	// Iteration is the subagent's current loop iteration, 1-based.
	Iteration int `json:"iteration,omitempty"`
	// MaxIterations is the subagent's iteration budget, when one applies.
	MaxIterations int `json:"maxIterations,omitempty"`
	// Depth is the delegation depth, 1 for a direct child of the root agent.
	Depth int `json:"depth,omitempty"`
	// Detail is a human-readable progress note.
	Detail string `json:"detail,omitempty"`
	// Error describes the failure when Phase is NexusSubagentFailed.
	Error string `json:"error,omitempty"`
}

NexusSubagentProgress reports the progress of delegated work: a delegate call, an orchestrator worker, or a remote agent invoked as a tool.

type NexusThinking

type NexusThinking struct {
	// Step is the 1-based index of the step within the turn.
	Step int `json:"step,omitempty"`
	// Content is the reasoning text. Empty when Redacted is true.
	Content string `json:"content,omitempty"`
	// Redacted reports that the provider withheld the reasoning text, which
	// several providers do for safety-filtered thinking blocks.
	Redacted bool `json:"redacted,omitempty"`
	// Signature is the provider's opaque integrity signature over the step,
	// when one was supplied.
	Signature string `json:"signature,omitempty"`
}

NexusThinking is one reasoning step emitted by the agent loop.

type NexusTokenUsage

type NexusTokenUsage struct {
	// Model names the model the counts apply to.
	Model string `json:"model,omitempty"`
	// InputTokens is the prompt token count.
	InputTokens int `json:"inputTokens,omitempty"`
	// OutputTokens is the completion token count.
	OutputTokens int `json:"outputTokens,omitempty"`
	// CachedInputTokens is the portion of InputTokens served from a provider
	// prompt cache.
	CachedInputTokens int `json:"cachedInputTokens,omitempty"`
	// ReasoningTokens is the portion of OutputTokens spent on reasoning, for
	// providers that report it separately.
	ReasoningTokens int `json:"reasoningTokens,omitempty"`
	// TotalTokens is the sum for this accounting unit.
	TotalTokens int `json:"totalTokens,omitempty"`
	// Cumulative reports that the counts are session totals rather than the
	// cost of a single turn.
	Cumulative bool `json:"cumulative,omitempty"`
}

NexusTokenUsage reports token accounting for a turn or for the session so far.

type NexusToolCall

type NexusToolCall struct {
	// CallID correlates the call with its NexusToolResult. Required.
	CallID string `json:"callId"`
	// Name is the tool name. Required.
	Name string `json:"name"`
	// Arguments is the tool's JSON argument object.
	Arguments json.RawMessage `json:"arguments,omitempty"`
	// Risk is the Nexus risk classification that drove any approval prompt.
	Risk string `json:"risk,omitempty"`
	// Approved reports the outcome of a human approval gate: nil when no gate
	// applied, otherwise the decision.
	Approved *bool `json:"approved,omitempty"`
}

NexusToolCall is a tool invocation the agent decided to make.

type NexusToolResult

type NexusToolResult struct {
	// CallID correlates the result with its NexusToolCall. Required.
	CallID string `json:"callId"`
	// Name is the tool name. Required.
	Name string `json:"name"`
	// Output is the tool's textual result.
	Output string `json:"output,omitempty"`
	// Error describes the failure when the tool failed. Empty on success.
	Error string `json:"error,omitempty"`
	// DurationMS is the wall-clock execution time in milliseconds.
	DurationMS int64 `json:"durationMs,omitempty"`
}

NexusToolResult is the outcome of a tool invocation.

type OAuth2SecurityScheme

type OAuth2SecurityScheme struct {
	// Description is a human-readable note about the scheme.
	Description string `json:"description,omitempty"`
	// Flows is the supported grant flow. Required, and exactly one arm is set.
	Flows OAuthFlows `json:"flows"`
	// OAuth2MetadataURL points at the RFC 8414 authorization server metadata
	// document, letting a client discover endpoints rather than hardcode them.
	OAuth2MetadataURL string `json:"oauth2MetadataUrl,omitempty"`
}

OAuth2SecurityScheme is an OAuth 2.0 scheme.

type OAuthFlows

type OAuthFlows struct {
	// AuthorizationCode is the authorization code grant, with PKCE.
	AuthorizationCode *AuthorizationCodeOAuthFlow `json:"authorizationCode,omitempty"`
	// ClientCredentials is the machine-to-machine grant.
	ClientCredentials *ClientCredentialsOAuthFlow `json:"clientCredentials,omitempty"`
	// DeviceCode is the device authorization grant.
	DeviceCode *DeviceCodeOAuthFlow `json:"deviceCode,omitempty"`
}

OAuthFlows selects the OAuth 2.0 grant flow an agent supports. It is a proto oneof, so exactly one arm is set — not a set of independently-toggled flows.

The implicit and resource-owner-password grants exist in the proto but are marked deprecated ("use Authorization Code + PKCE instead"). They are deliberately absent here: this codec will not help anyone advertise a grant the specification tells them not to use.

func (OAuthFlows) Empty

func (f OAuthFlows) Empty() bool

Empty reports whether no flow is declared.

type OpenIdConnectSecurityScheme

type OpenIdConnectSecurityScheme struct {
	// Description is a human-readable note about the scheme.
	Description string `json:"description,omitempty"`
	// OpenIdConnectURL is the OIDC discovery document URL. Required.
	OpenIdConnectURL string `json:"openIdConnectUrl"`
}

OpenIdConnectSecurityScheme is OpenID Connect Discovery. The spelling matches the proto message name, which is also what the JSON key derives from.

type Part

type Part struct {
	// Text is the string content of a text part.
	Text *string `json:"text,omitempty"`
	// Raw is inline binary content, base64-encoded in JSON.
	Raw []byte `json:"raw,omitempty"`
	// URL points at externally-hosted content.
	URL *string `json:"url,omitempty"`
	// Data is arbitrary structured JSON content.
	Data json.RawMessage `json:"data,omitempty"`
	// Metadata is free-form custom data attached to the part.
	Metadata map[string]any `json:"metadata,omitempty"`
	// Filename names the content when it represents a file.
	Filename string `json:"filename,omitempty"`
	// MediaType is the MIME type of the content. Valid for every part kind.
	MediaType string `json:"mediaType,omitempty"`
}

Part is a section of communication content.

A2A 1.0 flattened the 0.3-era TextPart/FilePart/DataPart hierarchy into this one struct. Exactly one of Text, Raw, URL or Data carries the content; the remaining fields (MediaType, Filename, Metadata) apply to every kind.

Text and URL are pointers so that a deliberately empty string round-trips distinctly from an unset field, matching ProtoJSON oneof presence semantics. Use TextPart, RawPart, URLPart and DataPart to construct values.

An explicitly-set but zero-length Raw is the one presence distinction this struct cannot preserve: it encodes the same as an unset Raw.

func DataPart

func DataPart(value any) (Part, error)

DataPart builds a Part carrying arbitrary structured JSON. The value is marshaled immediately so malformed data fails at construction rather than on the wire.

func NexusEventPart

func NexusEventPart(e NexusEvent) (Part, error)

NexusEventPart builds a data Part carrying the event, tagged with the extension URI in its metadata so a client can recognize and skip it without decoding.

func RawPart

func RawPart(raw []byte, mediaType, filename string) Part

RawPart builds a Part carrying inline binary content, which serializes as base64. An empty mediaType or filename is omitted.

func TextPart

func TextPart(text string) Part

TextPart builds a text Part.

func URLPart

func URLPart(u, mediaType string) Part

URLPart builds a Part referencing externally-hosted content. An empty mediaType is omitted.

func (Part) Kind

func (p Part) Kind() PartKind

Kind reports which content arm is set. It returns PartKindUnset when none is, and reports only the first set arm when several are (which is itself invalid; use ValidatePart to detect that).

func (Part) TextValue

func (p Part) TextValue() (string, bool)

TextValue returns the text content and whether this is a text part.

func (Part) URLValue

func (p Part) URLValue() (string, bool)

URLValue returns the URL content and whether this is a URL part.

type PartKind

type PartKind string

PartKind names which arm of a Part's content oneof is set.

const (
	PartKindUnset PartKind = ""
	PartKindText  PartKind = "text"
	PartKindRaw   PartKind = "raw"
	PartKindURL   PartKind = "url"
	PartKindData  PartKind = "data"
)

Part content kinds.

type ProtocolBinding

type ProtocolBinding string

ProtocolBinding names the protocol binding spoken at an AgentInterface URL.

This is deliberately a string alias over an open vocabulary rather than a closed enum: a2a.proto types AgentInterface.protocol_binding as a plain string and documents it as "an open form string, to be easily extended for other protocol bindings", naming JSONRPC, GRPC and HTTP+JSON as the three officially supported values. A card MAY therefore advertise a binding this codec has never heard of, and rejecting it would make this package the reason a conforming card fails to parse.

const (
	BindingJSONRPC  ProtocolBinding = "JSONRPC"
	BindingGRPC     ProtocolBinding = "GRPC"
	BindingHTTPJSON ProtocolBinding = "HTTP+JSON"
)

The three officially supported protocol bindings. Note the values are the bare names from the proto comment, NOT ProtoJSON enum spellings: there is no TransportProtocol enum in the specification.

func (ProtocolBinding) Core

func (b ProtocolBinding) Core() bool

Core reports whether the binding is one of the three the specification officially defines. A binding outside this set is legal on the wire; Core exists so a client can tell "I do not speak this" from "this is malformed".

type RESTError

type RESTError struct {
	Error RESTErrorStatus `json:"error"`
}

RESTError is the HTTP error body: the google.rpc.Status JSON representation wrapped in an "error" envelope.

func (RESTError) AsError

func (e RESTError) AsError() *Error

AsError converts a received REST error body back into an A2A Error. The error type is recovered from the google.rpc.ErrorInfo reason when one is present, since several A2A error types share an HTTP status; otherwise it falls back to the first type mapping to that status, and finally to InternalError.

type RESTErrorStatus

type RESTErrorStatus struct {
	// Code is the HTTP status code.
	Code int `json:"code"`
	// Status is the canonical gRPC status name, e.g. "NOT_FOUND".
	Status string `json:"status"`
	// Message is the human-readable description.
	Message string `json:"message"`
	// Details carries the structured detail objects, including the ErrorInfo
	// that disambiguates A2A error types sharing one HTTP status.
	Details []ErrorDetail `json:"details,omitempty"`
}

RESTErrorStatus is the google.rpc.Status body of a REST error response.

type RPCError

type RPCError struct {
	Code    int           `json:"code"`
	Message string        `json:"message"`
	Data    []ErrorDetail `json:"data,omitempty"`
}

RPCError is a JSON-RPC 2.0 error object. Per specification section 9.5, A2A carries its structured detail objects in the "data" field as an array.

func (*RPCError) AsError

func (e *RPCError) AsError() *Error

AsError converts a received JSON-RPC error object back into an A2A Error, recovering the error type from the numeric code where possible.

type Request

type Request struct {
	// JSONRPC must be "2.0".
	JSONRPC string `json:"jsonrpc"`
	// ID correlates the response. JSON-RPC permits a string, a number or null;
	// it is kept raw so it round-trips byte-identically.
	ID json.RawMessage `json:"id,omitempty"`
	// Method is the A2A operation name.
	Method string `json:"method"`
	// Params is the operation's parameter object.
	Params json.RawMessage `json:"params,omitempty"`
}

Request is a JSON-RPC 2.0 request envelope.

func NewRequest

func NewRequest(id any, method string, params any) (*Request, error)

NewRequest builds a JSON-RPC request for an A2A operation. The id may be any JSON-encodable value; JSON-RPC conventionally uses a string or a number.

func (*Request) Encode

func (r *Request) Encode() ([]byte, error)

Encode serializes the request envelope.

type Response

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

Response is a JSON-RPC 2.0 response envelope. Exactly one of Result and Error is set.

func DecodeResponse

func DecodeResponse(data []byte) (*Response, error)

DecodeResponse parses a JSON-RPC response envelope.

func NewErrorResponse

func NewErrorResponse(id json.RawMessage, err *Error) *Response

NewErrorResponse builds a JSON-RPC error response. A nil error is treated as an internal error so this never produces a response with neither arm set.

func NewResultResponse

func NewResultResponse(id json.RawMessage, result any) (*Response, error)

NewResultResponse builds a successful JSON-RPC response carrying result. The id should be the raw id from the originating request.

func (*Response) DecodeResult

func (r *Response) DecodeResult(dst any) error

DecodeResult unmarshals a successful response's result into dst. A response carrying an error yields that error instead.

func (*Response) Encode

func (r *Response) Encode() ([]byte, error)

Encode serializes the response envelope.

type Role

type Role string

Role identifies the sender of a Message.

const (
	RoleUnspecified Role = "ROLE_UNSPECIFIED"
	RoleUser        Role = "ROLE_USER"
	RoleAgent       Role = "ROLE_AGENT"
)

Canonical message roles.

func (Role) Valid

func (r Role) Valid() bool

Valid reports whether the role is one of the two addressable roles.

type Route

type Route struct {
	// Operation is the A2A operation name, identical to the JSON-RPC method.
	Operation string
	// HTTPMethod is the HTTP verb.
	HTTPMethod string
	// Path is the path template, with {id} and {configId} placeholders.
	Path string
	// Streaming reports whether the response is an SSE stream rather than a
	// single JSON body.
	Streaming bool
	// Supported reports whether this codec decodes the operation. Unsupported
	// routes are declared so that a server can answer them with the correct
	// protocol error instead of a bare 404.
	Supported bool
}

Route binds one A2A operation to its REST shape.

func MatchRoute

func MatchRoute(httpMethod, path string) (route Route, vars map[string]string, found bool, methodMismatch bool)

MatchRoute resolves an HTTP method and request path to an A2A route, extracting path placeholders into vars.

Matching is hand-rolled rather than delegated to http.ServeMux because A2A's custom verbs live in the last path segment after a colon: "/tasks/abc:cancel" and "/tasks/abc" differ only in that suffix, and a ServeMux "{id}" wildcard would swallow the verb into the id.

It reports found=false when nothing matches the path at all, and methodMismatch=true when the path matches a known route but the HTTP verb does not, so a caller can answer 405 rather than 404.

func RouteFor

func RouteFor(operation string) (Route, bool)

RouteFor returns the REST route for an A2A operation.

func Routes

func Routes() []Route

Routes returns the full REST route table. The returned slice is a fresh copy.

func SupportedRoutes

func SupportedRoutes() []Route

SupportedRoutes returns only the routes this codec decodes.

type SSEReader

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

SSEReader decodes an A2A SSE stream into StreamResponse frames. It handles multi-line "data:" records, comment lines, and blank-line record boundaries, and it auto-detects the JSON-RPC and REST framings.

It applies the same stream contract as SSEWriter, so a client detects a non-conforming server rather than silently mis-sequencing its own state. A contract violation is reported as an *Error of type InvalidAgentResponseError, which is the error the specification reserves for exactly that.

SSEReader is not safe for concurrent use; one goroutine owns the stream.

func NewSSEReader

func NewSSEReader(r io.Reader) *SSEReader

NewSSEReader reads an A2A SSE stream from r.

func (*SSEReader) Closed

func (sr *SSEReader) Closed() bool

Closed reports whether the stream has reached a terminating frame: a terminal task state, or a direct message reply.

func (*SSEReader) Next

func (sr *SSEReader) Next() (*StreamResponse, error)

Next reads and decodes the next frame. It returns io.EOF when the stream is exhausted, an *Error carrying a server-sent protocol error when the server framed one, and an *Error of type InvalidAgentResponseError when the server violated the stream contract.

func (*SSEReader) ReadAll

func (sr *SSEReader) ReadAll() ([]StreamResponse, error)

ReadAll drains the stream into a slice of frames, stopping at io.EOF. A frame decoded before the failure is retained, so a caller can inspect how far a failing stream got.

func (*SSEReader) State

func (sr *SSEReader) State() TaskState

State returns the last task state seen on the stream.

func (*SSEReader) TaskID

func (sr *SSEReader) TaskID() string

TaskID returns the task id the stream opened on, empty for a message-only stream.

type SSEWriter

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

SSEWriter serializes StreamResponse frames onto an io.Writer as Server-Sent Events while enforcing the A2A stream contract.

The contract it enforces, in order of application:

  1. Every frame must set exactly one payload arm and be internally valid (ValidateStreamResponse).
  2. The first frame must be a Task or a Message. Nothing else may open a stream.
  3. No later frame may be a Task or a Message; after the opening frame only TaskStatusUpdateEvent and TaskArtifactUpdateEvent are legal.
  4. Update frames must name the task and context the opening Task frame established.
  5. Status updates must follow a legal task state transition (ValidateTransition) from the last observed state.
  6. The stream closes as soon as a frame reports a terminal state — COMPLETED, FAILED, CANCELED or REJECTED alike. Writes after that return ErrStreamClosed.

Interleaving

Rules 2 and 3 are the whole of the ordering constraint. Status and artifact updates may interleave freely after the opening frame. A stricter reading ("all status updates, then all artifact updates") is not implementable: the COMPLETED status frame that closes a stream necessarily follows the artifact frames carrying the output it completes.

Concurrency

SSEWriter is safe for concurrent use: a mutex guards both the stream state machine and the byte writes, so frames are never torn. Nexus serve plugins still funnel every frame through one goroutine (bus handlers push onto a buffered channel, the HTTP goroutine drains it) — the lock is belt and braces against a caller that forgets.

func NewJSONRPCSSEWriter

func NewJSONRPCSSEWriter(w io.Writer, id json.RawMessage) *SSEWriter

NewJSONRPCSSEWriter wraps w for the JSON-RPC binding: each record's payload is a JSON-RPC Response envelope repeating id, whose result is the StreamResponse. A nil id is written as JSON null, which is what the envelope requires when the request id could not be recovered.

func NewSSEWriter

func NewSSEWriter(w io.Writer) *SSEWriter

NewSSEWriter wraps w for the HTTP+JSON/REST binding: each record's payload is a bare StreamResponse. If w implements http.Flusher every record is flushed.

func (*SSEWriter) Close

func (sw *SSEWriter) Close() error

Close marks the stream closed without emitting anything. It is idempotent and is what a serve layer calls when the client disconnects.

func (*SSEWriter) Closed

func (sw *SSEWriter) Closed() bool

Closed reports whether the stream has terminated and will accept no further frames.

func (*SSEWriter) Flush

func (sw *SSEWriter) Flush()

Flush flushes the underlying writer if it supports flushing.

func (*SSEWriter) Frames

func (sw *SSEWriter) Frames() int

Frames returns the number of payload frames written so far. Comments and error frames are not counted.

func (*SSEWriter) Interrupted

func (sw *SSEWriter) Interrupted() bool

Interrupted reports whether the stream is open and parked in a non-terminal interrupted state — INPUT_REQUIRED or AUTH_REQUIRED. See the package doc for why such a stream deliberately stays open and what a serving layer owes the client in that situation.

func (*SSEWriter) Ping

func (sw *SSEWriter) Ping() error

Ping emits a keep-alive comment.

func (*SSEWriter) State

func (sw *SSEWriter) State() TaskState

State returns the last task state observed on the stream, or TaskStateUnspecified before the opening frame.

func (*SSEWriter) TaskID

func (sw *SSEWriter) TaskID() string

TaskID returns the task id the opening Task frame established, empty for a message-only stream.

func (*SSEWriter) Write

func (sw *SSEWriter) Write(frame StreamResponse) error

Write validates and emits one StreamResponse frame, then closes the stream if the frame terminated the task. It returns ErrStreamClosed if the stream has already terminated, an error wrapping ErrStreamOrder for an ordering violation, and an *Error for a malformed frame or an illegal state transition.

func (*SSEWriter) WriteArtifact

func (sw *SSEWriter) WriteArtifact(e TaskArtifactUpdateEvent) error

WriteArtifact emits a task artifact update.

func (*SSEWriter) WriteComment

func (sw *SSEWriter) WriteComment(text string) error

WriteComment emits an SSE comment record. Comments carry no protocol meaning and are the conventional way to keep an idle connection alive through proxies with read timeouts — which is exactly what an INPUT_REQUIRED stream needs.

func (*SSEWriter) WriteError

func (sw *SSEWriter) WriteError(protoErr *Error) error

WriteError emits a protocol error as the final record of the stream and closes it. The error is framed as a JSON-RPC error response for the JSON-RPC binding and as the google.rpc.Status REST body otherwise.

An error frame is the transport-level escape hatch for a failure that cannot be expressed as a task state — a version mismatch, an authentication failure mid-stream. A failure of the work itself belongs in a FAILED status update, not here.

func (*SSEWriter) WriteMessage

func (sw *SSEWriter) WriteMessage(m Message) error

WriteMessage emits a direct message reply, which both opens and closes the stream.

func (*SSEWriter) WriteStatus

func (sw *SSEWriter) WriteStatus(e TaskStatusUpdateEvent) error

WriteStatus emits a task status update.

func (*SSEWriter) WriteTask

func (sw *SSEWriter) WriteTask(t Task) error

WriteTask emits the opening Task snapshot.

type SecurityRequirement

type SecurityRequirement struct {
	Schemes map[string]StringList `json:"schemes,omitempty"`
}

SecurityRequirement is one alternative set of credentials that satisfies access: every scheme named in Schemes must be satisfied, and its StringList carries the scopes that scheme requires (empty for schemes without scopes).

func NewSecurityRequirement

func NewSecurityRequirement(scheme string, scopes ...string) SecurityRequirement

NewSecurityRequirement builds a single-scheme requirement.

type SecurityScheme

type SecurityScheme struct {
	// APIKey carries a credential in a named header, query parameter or cookie.
	APIKey *APIKeySecurityScheme `json:"apiKeySecurityScheme,omitempty"`
	// HTTPAuth is an HTTP Authorization scheme such as Bearer or Basic.
	HTTPAuth *HTTPAuthSecurityScheme `json:"httpAuthSecurityScheme,omitempty"`
	// OAuth2 is an OAuth 2.0 scheme with exactly one supported flow.
	OAuth2 *OAuth2SecurityScheme `json:"oauth2SecurityScheme,omitempty"`
	// OpenIDConnect is OpenID Connect Discovery.
	OpenIDConnect *OpenIdConnectSecurityScheme `json:"openIdConnectSecurityScheme,omitempty"`
	// MutualTLS is client-certificate authentication.
	MutualTLS *MutualTlsSecurityScheme `json:"mtlsSecurityScheme,omitempty"`
}

SecurityScheme is one authentication scheme an agent accepts. Like Part it is a flattened oneof: exactly one arm is set.

func APIKeyScheme

func APIKeyScheme(name string, location APIKeyLocation, description string) SecurityScheme

APIKeyScheme builds an API-key security scheme.

func BearerScheme

func BearerScheme(bearerFormat, description string) SecurityScheme

BearerScheme builds an HTTP bearer-token security scheme.

func MutualTLSScheme

func MutualTLSScheme(description string) SecurityScheme

MutualTLSScheme builds a client-certificate security scheme.

func OpenIDConnectScheme

func OpenIDConnectScheme(discoveryURL, description string) SecurityScheme

OpenIDConnectScheme builds an OpenID Connect Discovery security scheme.

func (SecurityScheme) Kind

Kind reports which arm is set, or SecuritySchemeUnset when none is. It reports only the first set arm when several are; use ValidateSecurityScheme to detect that.

type SecuritySchemeKind

type SecuritySchemeKind string

SecuritySchemeKind names which arm of a SecurityScheme oneof is set.

const (
	SecuritySchemeUnset         SecuritySchemeKind = ""
	SecuritySchemeAPIKey        SecuritySchemeKind = "apiKey"
	SecuritySchemeHTTPAuth      SecuritySchemeKind = "httpAuth"
	SecuritySchemeOAuth2        SecuritySchemeKind = "oauth2"
	SecuritySchemeOpenIDConnect SecuritySchemeKind = "openIdConnect"
	SecuritySchemeMutualTLS     SecuritySchemeKind = "mutualTls"
)

Security scheme kinds.

type SendMessageConfiguration

type SendMessageConfiguration struct {
	// AcceptedOutputModes lists media types the client can accept in response
	// parts.
	AcceptedOutputModes []string `json:"acceptedOutputModes,omitempty"`
	// TaskPushNotificationConfig registers a webhook for the resulting task.
	TaskPushNotificationConfig *TaskPushNotificationConfig `json:"taskPushNotificationConfig,omitempty"`
	// HistoryLength caps how many recent history messages the response carries.
	// Unset means no client-imposed limit; zero means omit history entirely.
	HistoryLength *int `json:"historyLength,omitempty"`
	// ReturnImmediately makes the call non-blocking: it returns as soon as the
	// task exists rather than waiting for a terminal or interrupted state.
	// Blocking is the default (specification section 3.2.2).
	ReturnImmediately bool `json:"returnImmediately,omitempty"`
}

SendMessageConfiguration tunes a SendMessage or SendStreamingMessage call.

type SendMessageRequest

type SendMessageRequest struct {
	// Tenant is an opaque routing identifier.
	Tenant string `json:"tenant,omitempty"`
	// Message is the message to send. Required.
	Message Message `json:"message"`
	// Configuration tunes the call.
	Configuration *SendMessageConfiguration `json:"configuration,omitempty"`
	// Metadata is free-form custom data attached to the call.
	Metadata map[string]any `json:"metadata,omitempty"`
}

SendMessageRequest is the parameter object for SendMessage and SendStreamingMessage.

type SendMessageResponse

type SendMessageResponse struct {
	// Task is the created or updated task.
	Task *Task `json:"task,omitempty"`
	// Message is a direct reply from the agent.
	Message *Message `json:"message,omitempty"`
}

SendMessageResponse is the result of SendMessage: either the task tracking the work, or a direct message reply for interactions that need no task.

func DecodeSendMessageResponse

func DecodeSendMessageResponse(data []byte) (*SendMessageResponse, error)

DecodeSendMessageResponse parses a SendMessageResponse.

func MessageResponse

func MessageResponse(m Message) SendMessageResponse

MessageResponse wraps a direct message reply as a SendMessageResponse.

func TaskResponse

func TaskResponse(t Task) SendMessageResponse

TaskResponse wraps a task as a SendMessageResponse.

type ServiceParams

type ServiceParams struct {
	// Version is the normalized Major.Minor protocol version. It is never empty
	// after parsing: an absent parameter yields DefaultVersion.
	Version string
	// Extensions are the extension URIs the client declared support for, in the
	// order given, deduplicated.
	Extensions []string
}

ServiceParams are the A2A service parameters carried alongside a request.

func (ServiceParams) Apply

func (p ServiceParams) Apply(h http.Header)

Apply writes the service parameters onto an outgoing request's headers. An empty Version is written as ProtocolVersion, since clients must always send the header (specification section 3.6.1).

func (ServiceParams) SupportsExtension

func (p ServiceParams) SupportsExtension(uri string) bool

SupportsExtension reports whether the client declared support for uri.

type StreamPayloadKind

type StreamPayloadKind string

StreamPayloadKind names which arm of a StreamResponse payload oneof is set.

const (
	StreamPayloadUnset          StreamPayloadKind = ""
	StreamPayloadTask           StreamPayloadKind = "task"
	StreamPayloadMessage        StreamPayloadKind = "message"
	StreamPayloadStatusUpdate   StreamPayloadKind = "statusUpdate"
	StreamPayloadArtifactUpdate StreamPayloadKind = "artifactUpdate"
)

StreamResponse payload kinds.

type StreamResponse

type StreamResponse struct {
	// Task is a full task snapshot, typically the opening frame of a stream.
	Task *Task `json:"task,omitempty"`
	// Message is a direct message from the agent.
	Message *Message `json:"message,omitempty"`
	// StatusUpdate reports a task status transition.
	StatusUpdate *TaskStatusUpdateEvent `json:"statusUpdate,omitempty"`
	// ArtifactUpdate delivers an artifact or artifact chunk.
	ArtifactUpdate *TaskArtifactUpdateEvent `json:"artifactUpdate,omitempty"`
}

StreamResponse wraps the several payload shapes a streaming operation emits. Exactly one field is set per frame.

func DecodeStreamResponse

func DecodeStreamResponse(data []byte) (*StreamResponse, error)

DecodeStreamResponse parses one StreamResponse frame.

func StreamArtifactUpdate

func StreamArtifactUpdate(e TaskArtifactUpdateEvent) StreamResponse

StreamArtifactUpdate wraps an artifact update as a StreamResponse frame.

func StreamMessage

func StreamMessage(m Message) StreamResponse

StreamMessage wraps a direct message as a StreamResponse frame.

func StreamStatusUpdate

func StreamStatusUpdate(e TaskStatusUpdateEvent) StreamResponse

StreamStatusUpdate wraps a status update as a StreamResponse frame.

func StreamTask

func StreamTask(t Task) StreamResponse

StreamTask wraps a task snapshot as a StreamResponse frame.

func (StreamResponse) Kind

Kind reports which payload arm is set, or StreamPayloadUnset when none is.

func (StreamResponse) TerminalState

func (s StreamResponse) TerminalState() (TaskState, bool)

TerminalState returns the task state carried by this frame and whether that state is terminal. A streaming operation must close its stream once a frame reporting a terminal state has been delivered (specification section 11.7).

type StringList

type StringList struct {
	List []string `json:"list,omitempty"`
}

StringList is the proto's wrapper for a repeated string inside a map value, which protobuf maps cannot hold directly. It is why a security requirement's scopes serialize as {"list": [...]} rather than as a bare array.

type SubscribeToTaskRequest

type SubscribeToTaskRequest struct {
	// Tenant is an opaque routing identifier.
	Tenant string `json:"tenant,omitempty"`
	// ID is the task to subscribe to. Required.
	ID string `json:"id"`
}

SubscribeToTaskRequest is the parameter object for SubscribeToTask.

type Task

type Task struct {
	// ID is the server-generated unique identifier for the task. Required.
	ID string `json:"id"`
	// ContextID groups related tasks and messages into one logical conversation.
	ContextID string `json:"contextId,omitempty"`
	// Status is the current lifecycle status. Required.
	Status TaskStatus `json:"status"`
	// Artifacts are the outputs produced by the task.
	Artifacts []Artifact `json:"artifacts,omitempty"`
	// History is the sequence of messages exchanged during the task. Servers
	// decide which messages are persisted; clients must not rely on all of them
	// being present (specification section 3.7).
	History []Message `json:"history,omitempty"`
	// Metadata is free-form custom data attached to the task.
	Metadata map[string]any `json:"metadata,omitempty"`
}

Task is the core unit of action in A2A. It carries a current status, the artifacts produced so far, and the history of messages exchanged.

func DecodeTask

func DecodeTask(data []byte) (*Task, error)

DecodeTask parses a Task.

func NewTask

func NewTask(id, contextID string) Task

NewTask builds a Task in the submitted state.

type TaskArtifactUpdateEvent

type TaskArtifactUpdateEvent struct {
	// TaskID is the task that produced the artifact. Required.
	TaskID string `json:"taskId"`
	// ContextID is the context the task belongs to. Required.
	ContextID string `json:"contextId"`
	// Artifact is the generated or updated artifact. Required.
	Artifact Artifact `json:"artifact"`
	// Append reports whether this content extends a previously sent artifact
	// carrying the same artifactId rather than replacing it.
	Append bool `json:"append,omitempty"`
	// LastChunk reports whether this is the final chunk of the artifact.
	LastChunk bool `json:"lastChunk,omitempty"`
	// Metadata is free-form custom data attached to the update.
	Metadata map[string]any `json:"metadata,omitempty"`
}

TaskArtifactUpdateEvent delivers an artifact, or a chunk of one, for a task.

func DecodeArtifactUpdate

func DecodeArtifactUpdate(data []byte) (*TaskArtifactUpdateEvent, error)

DecodeArtifactUpdate parses a TaskArtifactUpdateEvent.

func NewArtifactChunk

func NewArtifactChunk(taskID, contextID string, artifact Artifact, appendChunk, last bool) TaskArtifactUpdateEvent

NewArtifactChunk builds a TaskArtifactUpdateEvent delivering one chunk of a streamed artifact. Chunks after the first set append; the final chunk sets lastChunk.

func NewArtifactUpdate

func NewArtifactUpdate(taskID, contextID string, artifact Artifact) TaskArtifactUpdateEvent

NewArtifactUpdate builds a TaskArtifactUpdateEvent delivering a whole artifact in one frame.

type TaskPushNotificationConfig

type TaskPushNotificationConfig struct {
	// Tenant is an opaque routing identifier.
	Tenant string `json:"tenant,omitempty"`
	// ID uniquely identifies this configuration.
	ID string `json:"id,omitempty"`
	// TaskID is the task this configuration applies to. Empty when the config is
	// supplied inline on a SendMessage request.
	TaskID string `json:"taskId,omitempty"`
	// URL is the webhook endpoint. Required.
	URL string `json:"url"`
	// Token is a caller-chosen value echoed back with each notification.
	Token string `json:"token,omitempty"`
	// Authentication describes how to authenticate to the webhook.
	Authentication *AuthenticationInfo `json:"authentication,omitempty"`
}

TaskPushNotificationConfig is a webhook configuration for a task.

type TaskState

type TaskState string

TaskState is the lifecycle state of a Task. Values are the ProtoJSON enum names from specification section 4.1.

const (
	TaskStateUnspecified   TaskState = "TASK_STATE_UNSPECIFIED"
	TaskStateSubmitted     TaskState = "TASK_STATE_SUBMITTED"
	TaskStateWorking       TaskState = "TASK_STATE_WORKING"
	TaskStateCompleted     TaskState = "TASK_STATE_COMPLETED"
	TaskStateFailed        TaskState = "TASK_STATE_FAILED"
	TaskStateCanceled      TaskState = "TASK_STATE_CANCELED"
	TaskStateInputRequired TaskState = "TASK_STATE_INPUT_REQUIRED"
	TaskStateRejected      TaskState = "TASK_STATE_REJECTED"
	TaskStateAuthRequired  TaskState = "TASK_STATE_AUTH_REQUIRED"
)

Canonical task states. TaskStateUnspecified is the proto zero value and is never a legal state for a live task; it stands for "no state known yet".

func TaskStates

func TaskStates() []TaskState

TaskStates returns the eight addressable task states, excluding the unspecified zero value. The returned slice is a fresh copy.

func (TaskState) Cancelable

func (s TaskState) Cancelable() bool

Cancelable reports whether a task in state s may be canceled. Terminal tasks may not be; attempting it yields TaskNotCancelableError.

func (TaskState) IsActive

func (s TaskState) IsActive() bool

IsActive reports whether s is a live, non-terminal state: the task may still progress. Interrupted states are active.

func (TaskState) IsInterrupted

func (s TaskState) IsInterrupted() bool

IsInterrupted reports whether s is an interrupted (non-terminal) state, in which the task is paused awaiting something from the client. A blocking SendMessage returns when a task reaches one of these.

func (TaskState) IsTerminal

func (s TaskState) IsTerminal() bool

IsTerminal reports whether s is a terminal state. Once a task reaches one, it accepts no further messages, no further transitions, and any open stream must close (specification sections 3.1.1 and 11.7).

func (TaskState) Known

func (s TaskState) Known() bool

Known reports whether s is a recognized enum value, including the unspecified zero value.

func (TaskState) String

func (s TaskState) String() string

String renders the task state without its TASK_STATE_ prefix, for logs and error messages. It is not a wire format.

func (TaskState) Valid

func (s TaskState) Valid() bool

Valid reports whether s is a recognized task state. The unspecified zero value is not valid for a live task.

type TaskStatus

type TaskStatus struct {
	// State is the current lifecycle state. Required.
	State TaskState `json:"state"`
	// Message optionally carries an agent message describing the status. This is
	// where an INPUT_REQUIRED question travels.
	Message *Message `json:"message,omitempty"`
	// Timestamp records when the status was observed.
	Timestamp *Timestamp `json:"timestamp,omitempty"`
}

TaskStatus is a task's state plus the optional message and timestamp that accompany it.

func NewTaskStatus

func NewTaskStatus(state TaskState) TaskStatus

NewTaskStatus builds a TaskStatus stamped with the current time.

func NewTaskStatusAt

func NewTaskStatusAt(state TaskState, at time.Time) TaskStatus

NewTaskStatusAt builds a TaskStatus stamped with a specific time, for deterministic tests and for replaying recorded histories.

func (TaskStatus) WithMessage

func (s TaskStatus) WithMessage(m Message) TaskStatus

WithMessage attaches a status message and returns the status, for chaining. An INPUT_REQUIRED question travels this way.

type TaskStatusUpdateEvent

type TaskStatusUpdateEvent struct {
	// TaskID is the task that changed. Required.
	TaskID string `json:"taskId"`
	// ContextID is the context the task belongs to. Required.
	ContextID string `json:"contextId"`
	// Status is the new status. Required.
	Status TaskStatus `json:"status"`
	// Metadata is free-form custom data attached to the update.
	Metadata map[string]any `json:"metadata,omitempty"`
}

TaskStatusUpdateEvent notifies a client that a task's status changed.

func DecodeStatusUpdate

func DecodeStatusUpdate(data []byte) (*TaskStatusUpdateEvent, error)

DecodeStatusUpdate parses a TaskStatusUpdateEvent.

func NewStatusUpdate

func NewStatusUpdate(taskID, contextID string, status TaskStatus) TaskStatusUpdateEvent

NewStatusUpdate builds a TaskStatusUpdateEvent.

type Timestamp

type Timestamp struct {
	time.Time
}

Timestamp wraps time.Time so that it marshals to the ISO 8601 UTC form A2A requires. Values are converted to UTC on encode; offsets other than "Z" are never emitted. Decoding accepts any RFC 3339 timestamp, including ones with a non-UTC offset or no fractional seconds, and normalizes to UTC.

func NewTimestamp

func NewTimestamp(t time.Time) *Timestamp

NewTimestamp wraps t as an A2A timestamp, normalized to UTC.

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON renders the timestamp as an ISO 8601 UTC string.

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(data []byte) error

UnmarshalJSON parses an ISO 8601 / RFC 3339 timestamp into UTC.

Directories

Path Synopsis
Package a2aclient is a pure-Go client for the Agent2Agent (A2A) protocol.
Package a2aclient is a pure-Go client for the Agent2Agent (A2A) protocol.
Package a2aconform is the shared A2A conformance vector suite: a declarative, transport-neutral corpus that every mapping producing A2A output in this repository must satisfy.
Package a2aconform is the shared A2A conformance vector suite: a declarative, transport-neutral corpus that every mapping producing A2A output in this repository must satisfy.

Jump to

Keyboard shortcuts

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