a2aclient

package
v0.32.2 Latest Latest
Warning

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

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

Documentation

Overview

Package a2aclient is a pure-Go client for the Agent2Agent (A2A) protocol. It resolves a remote agent's Agent Card, sends messages over either HTTP binding, consumes the Server-Sent Events stream a streaming call answers with, resumes an interrupted task, cancels a task and reads one back.

It is transport-only. It has no dependency on the Nexus engine, the event bus or any plugin, and it reimplements no wire concern: every byte it writes and reads goes through pkg/a2a's codec, SSE reader and error model. A serve plugin and this client therefore agree on the wire by construction rather than by review.

Bindings

A2A defines two HTTP bindings and this package speaks both. JSONRPC is the default because it is the binding every A2A implementation is expected to expose; HTTP+JSON is selectable with WithBinding. The choice affects only framing — the same operations, parameter objects and errors are reachable either way, and a stream produced by either binding is decoded by the same reader, which auto-detects the framing per record.

Discovery

New takes the remote's BASE URL, not an operation endpoint. The client fetches the Agent Card from AgentCardPath under that base on first use and reads the endpoint for the selected binding out of it, so an operator configures one URL rather than one URL per binding. Capabilities reports what the card promises: streaming support, the bindings on offer, the declared security schemes and the protocol extensions. An operator who was handed a card out of band (which specification section 8.2 sanctions as "Direct Configuration") supplies it with WithCard, and one who knows the endpoint outright supplies it with WithJSONRPCEndpoint or WithRESTEndpoint — either of which skips discovery entirely.

Credentials

Credentials are supplied through the CredentialSource seam, not baked in. The zero configuration — no source at all — works against an open endpoint, which is what a loopback development agent is. Concrete bearer, OAuth2 and mTLS sources are built on this interface elsewhere; nothing in this package knows how a credential is obtained, only that it is applied to each request and may be refreshed per call.

Robustness

A remote agent is somebody else's process and may be wrong. Every way this package has found for a remote to be wrong produces a typed error rather than a hang, a panic or a silently truncated result:

  • A card that will not parse, will not validate, or is answered with an HTTP error is a *CardError.
  • A binding the card does not expose, a protocol version it declares that this client does not speak, or a streaming call to an agent whose card says it does not stream, is a *BindingError.
  • An HTTP failure carrying no decodable A2A error body is an *HTTPError; one that does carry an A2A error body is the *a2a.Error it encodes, so errors.As recovers the protocol taxonomy.
  • Anything that goes wrong with a stream is a *StreamError carrying a Reason: a malformed frame, a frame that violates the stream contract (wrong opening frame, mid-stream identity change, illegal state transition), a stream that ends before reaching a terminal state, a non-SSE response where SSE was promised, an idle stream, or a cancellation.

Timeouts, retries and cancellation

Timeout and retry policy live here rather than in a caller, because they are properties of talking to a remote over HTTP and every caller would otherwise reinvent them. See RetryPolicy for what is retried and why the answer differs between an idempotent read and a message send.

Cancelling the context passed to any call aborts the in-flight HTTP request promptly. For a stream that means the reader goroutine and the idle watchdog both exit and the response body is closed; no goroutine outlives the call.

No third-party A2A SDK is used; this is standard-library Go on top of pkg/a2a.

Index

Constants

View Source
const (
	// DefaultRequestTimeout bounds a control-plane call — GetTask, CancelTask.
	// Those answer from the remote's task store and have no reason to be slow.
	DefaultRequestTimeout = 60 * time.Second
	// DefaultStreamOpenTimeout bounds the wait for a streaming call's response
	// HEADERS, not its body. A stream that has not been accepted in this long
	// is not going to be.
	DefaultStreamOpenTimeout = 30 * time.Second
	// DefaultStreamIdleTimeout bounds total silence on an open stream. See
	// WithStreamIdleTimeout for why the default is non-zero and why "silence"
	// is measured in bytes rather than frames.
	DefaultStreamIdleTimeout = 5 * time.Minute
	// DefaultUserAgent identifies this client to a remote agent.
	DefaultUserAgent = "nexus-a2aclient/1.0"
)

Defaults. Each is overridable; the reasoning for the value is with its option.

Variables

View Source
var ErrNoEndpoint = errors.New("a2aclient: no endpoint for the selected protocol binding")

ErrNoEndpoint reports that no endpoint is configured or discoverable for the selected binding. It is the sentinel behind a *BindingError raised when the card carries no matching interface.

Functions

func ResumeRequest

func ResumeRequest(taskID, contextID, messageID string, parts ...a2a.Part) a2a.SendMessageRequest

ResumeRequest builds a SendMessageRequest that continues an existing task.

It is the same request shape as any other send; the taskId and contextId on the message are what make it a resumption. Use it with SendMessage for a blocking continuation or SendStreamingMessage for a streaming one — a resumed task streams on a fresh connection, since the stream the interruption arrived on belongs to the earlier call.

func ResumeRequestForTask

func ResumeRequestForTask(task *a2a.Task, messageID string, parts ...a2a.Part) (a2a.SendMessageRequest, bool)

ResumeRequestForTask builds a continuation for a task read back with GetTask rather than observed on a stream. It is the path a client takes after a restart, when the stream that carried the interruption is long gone. The second return is false when the task is not parked on an interruption.

func ResumeText

func ResumeText(taskID, contextID, messageID, text string) a2a.SendMessageRequest

ResumeText builds a resume request whose payload is a single text part, which is what answering an INPUT_REQUIRED question usually amounts to.

Types

type BindingError

type BindingError struct {
	// Binding is the protocol binding that was requested, as a string so this
	// type does not force a pkg/a2a import on a caller only formatting it.
	Binding string
	// Operation names the A2A operation, empty when the failure is about the
	// binding as a whole rather than one call.
	Operation string
	// Detail explains the mismatch in operator-readable terms.
	Detail string
	// Err is the underlying cause, ErrNoEndpoint for a missing interface.
	Err error
}

BindingError reports that the remote cannot be reached over the binding this client was configured for: the card exposes no interface for it, the interface it exposes declares a protocol version this client does not speak, or the operation requires a capability the card denies.

func (*BindingError) Error

func (e *BindingError) Error() string

func (*BindingError) Unwrap

func (e *BindingError) Unwrap() error

Unwrap exposes the underlying cause to errors.Is and errors.As.

type Capabilities

type Capabilities struct {
	// Name, Description and Version identify the agent.
	Name        string
	Description string
	Version     string

	// Streaming reports whether the agent accepts SendStreamingMessage and
	// SubscribeToTask.
	Streaming bool
	// PushNotifications reports whether the agent supports push-notification
	// configs. This client implements no push operation, so the flag is
	// informational.
	PushNotifications bool
	// ExtendedAgentCard reports whether the agent serves an authenticated
	// extended card.
	ExtendedAgentCard bool

	// Bindings are the protocol bindings the card exposes an interface for, in
	// card order, which is preference order.
	Bindings []a2a.ProtocolBinding
	// Interfaces are the raw declarations, for a caller that needs the URL or
	// the per-interface protocol version.
	Interfaces []a2a.AgentInterface

	// SecuritySchemes are the declared schemes, sorted by name for a stable
	// presentation.
	SecuritySchemes []SchemeInfo
	// SecurityRequirements are the card-level requirements: each entry is one
	// alternative, and satisfying any one of them is enough.
	SecurityRequirements []a2a.SecurityRequirement

	// Extensions are the extension URIs the card declares.
	Extensions []string
	// RequiredExtensions are the subset a client MUST support to interact at
	// all (specification section 3.5): calling this agent without them will be
	// refused.
	RequiredExtensions []string

	// SkillIDs are the ids of the skills the card advertises.
	SkillIDs []string
}

Capabilities is a flat summary of what a remote's Agent Card promises. It exists so a caller can answer "can I stream to this agent, what must I authenticate with, and which bindings does it expose" without walking the card itself.

func SummarizeCard

func SummarizeCard(card *a2a.AgentCard) Capabilities

SummarizeCard flattens an Agent Card into its capability summary. It is exported so a caller holding a card obtained elsewhere can inspect it the same way.

func (Capabilities) RequiresAuth

func (c Capabilities) RequiresAuth() bool

RequiresAuth reports whether the card declares any security requirement. A card with schemes but no requirements is describing optional credentials.

func (Capabilities) Scheme

func (c Capabilities) Scheme(name string) (SchemeInfo, bool)

Scheme returns the declared security scheme with the given card key.

func (Capabilities) SupportsBinding

func (c Capabilities) SupportsBinding(b a2a.ProtocolBinding) bool

SupportsBinding reports whether the card exposes an interface for a binding.

type CardAwareCredentialSource

type CardAwareCredentialSource interface {
	CredentialSource
	// UseCard configures the source from the remote's Agent Card. It is called
	// at most once per resolved card.
	UseCard(ctx context.Context, card *a2a.AgentCard) error
}

CardAwareCredentialSource is an optional interface a CredentialSource may implement to be told which security schemes the remote declares.

It exists because the card is where the parameters of a scheme live: the token endpoint and scopes of an OAuth2 flow, the header name and location of an API key, the discovery URL of an OpenID Connect provider. A source that implements it is handed the card exactly once, after resolution and before the first request that uses it, so it can configure itself from the remote's own declaration instead of duplicating it in local config.

UseCard returning an error aborts the call: a source that cannot satisfy any scheme the remote accepts has nothing useful to do afterwards, and failing at resolution is a clearer diagnosis than a 401 on every subsequent request.

A client configured with an explicit endpoint never resolves a card, so a source that depends on UseCard must be given one with WithCard.

type CardError

type CardError struct {
	// URL is the card URL that was fetched.
	URL string
	// StatusCode is the HTTP status, or zero when the request never completed.
	StatusCode int
	// Stage names what failed: "fetch", "status", "decode" or "validate".
	Stage string
	// Err is the underlying cause. For "validate" it is the *a2a.Error the
	// codec's validator produced.
	Err error
}

CardError reports a failure to obtain a usable Agent Card: a transport failure, an HTTP error status, a body that will not decode, or a card that decodes but does not satisfy the specification's required fields.

func (*CardError) Error

func (e *CardError) Error() string

func (*CardError) Unwrap

func (e *CardError) Unwrap() error

Unwrap exposes the underlying cause to errors.Is and errors.As.

type Client

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

Client talks A2A to one remote agent. It is safe for concurrent use; the resolved Agent Card is fetched once and shared.

Construct one with New. The zero value is not usable.

func New

func New(baseURL string, opts ...Option) (*Client, error)

New builds a Client for the remote agent published at baseURL. The base URL is the ORIGIN (and optional path prefix) the agent is served under, not an operation endpoint: the Agent Card is fetched from AgentCardPath beneath it and names the per-binding endpoints.

The base URL may be empty only when an endpoint is pinned with WithJSONRPCEndpoint or WithRESTEndpoint, since discovery is then unnecessary.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the configured base URL, empty when only an endpoint was pinned.

func (*Client) Binding

func (c *Client) Binding() a2a.ProtocolBinding

Binding returns the protocol binding this client speaks.

func (*Client) CancelTask

func (c *Client) CancelTask(ctx context.Context, req a2a.CancelTaskRequest) (*a2a.Task, error)

CancelTask asks the remote to cancel a task and returns the task as it stands afterwards. A task already in a terminal state answers with TaskNotCancelableError, which arrives as an *a2a.Error.

It is NOT retried on a transport failure: a cancel that was delivered and whose response was lost has already happened, and re-sending it would race a task that has since moved on. A 429 or 503 is retried, since those say the request was not processed.

func (*Client) Capabilities

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

Capabilities resolves the card and summarizes it.

func (*Client) Card

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

Card returns the remote's Agent Card, fetching it on first use and caching it for the life of the client. A card supplied with WithCard is returned as-is and never fetched.

It is the discovery entry point: nothing else in this package needs to be called first, and every operation resolves the card implicitly if it has to.

func (*Client) CardURL

func (c *Client) CardURL() string

CardURL returns the well-known Agent Card URL for the configured base.

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, req a2a.GetTaskRequest) (*a2a.Task, error)

GetTask reads a task back from the remote. It is idempotent and is retried per the client's RetryPolicy.

func (*Client) Run

Run sends a streaming message and drains it to completion, returning the accumulated result. It is the convenience form for a caller that wants the outcome rather than the incremental frames; the result is returned even when the stream failed part way, alongside the error.

func (*Client) SendMessage

SendMessage sends a message and waits for the single response the remote answers with: the task tracking the work, or a direct message reply for an interaction that needed no task.

The call BLOCKS for the duration of the remote's work unless the request sets Configuration.ReturnImmediately (specification section 3.2.2). Its deadline is therefore the caller's context plus WithMessageTimeout, which defaults to no client-imposed bound; WithRequestTimeout deliberately does not apply.

A message carrying a TaskID and ContextID resumes an existing task; see ResumeRequest.

func (*Client) SendStreamingMessage

func (c *Client) SendStreamingMessage(ctx context.Context, req a2a.SendMessageRequest) (*Stream, error)

SendStreamingMessage sends a message and returns the live stream of frames the remote answers with.

It refuses before sending anything if the remote's Agent Card declares capabilities.streaming = false, since the specification's answer to a streaming call on a non-streaming agent is a refusal and discovering that locally is faster and clearer than discovering it over the wire.

A message carrying a TaskID and ContextID resumes an existing task on a fresh stream; see ResumeRequest.

func (*Client) SubscribeToTask

func (c *Client) SubscribeToTask(ctx context.Context, req a2a.SubscribeToTaskRequest) (*Stream, error)

SubscribeToTask reattaches to a task already in flight and streams its remaining frames. The stream opens with a Task snapshot in whatever state the task currently holds, which is why the reader does not apply the transition table to an opening frame.

type CredentialFunc

type CredentialFunc func(ctx context.Context, req *http.Request) error

CredentialFunc adapts a plain function to CredentialSource.

func (CredentialFunc) Apply

func (f CredentialFunc) Apply(ctx context.Context, req *http.Request) error

Apply implements CredentialSource.

type CredentialSource

type CredentialSource interface {
	// Apply attaches credentials to an outgoing request. Returning an error
	// aborts the call without sending it.
	Apply(ctx context.Context, req *http.Request) error
}

CredentialSource supplies the credentials for outbound A2A requests.

It is an interface rather than a token string because A2A's security schemes are not one shape: an API key rides in a header, a query parameter or a cookie; a bearer token expires and must be refreshed; an OAuth2 client credentials grant needs a token endpoint and a scope set. All of them come down to "mutate this request before it is sent, possibly doing work first", which is what Apply is.

Apply is called once per HTTP attempt, including each retry, so a source that refreshes an expired token does so at the last possible moment and a retry after a 401 carries a fresh credential. Implementations must be safe for concurrent use: one client may have several calls in flight.

A nil source is legal and means "send no credentials", which is the correct configuration for an open endpoint such as a loopback development agent.

Transport-level schemes — mutual TLS in particular — are not expressible as a request mutation. Those are configured by supplying a pre-built *http.Client with the right TLS configuration through WithHTTPClient, and a source that needs both implements CardAwareCredentialSource to read the card's mtls scheme and Apply to add whatever header accompanies it.

type HTTPError

type HTTPError struct {
	// StatusCode is the HTTP status.
	StatusCode int
	// Status is the HTTP status line.
	Status string
	// URL is the request URL.
	URL string
	// ContentType is the response Content-Type, which is usually the tell.
	ContentType string
	// Body is a bounded snippet of the response body.
	Body string
}

HTTPError reports a non-2xx HTTP response that carried no decodable A2A error body. A response that DOES carry one is returned as the *a2a.Error instead, so this type means "something in front of the agent answered", which is exactly the case an operator needs to see the raw body for.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type NoCredentials

type NoCredentials struct{}

NoCredentials is a CredentialSource that sends nothing. It is what a client with no configured source uses, and exists so that "open endpoint" is a value a caller can pass explicitly rather than a nil it has to reason about.

func (NoCredentials) Apply

Apply implements CredentialSource and does nothing.

type Option

type Option func(*Client)

Option configures a Client.

func WithBinding

func WithBinding(b a2a.ProtocolBinding) Option

WithBinding selects the protocol binding. a2a.BindingJSONRPC is the default; a2a.BindingHTTPJSON selects the REST binding. Any other value is rejected by New, since this package implements only the two HTTP bindings.

func WithCard

func WithCard(card *a2a.AgentCard) Option

WithCard supplies a pre-obtained Agent Card, skipping the well-known fetch. Specification section 8.2 sanctions distributing a card out of band ("Direct Configuration") for an agent that does not publish one.

func WithCardValidation

func WithCardValidation(enabled bool) Option

WithCardValidation controls whether a fetched card is checked against the specification's required fields. It is on by default: a card that omits them is a remote this client cannot reason about, and failing at discovery is a better diagnosis than a confusing failure three calls later. Turn it off to interoperate with a remote whose card is usable but not strictly conformant.

func WithCredentials

func WithCredentials(src CredentialSource) Option

WithCredentials sets the credential source applied to every request. A nil source means no credentials, which is correct for an open endpoint.

func WithExtensions

func WithExtensions(uris ...string) Option

WithExtensions declares the A2A protocol extension URIs this client understands, sent as the A2A-Extensions service parameter. A server activates only the extensions a client asked for.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient overrides the underlying *http.Client. This is also how mutual TLS is configured: supply a client whose Transport carries the client certificate.

A Timeout set on the supplied client applies to streaming calls too and will truncate a long-running stream. Leave it zero and use WithRequestTimeout, which this package applies per call and only where it is safe.

func WithJSONRPCEndpoint

func WithJSONRPCEndpoint(endpoint string) Option

WithJSONRPCEndpoint pins the JSON-RPC endpoint URL, skipping Agent Card discovery for it. Use it when the endpoint is known out of band.

func WithMessageTimeout

func WithMessageTimeout(d time.Duration) Option

WithMessageTimeout bounds a non-streaming SendMessage. It defaults to zero — no client-imposed deadline — because a blocking SendMessage legitimately takes as long as the remote's work does, and a package-level guess at that duration would abort correct calls. Set it when the caller knows the bound.

func WithRESTEndpoint

func WithRESTEndpoint(endpoint string) Option

WithRESTEndpoint pins the HTTP+JSON base URL — the prefix the operation paths hang off, not a single operation URL — skipping Agent Card discovery for it.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) Option

WithRequestTimeout bounds a control-plane call: GetTask and CancelTask. It does NOT bound SendMessage, which blocks for the duration of the remote's work by design (specification section 3.2.2) and is bounded by WithMessageTimeout instead. Zero disables it, leaving the caller's context as the only deadline.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) Option

WithRetryPolicy overrides the retry policy. See RetryPolicy for what is retried and why it differs between reads and message sends.

func WithStreamIdleTimeout

func WithStreamIdleTimeout(d time.Duration) Option

WithStreamIdleTimeout bounds total silence on an open stream. Zero disables it.

Silence is measured in BYTES READ, not frames decoded. That distinction is the whole reason a non-zero default is safe: A2A's keep-alive mechanism is an SSE comment record, which carries no frame, and a client that reset its idle clock only on frames would kill exactly the parked INPUT_REQUIRED stream the comments exist to hold open. Counting bytes means any sign of life counts, and only a genuinely dead connection trips the timeout.

func WithStreamOpenTimeout

func WithStreamOpenTimeout(d time.Duration) Option

WithStreamOpenTimeout bounds the wait for a streaming call's response headers. Zero disables it.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the User-Agent header.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the total number of attempts including the first. Values
	// below 2 disable retrying.
	MaxAttempts int
	// BaseDelay is the delay before the second attempt.
	BaseDelay time.Duration
	// MaxDelay caps the computed backoff. A Retry-After longer than this is
	// still honored in full — the server's instruction is not a suggestion.
	MaxDelay time.Duration
}

RetryPolicy governs re-attempts of a failed HTTP call.

What is retried, and why the answer depends on the operation

A2A operations are not uniformly safe to repeat. GetTask and ListTasks are reads: repeating one costs a round trip and nothing else. SendMessage and CancelTask are not reads — a SendMessage that reached the agent and then lost its response would, on a blind retry, run the agent's work twice and put two messages in the task history. A2A defines no idempotency key, so the client cannot make that safe; it can only decline to make it unsafe.

The policy therefore splits by what the failure proves:

  • A TRANSPORT failure (connection refused, reset, TLS failure) proves nothing about whether the server processed the request. It is retried for reads only.
  • HTTP 429 and 503 are the two statuses that say, by definition, that the server did NOT process the request — it is rate-limiting or unavailable. Those are retried for every operation, honoring Retry-After.
  • HTTP 502 and 504 mean an intermediary gave up, which does not prove the origin did not process the request. Those are retried for reads only.
  • Every other status is an answer, not a failure of delivery, and is never retried. A 500 from the agent is the agent's answer.

Backoff is exponential from BaseDelay, doubling, capped at MaxDelay, with no jitter: a single client's retries do not need decorrelating, and a deterministic schedule is one a test can assert. A Retry-After header always wins over the computed delay.

The retry loop covers establishing a stream (the request and its response headers) but never a stream already in progress: replaying a partially consumed stream would duplicate frames a caller has already acted on.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy is the policy a client uses when none is configured.

func NoRetry

func NoRetry() RetryPolicy

NoRetry is a policy that attempts each call exactly once.

type SchemeInfo

type SchemeInfo struct {
	// Name is the card's key for this scheme.
	Name string
	// Kind is the scheme arm that is set.
	Kind a2a.SecuritySchemeKind
	// Scheme is the full declaration.
	Scheme a2a.SecurityScheme
}

SchemeInfo is one security scheme a remote declares, flattened to the two facts a caller needs before it can choose a credential: the name the card keys it under (which is what a security requirement references) and which kind of scheme it is. The full declaration is carried along for a credential source that needs the flow parameters.

type Stream

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

Stream is a live A2A streaming call: SendStreamingMessage or SubscribeToTask. It hands the caller each decoded frame as it arrives while accumulating the whole exchange into a StreamResult.

Lifecycle

Range over Frames() until it closes. It closes when the remote reaches a terminal task state, when the remote closes the connection, when a frame fails to decode or violates the stream contract, when the idle timeout fires, or when the caller cancels the context or calls Close.

After Frames() is drained, Result() carries everything observed and Err() carries the terminal error — nil for a stream that reached a terminal state cleanly. Both are safe to call at any time (they are mutex-guarded) but are only COMPLETE once the channel has closed.

Close is idempotent, safe to call concurrently with draining, and is what releases the underlying HTTP response. A caller that abandons a stream early must call it; a caller that drains to the end need not, though calling it is harmless. Nothing outlives it: the reader goroutine and the idle watchdog both exit before the underlying body is done being read.

func (*Stream) Close

func (s *Stream) Close() error

Close abandons the stream, releasing the HTTP response and unblocking the reader. It is idempotent and safe to call concurrently with draining Frames().

func (*Stream) Err

func (s *Stream) Err() error

Err returns the stream's terminal error, or nil when it reached a terminal task state cleanly. It is meaningful once Frames() has closed. Every non-nil value is a *StreamError.

func (*Stream) Frames

func (s *Stream) Frames() <-chan a2a.StreamResponse

Frames returns the channel of decoded stream frames. It is closed when the stream terminates for any reason.

func (*Stream) Result

func (s *Stream) Result() StreamResult

Result returns everything observed so far: the frames in order, the task and context identity, the latest status, and the reassembled artifacts. It is complete once Frames() has closed, and is populated even when Err() is non-nil, so a caller can see how far a failing stream got.

type StreamError

type StreamError struct {
	// Reason classifies the failure.
	Reason StreamReason
	// Operation is the A2A operation whose stream failed.
	Operation string
	// Detail explains the failure in operator-readable terms.
	Detail string
	// Frames is how many frames were successfully decoded before the failure.
	Frames int
	// Err is the underlying cause, nil when there is none beyond Detail.
	Err error
}

StreamError reports a stream that did not run to a clean terminal state. It wraps the underlying cause, so errors.As still recovers an *a2a.Error for a protocol violation the codec's reader detected and context.Canceled for a cancellation.

func (*StreamError) Error

func (e *StreamError) Error() string

func (*StreamError) Unwrap

func (e *StreamError) Unwrap() error

Unwrap exposes the underlying cause to errors.Is and errors.As.

type StreamReason

type StreamReason string

StreamReason classifies why a stream failed.

const (
	// StreamReasonNotSSE means the response was not a text/event-stream body:
	// an HTTP error where a stream was promised, or a 200 with the wrong
	// content type.
	StreamReasonNotSSE StreamReason = "not_sse"
	// StreamReasonMalformed means a record could not be decoded into a frame.
	StreamReasonMalformed StreamReason = "malformed"
	// StreamReasonProtocol means a decoded frame violated the A2A stream
	// contract: an illegal opening frame, an update naming a different task or
	// context, an illegal task state transition, or a frame after a terminal
	// state.
	StreamReasonProtocol StreamReason = "protocol"
	// StreamReasonTruncated means the remote closed the stream before any frame
	// reported a terminal state and without parking the task in an interrupted
	// state. The frames decoded before the close are retained in the result.
	StreamReasonTruncated StreamReason = "truncated"
	// StreamReasonRemoteError means the remote deliberately framed a protocol
	// error onto the stream and ended it — an authentication failure, a version
	// mismatch, an unknown task. The wrapped cause is the *a2a.Error.
	StreamReasonRemoteError StreamReason = "remote_error"
	// StreamReasonOpenTimeout means the remote sent no response headers within
	// the configured stream-open timeout.
	StreamReasonOpenTimeout StreamReason = "open_timeout"
	// StreamReasonIdle means no bytes arrived for longer than the configured
	// idle timeout.
	StreamReasonIdle StreamReason = "idle"
	// StreamReasonCanceled means the caller's context was cancelled or the
	// stream was closed by the caller before it terminated.
	StreamReasonCanceled StreamReason = "canceled"
	// StreamReasonTransport means the connection failed mid-stream.
	StreamReasonTransport StreamReason = "transport"
)

Stream failure reasons.

type StreamResult

type StreamResult struct {
	// Operation is the A2A operation that produced the stream.
	Operation string
	// Header is the streaming response's header set, which carries the
	// A2A-Version the remote answered with and the extensions it activated.
	Header http.Header

	// Frames is every decoded frame, in arrival order.
	Frames []a2a.StreamResponse

	// TaskID and ContextID are the identity the stream opened on. TaskID is
	// empty for a message-only stream, which has no task.
	TaskID    string
	ContextID string

	// Task is the opening Task snapshot, nil for a message-only stream.
	Task *a2a.Task
	// Status is the latest status observed, from the opening snapshot or the
	// most recent status update.
	Status *a2a.TaskStatus
	// State is the latest task state observed.
	State a2a.TaskState
	// Message is the direct agent reply for a message-only stream, nil
	// otherwise.
	Message *a2a.Message

	// Artifacts are the task's outputs, reassembled from their chunks in first
	// appearance order.
	Artifacts []a2a.Artifact

	// Terminal reports whether the stream reached a terminal task state or a
	// direct message reply, as opposed to ending early.
	Terminal bool
}

StreamResult is the accumulated outcome of a streaming call: every frame in order, plus the derived view a caller actually wants — who the task is, what state it ended in, and what it produced.

The derived view exists because the frame sequence alone is not the answer. A task's output arrives as artifact frames that may be CHUNKED: several frames carrying the same artifactId, the later ones with append set, the last with lastChunk. Reassembling them is the client's job (specification section 11.7) and doing it once here is better than every caller doing it differently.

func (StreamResult) ActivatedExtensions

func (r StreamResult) ActivatedExtensions() []string

ActivatedExtensions returns the extension URIs the remote echoed in the response's A2A-Extensions header, which is how a server states which of the requested extensions it actually activated (specification section 3.5).

func (StreamResult) ArtifactText

func (r StreamResult) ArtifactText() string

ArtifactText concatenates the text parts of every reassembled artifact, in order, separated by newlines. It is the convenience for the common case where a remote agent's answer is prose; a caller needing files or structured data walks Artifacts itself.

func (StreamResult) Failed

func (r StreamResult) Failed() bool

Failed reports whether the task ended in FAILED or REJECTED. Both are terminal and both mean the work did not happen, so a caller that only wants to know "did this succeed" checks this rather than enumerating states.

func (StreamResult) Interrupt

func (r StreamResult) Interrupt() (*a2a.Message, bool)

Interrupt returns the agent's question and true when the stream ended parked in an interrupted state — INPUT_REQUIRED or AUTH_REQUIRED. It is the anchor for the resume path: hand the returned message to a human (or an authenticator), then send the answer with ResumeRequest.

The message may be nil even when the bool is true: a remote is not obliged to attach one, though a useful one does.

func (StreamResult) ResumeRequest

func (r StreamResult) ResumeRequest(messageID string, parts ...a2a.Part) (a2a.SendMessageRequest, bool)

ResumeRequest builds the continuation for an interrupted stream result, carrying the task and context identity the stream established. The second return is false when the result is not resumable — it never reached a task, or it ended in a terminal state rather than an interruption — so a caller cannot accidentally address a continuation at a task that is finished.

func (StreamResult) StatusText

func (r StreamResult) StatusText() string

StatusText returns the text of the message attached to the latest status, empty when there is none. An INPUT_REQUIRED question and a FAILED explanation both travel this way.

func (StreamResult) Succeeded

func (r StreamResult) Succeeded() bool

Succeeded reports whether the task ended in COMPLETED.

Jump to

Keyboard shortcuts

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