Documentation
¶
Overview ¶
Package a2a implements the client side of the Agent-to-Agent (A2A) protocol.
It provides the protocol types, a JSON-RPC Client for discovering and calling agents, an Executor that exposes A2A skills as tools, and a ToolBridge that builds tool descriptors from an agent card. The package speaks A2A 1.0 and 0.3: the types marshal as 1.0 and unmarshal either version's JSON, and ProtocolVersion produces the wire shape for a given peer.
Types are derived from the A2A protocol specification (a2a.proto) and use camelCase JSON tags matching the JSON-RPC binding convention.
Index ¶
- Constants
- Variables
- func ExtractResponseParts(task *Task) []types.ContentPart
- func ExtractResponseText(task *Task) string
- func InferContentType(mediaType string) string
- func IsJSONRPCBinding(binding string) bool
- func LookupMethod(method string) (op Operation, v ProtocolVersion, ok bool)
- func MessageToMessage(msg *Message) (*types.Message, error)
- func PartToContentPart(part *Part) (types.ContentPart, error)
- func ReadSSE(ctx context.Context, r io.Reader, ch chan<- StreamEvent)
- func ReadSSEWithIdleTimeout(ctx context.Context, r io.Reader, ch chan<- StreamEvent, ...)
- func ReadServerRequest(r *http.Request) (*ServerRequest, *JSONRPCResponse)
- type APIKeySecurityScheme
- type AgentCapabilities
- type AgentCard
- type AgentCardSignature
- type AgentExtension
- type AgentInterface
- type AgentProvider
- type AgentSkill
- type Artifact
- type AuthenticationInfo
- type CancelTaskRequest
- type Client
- func (c *Client) CancelTask(ctx context.Context, taskID string) error
- func (c *Client) Discover(ctx context.Context) (*AgentCard, error)
- func (c *Client) GetExtendedAgentCard(ctx context.Context) (*AgentCard, error)
- func (c *Client) GetTask(ctx context.Context, taskID string) (*Task, error)
- func (c *Client) ListTasks(ctx context.Context, params *ListTasksRequest) ([]*Task, error)
- func (c *Client) ListTasksPage(ctx context.Context, params *ListTasksRequest) (*ListTasksResponse, error)
- func (c *Client) ProtocolVersion() ProtocolVersion
- func (c *Client) SendMessage(ctx context.Context, params *SendMessageRequest) (*Task, error)
- func (c *Client) SendMessageStream(ctx context.Context, params *SendMessageRequest) (<-chan StreamEvent, error)
- func (c *Client) SubscribeToTask(ctx context.Context, taskID string) (<-chan StreamEvent, error)
- func (c *Client) WaitForTask(ctx context.Context, task *Task) (*Task, error)
- type ClientOption
- func WithAuth(scheme, token string) ClientOption
- func WithHTTPClient(hc *http.Client) ClientOption
- func WithHeaders(headers map[string]string) ClientOption
- func WithProtocolVersion(v ProtocolVersion) ClientOption
- func WithRequestTimeout(d time.Duration) ClientOption
- func WithSSEIdleTimeout(d time.Duration) ClientOption
- type Executor
- func (e *Executor) Close() error
- func (e *Executor) Execute(ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage) (json.RawMessage, error)
- func (e *Executor) ExecuteMultimodal(ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage) (json.RawMessage, []types.ContentPart, error)
- func (e *Executor) Name() string
- type ExecutorOption
- type GetTaskRequest
- type HTTPAuthSecurityScheme
- type HTTPStatusError
- type JSONRPCError
- type JSONRPCRequest
- type JSONRPCResponse
- type ListTasksRequest
- type ListTasksResponse
- type Message
- type MutualTLSSecurityScheme
- type OAuth2SecurityScheme
- type OAuthFlow
- type OAuthFlows
- type OpenIDConnectSecurityScheme
- type Operation
- type Part
- type ProtocolVersion
- func (v ProtocolVersion) Method(op Operation) string
- func (v ProtocolVersion) WireAgentCard(card *AgentCard) any
- func (v ProtocolVersion) WireSendParams(req *SendMessageRequest) any
- func (v ProtocolVersion) WireSendResult(task *Task) any
- func (v ProtocolVersion) WireStreamEvent(event any) (any, error)
- func (v ProtocolVersion) WireTask(task *Task) any
- type RPCError
- type RetryPolicy
- type Role
- type SecurityRequirement
- type SecurityScheme
- type SendMessageConfiguration
- type SendMessageRequest
- type SendMessageResponse
- type ServerRequest
- type StreamEvent
- type StreamResponse
- type SubscribeTaskRequest
- type Task
- type TaskArtifactUpdateEvent
- type TaskPushNotificationConfig
- type TaskState
- type TaskStatus
- type TaskStatusUpdateEvent
- type ToolBridge
Examples ¶
Constants ¶
const ( AgentCardPath = "/.well-known/agent-card.json" LegacyAgentCardPath = "/.well-known/agent.json" )
Agent card discovery paths. A2A 0.3 (§5.3) and 1.0 (§8.2) serve the card at AgentCardPath; 0.2 and earlier servers used LegacyAgentCardPath.
const ( DefaultA2AMaxRetries = 3 DefaultA2AInitialDelay = 500 * time.Millisecond DefaultA2AMaxDelay = 30 * time.Second // DefaultClientTTL is the default time-to-live for cached A2A clients. // Clients not used within this duration are evicted from the cache. DefaultClientTTL = 30 * time.Minute // DefaultMaxClients is the default maximum number of cached A2A clients. // When exceeded, the least recently used client is evicted. DefaultMaxClients = 100 )
Default retry constants for A2A executor.
const ( MethodV1SendMessage = "SendMessage" MethodV1SendStreamingMessage = "SendStreamingMessage" MethodV1GetTask = "GetTask" MethodV1CancelTask = "CancelTask" MethodV1ListTasks = "ListTasks" MethodV1SubscribeToTask = "SubscribeToTask" MethodV1GetExtendedAgentCard = "GetExtendedAgentCard" MethodV1CreateTaskPushNotificationConfig = "CreateTaskPushNotificationConfig" MethodV1GetTaskPushNotificationConfig = "GetTaskPushNotificationConfig" MethodV1ListTaskPushNotificationConfigs = "ListTaskPushNotificationConfigs" MethodV1DeleteTaskPushNotificationConfig = "DeleteTaskPushNotificationConfig" )
A2A 1.0 JSON-RPC method names (A2A 1.0 §5.3).
const ( MethodSendMessage = "message/send" MethodSendStreamingMessage = "message/stream" MethodGetTask = "tasks/get" MethodCancelTask = "tasks/cancel" MethodListTasks = "tasks/list" MethodTaskSubscribe = "tasks/subscribe" )
The method names PromptKit used before it spoke A2A 1.0 and 0.3 by version. They keep their values: a server still answers every one of them, and code comparing against them keeps working.
Deprecated: use the MethodV1* names for A2A 1.0 and MethodV03* for 0.3, or resolve a method with LookupMethod.
const ( MethodV03SendMessage = "message/send" MethodV03SendStreamingMessage = "message/stream" MethodV03GetTask = "tasks/get" MethodV03CancelTask = "tasks/cancel" MethodV03Resubscribe = "tasks/resubscribe" MethodV03GetExtendedCard = "agent/getAuthenticatedExtendedCard" MethodV03SetPushNotificationConfig = "tasks/pushNotificationConfig/set" MethodV03GetPushNotificationConfig = "tasks/pushNotificationConfig/get" MethodV03ListPushNotificationConfig = "tasks/pushNotificationConfig/list" MethodV03DeletePushNotificationConfig = "tasks/pushNotificationConfig/delete" // MethodLegacyListTasks and MethodLegacySubscribe are the names PromptKit // servers before A2A 1.0 conformance answered to; they are in neither // 0.3 nor 1.0 and are accepted only so older PromptKit clients keep // working. MethodLegacyListTasks = MethodListTasks MethodLegacySubscribe = MethodTaskSubscribe )
A2A 0.3 JSON-RPC method names. A 0.3 server knows only these.
const ( ErrCodeTaskNotFound = -32001 ErrCodeTaskNotCancelable = -32002 ErrCodePushNotificationNotSupported = -32003 ErrCodeUnsupportedOperation = -32004 ErrCodeContentTypeNotSupported = -32005 ErrCodeInvalidAgentResponse = -32006 ErrCodeExtendedAgentCardNotConfigured = -32007 ErrCodeExtensionSupportRequired = -32008 ErrCodeVersionNotSupported = -32009 )
A2A-specific JSON-RPC error codes (A2A 1.0 §5.4, identical in 0.3).
const ( ErrCodeParse = -32700 ErrCodeInvalidRequest = -32600 ErrCodeMethodNotFound = -32601 ErrCodeInvalidParams = -32602 ErrCodeInternal = -32603 )
Standard JSON-RPC 2.0 error codes.
const ( // DefaultSSEIdleTimeout is the default idle timeout for SSE streams. // If no line is received within this duration, reading stops so callers // can reconnect. DefaultSSEIdleTimeout = 5 * time.Minute )
HTTP client defaults for A2A communication.
const HeaderVersion = "A2A-Version"
HeaderVersion is the service parameter carrying the protocol version a request speaks. A request without it is 0.3 (A2A 1.0 §3.6.2).
const ProtocolBindingJSONRPC = "JSONRPC"
ProtocolBindingJSONRPC is the AgentInterface binding name of the JSON-RPC transport (0.3 calls the same field "transport").
Variables ¶
var ErrContentTypeNotSupported = errors.New("a2a: content type not supported")
ErrContentTypeNotSupported is wrapped by the errors PartToContentPart and MessageToMessage return for content whose media type cannot be determined, or is application/octet-stream, which names none. A server answers it with ContentTypeNotSupportedError (ErrCodeContentTypeNotSupported).
var ErrSSEIdleTimeout = fmt.Errorf("a2a: SSE idle timeout exceeded")
ErrSSEIdleTimeout is the StreamEvent.Error of the last event on an SSE stream that received nothing within the idle timeout. Test for it with errors.Is.
var ErrUnknownTaskState = errors.New("a2a: task is in a state the client does not know")
ErrUnknownTaskState is the error WaitForTask returns for a task in a state the client does not know (TaskStateUnknown): one a later protocol version defines, or 1.0's TASK_STATE_UNSPECIFIED. Nothing says such a task will ever finish, so the wait stops. Test for it with errors.Is.
Functions ¶
func ExtractResponseParts ¶
func ExtractResponseParts(task *Task) []types.ContentPart
ExtractResponseParts converts all A2A Parts from a completed task into PromptKit ContentParts. It collects parts from the status message (if present) and then all artifacts. Parts that fail conversion, such as structured data, are skipped.
func ExtractResponseText ¶
ExtractResponseText extracts text from a completed A2A task. It returns the first text part of the status message; if there is none, the text parts of all artifacts joined with newlines. It returns "" when the task has no text.
func InferContentType ¶
InferContentType maps a MIME type to a PromptKit content type string: image, audio or video for the matching "image/", "audio/" or "video/" prefix, and document for everything else.
func IsJSONRPCBinding ¶ added in v2.11.0
IsJSONRPCBinding reports whether binding names the JSON-RPC transport: ProtocolBindingJSONRPC in any case, or one of the names PromptKit used for it before A2A 1.0 (jsonrpc+http, json-rpc, jsonrpc2).
func LookupMethod ¶ added in v2.8.0
func LookupMethod(method string) (op Operation, v ProtocolVersion, ok bool)
LookupMethod resolves a JSON-RPC method name to its operation and the version that names it that way. ok is false for an unknown method.
func MessageToMessage ¶
MessageToMessage converts an A2A Message to a PromptKit Message. The "agent" role becomes "assistant"; any other role is copied unchanged. Metadata becomes Meta. Parts are converted with PartToContentPart, except that a data part becomes a text part holding the value's JSON. Content is set from the text parts. It returns an error naming the first part that fails to convert; content of a type that cannot be determined wraps ErrContentTypeNotSupported.
Example ¶
ExampleMessageToMessage shows converting an A2A protocol Message into PromptKit's internal types.Message. It is a pure conversion: it needs no network call and no running A2A server. The "agent" role maps to PromptKit's "assistant" role.
package main
import (
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/a2a"
)
func main() {
text := "hello from agent"
msg := &a2a.Message{
MessageID: "m1",
Role: a2a.RoleAgent,
Parts: []a2a.Part{{Text: &text}},
}
out, err := a2a.MessageToMessage(msg)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(out.Role, "->", out.GetContent())
}
Output: assistant -> hello from agent
func PartToContentPart ¶
func PartToContentPart(part *Part) (types.ContentPart, error)
PartToContentPart converts an A2A Part to a PromptKit ContentPart. A text part becomes a text content part. A Raw or URL part becomes a media content part.
Its media type is MediaType when set; A2A makes that field optional, so otherwise it is taken from Filename's extension, then from a data URL's header (text/plain when the header names none, as RFC 2397 says) or the URL path's extension, or from sniffing Raw's bytes. Every media type is reported under the name providers list: lowercase, without parameters, and with aliases such as audio/x-wav and audio/wave given as audio/wav.
A media part whose type none of these name, whose type is application/octet-stream, or whose undeclared text is not UTF-8, returns an error wrapping ErrContentTypeNotSupported. A data URL without a comma, a structured data part, or a part with none of text, raw, a non-empty URL or data, returns an error.
func ReadSSE ¶
func ReadSSE(ctx context.Context, r io.Reader, ch chan<- StreamEvent)
ReadSSE reads SSE events from r and sends parsed StreamEvents to ch. It returns when r ends, ctx is canceled, or an error event is sent, and does not close ch. It has no idle timeout; use ReadSSEWithIdleTimeout for timeout support.
func ReadSSEWithIdleTimeout ¶
func ReadSSEWithIdleTimeout(ctx context.Context, r io.Reader, ch chan<- StreamEvent, idleTimeout time.Duration)
ReadSSEWithIdleTimeout reads SSE events from r and sends parsed StreamEvents to ch. If idleTimeout is positive and no line is received within that duration, it sends a last event whose Error is ErrSSEIdleTimeout and stops reading, so the caller can tell a stall from a clean end and reconnect. A zero or negative idleTimeout disables idle detection. It does not close ch.
func ReadServerRequest ¶ added in v2.22.0
func ReadServerRequest(r *http.Request) (*ServerRequest, *JSONRPCResponse)
ReadServerRequest reads one JSON-RPC request from r's body and checks it as an A2A server must. When the request cannot be served it returns nil and the error response to send, with the request's id when that could be read:
- a body that is not JSON is Parse error (-32700);
- a body that is not a JSON-RPC 2.0 Request object is Invalid Request (-32600): "jsonrpc" not exactly "2.0", a method that is not a non-empty string, an id that is not a string, number or null, or a batch;
- an unknown method is Method not found (-32601);
- an unsupported A2A-Version, or a 1.0 method name in a 0.3 request, is VersionNotSupportedError (-32009), and a 0.3 method name in a 1.0 request is Method not found.
The version is the one A2A-Version names (see RequestVersion); a request that names none is 0.3 (A2A 1.0 §3.6.2). The id is kept as the JSON text it was sent as, so a response echoes it exactly.
Types ¶
type APIKeySecurityScheme ¶ added in v2.8.0
type APIKeySecurityScheme struct {
Description string `json:"description,omitempty"`
// Location is "header", "query" or "cookie".
Location string `json:"location"`
Name string `json:"name"`
}
APIKeySecurityScheme is an API key sent in a header, query parameter or cookie.
type AgentCapabilities ¶
type AgentCapabilities struct {
Streaming bool `json:"streaming,omitempty"`
PushNotifications bool `json:"pushNotifications,omitempty"`
ExtendedAgentCard bool `json:"extendedAgentCard,omitempty"`
Extensions []AgentExtension `json:"extensions,omitempty"`
}
AgentCapabilities describes what the agent supports.
type AgentCard ¶
type AgentCard struct {
Name string `json:"name"`
Description string `json:"description"`
Version string `json:"version"`
Provider *AgentProvider `json:"provider,omitempty"`
Capabilities AgentCapabilities `json:"capabilities"`
Skills []AgentSkill `json:"skills"`
DefaultInputModes []string `json:"defaultInputModes"`
DefaultOutputModes []string `json:"defaultOutputModes"`
SupportedInterfaces []AgentInterface `json:"supportedInterfaces"`
IconURL string `json:"iconUrl,omitempty"`
DocumentationURL string `json:"documentationUrl,omitempty"`
// SecuritySchemes declares the authentication schemes the agent accepts,
// keyed by a name SecurityRequirements refer to (A2A 1.0 §7.3).
SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
// SecurityRequirements lists the scheme combinations a caller must
// satisfy; any one requirement suffices.
SecurityRequirements []SecurityRequirement `json:"securityRequirements,omitempty"`
// Signatures are JSON Web Signatures computed over the card (A2A 1.0
// §8.4). PromptKit carries them; it does not compute or verify them.
Signatures []AgentCardSignature `json:"signatures,omitempty"`
}
AgentCard describes an agent's capabilities and endpoints.
A card always encodes the fields A2A 1.0 marks REQUIRED (name, description, supportedInterfaces, version, capabilities, defaultInputModes, defaultOutputModes and skills), as empty values when unset, so a strict client finds every one of them.
func (AgentCard) MarshalJSON ¶ added in v2.22.0
MarshalJSON implements json.Marshaler. The REQUIRED lists encode as [] when unset rather than null, which a strict 1.0 client rejects.
func (*AgentCard) PreferredVersion ¶ added in v2.8.0
func (card *AgentCard) PreferredVersion() ProtocolVersion
PreferredVersion picks the protocol version to speak to the agent that published card: 1.0 when any JSON-RPC interface declares it, or when the card declares no interfaces or none that use JSON-RPC; otherwise 0.3.
func (*AgentCard) UnmarshalJSON ¶ added in v2.8.0
UnmarshalJSON implements json.Unmarshaler. A 0.3 card declares its endpoint in url/preferredTransport/additionalInterfaces rather than supportedInterfaces, and its requirements in "security"; both are folded into the 1.0 fields when the card does not carry them itself.
type AgentCardSignature ¶ added in v2.22.0
type AgentCardSignature struct {
// Protected is the base64url-encoded JWS protected header.
Protected string `json:"protected"`
// Signature is the base64url-encoded signature.
Signature string `json:"signature"`
// Header holds the unprotected JWS header values.
Header map[string]any `json:"header,omitempty"`
}
AgentCardSignature is a JWS signature of an AgentCard in RFC 7515 JSON form (A2A 1.0 §8.4.2).
type AgentExtension ¶
type AgentExtension struct {
URI string `json:"uri"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
// Params is the extension's own configuration, passed through as is.
Params map[string]any `json:"params,omitempty"`
}
AgentExtension describes an optional protocol extension.
type AgentInterface ¶
type AgentInterface struct {
URL string `json:"url"`
// ProtocolBinding is the transport: [ProtocolBindingJSONRPC], "GRPC" or
// "HTTP+JSON".
ProtocolBinding string `json:"protocolBinding"`
// ProtocolVersion is the A2A Major.Minor version served at URL.
ProtocolVersion string `json:"protocolVersion"`
Tenant string `json:"tenant,omitempty"`
}
AgentInterface describes a protocol endpoint. URL, ProtocolBinding and ProtocolVersion are REQUIRED in A2A 1.0 and always encoded.
type AgentProvider ¶
AgentProvider identifies the organization behind an agent. Both fields are REQUIRED in A2A 1.0.
type AgentSkill ¶
type AgentSkill struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Tags []string `json:"tags"`
Examples []string `json:"examples,omitempty"`
InputModes []string `json:"inputModes,omitempty"`
OutputModes []string `json:"outputModes,omitempty"`
SecurityRequirements []SecurityRequirement `json:"securityRequirements,omitempty"`
}
AgentSkill describes a specific skill an agent can perform. Description and tags are REQUIRED in A2A 1.0 and always encoded.
func (AgentSkill) MarshalJSON ¶ added in v2.22.0
func (s AgentSkill) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. Tags is REQUIRED and encodes as [] when unset.
func (*AgentSkill) UnmarshalJSON ¶ added in v2.22.0
func (s *AgentSkill) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler. A 0.3 skill declares its requirements in "security"; they are folded into SecurityRequirements when the skill does not carry the 1.0 field itself.
type Artifact ¶
type Artifact struct {
ArtifactID string `json:"artifactId"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Parts []Part `json:"parts"`
Extensions []string `json:"extensions,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Artifact is a named output generated by an agent.
func ContentPartsToArtifacts ¶
func ContentPartsToArtifacts(parts []types.ContentPart) ([]Artifact, error)
ContentPartsToArtifacts converts PromptKit ContentParts into A2A Artifacts. It returns a single Artifact, with ID "artifact-1", containing every part. It returns nil for an empty parts slice and an error if any part fails to convert.
type AuthenticationInfo ¶ added in v2.22.0
type AuthenticationInfo struct {
// Scheme is an HTTP authentication scheme (Bearer, Basic, ...). REQUIRED.
Scheme string `json:"scheme"`
// Credentials are the scheme's credentials, a token for Bearer.
Credentials string `json:"credentials,omitempty"`
}
AuthenticationInfo is how an agent authenticates to a push webhook (A2A 1.0 §4.3.2).
type CancelTaskRequest ¶
CancelTaskRequest is the params for CancelTask (0.3: tasks/cancel).
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client for discovering and calling external A2A agents over JSON-RPC. It speaks A2A 1.0 and falls back to 0.3 when the agent rejects a 1.0 method, unless the version is pinned with WithProtocolVersion or settled by a discovered agent card. Calls go to the JSON-RPC interface the agent card declares on the configured host, or to {base}/a2a when no card is available. A Client is safe for concurrent use.
func NewClient ¶
func NewClient(baseURL string, opts ...ClientOption) *Client
NewClient creates a Client targeting baseURL.
func (*Client) CancelTask ¶
CancelTask cancels a task by ID (CancelTask; 0.3: tasks/cancel).
func (*Client) Discover ¶
Discover fetches the agent card, trying AgentCardPath first and falling back to LegacyAgentCardPath when the agent does not serve it (404/405). The card is cached after the first successful call, and a card that declares a JSON-RPC interface on the client's host also settles the protocol version.
func (*Client) GetExtendedAgentCard ¶ added in v2.22.0
GetExtendedAgentCard fetches the card the agent serves to an authenticated caller (GetExtendedAgentCard; 0.3: agent/getAuthenticatedExtendedCard), using the client's credentials. The returned card replaces the one Discover cached, as A2A 1.0 §3.1.11 recommends, so later calls are routed by it. An agent without one answers UnsupportedOperationError, or ExtendedAgentCardNotConfiguredError when its card declares one it has not configured; both come back as an *RPCError.
func (*Client) ListTasks ¶
ListTasks lists one page of tasks (ListTasks, which A2A 1.0 added; to a 0.3 agent the client sends the legacy PromptKit tasks/list, which only PromptKit servers answer). The server returns at most params.PageSize tasks, or its default page size when that is unset (50 on a 1.0 server); use ListTasksPage to read the next-page token and page through the rest.
func (*Client) ListTasksPage ¶ added in v2.13.0
func (c *Client) ListTasksPage(ctx context.Context, params *ListTasksRequest) (*ListTasksResponse, error)
ListTasksPage lists one page of tasks, like ListTasks, and returns the whole response: NextPageToken (empty on the last page), PageSize and TotalSize. To read the next page, send the same params with PageToken set to NextPageToken.
func (*Client) ProtocolVersion ¶ added in v2.8.0
func (c *Client) ProtocolVersion() ProtocolVersion
ProtocolVersion returns the protocol version the client speaks. It can change from 1.0 to 0.3 on the first call, if the agent rejects 1.0.
func (*Client) SendMessage ¶
SendMessage sends a message (SendMessage; 0.3: message/send) and returns the resulting task. The task may not be finished; see WaitForTask.
An agent that answers with a Message rather than a Task gets a completed task synthesized around it, the message as its status message, so callers have one shape to read.
func (*Client) SendMessageStream ¶
func (c *Client) SendMessageStream(ctx context.Context, params *SendMessageRequest) (<-chan StreamEvent, error)
SendMessageStream sends a streaming message (SendStreamingMessage; 0.3: message/stream) and returns a channel of streaming events. The channel is closed when the stream ends, the context is canceled, or the stream is idle for longer than the SSE idle timeout. An error the agent sends in the stream, and an idle timeout (ErrSSEIdleTimeout), arrive as the last event, with StreamEvent.Error set. An agent that refuses the request before streaming returns an *RPCError from this call.
func (*Client) SubscribeToTask ¶ added in v2.22.0
SubscribeToTask follows a task that is already running (SubscribeToTask; 0.3: tasks/resubscribe), as after a stream dropped or a SendMessage that returned early. The first event is the task as it stands (A2A 1.0 §3.1.6), then its status and artifact updates; the channel closes when the task finishes or needs the caller, and otherwise behaves as SendMessageStream's. A refusal is an *RPCError from this call: TaskNotFoundError for an unknown task, UnsupportedOperationError for a finished one or an agent that does not stream.
func (*Client) WaitForTask ¶ added in v2.8.0
WaitForTask polls task until it finishes or needs the caller (a terminal or interrupted state), and returns it as it then stands. A task that is already there is returned as is. ctx bounds the wait; when it ends, the last state seen is returned with ctx's error. A task in a state the client does not know ends the wait too, returned with an error matching ErrUnknownTaskState.
A SendMessage can come back before its task is done: with returnImmediately, from a 0.3 agent that does not block, or from a server that caps how long it holds a request.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption configures a Client.
func WithAuth ¶
func WithAuth(scheme, token string) ClientOption
WithAuth sets the Authorization header on all requests to "scheme token". An empty token sets no header.
func WithHTTPClient ¶
func WithHTTPClient(hc *http.Client) ClientOption
WithHTTPClient sets the underlying HTTP client.
func WithHeaders ¶
func WithHeaders(headers map[string]string) ClientOption
WithHeaders sets custom headers that are sent on all requests.
func WithProtocolVersion ¶ added in v2.8.0
func WithProtocolVersion(v ProtocolVersion) ClientOption
WithProtocolVersion pins the A2A protocol version the client speaks, disabling negotiation. Without it the client speaks 1.0, or what a discovered agent card prefers, and falls back to 0.3 when the agent rejects a 1.0 method.
func WithRequestTimeout ¶ added in v2.8.0
func WithRequestTimeout(d time.Duration) ClientOption
WithRequestTimeout sets the timeout for non-streaming requests (agent card discovery, SendMessage, GetTask and so on). The default is 60s. It does not affect SSE streams, which use a separate client with a 30-minute limit and the SSE idle timeout. A zero or negative value leaves the default in place.
func WithSSEIdleTimeout ¶
func WithSSEIdleTimeout(d time.Duration) ClientOption
WithSSEIdleTimeout sets the idle timeout for SSE streams; the default is DefaultSSEIdleTimeout. If no line is received within this duration, the stream is considered stale: reading stops, the channel returned by SendMessageStream receives a last event whose Error is ErrSSEIdleTimeout, and the channel is closed, so callers can tell a stall from a finished stream and reconnect. A zero or negative value disables the idle timeout.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor implements tools.Executor and tools.MultimodalExecutor for A2A agent tools. It dispatches tool calls to remote A2A agents via the A2A client.
A call sends the "query" argument, plus any image_url, image_data or audio_data, as a message with returnImmediately set, then polls the task until it finishes. The result is a JSON object with a "response" string. A task that does not complete, whether failed, rejected, canceled or waiting for input, is an error. If the wait ends first, the executor asks the agent to cancel the task. The tool's A2AConfig.TimeoutMs, when positive, bounds the whole call.
The executor keeps a cache of clients keyed by agent URL, with TTL-based and least-recently-used eviction. The first A2AConfig seen for a URL decides the client's auth and headers. Call Close when you are done with the executor to release resources.
func NewExecutor ¶
func NewExecutor(opts ...ExecutorOption) *Executor
NewExecutor creates a new A2A executor with optional configuration. The executor starts a background goroutine for cache cleanup. Call Close when you are done with the executor.
func (*Executor) Close ¶
Close stops the background cleanup goroutine and clears the client cache. Calling it more than once is safe.
func (*Executor) Execute ¶
func (e *Executor) Execute( ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage, ) (json.RawMessage, error)
Execute calls a remote A2A agent with the tool arguments and returns the response.
func (*Executor) ExecuteMultimodal ¶
func (e *Executor) ExecuteMultimodal( ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage, ) (json.RawMessage, []types.ContentPart, error)
ExecuteMultimodal calls a remote A2A agent and returns both JSON result and multimodal content parts. It implements tools.MultimodalExecutor.
type ExecutorOption ¶
type ExecutorOption func(*Executor)
ExecutorOption configures an Executor.
func WithClientTTL ¶
func WithClientTTL(d time.Duration) ExecutorOption
WithClientTTL sets the time-to-live for cached A2A clients. Clients not used within this duration are evicted from the cache.
func WithMaxClients ¶
func WithMaxClients(n int) ExecutorOption
WithMaxClients sets the maximum number of cached A2A clients. When exceeded, the least recently used client is evicted.
func WithNoRetry ¶
func WithNoRetry() ExecutorOption
WithNoRetry disables retry for the A2A executor.
func WithRetryPolicy ¶
func WithRetryPolicy(policy RetryPolicy) ExecutorOption
WithRetryPolicy sets the retry policy for the A2A executor.
type GetTaskRequest ¶
type GetTaskRequest struct {
Tenant string `json:"tenant,omitempty"`
ID string `json:"id"`
HistoryLength *int `json:"historyLength,omitempty"`
}
GetTaskRequest is the params for GetTask (0.3: tasks/get).
type HTTPAuthSecurityScheme ¶ added in v2.8.0
type HTTPAuthSecurityScheme struct {
Description string `json:"description,omitempty"`
Scheme string `json:"scheme"`
BearerFormat string `json:"bearerFormat,omitempty"`
}
HTTPAuthSecurityScheme is an HTTP Authorization scheme such as Bearer.
type HTTPStatusError ¶
HTTPStatusError is returned when an A2A HTTP request receives a non-200 status code. Method is the JSON-RPC method of the failed call. RetryAfter is how long the agent asked the caller to wait before trying again (its Retry-After header), or zero when it did not say.
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
type JSONRPCError ¶
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
JSONRPCError is a JSON-RPC 2.0 error object.
func ErrorFor ¶ added in v2.22.0
func ErrorFor(v ProtocolVersion, code int, message string, metadata map[string]string) *JSONRPCError
ErrorFor builds the JSON-RPC error object a server sends for code, in version v's shape. A 1.0 A2A error (-32001 to -32009) carries a google.rpc.ErrorInfo in data, an array of typed details (A2A 1.0 §9.5), with metadata when there is any; so does VersionNotSupportedError, which only 1.0 defines, whatever version the request was read as. A 0.3 error, whose clients read data as an object, and a standard JSON-RPC error carry no data.
type JSONRPCRequest ¶
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
JSONRPCRequest is a JSON-RPC 2.0 request.
type JSONRPCResponse ¶
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
}
JSONRPCResponse is a JSON-RPC 2.0 response.
type ListTasksRequest ¶
type ListTasksRequest struct {
Tenant string `json:"tenant,omitempty"`
ContextID string `json:"contextId,omitempty"`
Status *TaskState `json:"status,omitempty"`
PageSize int `json:"pageSize,omitempty"`
PageToken string `json:"pageToken,omitempty"`
HistoryLength *int `json:"historyLength,omitempty"`
StatusTimestampAfter *time.Time `json:"statusTimestampAfter,omitempty"`
// IncludeArtifacts asks for each task's artifacts; they are omitted by
// default.
IncludeArtifacts bool `json:"includeArtifacts,omitempty"`
}
ListTasksRequest is the params for ListTasks (1.0 only).
type ListTasksResponse ¶
type ListTasksResponse struct {
Tasks []Task `json:"tasks"`
NextPageToken string `json:"nextPageToken"`
PageSize int `json:"pageSize"`
TotalSize int `json:"totalSize"`
}
ListTasksResponse is the result for ListTasks. NextPageToken is empty on the last page.
type Message ¶
type Message struct {
MessageID string `json:"messageId"`
ContextID string `json:"contextId,omitempty"`
TaskID string `json:"taskId,omitempty"`
Role Role `json:"role"`
Parts []Part `json:"parts"`
ReferenceTaskIDs []string `json:"referenceTaskIds,omitempty"`
Extensions []string `json:"extensions,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Message is a communication unit in the A2A protocol.
type MutualTLSSecurityScheme ¶ added in v2.8.0
type MutualTLSSecurityScheme struct {
Description string `json:"description,omitempty"`
}
MutualTLSSecurityScheme is mutual TLS.
type OAuth2SecurityScheme ¶ added in v2.8.0
type OAuth2SecurityScheme struct {
Description string `json:"description,omitempty"`
Flows OAuthFlows `json:"flows"`
OAuth2MetadataURL string `json:"oauth2MetadataUrl,omitempty"`
}
OAuth2SecurityScheme is OAuth 2.0.
type OAuthFlow ¶ added in v2.8.0
type OAuthFlow struct {
AuthorizationURL string `json:"authorizationUrl,omitempty"`
DeviceAuthorizationURL string `json:"deviceAuthorizationUrl,omitempty"`
TokenURL string `json:"tokenUrl,omitempty"`
RefreshURL string `json:"refreshUrl,omitempty"`
Scopes map[string]string `json:"scopes"`
PKCERequired bool `json:"pkceRequired,omitempty"`
}
OAuthFlow is one OAuth 2.0 flow; which URLs apply depends on the flow.
type OAuthFlows ¶ added in v2.8.0
type OAuthFlows struct {
AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
DeviceCode *OAuthFlow `json:"deviceCode,omitempty"`
Implicit *OAuthFlow `json:"implicit,omitempty"`
Password *OAuthFlow `json:"password,omitempty"`
}
OAuthFlows lists the OAuth 2.0 flows the agent supports.
type OpenIDConnectSecurityScheme ¶ added in v2.8.0
type OpenIDConnectSecurityScheme struct {
Description string `json:"description,omitempty"`
OpenIDConnectURL string `json:"openIdConnectUrl"`
}
OpenIDConnectSecurityScheme is OpenID Connect discovery.
type Operation ¶ added in v2.8.0
type Operation int
Operation is a protocol operation, independent of any version's name for it.
type Part ¶
type Part struct {
Text *string `json:"text,omitempty"`
Raw []byte `json:"raw,omitempty"`
URL *string `json:"url,omitempty"`
Data map[string]any `json:"data,omitempty"`
// DataValue holds a data part whose value is not a JSON object: A2A 1.0
// types data as any JSON value (an array, string, number or boolean as
// well). An object is decoded into Data; anything else into DataValue,
// JSON null as json.RawMessage("null"). When both are set, Data is sent.
DataValue any `json:"-"`
Metadata map[string]any `json:"metadata,omitempty"`
Filename string `json:"filename,omitempty"`
MediaType string `json:"mediaType,omitempty"`
}
Part represents a piece of content within a message or artifact. Exactly one of Text, Raw, URL, or Data (or DataValue) should be set.
func ContentPartToA2APart ¶
func ContentPartToA2APart(part types.ContentPart) (Part, error)
ContentPartToA2APart converts a PromptKit ContentPart to an A2A Part. A text part becomes a text part. A media part becomes a Raw part when it carries base64 data, otherwise a URL part when it carries a URL. Any other part returns an error.
func (Part) MarshalJSON ¶ added in v2.11.0
MarshalJSON implements json.Marshaler. It writes the A2A 1.0 shape, with "data" carrying Data (an empty object included) or DataValue.
func (*Part) UnmarshalJSON ¶ added in v2.8.0
UnmarshalJSON implements json.Unmarshaler. Besides the A2A 1.0 shape it accepts 0.3's kind-tagged parts: {"kind":"text"}, {"kind":"data"} and {"kind":"file","file":{"bytes"|"uri",...}}. A 0.3 data part flagged data_part_compat in its metadata carries a non-object value as {"value": v}; it is unwrapped, and the flag dropped.
type ProtocolVersion ¶ added in v2.8.0
type ProtocolVersion string
ProtocolVersion is an A2A protocol version, as Major.Minor (A2A 1.0 §3.6).
const ( ProtocolVersion10 ProtocolVersion = "1.0" ProtocolVersion03 ProtocolVersion = "0.3" )
Supported protocol versions.
func ParseProtocolVersion ¶ added in v2.8.0
func ParseProtocolVersion(s string) (ProtocolVersion, error)
ParseProtocolVersion resolves an A2A-Version value to a supported version. Patch numbers are ignored, as the spec requires. An empty value returns ("", nil): the caller decides what an unversioned request means.
func RequestVersion ¶ added in v2.22.0
func RequestVersion(r *http.Request) (v ProtocolVersion, named string, err error)
RequestVersion resolves the protocol version a request names in its A2A-Version header or, when no header line names one, its A2A-Version query parameter. A blank value names nothing, and a request that names nothing is 0.3 (A2A 1.0 §3.6.2). named is the value the request named, "" for none. Header lines that name different versions are an error, as is a version the package does not speak.
func (ProtocolVersion) Method ¶ added in v2.8.0
func (v ProtocolVersion) Method(op Operation) string
Method returns version v's JSON-RPC method name for op (1.0's for any version other than 0.3). 0.3 has no ListTasks; the legacy PromptKit name is returned for it. It returns "" for OpPushNotificationConfig, which has several methods, and for OpUnknown.
func (ProtocolVersion) WireAgentCard ¶ added in v2.8.0
func (v ProtocolVersion) WireAgentCard(card *AgentCard) any
WireAgentCard returns card in version v's shape.
For 1.0 the card is returned as is. For 0.3 it is the 0.3 card (url, preferredTransport, protocolVersion, additionalInterfaces, 0.3-style security) with supportedInterfaces kept as well, so a 1.0 client reading the same document still finds its interface. A request that names no version is 0.3.
func (ProtocolVersion) WireSendParams ¶ added in v2.8.0
func (v ProtocolVersion) WireSendParams(req *SendMessageRequest) any
WireSendParams returns SendMessage params in version v's shape (0.3 parts are kind-tagged). The 1.0 shape leaves out Configuration.Blocking, 0.3's switch, which 1.0 does not define: ProtoJSON parsers refuse fields they do not know unless told to discard them. req is not changed.
func (ProtocolVersion) WireSendResult ¶ added in v2.8.0
func (v ProtocolVersion) WireSendResult(task *Task) any
WireSendResult returns the SendMessage result for task in version v's shape: 1.0 wraps it as {"task": ...}, 0.3 sends the kind-tagged task bare.
func (ProtocolVersion) WireStreamEvent ¶ added in v2.8.0
func (v ProtocolVersion) WireStreamEvent(event any) (any, error)
WireStreamEvent returns one streaming result in version v's shape. event is a *Task, *Message, *TaskStatusUpdateEvent or *TaskArtifactUpdateEvent. 1.0 wraps it in a StreamResponse; 0.3 sends it bare with its "kind" and, on a status update, "final" set when the state ends the stream.
func (ProtocolVersion) WireTask ¶ added in v2.8.0
func (v ProtocolVersion) WireTask(task *Task) any
WireTask returns task in version v's shape (the result of GetTask and CancelTask).
type RPCError ¶
type RPCError struct {
Code int
Message string
// Data is the error object's optional data member (A2A 1.0 §9.5: an
// array of detail objects, each with an "@type").
Data any
}
RPCError represents a JSON-RPC error returned by an A2A agent.
type RetryPolicy ¶
type RetryPolicy struct {
// MaxRetries is the number of retries after the first attempt.
MaxRetries int
// InitialDelay is the delay before the first retry. Zero or negative means
// DefaultA2AInitialDelay.
InitialDelay time.Duration
// MaxDelay caps the exponential delay; jitter then shortens it by up to
// 50%, so no delay exceeds MaxDelay. Zero or negative means
// DefaultA2AMaxDelay.
MaxDelay time.Duration
}
RetryPolicy configures retry behavior for the A2A executor. The executor retries only the SendMessage call, on HTTP 429, 502, 503 and 504 and on transient network errors, and waits an exponentially growing delay between attempts, capped at MaxDelay, with random jitter that shortens each delay by up to 50%. No delay exceeds MaxDelay, and delays at the cap still vary. A Retry-After from the agent replaces the delay; one past MaxDelay is not waited, and the call fails at once. A tool's A2AConfig.RetryPolicy is merged onto this policy for that agent, unless MaxRetries is zero.
func DefaultRetryPolicy ¶
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy returns the default retry policy for A2A calls.
type Role ¶
type Role string
Role identifies the sender of a message.
Like TaskState, a Role marshals to its A2A 1.0 name (ROLE_USER) and unmarshals from either version's spelling.
func (Role) MarshalJSON ¶ added in v2.8.0
MarshalJSON implements json.Marshaler, writing the A2A 1.0 name.
func (*Role) UnmarshalJSON ¶ added in v2.8.0
UnmarshalJSON implements json.Unmarshaler, accepting either version's spelling. An unrecognized role is kept verbatim.
type SecurityRequirement ¶ added in v2.8.0
SecurityRequirement names the schemes (and their scopes) a caller must satisfy together. It marshals in the 1.0 shape ({"schemes": {"bearer": {"list": []}}}) and unmarshals from that or 0.3's {"bearer": []}.
func RequireScheme ¶ added in v2.8.0
func RequireScheme(name string, scopes ...string) SecurityRequirement
RequireScheme returns a requirement for a single scheme with optional scopes.
func (SecurityRequirement) MarshalJSON ¶ added in v2.8.0
func (r SecurityRequirement) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler in the A2A 1.0 shape.
func (*SecurityRequirement) UnmarshalJSON ¶ added in v2.8.0
func (r *SecurityRequirement) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for both versions' shapes.
type SecurityScheme ¶ added in v2.8.0
type SecurityScheme struct {
APIKey *APIKeySecurityScheme `json:"apiKeySecurityScheme,omitempty"`
HTTPAuth *HTTPAuthSecurityScheme `json:"httpAuthSecurityScheme,omitempty"`
OAuth2 *OAuth2SecurityScheme `json:"oauth2SecurityScheme,omitempty"`
OpenIDConnect *OpenIDConnectSecurityScheme `json:"openIdConnectSecurityScheme,omitempty"`
MutualTLS *MutualTLSSecurityScheme `json:"mtlsSecurityScheme,omitempty"`
}
SecurityScheme declares one way a caller can authenticate (A2A 1.0 §4.5). Exactly one field is set. It marshals in the 1.0 shape ({"httpAuthSecurityScheme": {...}}) and unmarshals from either that or 0.3's OpenAPI-style {"type": "http", ...}.
func (*SecurityScheme) UnmarshalJSON ¶ added in v2.8.0
func (s *SecurityScheme) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for both versions' shapes.
type SendMessageConfiguration ¶
type SendMessageConfiguration struct {
AcceptedOutputModes []string `json:"acceptedOutputModes,omitempty"`
HistoryLength *int `json:"historyLength,omitempty"`
// Blocking is A2A 0.3's switch.
Blocking bool `json:"blocking,omitempty"`
// ReturnImmediately is A2A 1.0's switch.
ReturnImmediately bool `json:"returnImmediately,omitempty"`
// TaskPushNotificationConfig asks the agent to push the task's updates to
// a webhook (0.3: pushNotificationConfig). Only an agent whose card
// declares capabilities.pushNotifications honors it; a PromptKit server
// does not, and refuses a message that carries one with
// PushNotificationNotSupportedError.
TaskPushNotificationConfig *TaskPushNotificationConfig `json:"taskPushNotificationConfig,omitempty"`
}
SendMessageConfiguration controls message handling.
Blocking and ReturnImmediately are the same switch in two versions: A2A 0.3 sends blocking (default false), 1.0 sends returnImmediately (default false, so 1.0 blocks by default). A server reads the one its caller's version defines; see SendMessageConfiguration.WaitsForCompletion. Both fields survive a json.Marshal round trip; ProtocolVersion.WireSendParams sends each version only its own.
func (*SendMessageConfiguration) UnmarshalJSON ¶ added in v2.22.0
func (c *SendMessageConfiguration) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler. Besides 1.0's taskPushNotificationConfig it accepts 0.3's pushNotificationConfig.
func (*SendMessageConfiguration) WaitsForCompletion ¶ added in v2.8.0
func (c *SendMessageConfiguration) WaitsForCompletion(v ProtocolVersion) bool
WaitsForCompletion reports whether a SendMessage under version v should wait for the task to finish or be interrupted before answering. A nil configuration takes the version's default.
type SendMessageRequest ¶
type SendMessageRequest struct {
Tenant string `json:"tenant,omitempty"`
Message Message `json:"message"`
Configuration *SendMessageConfiguration `json:"configuration,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
SendMessageRequest is the params for SendMessage and SendStreamingMessage (0.3: message/send, message/stream).
type SendMessageResponse ¶ added in v2.8.0
type SendMessageResponse struct {
Task *Task `json:"task,omitempty"`
Message *Message `json:"message,omitempty"`
}
SendMessageResponse is the A2A 1.0 result of SendMessage: exactly one of Task or Message is set. (0.3 returns the Task or Message bare.)
type ServerRequest ¶ added in v2.22.0
type ServerRequest struct {
JSONRPCRequest
// Operation is what Method names, independent of its version.
Operation Operation
// Version is the protocol version to answer in.
Version ProtocolVersion
}
ServerRequest is one JSON-RPC request a server has read and checked: a JSON-RPC 2.0 Request object, for a method the server knows, in a protocol version that has that method.
type StreamEvent ¶
type StreamEvent struct {
Task *Task
Message *Message
StatusUpdate *TaskStatusUpdateEvent
ArtifactUpdate *TaskArtifactUpdateEvent
// Error is set when the stream ends in an error: the agent sent a
// JSON-RPC error (an *RPCError), or the stream went idle
// ([ErrSSEIdleTimeout]). It is the last event on the channel.
Error error
}
StreamEvent represents a single event received during message streaming. Exactly one field is set. A conforming agent opens a task stream with the Task itself, or answers with a single Message.
type StreamResponse ¶ added in v2.8.0
type StreamResponse struct {
Task *Task `json:"task,omitempty"`
Message *Message `json:"message,omitempty"`
StatusUpdate *TaskStatusUpdateEvent `json:"statusUpdate,omitempty"`
ArtifactUpdate *TaskArtifactUpdateEvent `json:"artifactUpdate,omitempty"`
}
StreamResponse is one A2A 1.0 streaming result: exactly one field is set. (0.3 sends each object bare, discriminated by its "kind".)
type SubscribeTaskRequest ¶
SubscribeTaskRequest is the params for SubscribeToTask (0.3: tasks/resubscribe).
type Task ¶
type Task struct {
ID string `json:"id"`
ContextID string `json:"contextId"`
Status TaskStatus `json:"status"`
Artifacts []Artifact `json:"artifacts,omitempty"`
History []Message `json:"history,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Task is the top-level unit of work in the A2A protocol.
type TaskArtifactUpdateEvent ¶
type TaskArtifactUpdateEvent struct {
TaskID string `json:"taskId"`
ContextID string `json:"contextId"`
Artifact Artifact `json:"artifact"`
Append bool `json:"append,omitempty"`
LastChunk bool `json:"lastChunk,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
TaskArtifactUpdateEvent is sent during streaming when an artifact is produced.
type TaskPushNotificationConfig ¶ added in v2.22.0
type TaskPushNotificationConfig struct {
Tenant string `json:"tenant,omitempty"`
ID string `json:"id,omitempty"`
TaskID string `json:"taskId,omitempty"`
// URL is the webhook the agent POSTs to. REQUIRED.
URL string `json:"url"`
// Token is a value unique to the task or session, sent with each
// notification so the receiver can check it.
Token string `json:"token,omitempty"`
Authentication *AuthenticationInfo `json:"authentication,omitempty"`
}
TaskPushNotificationConfig is where, and with what credentials, an agent pushes a task's updates (A2A 1.0 §4.3.1). In a SendMessage configuration TaskID is left empty.
type TaskState ¶
type TaskState string
TaskState represents the state of an A2A task.
The Go values are PromptKit's own and never appear on the wire: a TaskState marshals to its A2A 1.0 name (TASK_STATE_COMPLETED, ...) and unmarshals from the 1.0, 0.3 (input-required) and legacy (input_required) spellings alike.
const ( TaskStateSubmitted TaskState = "submitted" TaskStateWorking TaskState = "working" TaskStateCompleted TaskState = "completed" TaskStateFailed TaskState = "failed" TaskStateCanceled TaskState = "canceled" TaskStateInputRequired TaskState = "input_required" TaskStateRejected TaskState = "rejected" TaskStateAuthRequired TaskState = "auth_required" // TaskStateUnknown is 1.0's TASK_STATE_UNSPECIFIED and 0.3's "unknown". TaskStateUnknown TaskState = "unknown" )
TaskState constants for the A2A protocol.
func ParseTaskState ¶ added in v2.8.0
ParseTaskState resolves a wire spelling (1.0, 0.3 or legacy PromptKit) to a TaskState.
func (TaskState) IsInterrupted ¶ added in v2.8.0
IsInterrupted reports whether s pauses the task for the client (input-required or auth-required). A stream ends at an interrupted state.
func (TaskState) IsTerminal ¶ added in v2.8.0
IsTerminal reports whether no further transitions are possible from s.
func (TaskState) MarshalJSON ¶
MarshalJSON implements json.Marshaler, writing the A2A 1.0 name.
func (*TaskState) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler, accepting any version's spelling. A spelling no version defines (a state a later version adds, say) decodes as TaskStateUnknown rather than failing the object it is in: A2A 1.0 §5.7 asks implementations to ignore what they do not recognize. Use ParseTaskState to refuse it instead.
type TaskStatus ¶
type TaskStatus struct {
State TaskState `json:"state"`
Message *Message `json:"message,omitempty"`
Timestamp *time.Time `json:"timestamp,omitempty"`
}
TaskStatus describes the current status of a task.
func (TaskStatus) MarshalJSON ¶ added in v2.22.0
func (s TaskStatus) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. Timestamp is written as a ProtoJSON google.protobuf.Timestamp (A2A 1.0 TaskStatus.timestamp): RFC 3339 in UTC, with 0, 3, 6 or 9 fractional digits, whatever zone the time is held in.
type TaskStatusUpdateEvent ¶
type TaskStatusUpdateEvent struct {
TaskID string `json:"taskId"`
ContextID string `json:"contextId"`
Status TaskStatus `json:"status"`
Metadata map[string]any `json:"metadata,omitempty"`
}
TaskStatusUpdateEvent is sent during streaming when a task's status changes.
type ToolBridge ¶
type ToolBridge struct {
// contains filtered or unexported fields
}
ToolBridge discovers an A2A agent and creates ToolDescriptor entries for each of the agent's skills so they can be invoked through the standard tool registry.
func NewToolBridge ¶
func NewToolBridge(client *Client) *ToolBridge
NewToolBridge creates a ToolBridge backed by the given A2A client.
func NewToolBridgeWithConfig ¶
func NewToolBridgeWithConfig(client *Client, cfg *tools.A2AConfig) *ToolBridge
NewToolBridgeWithConfig creates a ToolBridge that applies the given A2AConfig (headers, auth, retry, skill filter) to all generated tool descriptors.
func (*ToolBridge) GetToolDescriptors ¶
func (b *ToolBridge) GetToolDescriptors() []*tools.ToolDescriptor
GetToolDescriptors returns all tool descriptors accumulated via RegisterAgent calls.
func (*ToolBridge) RegisterAgent ¶
func (b *ToolBridge) RegisterAgent(ctx context.Context) ([]*tools.ToolDescriptor, error)
RegisterAgent discovers the agent card and creates a ToolDescriptor for each skill. The descriptors are appended to the bridge's internal list (supporting multi-agent composition via GetToolDescriptors). Skills excluded by the skill filter are skipped.
Each tool is named a2a__<agent>__<skill>, with the card name and skill ID lower-cased and non-alphanumeric runs replaced by "_". Its input schema requires a "query" string, plus image_url and image_data when the skill accepts image input and audio_data when it accepts audio input. Its output schema has a "response" string, plus media_url and media_type when the skill produces image or audio output.
func (*ToolBridge) ShareCards ¶ added in v2.11.0
func (b *ToolBridge) ShareCards(e *Executor)
ShareCards hands the agent card the bridge discovered to e, so the tools it registered reach the interface the card declares without e fetching the card again. It does nothing before RegisterAgent has succeeded.