a2a

package
v0.0.0-...-3f9b805 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package a2a 实现 Google A2A (Agent-to-Agent) 协议

A2A 是一个开放协议,使 AI Agent 能够安全地相互通信、协调任务、共享上下文。 本包提供了完整的 A2A 协议实现,包括:

  • AgentCard: Agent 元数据描述
  • Task: 任务生命周期管理
  • Message: Agent 间消息通信
  • Artifact: 任务输出产物
  • 推送通知: 服务端主动推送

规范参考:

使用示例:

// 创建 A2A 服务器
card := &a2a.AgentCard{
    Name:        "assistant",
    Description: "通用助手 Agent",
    URL:         "http://localhost:8080",
    Version:     "1.0.0",
}
server := a2a.NewServer(card, handler)
server.Start(":8080")

// 创建 A2A 客户端
client := a2a.NewClient("http://localhost:8080")
card, _ := client.GetAgentCard(ctx)

Index

Constants

View Source
const (
	// ProtocolVersion A2A 协议版本
	ProtocolVersion = "1.0"

	// ContentTypeJSON JSON 内容类型
	ContentTypeJSON = "application/json"

	// ContentTypeSSE SSE 内容类型
	ContentTypeSSE = "text/event-stream"
)
View Source
const (
	// PathAgentCard Agent Card 路径
	PathAgentCard = "/.well-known/agent-card.json"

	// PathTasks 任务列表路径
	PathTasks = "/tasks"

	// PathTaskSend 发送消息路径
	PathTaskSend = "/tasks/send"

	// PathTaskSendStream 流式发送消息路径
	PathTaskSendStream = "/tasks/sendSubscribe"

	// PathTaskGet 获取任务路径(带 taskId 参数)
	PathTaskGet = "/tasks/get"

	// PathTaskCancel 取消任务路径
	PathTaskCancel = "/tasks/cancel"

	// PathTaskResubscribe 重新订阅任务路径
	PathTaskResubscribe = "/tasks/resubscribe"

	// PathPushNotification 推送通知配置路径前缀
	PathPushNotification = "/tasks/pushNotification"

	// PathPushNotificationGet 获取推送配置路径
	PathPushNotificationGet = "/tasks/pushNotification/get"

	// PathPushNotificationSet 设置推送配置路径
	PathPushNotificationSet = "/tasks/pushNotification/set"
)
View Source
const (
	// MethodSendMessage 发送消息方法
	MethodSendMessage = "tasks/send"

	// MethodSendMessageStream 流式发送消息方法
	MethodSendMessageStream = "tasks/sendSubscribe"

	// MethodGetTask 获取任务方法
	MethodGetTask = "tasks/get"

	// MethodListTasks 列出任务方法
	MethodListTasks = "tasks/list"

	// MethodCancelTask 取消任务方法
	MethodCancelTask = "tasks/cancel"

	// MethodResubscribe 重新订阅方法
	MethodResubscribe = "tasks/resubscribe"

	// MethodSetPushNotification 设置推送通知方法
	MethodSetPushNotification = "tasks/pushNotification/set"

	// MethodGetPushNotification 获取推送通知方法
	MethodGetPushNotification = "tasks/pushNotification/get"
)
View Source
const (
	// EventTypeTaskStatus 任务状态事件
	EventTypeTaskStatus = "task-status"

	// EventTypeArtifact 产物事件
	EventTypeArtifact = "artifact"

	// EventTypeError 错误事件
	EventTypeError = "error"

	// EventTypeDone 完成事件
	EventTypeDone = "done"
)
View Source
const (
	// CodeParseError JSON 解析错误 (-32700)
	CodeParseError = -32700

	// CodeInvalidRequest 无效请求 (-32600)
	CodeInvalidRequest = -32600

	// CodeMethodNotFound 方法不存在 (-32601)
	CodeMethodNotFound = -32601

	// CodeInvalidParams 无效参数 (-32602)
	CodeInvalidParams = -32602

	// CodeInternalError 内部错误 (-32603)
	CodeInternalError = -32603

	// CodeTaskNotFound 任务不存在 (-32001)
	CodeTaskNotFound = -32001

	// CodeTaskNotCancelable 任务不可取消 (-32002)
	CodeTaskNotCancelable = -32002

	// CodePushNotificationNotSupported 不支持推送通知 (-32003)
	CodePushNotificationNotSupported = -32003

	// CodeUnsupportedOperation 不支持的操作 (-32004)
	CodeUnsupportedOperation = -32004

	// CodeContentTypeNotSupported 不支持的内容类型 (-32005)
	CodeContentTypeNotSupported = -32005

	// CodeAuthenticationRequired 需要认证 (-32010)
	CodeAuthenticationRequired = -32010

	// CodeAuthenticationFailed 认证失败 (-32011)
	CodeAuthenticationFailed = -32011

	// CodePermissionDenied 权限不足 (-32012)
	CodePermissionDenied = -32012
)

A2A 标准错误码 参考 JSON-RPC 2.0 规范和 A2A 协议规范

Variables

View Source
var (
	// ErrTaskNotFound 任务不存在
	ErrTaskNotFound = errors.New("task not found")

	// ErrTaskNotCancelable 任务不可取消
	ErrTaskNotCancelable = errors.New("task is not cancelable")

	// ErrPushNotSupported 不支持推送通知
	ErrPushNotSupported = errors.New("push notification not supported")

	// ErrUnsupportedOperation 不支持的操作
	ErrUnsupportedOperation = errors.New("unsupported operation")

	// ErrInvalidMessage 无效消息
	ErrInvalidMessage = errors.New("invalid message")

	// ErrInvalidTask 无效任务
	ErrInvalidTask = errors.New("invalid task")

	// ErrAuthRequired 需要认证
	ErrAuthRequired = errors.New("authentication required")

	// ErrAuthFailed 认证失败
	ErrAuthFailed = errors.New("authentication failed")

	// ErrPermissionDenied 权限不足
	ErrPermissionDenied = errors.New("permission denied")

	// ErrStreamingNotSupported 不支持流式响应
	ErrStreamingNotSupported = errors.New("streaming not supported")

	// ErrServerStopped 服务器已停止
	ErrServerStopped = errors.New("server stopped")

	// ErrClientClosed 客户端已关闭
	ErrClientClosed = errors.New("client closed")
)
View Source
var DefaultRetryConfig = RetryConfig{
	MaxRetries:   3,
	InitialDelay: 100 * time.Millisecond,
	MaxDelay:     5 * time.Second,
	Multiplier:   2.0,
}

DefaultRetryConfig 默认重试配置

Functions

func AuthMiddleware

func AuthMiddleware(validator AuthValidator) func(http.Handler) http.Handler

AuthMiddleware 创建认证中间件

func CardToAgentInfo

func CardToAgentInfo(card *AgentCard) *agent.AgentInfo

CardToAgentInfo 将 A2A AgentCard 转换为 Hexagon AgentInfo

转换规则:

  • URL -> Endpoint
  • Name -> Name
  • Description -> Description
  • Version -> Version
  • Skills -> Capabilities

func IsA2AError

func IsA2AError(err error) bool

IsA2AError 检查是否为 A2A 错误

func MessageToAgentInput

func MessageToAgentInput(msg *Message) agent.Input

MessageToAgentInput 将 A2A Message 转换为 Hexagon Agent Input

func MessageToAgentOutput

func MessageToAgentOutput(msg *Message) agent.Output

MessageToAgentOutput 将 A2A Message 转换为 Hexagon Agent Output

func OptionalAuthMiddleware

func OptionalAuthMiddleware(validator AuthValidator) func(http.Handler) http.Handler

OptionalAuthMiddleware 可选认证中间件 尝试验证但不要求认证。

func WithAuthContext

func WithAuthContext(ctx context.Context, authCtx *AuthContext) context.Context

WithAuthContext 将认证上下文添加到 context

Types

type APIKeyAuth

type APIKeyAuth struct {
	// Key API Key 名称
	Key string

	// Value API Key 值
	Value string

	// In 位置 (header, query)
	In string
}

APIKeyAuth API Key 认证

func (*APIKeyAuth) Authenticate

func (a *APIKeyAuth) Authenticate(req *http.Request) error

Authenticate 实现认证

type APIKeyValidator

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

APIKeyValidator API Key 验证器

func NewAPIKeyValidator

func NewAPIKeyValidator(name, in string) *APIKeyValidator

NewAPIKeyValidator 创建 API Key 验证器

func (*APIKeyValidator) AddKey

func (v *APIKeyValidator) AddKey(key, clientID string)

AddKey 添加有效 API Key

func (*APIKeyValidator) RemoveKey

func (v *APIKeyValidator) RemoveKey(key string)

RemoveKey 移除 API Key

func (*APIKeyValidator) Validate

func (v *APIKeyValidator) Validate(r *http.Request) (string, error)

Validate 实现 AuthValidator 接口

type AgentCapabilities

type AgentCapabilities struct {
	// Streaming 是否支持流式响应
	Streaming bool `json:"streaming,omitempty"`

	// PushNotifications 是否支持推送通知
	PushNotifications bool `json:"pushNotifications,omitempty"`

	// StateTransitionHistory 是否支持状态转换历史
	StateTransitionHistory bool `json:"stateTransitionHistory,omitempty"`
}

AgentCapabilities Agent 能力配置

type AgentCard

type AgentCard struct {
	// Name Agent 名称(必需)
	Name string `json:"name"`

	// Description Agent 描述
	Description string `json:"description,omitempty"`

	// URL Agent 服务地址(必需)
	URL string `json:"url"`

	// Provider Agent 提供者信息
	Provider *AgentProvider `json:"provider,omitempty"`

	// Version 版本号
	Version string `json:"version"`

	// DocumentationURL 文档地址
	DocumentationURL string `json:"documentationUrl,omitempty"`

	// Capabilities Agent 能力
	Capabilities AgentCapabilities `json:"capabilities"`

	// Authentication 认证配置
	Authentication *AuthConfig `json:"authentication,omitempty"`

	// DefaultInputModes 默认输入模式 (text, file, data)
	DefaultInputModes []string `json:"defaultInputModes,omitempty"`

	// DefaultOutputModes 默认输出模式 (text, file, data)
	DefaultOutputModes []string `json:"defaultOutputModes,omitempty"`

	// Skills Agent 技能列表
	Skills []AgentSkill `json:"skills,omitempty"`
}

AgentCard Agent 元数据卡片 遵循 Google A2A 规范,位于 .well-known/agent-card.json

Agent Card 是 A2A 协议的核心概念,描述了 Agent 的基本信息、能力和技能。 客户端通过获取 Agent Card 来了解如何与 Agent 交互。

func AgentInfoToCard

func AgentInfoToCard(info *agent.AgentInfo, baseURL string) *AgentCard

AgentInfoToCard 将 Hexagon AgentInfo 转换为 A2A AgentCard

转换规则:

  • ID -> URL 参数(需要外部提供完整 URL)
  • Name -> Name
  • Description -> Description
  • Version -> Version
  • Tags -> Skills.Tags
  • Capabilities -> Skills (名称转换为技能)
  • Endpoint -> URL

func NewAgentCard

func NewAgentCard(name, url, version string) *AgentCard

NewAgentCard 创建 Agent Card

type AgentFilter

type AgentFilter struct {
	// Name Agent 名称(支持通配符)
	Name string

	// Skills 技能过滤
	Skills []string

	// Tags 标签过滤
	Tags []string

	// Capabilities 能力过滤
	Capabilities *AgentCapabilities
}

AgentFilter Agent 过滤条件

type AgentProvider

type AgentProvider struct {
	// Organization 组织名称
	Organization string `json:"organization"`

	// URL 组织网站
	URL string `json:"url,omitempty"`
}

AgentProvider Agent 提供者信息

type AgentSkill

type AgentSkill struct {
	// ID 技能 ID
	ID string `json:"id"`

	// Name 技能名称
	Name string `json:"name"`

	// Description 技能描述
	Description string `json:"description,omitempty"`

	// Tags 标签列表
	Tags []string `json:"tags,omitempty"`

	// Examples 使用示例
	Examples []string `json:"examples,omitempty"`

	// InputModes 支持的输入模式
	InputModes []string `json:"inputModes,omitempty"`

	// OutputModes 支持的输出模式
	OutputModes []string `json:"outputModes,omitempty"`
}

AgentSkill Agent 技能

type AgentWrapper

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

AgentWrapper 将 Hexagon Agent 包装为 A2A TaskHandler 使得任意 Hexagon Agent 都可以作为 A2A 服务暴露。

使用示例:

// 创建 Hexagon Agent
myAgent := agent.NewReActAgent(
    agent.WithName("assistant"),
    agent.WithLLM(llm),
)

// 包装为 A2A Handler
handler := a2a.WrapAgent(myAgent)

// 创建 A2A Server
card := a2a.AgentInfoToCard(myAgent.Info(), "http://localhost:8080")
server := a2a.NewServer(card, handler)

func WrapAgent

func WrapAgent(a agent.Agent) *AgentWrapper

WrapAgent 将 Hexagon Agent 包装为 A2A TaskHandler

func (*AgentWrapper) HandleTask

func (w *AgentWrapper) HandleTask(ctx context.Context, task *Task, msg *Message) (*TaskUpdate, error)

HandleTask 实现 TaskHandler 接口

type Artifact

type Artifact struct {
	// Name 产物名称
	Name string `json:"name,omitempty"`

	// Description 产物描述
	Description string `json:"description,omitempty"`

	// Parts 产物内容部分
	Parts []Part `json:"parts"`

	// Index 产物索引(用于多个产物)
	Index int `json:"index,omitempty"`

	// Append 是否追加到已有产物
	Append bool `json:"append,omitempty"`

	// LastChunk 是否为最后一块(用于流式)
	LastChunk bool `json:"lastChunk,omitempty"`

	// Metadata 元数据
	Metadata map[string]any `json:"metadata,omitempty"`
}

Artifact 任务产物 产物是任务执行过程中生成的输出,可以是文本、文件或结构化数据。

func AgentOutputToArtifact

func AgentOutputToArtifact(output agent.Output, name string) Artifact

AgentOutputToArtifact 将 Agent Output 转换为 Artifact

func NewTextArtifact

func NewTextArtifact(name, text string) Artifact

NewTextArtifact 创建文本产物

func (*Artifact) GetTextContent

func (a *Artifact) GetTextContent() string

GetTextContent 获取产物的纯文本内容

func (*Artifact) UnmarshalJSON

func (a *Artifact) UnmarshalJSON(data []byte) error

UnmarshalJSON 自定义 JSON 反序列化

type ArtifactEvent

type ArtifactEvent struct {
	// ID 任务 ID
	ID string `json:"id"`

	// Artifact 产物
	Artifact Artifact `json:"artifact"`
}

ArtifactEvent 产物事件

func (*ArtifactEvent) EventType

func (e *ArtifactEvent) EventType() string

EventType 返回事件类型

type AsyncPushService

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

AsyncPushService 异步推送服务 在后台异步发送推送通知,不阻塞主流程。

func NewAsyncPushService

func NewAsyncPushService(underlying PushService, queueSize, workers int) *AsyncPushService

NewAsyncPushService 创建异步推送服务

func (*AsyncPushService) Close

func (s *AsyncPushService) Close()

Close 关闭异步推送服务

func (*AsyncPushService) Push

func (s *AsyncPushService) Push(_ context.Context, config *PushNotificationConfig, task *Task) error

Push 异步发送推送

type AuthConfig

type AuthConfig struct {
	// Schemes 支持的认证方案列表
	Schemes []AuthScheme `json:"schemes"`
}

AuthConfig 认证配置

type AuthContext

type AuthContext struct {
	// ClientID 客户端 ID
	ClientID string

	// Authenticated 是否已认证
	Authenticated bool

	// AuthTime 认证时间
	AuthTime time.Time

	// Metadata 额外元数据
	Metadata map[string]any
}

AuthContext 认证上下文

func GetAuthContext

func GetAuthContext(ctx context.Context) *AuthContext

GetAuthContext 从 context 获取认证上下文

type AuthScheme

type AuthScheme struct {
	// Type 认证类型 (apiKey, bearer, oauth2, basic)
	Type string `json:"type"`

	// In 参数位置 (header, query) - 用于 apiKey
	In string `json:"in,omitempty"`

	// Name 参数名称 - 用于 apiKey
	Name string `json:"name,omitempty"`

	// BearerFormat Bearer 格式 - 用于 bearer
	BearerFormat string `json:"bearerFormat,omitempty"`

	// Flows OAuth2 流程 - 用于 oauth2
	Flows *OAuth2Flows `json:"flows,omitempty"`
}

AuthScheme 认证方案

type AuthValidator

type AuthValidator interface {
	// Validate 验证请求
	// 返回用户/客户端标识,如果验证失败返回错误
	Validate(r *http.Request) (string, error)
}

AuthValidator 认证验证器接口 用于服务端验证客户端请求的认证信息。

type Authenticator

type Authenticator interface {
	// Authenticate 对请求进行认证
	Authenticate(req *http.Request) error
}

Authenticator 认证器接口

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth 基本认证

func (*BasicAuth) Authenticate

func (a *BasicAuth) Authenticate(req *http.Request) error

Authenticate 实现认证

type BasicAuthValidator

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

BasicAuthValidator Basic 认证验证器

func NewBasicAuthValidator

func NewBasicAuthValidator() *BasicAuthValidator

NewBasicAuthValidator 创建 Basic 认证验证器

func (*BasicAuthValidator) AddCredentials

func (v *BasicAuthValidator) AddCredentials(username, password, clientID string)

AddCredentials 添加凭证

func (*BasicAuthValidator) RemoveCredentials

func (v *BasicAuthValidator) RemoveCredentials(username, password string)

RemoveCredentials 移除凭证

func (*BasicAuthValidator) Validate

func (v *BasicAuthValidator) Validate(r *http.Request) (string, error)

Validate 实现 AuthValidator 接口

type BearerAuth

type BearerAuth struct {
	Token string
}

BearerAuth Bearer Token 认证

func (*BearerAuth) Authenticate

func (a *BearerAuth) Authenticate(req *http.Request) error

Authenticate 实现认证

type BearerTokenValidator

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

BearerTokenValidator Bearer Token 验证器

func NewBearerTokenValidator

func NewBearerTokenValidator() *BearerTokenValidator

NewBearerTokenValidator 创建 Bearer Token 验证器

func (*BearerTokenValidator) AddToken

func (v *BearerTokenValidator) AddToken(token, clientID string)

AddToken 添加有效 token

func (*BearerTokenValidator) RemoveToken

func (v *BearerTokenValidator) RemoveToken(token string)

RemoveToken 移除 token

func (*BearerTokenValidator) Validate

func (v *BearerTokenValidator) Validate(r *http.Request) (string, error)

Validate 实现 AuthValidator 接口

type CancelTaskRequest

type CancelTaskRequest struct {
	// ID 任务 ID
	ID string `json:"id"`
}

CancelTaskRequest 取消任务请求

type CancelTaskResponse

type CancelTaskResponse = Task

CancelTaskResponse 取消任务响应

type ChainHandler

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

ChainHandler 链式处理器 按顺序执行多个处理器,第一个返回非空结果的处理器生效。

func NewChainHandler

func NewChainHandler(handlers ...TaskHandler) *ChainHandler

NewChainHandler 创建链式处理器

func (*ChainHandler) HandleTask

func (h *ChainHandler) HandleTask(ctx context.Context, task *Task, msg *Message) (*TaskUpdate, error)

HandleTask 实现 TaskHandler 接口

type ChainValidator

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

ChainValidator 链式验证器 按顺序尝试多个验证器,第一个成功的生效。

func NewChainValidator

func NewChainValidator(validators ...AuthValidator) *ChainValidator

NewChainValidator 创建链式验证器

func (*ChainValidator) Validate

func (v *ChainValidator) Validate(r *http.Request) (string, error)

Validate 实现 AuthValidator 接口

type Client

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

Client A2A 客户端 提供与 A2A Agent 服务器通信的能力。

使用示例:

client := a2a.NewClient("http://localhost:8080")

// 获取 Agent Card
card, _ := client.GetAgentCard(ctx)

// 发送消息
task, _ := client.SendMessage(ctx, &a2a.SendMessageRequest{
    Message: a2a.NewUserMessage("你好"),
})

func NewClient

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

NewClient 创建 A2A 客户端

func (*Client) CancelTask

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

CancelTask 取消任务

func (*Client) Close

func (c *Client) Close() error

Close 关闭客户端

func (*Client) GetAgentCard

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

GetAgentCard 获取 Agent Card

func (*Client) GetPushNotification

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

GetPushNotification 获取推送配置

func (*Client) GetTask

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

GetTask 获取任务状态

func (*Client) IsClosed

func (c *Client) IsClosed() bool

IsClosed 检查客户端是否已关闭

func (*Client) ListTasks

func (c *Client) ListTasks(ctx context.Context, opts *ListTasksRequest) (*ListTasksResponse, error)

ListTasks 列出任务

func (*Client) Resubscribe

func (c *Client) Resubscribe(ctx context.Context, taskID string) (<-chan StreamEvent, error)

Resubscribe 重新订阅任务事件流

func (*Client) SendMessage

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

SendMessage 发送消息(创建或继续任务)

func (*Client) SendMessageStream

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

SendMessageStream 流式发送消息 返回一个事件通道,调用者需要消费所有事件直到通道关闭。

func (*Client) SetPushNotification

func (c *Client) SetPushNotification(ctx context.Context, taskID string, config *PushNotificationConfig) error

SetPushNotification 设置推送通知

type ClientOption

type ClientOption func(*Client)

ClientOption 客户端选项

func WithAuth

func WithAuth(auth Authenticator) ClientOption

WithAuth 设置认证器

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient 设置 HTTP 客户端

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout 设置默认超时时间

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithUserAgent 设置 User-Agent

type DataPart

type DataPart struct {
	// Data 结构化数据
	Data map[string]any `json:"data"`
}

DataPart 结构化数据部分

func (*DataPart) MarshalJSON

func (p *DataPart) MarshalJSON() ([]byte, error)

MarshalJSON 自定义 JSON 序列化

func (*DataPart) Type

func (p *DataPart) Type() PartType

Type 返回数据类型

type Discovery

type Discovery interface {
	// Discover 发现符合条件的 Agent
	Discover(ctx context.Context, filter *AgentFilter) ([]*AgentCard, error)

	// Register 注册 Agent
	Register(ctx context.Context, card *AgentCard) error

	// Deregister 注销 Agent
	Deregister(ctx context.Context, url string) error

	// Get 获取指定 Agent
	Get(ctx context.Context, url string) (*AgentCard, error)

	// Watch 监听 Agent 变化
	Watch(ctx context.Context, filter *AgentFilter) (<-chan DiscoveryEvent, error)
}

Discovery Agent 发现服务接口 用于发现和管理 A2A Agent。

type DiscoveryEvent

type DiscoveryEvent struct {
	// Type 事件类型
	Type DiscoveryEventType

	// Card Agent Card
	Card *AgentCard

	// Timestamp 时间戳
	Timestamp time.Time
}

DiscoveryEvent 发现事件

type DiscoveryEventType

type DiscoveryEventType string

DiscoveryEventType 发现事件类型

const (
	// EventTypeRegistered Agent 注册
	EventTypeRegistered DiscoveryEventType = "registered"

	// EventTypeDeregistered Agent 注销
	EventTypeDeregistered DiscoveryEventType = "deregistered"

	// EventTypeUpdated Agent 更新
	EventTypeUpdated DiscoveryEventType = "updated"
)

type DoneEvent

type DoneEvent struct {
	// Task 最终任务状态
	Task *Task `json:"task,omitempty"`
}

DoneEvent 完成事件

func (*DoneEvent) EventType

func (e *DoneEvent) EventType() string

EventType 返回事件类型

type EchoHandler

type EchoHandler struct{}

EchoHandler 回显处理器 简单地将用户消息回显,用于测试。

func NewEchoHandler

func NewEchoHandler() *EchoHandler

NewEchoHandler 创建回显处理器

func (*EchoHandler) HandleTask

func (h *EchoHandler) HandleTask(_ context.Context, _ *Task, msg *Message) (*TaskUpdate, error)

HandleTask 实现 TaskHandler 接口

type Error

type Error struct {
	// Code 错误码
	Code int `json:"code"`

	// Message 错误消息
	Message string `json:"message"`

	// Data 附加数据(可选)
	Data any `json:"data,omitempty"`
}

Error A2A 错误 实现 JSON-RPC 2.0 错误格式

func GetA2AError

func GetA2AError(err error) *Error

GetA2AError 获取 A2A 错误

func NewAuthFailedError

func NewAuthFailedError(reason string) *Error

NewAuthFailedError 创建认证失败错误

func NewAuthRequiredError

func NewAuthRequiredError() *Error

NewAuthRequiredError 创建需要认证错误

func NewError

func NewError(code int, message string, data ...any) *Error

NewError 创建 A2A 错误

func NewInternalError

func NewInternalError(message string) *Error

NewInternalError 创建内部错误

func NewInvalidParamsError

func NewInvalidParamsError(message string) *Error

NewInvalidParamsError 创建无效参数错误

func NewInvalidRequestError

func NewInvalidRequestError(message string) *Error

NewInvalidRequestError 创建无效请求错误

func NewMethodNotFoundError

func NewMethodNotFoundError(method string) *Error

NewMethodNotFoundError 创建方法不存在错误

func NewParseError

func NewParseError(message string) *Error

NewParseError 创建解析错误

func NewPermissionDeniedError

func NewPermissionDeniedError(reason string) *Error

NewPermissionDeniedError 创建权限不足错误

func NewPushNotSupportedError

func NewPushNotSupportedError() *Error

NewPushNotSupportedError 创建不支持推送通知错误

func NewTaskNotCancelableError

func NewTaskNotCancelableError(taskID string) *Error

NewTaskNotCancelableError 创建任务不可取消错误

func NewTaskNotFoundError

func NewTaskNotFoundError(taskID string) *Error

NewTaskNotFoundError 创建任务不存在错误

func NewUnsupportedOperationError

func NewUnsupportedOperationError(op string) *Error

NewUnsupportedOperationError 创建不支持操作错误

func ToA2AError

func ToA2AError(err error) *Error

ToA2AError 将普通错误转换为 A2A 错误

func (*Error) Error

func (e *Error) Error() string

Error 实现 error 接口

type ErrorEvent

type ErrorEvent struct {
	// Error 错误信息
	Error *Error `json:"error"`
}

ErrorEvent 错误事件

func (*ErrorEvent) EventType

func (e *ErrorEvent) EventType() string

EventType 返回事件类型

type FileContent

type FileContent struct {
	// Name 文件名
	Name string `json:"name,omitempty"`

	// MimeType MIME 类型
	MimeType string `json:"mimeType,omitempty"`

	// URI 文件 URI(与 Bytes 二选一)
	URI string `json:"uri,omitempty"`

	// Bytes Base64 编码的文件内容(与 URI 二选一)
	Bytes string `json:"bytes,omitempty"`
}

FileContent 文件内容

type FilePart

type FilePart struct {
	// File 文件内容
	File FileContent `json:"file"`
}

FilePart 文件部分

func (*FilePart) MarshalJSON

func (p *FilePart) MarshalJSON() ([]byte, error)

MarshalJSON 自定义 JSON 序列化

func (*FilePart) Type

func (p *FilePart) Type() PartType

Type 返回文件类型

type FuncHandler

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

FuncHandler 函数式任务处理器 将普通函数包装为 TaskHandler。

func NewFuncHandler

func NewFuncHandler(fn TaskFunc) *FuncHandler

NewFuncHandler 创建函数式处理器

func (*FuncHandler) HandleTask

func (h *FuncHandler) HandleTask(ctx context.Context, task *Task, msg *Message) (*TaskUpdate, error)

HandleTask 实现 TaskHandler 接口

type GetPushNotificationRequest

type GetPushNotificationRequest struct {
	// TaskID 任务 ID
	TaskID string `json:"id"`
}

GetPushNotificationRequest 获取推送通知请求

type GetPushNotificationResponse

type GetPushNotificationResponse struct {
	// Config 推送配置
	Config *PushNotificationConfig `json:"pushNotificationConfig,omitempty"`
}

GetPushNotificationResponse 获取推送通知响应

type GetTaskRequest

type GetTaskRequest struct {
	// ID 任务 ID
	ID string `json:"id"`

	// HistoryLength 返回的历史消息数量
	HistoryLength int `json:"historyLength,omitempty"`
}

GetTaskRequest 获取任务请求

type GetTaskResponse

type GetTaskResponse = Task

GetTaskResponse 获取任务响应

type HTTPPushService

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

HTTPPushService HTTP 推送服务

func NewHTTPPushService

func NewHTTPPushService() *HTTPPushService

NewHTTPPushService 创建 HTTP 推送服务

func (*HTTPPushService) Push

func (s *HTTPPushService) Push(ctx context.Context, config *PushNotificationConfig, task *Task) error

Push 发送推送通知

type JSONRPCRequest

type JSONRPCRequest struct {
	// JSONRPC 版本(必须为 "2.0")
	JSONRPC string `json:"jsonrpc"`

	// ID 请求 ID
	ID any `json:"id,omitempty"`

	// Method 方法名
	Method string `json:"method"`

	// Params 参数
	Params json.RawMessage `json:"params,omitempty"`
}

JSONRPCRequest JSON-RPC 2.0 请求

func NewJSONRPCRequest

func NewJSONRPCRequest(id any, method string, params any) (*JSONRPCRequest, error)

NewJSONRPCRequest 创建 JSON-RPC 请求

type JSONRPCResponse

type JSONRPCResponse struct {
	// JSONRPC 版本(必须为 "2.0")
	JSONRPC string `json:"jsonrpc"`

	// ID 请求 ID
	ID any `json:"id,omitempty"`

	// Result 结果(成功时)
	Result json.RawMessage `json:"result,omitempty"`

	// Error 错误(失败时)
	Error *Error `json:"error,omitempty"`
}

JSONRPCResponse JSON-RPC 2.0 响应

func NewJSONRPCErrorResponse

func NewJSONRPCErrorResponse(id any, err *Error) *JSONRPCResponse

NewJSONRPCErrorResponse 创建错误响应

func NewJSONRPCResponse

func NewJSONRPCResponse(id any, result any) (*JSONRPCResponse, error)

NewJSONRPCResponse 创建成功响应

type ListTasksRequest

type ListTasksRequest struct {
	// SessionID 会话 ID(可选,过滤条件)
	SessionID string `json:"sessionId,omitempty"`

	// Status 状态过滤(可选)
	Status []TaskState `json:"status,omitempty"`

	// Limit 返回数量限制
	Limit int `json:"limit,omitempty"`

	// Offset 偏移量
	Offset int `json:"offset,omitempty"`
}

ListTasksRequest 列出任务请求

type ListTasksResponse

type ListTasksResponse struct {
	// Tasks 任务列表
	Tasks []*Task `json:"tasks"`

	// Total 总数
	Total int `json:"total,omitempty"`
}

ListTasksResponse 列出任务响应

type MemoryStoreOption

type MemoryStoreOption func(*MemoryTaskStore)

MemoryStoreOption 内存存储选项

func WithMaxTasks

func WithMaxTasks(max int) MemoryStoreOption

WithMaxTasks 设置最大任务数

func WithTaskTTL

func WithTaskTTL(ttl time.Duration) MemoryStoreOption

WithTaskTTL 设置任务过期时间

type MemoryTaskStore

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

MemoryTaskStore 内存任务存储 用于开发和测试,生产环境应使用持久化存储。

重要:使用完毕后必须调用 Close() 释放清理协程,否则会导致 goroutine 泄漏。

func NewMemoryTaskStore

func NewMemoryTaskStore(opts ...MemoryStoreOption) *MemoryTaskStore

NewMemoryTaskStore 创建内存任务存储

func (*MemoryTaskStore) Close

func (s *MemoryTaskStore) Close()

Close 关闭内存任务存储,停止清理协程 必须在不再使用 MemoryTaskStore 时调用,否则清理协程会泄漏。

func (*MemoryTaskStore) Create

func (s *MemoryTaskStore) Create(_ context.Context, task *Task) error

Create 创建任务

func (*MemoryTaskStore) Delete

func (s *MemoryTaskStore) Delete(_ context.Context, id string) error

Delete 删除任务

func (*MemoryTaskStore) GenerateID

func (s *MemoryTaskStore) GenerateID() string

GenerateID 生成任务 ID

func (*MemoryTaskStore) Get

func (s *MemoryTaskStore) Get(_ context.Context, id string) (*Task, error)

Get 获取任务

func (*MemoryTaskStore) GetPushConfig

func (s *MemoryTaskStore) GetPushConfig(_ context.Context, taskID string) (*PushNotificationConfig, error)

GetPushConfig 获取推送配置

func (*MemoryTaskStore) List

List 列出任务

func (*MemoryTaskStore) SetPushConfig

func (s *MemoryTaskStore) SetPushConfig(_ context.Context, taskID string, config *PushNotificationConfig) error

SetPushConfig 设置推送配置

func (*MemoryTaskStore) Update

func (s *MemoryTaskStore) Update(_ context.Context, task *Task) error

Update 更新任务

type Message

type Message struct {
	// Role 消息角色 (user, agent)
	Role Role `json:"role"`

	// Parts 消息部分(多模态支持)
	Parts []Part `json:"parts"`

	// Metadata 元数据
	Metadata map[string]any `json:"metadata,omitempty"`
}

Message 消息 消息是 Agent 与用户之间的通信单元,支持多模态内容。

func AgentInputToMessage

func AgentInputToMessage(input agent.Input) Message

AgentInputToMessage 将 Hexagon Agent Input 转换为 A2A Message

func AgentOutputToMessage

func AgentOutputToMessage(output agent.Output) Message

AgentOutputToMessage 将 Hexagon Agent Output 转换为 A2A Message

func NewAgentMessage

func NewAgentMessage(text string) Message

NewAgentMessage 创建 Agent 消息

func NewTextMessage

func NewTextMessage(role Role, text string) Message

NewTextMessage 创建文本消息

func NewUserMessage

func NewUserMessage(text string) Message

NewUserMessage 创建用户消息

func (*Message) GetTextContent

func (m *Message) GetTextContent() string

GetTextContent 获取消息的纯文本内容

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON 自定义 JSON 反序列化

type Middleware

type Middleware func(TaskHandler) TaskHandler

Middleware 中间件类型

func LoggingMiddleware

func LoggingMiddleware(logger func(format string, args ...any)) Middleware

LoggingMiddleware 日志中间件

func RecoveryMiddleware

func RecoveryMiddleware() Middleware

RecoveryMiddleware 恢复中间件

func TimeoutMiddleware

func TimeoutMiddleware(timeout time.Duration) Middleware

TimeoutMiddleware 超时中间件

type NetworkBridge

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

NetworkBridge 将 A2A 消息桥接到 Hexagon AgentNetwork 使得 A2A 客户端可以与 Hexagon Agent 网络中的 Agent 通信。

func NewNetworkBridge

func NewNetworkBridge(network *agent.AgentNetwork, store TaskStore) *NetworkBridge

NewNetworkBridge 创建网络桥接

func (*NetworkBridge) BroadcastMessage

func (b *NetworkBridge) BroadcastMessage(ctx context.Context, fromAgent string, msg *Message) error

BroadcastMessage 广播消息到网络中的所有 Agent

func (*NetworkBridge) SendToAgent

func (b *NetworkBridge) SendToAgent(ctx context.Context, agentID string, msg *Message) (*Message, error)

SendToAgent 将 A2A 消息发送到网络中的 Agent

func (*NetworkBridge) SendToAgentNetwork

func (b *NetworkBridge) SendToAgentNetwork(ctx context.Context, fromAgent, toAgent string, msg *Message) error

SendToAgentNetwork 通过网络消息路由发送

type NoAuthValidator

type NoAuthValidator struct{}

NoAuthValidator 无认证验证器 允许所有请求。

func (*NoAuthValidator) Validate

func (v *NoAuthValidator) Validate(_ *http.Request) (string, error)

Validate 实现 AuthValidator 接口

type OAuth2Flow

type OAuth2Flow struct {
	// AuthorizationURL 授权地址
	AuthorizationURL string `json:"authorizationUrl,omitempty"`

	// TokenURL Token 地址
	TokenURL string `json:"tokenUrl"`

	// Scopes 作用域
	Scopes map[string]string `json:"scopes,omitempty"`
}

OAuth2Flow OAuth2 流程详情

type OAuth2Flows

type OAuth2Flows struct {
	// AuthorizationCode 授权码流程
	AuthorizationCode *OAuth2Flow `json:"authorizationCode,omitempty"`

	// ClientCredentials 客户端凭证流程
	ClientCredentials *OAuth2Flow `json:"clientCredentials,omitempty"`
}

OAuth2Flows OAuth2 流程配置

type Part

type Part interface {
	// Type 返回部分类型
	Type() PartType
}

Part 消息部分接口 支持多模态内容:文本、文件、结构化数据

func UnmarshalPart

func UnmarshalPart(data []byte) (Part, error)

UnmarshalPart 从 JSON 反序列化 Part

func UnmarshalParts

func UnmarshalParts(data []byte) ([]Part, error)

UnmarshalParts 从 JSON 数组反序列化 Parts

type PartType

type PartType string

PartType 消息部分类型

const (
	// PartTypeText 文本类型
	PartTypeText PartType = "text"

	// PartTypeFile 文件类型
	PartTypeFile PartType = "file"

	// PartTypeData 数据类型
	PartTypeData PartType = "data"
)

type Permission

type Permission string

Permission 权限

const (
	// PermissionRead 读取权限
	PermissionRead Permission = "read"

	// PermissionWrite 写入权限
	PermissionWrite Permission = "write"

	// PermissionAdmin 管理权限
	PermissionAdmin Permission = "admin"

	// PermissionSendMessage 发送消息权限
	PermissionSendMessage Permission = "send_message"

	// PermissionCancelTask 取消任务权限
	PermissionCancelTask Permission = "cancel_task"

	// PermissionConfigPush 配置推送权限
	PermissionConfigPush Permission = "config_push"
)

type PushAuth

type PushAuth struct {
	// Schemes 支持的认证方案
	Schemes []string `json:"schemes,omitempty"`

	// Credentials 凭证信息
	Credentials string `json:"credentials,omitempty"`
}

PushAuth 推送认证配置

type PushConfigStore

type PushConfigStore interface {
	// SetPushConfig 设置推送配置
	SetPushConfig(ctx context.Context, taskID string, config *PushNotificationConfig) error

	// GetPushConfig 获取推送配置
	GetPushConfig(ctx context.Context, taskID string) (*PushNotificationConfig, error)
}

PushConfigStore 推送配置存储接口

type PushManager

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

PushManager 推送管理器 管理任务的推送配置和发送推送通知。

func NewPushManager

func NewPushManager(service PushService, opts ...PushManagerOption) *PushManager

NewPushManager 创建推送管理器

func (*PushManager) GetConfig

func (m *PushManager) GetConfig(taskID string) (*PushNotificationConfig, bool)

GetConfig 获取推送配置

func (*PushManager) Push

func (m *PushManager) Push(ctx context.Context, taskID string, notification *PushNotification) error

Push 发送推送通知

func (*PushManager) PushArtifact

func (m *PushManager) PushArtifact(ctx context.Context, taskID string, artifact *Artifact) error

PushArtifact 发送产物推送

func (*PushManager) PushTask

func (m *PushManager) PushTask(ctx context.Context, task *Task) error

PushTask 发送任务状态推送

func (*PushManager) RemoveConfig

func (m *PushManager) RemoveConfig(taskID string)

RemoveConfig 移除推送配置

func (*PushManager) SetConfig

func (m *PushManager) SetConfig(taskID string, config *PushNotificationConfig)

SetConfig 设置推送配置

type PushManagerOption

type PushManagerOption func(*PushManager)

PushManagerOption 推送管理器选项

func WithRateLimit

func WithRateLimit(limit int, window time.Duration) PushManagerOption

WithRateLimit 设置速率限制 limit: 窗口内允许的最大请求数 window: 时间窗口

func WithRetryConfig

func WithRetryConfig(config RetryConfig) PushManagerOption

WithRetryConfig 设置重试配置

type PushNotification

type PushNotification struct {
	// TaskID 任务 ID
	TaskID string `json:"taskId"`

	// Event 事件类型
	Event string `json:"event"`

	// Task 任务状态(完整状态)
	Task *Task `json:"task,omitempty"`

	// Status 任务状态(仅状态)
	Status *TaskStatus `json:"status,omitempty"`

	// Artifact 产物(仅产物事件)
	Artifact *Artifact `json:"artifact,omitempty"`

	// Timestamp 时间戳
	Timestamp time.Time `json:"timestamp"`
}

PushNotification 推送通知内容

func NewArtifactNotification

func NewArtifactNotification(taskID string, artifact *Artifact) *PushNotification

NewArtifactNotification 创建产物通知

func NewTaskStatusNotification

func NewTaskStatusNotification(task *Task) *PushNotification

NewTaskStatusNotification 创建任务状态通知

type PushNotificationConfig

type PushNotificationConfig struct {
	// URL 推送目标 URL
	URL string `json:"url"`

	// Token 认证 Token(可选)
	Token string `json:"token,omitempty"`

	// Authentication 认证配置(可选)
	Authentication *PushAuth `json:"authentication,omitempty"`
}

PushNotificationConfig 推送通知配置

type PushService

type PushService interface {
	// Push 发送推送通知
	Push(ctx context.Context, config *PushNotificationConfig, task *Task) error
}

PushService 推送服务接口

func NewDefaultPushService

func NewDefaultPushService() PushService

NewDefaultPushService 创建默认推送服务

type RBACValidator

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

RBACValidator RBAC 验证器

func NewRBACValidator

func NewRBACValidator(authValidator AuthValidator) *RBACValidator

NewRBACValidator 创建 RBAC 验证器

func (*RBACValidator) AddPermission

func (v *RBACValidator) AddPermission(clientID string, permission Permission)

AddPermission 添加权限

func (*RBACValidator) HasPermission

func (v *RBACValidator) HasPermission(clientID string, permission Permission) bool

HasPermission 检查权限

func (*RBACValidator) RequirePermission

func (v *RBACValidator) RequirePermission(permission Permission) func(http.Handler) http.Handler

RequirePermission 创建需要特定权限的中间件

func (*RBACValidator) SetPermissions

func (v *RBACValidator) SetPermissions(clientID string, permissions ...Permission)

SetPermissions 设置客户端权限

func (*RBACValidator) Validate

func (v *RBACValidator) Validate(r *http.Request) (string, error)

Validate 实现 AuthValidator 接口

type RegistryDiscovery

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

RegistryDiscovery 基于 Hexagon Registry 的 Agent 发现服务 将 Hexagon 的 Agent 注册表与 A2A 协议桥接。

func NewRegistryDiscovery

func NewRegistryDiscovery(registry *agent.Registry, baseURL string) *RegistryDiscovery

NewRegistryDiscovery 创建基于 Registry 的发现服务

func (*RegistryDiscovery) Deregister

func (d *RegistryDiscovery) Deregister(_ context.Context, url string) error

Deregister 注销 Agent

func (*RegistryDiscovery) Discover

func (d *RegistryDiscovery) Discover(_ context.Context, filter *AgentFilter) ([]*AgentCard, error)

Discover 发现符合条件的 Agent

func (*RegistryDiscovery) Get

Get 获取指定 Agent

func (*RegistryDiscovery) Register

func (d *RegistryDiscovery) Register(_ context.Context, card *AgentCard) error

Register 注册 Agent

func (*RegistryDiscovery) Watch

Watch 监听 Agent 变化

type RemoteAgent

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

RemoteAgent 将远程 A2A Agent 包装为 Hexagon Agent 使得 A2A Agent 可以参与 Hexagon Agent 网络。

func ConnectToA2AAgent

func ConnectToA2AAgent(url string, opts ...ClientOption) (*RemoteAgent, error)

ConnectToA2AAgent 连接到远程 A2A Agent 返回一个可用于 Hexagon Agent 网络的 Agent。

func NewRemoteAgent

func NewRemoteAgent(url string, opts ...ClientOption) (*RemoteAgent, error)

NewRemoteAgent 创建远程 Agent

func (*RemoteAgent) Card

func (a *RemoteAgent) Card() *AgentCard

Card 返回 Agent Card

func (*RemoteAgent) Close

func (a *RemoteAgent) Close() error

Close 关闭远程 Agent

func (*RemoteAgent) ID

func (a *RemoteAgent) ID() string

ID 返回 Agent ID

func (*RemoteAgent) Name

func (a *RemoteAgent) Name() string

Name 返回 Agent 名称

func (*RemoteAgent) NewSession

func (a *RemoteAgent) NewSession()

NewSession 开始新会话

func (*RemoteAgent) Run

func (a *RemoteAgent) Run(ctx context.Context, input agent.Input) (agent.Output, error)

Run 执行 Agent

type RemoteDiscovery

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

RemoteDiscovery 远程 Agent 发现服务 通过 HTTP 获取远程 Agent 的 Card。

func NewRemoteDiscovery

func NewRemoteDiscovery(cacheTTL time.Duration) *RemoteDiscovery

NewRemoteDiscovery 创建远程发现服务

func (*RemoteDiscovery) AddAgent

func (d *RemoteDiscovery) AddAgent(url string)

AddAgent 添加要发现的 Agent URL

func (*RemoteDiscovery) Deregister

func (d *RemoteDiscovery) Deregister(_ context.Context, url string) error

Deregister 注销 Agent

func (*RemoteDiscovery) Discover

func (d *RemoteDiscovery) Discover(ctx context.Context, filter *AgentFilter) ([]*AgentCard, error)

Discover 发现符合条件的 Agent

func (*RemoteDiscovery) Get

func (d *RemoteDiscovery) Get(ctx context.Context, url string) (*AgentCard, error)

Get 获取指定 Agent

func (*RemoteDiscovery) Register

func (d *RemoteDiscovery) Register(_ context.Context, card *AgentCard) error

Register 注册 Agent(添加到发现列表)

func (*RemoteDiscovery) Watch

func (d *RemoteDiscovery) Watch(_ context.Context, _ *AgentFilter) (<-chan DiscoveryEvent, error)

Watch 监听 Agent 变化(远程发现不支持实时监听)

type ResubscribeRequest

type ResubscribeRequest struct {
	// TaskID 任务 ID
	TaskID string `json:"id"`
}

ResubscribeRequest 重新订阅请求

type RetryConfig

type RetryConfig struct {
	// MaxRetries 最大重试次数
	MaxRetries int

	// InitialDelay 初始延迟
	InitialDelay time.Duration

	// MaxDelay 最大延迟
	MaxDelay time.Duration

	// Multiplier 延迟乘数
	Multiplier float64
}

RetryConfig 重试配置

type Role

type Role string

Role 消息角色

const (
	// RoleUser 用户角色
	RoleUser Role = "user"

	// RoleAgent Agent 角色
	RoleAgent Role = "agent"
)

type SendMessageRequest

type SendMessageRequest struct {
	// TaskID 任务 ID(可选,不提供则创建新任务)
	TaskID string `json:"id,omitempty"`

	// SessionID 会话 ID(可选)
	SessionID string `json:"sessionId,omitempty"`

	// Message 消息内容
	Message Message `json:"message"`

	// AcceptedOutputModes 接受的输出模式
	AcceptedOutputModes []string `json:"acceptedOutputModes,omitempty"`

	// PushNotification 推送通知配置(可选)
	PushNotification *PushNotificationConfig `json:"pushNotification,omitempty"`

	// HistoryLength 返回的历史消息数量
	HistoryLength int `json:"historyLength,omitempty"`

	// Metadata 元数据
	Metadata map[string]any `json:"metadata,omitempty"`
}

SendMessageRequest 发送消息请求

type SendMessageResponse

type SendMessageResponse = Task

SendMessageResponse 发送消息响应 直接返回 Task 对象

type Server

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

Server A2A 服务器 提供 A2A 协议的服务端实现。

使用示例:

card := &a2a.AgentCard{
    Name:    "assistant",
    URL:     "http://localhost:8080",
    Version: "1.0.0",
}

handler := &MyTaskHandler{}
server := a2a.NewServer(card, handler)
server.Start(":8080")

func ExposeAgent

func ExposeAgent(a agent.Agent, baseURL string, opts ...ServerOption) *Server

ExposeAgent 将 Hexagon Agent 作为 A2A 服务暴露 返回一个可直接启动的 A2A Server。

func NewServer

func NewServer(card *AgentCard, handler TaskHandler, opts ...ServerOption) *Server

NewServer 创建 A2A 服务器

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler 返回 HTTP Handler

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP 实现 http.Handler 接口

func (*Server) Start

func (s *Server) Start(addr string) error

Start 启动服务器

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop 停止服务器

type ServerOption

type ServerOption func(*Server)

ServerOption 服务器选项

func WithCORS

func WithCORS(enabled bool, origins ...string) ServerOption

WithCORS 设置 CORS

func WithPushService

func WithPushService(pushService PushService) ServerOption

WithPushService 设置推送服务

func WithStore

func WithStore(store TaskStore) ServerOption

WithStore 设置任务存储

type SetPushNotificationRequest

type SetPushNotificationRequest struct {
	// TaskID 任务 ID
	TaskID string `json:"id"`

	// Config 推送配置
	Config PushNotificationConfig `json:"pushNotificationConfig"`
}

SetPushNotificationRequest 设置推送通知请求

type SetPushNotificationResponse

type SetPushNotificationResponse struct {
	// Config 推送配置
	Config PushNotificationConfig `json:"pushNotificationConfig"`
}

SetPushNotificationResponse 设置推送通知响应

type SkillMatcher

type SkillMatcher func(msg *Message) bool

SkillMatcher 技能匹配器

func AlwaysMatcher

func AlwaysMatcher() SkillMatcher

AlwaysMatcher 创建始终匹配的匹配器

func ContainsMatcher

func ContainsMatcher(substr string) SkillMatcher

ContainsMatcher 创建包含匹配器

func PrefixMatcher

func PrefixMatcher(prefix string) SkillMatcher

PrefixMatcher 创建前缀匹配器

type SkillRoute

type SkillRoute struct {
	// Matcher 匹配器
	Matcher SkillMatcher

	// Handler 处理器
	Handler TaskHandler
}

SkillRoute 技能路由

type SkillRouter

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

SkillRouter 技能路由器 根据消息内容路由到不同的处理器。

func NewSkillRouter

func NewSkillRouter() *SkillRouter

NewSkillRouter 创建技能路由器

func (*SkillRouter) Default

func (r *SkillRouter) Default(handler TaskHandler) *SkillRouter

Default 设置默认处理器

func (*SkillRouter) HandleTask

func (r *SkillRouter) HandleTask(ctx context.Context, task *Task, msg *Message) (*TaskUpdate, error)

HandleTask 实现 TaskHandler 接口

func (*SkillRouter) Route

func (r *SkillRouter) Route(matcher SkillMatcher, handler TaskHandler) *SkillRouter

Route 添加路由

type StaticDiscovery

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

StaticDiscovery 静态 Agent 发现服务 用于已知固定 Agent 列表的场景。

func NewStaticDiscovery

func NewStaticDiscovery(cards ...*AgentCard) *StaticDiscovery

NewStaticDiscovery 创建静态发现服务

func (*StaticDiscovery) Deregister

func (d *StaticDiscovery) Deregister(_ context.Context, url string) error

Deregister 注销 Agent

func (*StaticDiscovery) Discover

func (d *StaticDiscovery) Discover(_ context.Context, filter *AgentFilter) ([]*AgentCard, error)

Discover 发现符合条件的 Agent

func (*StaticDiscovery) Get

func (d *StaticDiscovery) Get(_ context.Context, url string) (*AgentCard, error)

Get 获取指定 Agent

func (*StaticDiscovery) Register

func (d *StaticDiscovery) Register(_ context.Context, card *AgentCard) error

Register 注册 Agent

func (*StaticDiscovery) Watch

func (d *StaticDiscovery) Watch(_ context.Context, _ *AgentFilter) (<-chan DiscoveryEvent, error)

Watch 监听 Agent 变化(静态发现不支持监听)

type StreamEvent

type StreamEvent interface {
	// EventType 返回事件类型
	EventType() string
}

StreamEvent 流式事件接口

type StreamingAgentWrapper

type StreamingAgentWrapper struct {
	*AgentWrapper
}

StreamingAgentWrapper 流式 Agent 包装器 使用 Agent 的 Stream 方法实现流式输出。

func WrapStreamingAgent

func WrapStreamingAgent(a agent.Agent) *StreamingAgentWrapper

WrapStreamingAgent 包装 Agent 为流式处理器 Agent 必须实现 Stream 方法(所有实现 Runnable 接口的 Agent 都支持)

func (*StreamingAgentWrapper) HandleTaskStream

func (w *StreamingAgentWrapper) HandleTaskStream(ctx context.Context, task *Task, msg *Message) (<-chan *TaskUpdate, error)

HandleTaskStream 实现 StreamingTaskHandler 接口

type StreamingFuncHandler

type StreamingFuncHandler struct {
	*FuncHandler
	// contains filtered or unexported fields
}

StreamingFuncHandler 流式函数处理器

func NewStreamingFuncHandler

func NewStreamingFuncHandler(fn TaskFunc, streamFn StreamingTaskFunc) *StreamingFuncHandler

NewStreamingFuncHandler 创建流式函数处理器

func (*StreamingFuncHandler) HandleTaskStream

func (h *StreamingFuncHandler) HandleTaskStream(ctx context.Context, task *Task, msg *Message) (<-chan *TaskUpdate, error)

HandleTaskStream 实现 StreamingTaskHandler 接口

type StreamingTaskFunc

type StreamingTaskFunc func(ctx context.Context, task *Task, msg *Message) (<-chan *TaskUpdate, error)

StreamingTaskFunc 流式任务处理函数类型

type StreamingTaskHandler

type StreamingTaskHandler interface {
	TaskHandler

	// HandleTaskStream 流式处理任务消息
	//
	// 参数:
	//   - ctx: 上下文
	//   - task: 当前任务状态
	//   - msg: 收到的消息
	//
	// 返回:
	//   - <-chan *TaskUpdate: 任务更新流
	//   - error: 处理错误
	HandleTaskStream(ctx context.Context, task *Task, msg *Message) (<-chan *TaskUpdate, error)
}

StreamingTaskHandler 流式任务处理器接口 支持流式输出的处理器应实现此接口。

type Task

type Task struct {
	// ID 任务 ID(必需)
	ID string `json:"id"`

	// SessionID 会话 ID(可选,用于关联多个任务)
	SessionID string `json:"sessionId,omitempty"`

	// Status 任务状态
	Status TaskStatus `json:"status"`

	// History 消息历史
	History []Message `json:"history,omitempty"`

	// Artifacts 任务产物
	Artifacts []Artifact `json:"artifacts,omitempty"`

	// Metadata 元数据
	Metadata map[string]any `json:"metadata,omitempty"`

	// CreatedAt 创建时间
	CreatedAt time.Time `json:"createdAt"`

	// UpdatedAt 更新时间
	UpdatedAt time.Time `json:"updatedAt"`
}

Task 任务定义 任务是 A2A 协议中的核心工作单元,表示一次 Agent 交互的完整生命周期。

func NewTask

func NewTask(id string) *Task

NewTask 创建新任务

type TaskFunc

type TaskFunc func(ctx context.Context, task *Task, msg *Message) (*TaskUpdate, error)

TaskFunc 任务处理函数类型

type TaskHandler

type TaskHandler interface {
	// HandleTask 处理任务消息
	//
	// 参数:
	//   - ctx: 上下文
	//   - task: 当前任务状态
	//   - msg: 收到的消息
	//
	// 返回:
	//   - TaskUpdate: 任务更新(状态、消息、产物等)
	//   - error: 处理错误
	HandleTask(ctx context.Context, task *Task, msg *Message) (*TaskUpdate, error)
}

TaskHandler 任务处理器接口 实现此接口来处理 A2A 任务请求。

使用示例:

type MyHandler struct {
    llm llm.Provider
}

func (h *MyHandler) HandleTask(ctx context.Context, task *Task, msg *Message) (*TaskUpdate, error) {
    // 调用 LLM 处理消息
    resp, err := h.llm.Complete(ctx, ...)
    if err != nil {
        return &TaskUpdate{
            Status: TaskStatus{State: TaskStateFailed},
        }, nil
    }

    return &TaskUpdate{
        Status: TaskStatus{State: TaskStateCompleted},
        Message: &Message{Role: RoleAgent, Parts: []Part{&TextPart{Text: resp}}},
    }, nil
}

func ApplyMiddleware

func ApplyMiddleware(handler TaskHandler, middlewares ...Middleware) TaskHandler

ApplyMiddleware 应用中间件

type TaskState

type TaskState string

TaskState 任务状态枚举

const (
	// TaskStateSubmitted 已提交 - 任务已创建,等待处理
	TaskStateSubmitted TaskState = "submitted"

	// TaskStateWorking 处理中 - Agent 正在处理任务
	TaskStateWorking TaskState = "working"

	// TaskStateInputRequired 需要输入 - 等待用户提供更多信息
	TaskStateInputRequired TaskState = "input-required"

	// TaskStateCompleted 已完成 - 任务成功完成
	TaskStateCompleted TaskState = "completed"

	// TaskStateFailed 已失败 - 任务执行失败
	TaskStateFailed TaskState = "failed"

	// TaskStateCanceled 已取消 - 任务被取消
	TaskStateCanceled TaskState = "canceled"
)

func AgentStatusToTaskState

func AgentStatusToTaskState(status agent.AgentStatus) TaskState

AgentStatusToTaskState 将 Hexagon Agent Status 转换为 A2A TaskState

func (TaskState) IsActive

func (s TaskState) IsActive() bool

IsActive 检查状态是否为活动状态

func (TaskState) IsTerminal

func (s TaskState) IsTerminal() bool

IsTerminal 检查状态是否为终态

type TaskStatus

type TaskStatus struct {
	// State 状态值
	State TaskState `json:"state"`

	// Message 状态消息(可选)
	Message *Message `json:"message,omitempty"`

	// Timestamp 状态更新时间
	Timestamp time.Time `json:"timestamp"`
}

TaskStatus 任务状态

type TaskStatusEvent

type TaskStatusEvent struct {
	// ID 任务 ID
	ID string `json:"id"`

	// Status 任务状态
	Status TaskStatus `json:"status"`

	// Final 是否为最终状态
	Final bool `json:"final,omitempty"`
}

TaskStatusEvent 任务状态事件

func (*TaskStatusEvent) EventType

func (e *TaskStatusEvent) EventType() string

EventType 返回事件类型

type TaskStore

type TaskStore interface {
	// Create 创建任务
	Create(ctx context.Context, task *Task) error

	// Get 获取任务
	Get(ctx context.Context, id string) (*Task, error)

	// Update 更新任务
	Update(ctx context.Context, task *Task) error

	// Delete 删除任务
	Delete(ctx context.Context, id string) error

	// List 列出任务
	List(ctx context.Context, opts *ListTasksRequest) (*ListTasksResponse, error)

	// GenerateID 生成任务 ID
	GenerateID() string
}

TaskStore 任务存储接口 提供任务的持久化存储能力。

type TaskUpdate

type TaskUpdate struct {
	// Status 新状态(可选,为空表示不更新状态)
	Status *TaskStatus `json:"status,omitempty"`

	// Message Agent 回复消息(可选)
	Message *Message `json:"message,omitempty"`

	// Artifact 产物(可选)
	Artifact *Artifact `json:"artifact,omitempty"`

	// Metadata 元数据更新(可选)
	Metadata map[string]any `json:"metadata,omitempty"`

	// Final 是否为最终更新
	Final bool `json:"final,omitempty"`
}

TaskUpdate 任务更新 表示任务状态的一次更新。

func NewArtifactUpdate

func NewArtifactUpdate(artifact *Artifact) *TaskUpdate

NewArtifactUpdate 创建产物更新

func NewCompletedUpdate

func NewCompletedUpdate(msg *Message) *TaskUpdate

NewCompletedUpdate 创建完成更新

func NewFailedUpdate

func NewFailedUpdate(errMsg string) *TaskUpdate

NewFailedUpdate 创建失败更新

func NewInputRequiredUpdate

func NewInputRequiredUpdate(prompt string) *TaskUpdate

NewInputRequiredUpdate 创建需要输入更新

func NewMessageUpdate

func NewMessageUpdate(msg *Message) *TaskUpdate

NewMessageUpdate 创建消息更新

func NewStatusUpdate

func NewStatusUpdate(state TaskState) *TaskUpdate

NewStatusUpdate 创建状态更新

type TextPart

type TextPart struct {
	// Text 文本内容
	Text string `json:"text"`
}

TextPart 文本部分

func (*TextPart) MarshalJSON

func (p *TextPart) MarshalJSON() ([]byte, error)

MarshalJSON 自定义 JSON 序列化

func (*TextPart) Type

func (p *TextPart) Type() PartType

Type 返回文本类型

type WebhookPushOption

type WebhookPushOption func(*WebhookPushService)

WebhookPushOption Webhook 推送选项

func WithPushHTTPClient

func WithPushHTTPClient(client *http.Client) WebhookPushOption

WithPushHTTPClient 设置 HTTP 客户端

func WithPushHeaders

func WithPushHeaders(headers map[string]string) WebhookPushOption

WithPushHeaders 设置默认请求头

func WithPushSignKey

func WithPushSignKey(key string) WebhookPushOption

WithPushSignKey 设置签名密钥

type WebhookPushService

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

WebhookPushService Webhook 推送服务 通过 HTTP POST 发送推送通知到配置的 URL。

func NewWebhookPushService

func NewWebhookPushService(opts ...WebhookPushOption) *WebhookPushService

NewWebhookPushService 创建 Webhook 推送服务

func (*WebhookPushService) Push

func (s *WebhookPushService) Push(ctx context.Context, config *PushNotificationConfig, task *Task) error

Push 发送推送通知

Jump to

Keyboard shortcuts

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