protocol

package
v0.3.0 Latest Latest
Warning

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

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

Documentation

Overview

Package protocol implements the A2A-over-P2P message exchange protocol.

Index

Constants

View Source
const ProtocolID = "/lango/a2a/1.0.0"

ProtocolID is the libp2p protocol identifier for A2A messages.

Variables

View Source
var (
	ErrMissingToolName       = errors.New("missing toolName in payload")
	ErrAgentCardUnavailable  = errors.New("agent card not available")
	ErrNoApprovalHandler     = errors.New("no approval handler configured for remote tool invocation")
	ErrDeniedByOwner         = errors.New("tool invocation denied by owner")
	ErrExecutorNotConfigured = errors.New("tool executor not configured")
	ErrInvalidSession        = errors.New("invalid or expired session token")
	ErrInvalidPaymentAuth    = errors.New("invalid payment authorization")
)

Sentinel errors for protocol-level failures.

Functions

This section is empty.

Types

type AttestationData

type AttestationData struct {
	Proof        []byte `json:"proof"`
	PublicInputs []byte `json:"publicInputs"`
	CircuitID    string `json:"circuitId"`
	Scheme       string `json:"scheme"`
}

AttestationData holds structured ZK attestation proof with metadata.

type CapabilityQueryPayload

type CapabilityQueryPayload struct {
	Filter string `json:"filter,omitempty"` // optional tool name prefix filter
}

CapabilityQueryPayload is the payload for a capability query.

type CardProvider

type CardProvider func() map[string]interface{}

CardProvider returns the local agent card as a map.

type Handler

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

Handler processes A2A-over-P2P messages on libp2p streams.

func NewHandler

func NewHandler(cfg HandlerConfig) *Handler

NewHandler creates a new A2A-over-P2P protocol handler.

func (*Handler) SetApprovalFunc

func (h *Handler) SetApprovalFunc(fn ToolApprovalFunc)

SetApprovalFunc sets the owner approval callback for remote tool invocations.

func (*Handler) SetExecutor

func (h *Handler) SetExecutor(exec ToolExecutor)

SetExecutor sets the tool executor callback.

func (*Handler) SetPayGate

func (h *Handler) SetPayGate(gate PayGateChecker)

SetPayGate sets the payment gate checker for paid tool invocations.

func (*Handler) SetSandboxExecutor

func (h *Handler) SetSandboxExecutor(exec ToolExecutor)

SetSandboxExecutor sets an isolated executor for remote tool invocations. When set, tool calls from remote peers use this executor instead of the default in-process executor, preventing access to parent process memory.

func (*Handler) SetSecurityEvents

func (h *Handler) SetSecurityEvents(tracker SecurityEventTracker)

SetSecurityEvents sets the security event tracker for recording tool execution outcomes and triggering auto-invalidation on repeated failures.

func (*Handler) StreamHandler

func (h *Handler) StreamHandler() network.StreamHandler

StreamHandler returns a libp2p stream handler for incoming A2A messages.

type HandlerConfig

type HandlerConfig struct {
	Sessions *handshake.SessionStore
	Firewall *firewall.Firewall
	Executor ToolExecutor
	CardFn   CardProvider
	LocalDID string
	Logger   *zap.SugaredLogger
}

HandlerConfig configures the protocol handler.

type P2PRemoteAgent

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

P2PRemoteAgent represents a remote agent accessible over P2P. It can be used as a sub-agent in the orchestration framework.

func NewRemoteAgent

func NewRemoteAgent(cfg RemoteAgentConfig) *P2PRemoteAgent

NewRemoteAgent creates a remote agent adapter for P2P communication.

func (*P2PRemoteAgent) Capabilities

func (a *P2PRemoteAgent) Capabilities() []string

Capabilities returns the remote agent's advertised capabilities.

func (*P2PRemoteAgent) DID

func (a *P2PRemoteAgent) DID() string

DID returns the remote agent's decentralized identifier.

func (*P2PRemoteAgent) FetchAgentCard

func (a *P2PRemoteAgent) FetchAgentCard(ctx context.Context) (map[string]interface{}, error)

FetchAgentCard fetches the remote agent card.

func (*P2PRemoteAgent) InvokeTool

func (a *P2PRemoteAgent) InvokeTool(ctx context.Context, toolName string, params map[string]interface{}) (map[string]interface{}, error)

InvokeTool sends a tool invocation to the remote agent.

func (*P2PRemoteAgent) InvokeToolPaid

func (a *P2PRemoteAgent) InvokeToolPaid(
	ctx context.Context,
	toolName string,
	params map[string]interface{},
	paymentAuth map[string]interface{},
) (*Response, error)

InvokeToolPaid sends a paid tool invocation to the remote agent.

func (*P2PRemoteAgent) Name

func (a *P2PRemoteAgent) Name() string

Name returns the remote agent's name.

func (*P2PRemoteAgent) PeerID

func (a *P2PRemoteAgent) PeerID() peer.ID

PeerID returns the remote agent's libp2p peer ID.

func (*P2PRemoteAgent) QueryCapabilities

func (a *P2PRemoteAgent) QueryCapabilities(ctx context.Context) (map[string]interface{}, error)

QueryCapabilities fetches the remote agent's capabilities.

func (*P2PRemoteAgent) QueryPrice

func (a *P2PRemoteAgent) QueryPrice(ctx context.Context, toolName string) (*PriceQuoteResult, error)

QueryPrice queries the pricing for a tool on the remote agent.

func (*P2PRemoteAgent) SetAttestVerifier

func (a *P2PRemoteAgent) SetAttestVerifier(fn ZKAttestVerifyFunc)

SetAttestVerifier sets the ZK attestation verification callback.

type PaidInvokePayload

type PaidInvokePayload struct {
	ToolName    string                 `json:"toolName"`
	Params      map[string]interface{} `json:"params"`
	PaymentAuth map[string]interface{} `json:"paymentAuth,omitempty"`
}

PaidInvokePayload is the payload for a paid tool invocation.

type PayGateChecker

type PayGateChecker interface {
	Check(peerDID, toolName string, payload map[string]interface{}) (PayGateResult, error)
}

PayGateChecker checks payment for a tool invocation.

type PayGateResult

type PayGateResult struct {
	Status     string                 // payGateStatusFree, payGateStatusVerified, payGateStatusPaymentRequired, payGateStatusInvalid
	Auth       interface{}            // the verified authorization (opaque to handler)
	PriceQuote map[string]interface{} // price quote when payment required
}

PayGateResult represents the payment check outcome.

type PriceQuoteResult

type PriceQuoteResult struct {
	ToolName     string `json:"toolName"`
	Price        string `json:"price"`
	Currency     string `json:"currency"`
	USDCContract string `json:"usdcContract"`
	ChainID      int64  `json:"chainId"`
	SellerAddr   string `json:"sellerAddr"`
	QuoteExpiry  int64  `json:"quoteExpiry"`
	IsFree       bool   `json:"isFree"`
}

PriceQuoteResult is returned when querying tool pricing.

type RemoteAgentConfig

type RemoteAgentConfig struct {
	Name           string
	DID            string
	PeerID         peer.ID
	SessionToken   string
	Host           host.Host
	Capabilities   []string
	AttestVerifier ZKAttestVerifyFunc
	Logger         *zap.SugaredLogger
}

RemoteAgentConfig configures a P2P remote agent.

type Request

type Request struct {
	Type         RequestType            `json:"type"`
	SessionToken string                 `json:"sessionToken"`
	RequestID    string                 `json:"requestId"`
	Payload      map[string]interface{} `json:"payload,omitempty"`
}

Request is a P2P A2A request message.

type RequestType

type RequestType string

RequestType identifies the type of A2A request.

const (
	// RequestToolInvoke invokes a tool on the remote agent.
	RequestToolInvoke RequestType = "tool_invoke"

	// RequestCapabilityQuery queries the capabilities of the remote agent.
	RequestCapabilityQuery RequestType = "capability_query"

	// RequestAgentCard requests the agent card of the remote agent.
	RequestAgentCard RequestType = "agent_card"

	// RequestPriceQuery queries the pricing for a tool on the remote agent.
	RequestPriceQuery RequestType = "price_query"

	// RequestToolInvokePaid invokes a paid tool on the remote agent.
	RequestToolInvokePaid RequestType = "tool_invoke_paid"
)

type Response

type Response struct {
	RequestID        string                 `json:"requestId"`
	Status           ResponseStatus         `json:"status"` // ResponseStatusOK, ResponseStatusError, ResponseStatusDenied
	Result           map[string]interface{} `json:"result,omitempty"`
	Error            string                 `json:"error,omitempty"`
	AttestationProof []byte                 `json:"attestationProof,omitempty"` // Deprecated: use Attestation
	Attestation      *AttestationData       `json:"attestation,omitempty"`
	Timestamp        time.Time              `json:"timestamp"`
}

Response is a P2P A2A response message.

func SendRequest

func SendRequest(ctx context.Context, s network.Stream, reqType RequestType, token string, payload map[string]interface{}) (*Response, error)

SendRequest sends an A2A request to a remote peer over a stream.

type ResponseStatus

type ResponseStatus string

ResponseStatus identifies the status of an A2A response.

const (
	// ResponseStatusOK indicates a successful response.
	ResponseStatusOK ResponseStatus = "ok"

	// ResponseStatusError indicates an error response.
	ResponseStatusError ResponseStatus = "error"

	// ResponseStatusDenied indicates the request was denied.
	ResponseStatusDenied ResponseStatus = "denied"

	// ResponseStatusPaymentRequired indicates payment is needed.
	ResponseStatusPaymentRequired ResponseStatus = "payment_required"
)

func (ResponseStatus) Valid

func (s ResponseStatus) Valid() bool

Valid reports whether s is a known response status.

type SecurityEventTracker

type SecurityEventTracker interface {
	RecordToolFailure(peerDID string)
	RecordToolSuccess(peerDID string)
}

SecurityEventTracker records tool execution outcomes for security monitoring. Uses the callback pattern to avoid import cycles with the handshake package.

type ToolApprovalFunc

type ToolApprovalFunc func(ctx context.Context, peerDID, toolName string, params map[string]interface{}) (bool, error)

ToolApprovalFunc asks the local owner for approval before executing a remote tool invocation. Returns true if approved, false if denied. Uses the callback pattern to avoid import cycles with the approval package.

type ToolExecutor

type ToolExecutor func(ctx context.Context, toolName string, params map[string]interface{}) (map[string]interface{}, error)

ToolExecutor executes a tool by name with the given parameters. Uses the callback pattern to avoid import cycles with the agent package.

type ToolInvokePayload

type ToolInvokePayload struct {
	ToolName string                 `json:"toolName"`
	Params   map[string]interface{} `json:"params"`
}

ToolInvokePayload is the payload for a tool invocation request.

type ZKAttestVerifyFunc

type ZKAttestVerifyFunc func(ctx context.Context, attestation *AttestationData) (bool, error)

ZKAttestVerifyFunc verifies a ZK attestation proof from a remote peer.

Jump to

Keyboard shortcuts

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