protocol

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
const (
	OntologyActionAccepted = "accepted"
	OntologyActionPartial  = "partial"
	OntologyActionRejected = "rejected"
)

Ontology proposal action outcomes.

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")
	ErrNoSandboxExecutor     = errors.New("tool execution refused: no sandbox executor configured for remote peer requests")
	ErrToolSafetyBlocked     = errors.New("tool blocked by P2P safety level policy")
)

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 ContextSharePayload added in v0.4.0

type ContextSharePayload struct {
	TeamID  string                 `json:"teamId"`
	Context map[string]interface{} `json:"context"`
}

ContextSharePayload is the payload for sharing scoped context with a team member.

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) SetEventBus added in v0.4.0

func (h *Handler) SetEventBus(bus *eventbus.Bus)

SetEventBus sets the event bus for post-execution event publishing.

func (*Handler) SetExecutor

func (h *Handler) SetExecutor(exec ToolExecutor)

SetExecutor sets the tool executor callback.

func (*Handler) SetNegotiator added in v0.5.0

func (h *Handler) SetNegotiator(fn NegotiateHandler)

SetNegotiator sets the handler for negotiation protocol messages.

func (*Handler) SetOntologyHandler added in v0.7.0

func (h *Handler) SetOntologyHandler(oh OntologyHandler)

SetOntologyHandler sets the handler for ontology schema exchange messages.

func (*Handler) SetPayGate

func (h *Handler) SetPayGate(gate PayGateChecker)

SetPayGate sets the payment gate checker for paid tool invocations.

func (*Handler) SetSafetyGate added in v0.7.0

func (h *Handler) SetSafetyGate(checker SafetyLevelChecker, maxLevel int, allowedTools []string)

SetSafetyGate configures the safety-level gate for P2P tool invocations. maxLevel is the numeric safety threshold (1=safe, 2=moderate, 3=dangerous). checker looks up a tool's safety level; allowedTools bypasses the gate.

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) SetTeamHandler added in v0.6.0

func (h *Handler) SetTeamHandler(fn TeamHandler)

SetTeamHandler sets the handler for team protocol messages.

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 NegotiateHandler added in v0.5.0

type NegotiateHandler func(ctx context.Context, peerDID string, payload NegotiatePayload) (map[string]interface{}, error)

NegotiateHandler processes negotiation protocol messages.

type NegotiatePayload added in v0.5.0

type NegotiatePayload struct {
	SessionID string `json:"sessionId,omitempty"` // empty for initial proposal
	Action    string `json:"action"`              // "propose", "counter", "accept", "reject"
	ToolName  string `json:"toolName,omitempty"`
	Price     string `json:"price,omitempty"` // USDC amount as string
	Reason    string `json:"reason,omitempty"`
}

NegotiatePayload is the payload for negotiation messages.

type OntologyHandler added in v0.7.0

type OntologyHandler interface {
	HandleSchemaQuery(ctx context.Context, peerDID string, req SchemaQueryRequest) (*SchemaQueryResponse, error)
	HandleSchemaPropose(ctx context.Context, peerDID string, req SchemaProposeRequest) (*SchemaProposeResponse, error)
}

OntologyHandler processes ontology exchange protocol messages. Implementations live in the bridge package to avoid import cycles.

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) SendTeamDisband added in v0.6.0

func (a *P2PRemoteAgent) SendTeamDisband(ctx context.Context, disband TeamDisbandPayload) (*Response, error)

SendTeamDisband notifies the remote agent that the team is disbanding.

func (*P2PRemoteAgent) SendTeamInvite added in v0.6.0

func (a *P2PRemoteAgent) SendTeamInvite(ctx context.Context, invite TeamInvitePayload) (*Response, error)

SendTeamInvite sends a team invitation to the remote agent.

func (*P2PRemoteAgent) SendTeamTask added in v0.6.0

func (a *P2PRemoteAgent) SendTeamTask(ctx context.Context, task TeamTaskPayload) (*Response, error)

SendTeamTask delegates a task to the remote agent as a team member.

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, payGateStatusPostPayApproved
	Auth         interface{}            // the verified authorization (opaque to handler)
	PriceQuote   map[string]interface{} // price quote when payment required
	SettlementID string                 // deferred settlement ID for post-pay
}

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"

	// RequestContextShare shares scoped context with a team member.
	RequestContextShare RequestType = "context_share"

	// RequestNegotiatePropose proposes a negotiation session.
	RequestNegotiatePropose RequestType = "negotiate_propose"

	// RequestNegotiateRespond responds to a negotiation (counter/accept/reject).
	RequestNegotiateRespond RequestType = "negotiate_respond"

	// RequestSchemaQuery queries a peer's ontology schema bundle.
	RequestSchemaQuery RequestType = "schema_query"

	// RequestSchemaPropose proposes ontology schema elements for import.
	RequestSchemaPropose RequestType = "schema_propose"
)
const (
	// RequestTeamInvite invites a remote agent to join a team.
	RequestTeamInvite RequestType = "team_invite"

	// RequestTeamAccept acknowledges acceptance of a team invitation.
	RequestTeamAccept RequestType = "team_accept"

	// RequestTeamTask delegates a task to a team member.
	RequestTeamTask RequestType = "team_task"

	// RequestTeamResult reports the result of a delegated task back to the leader.
	RequestTeamResult RequestType = "team_result"

	// RequestTeamDisband notifies team members that the team is disbanding.
	RequestTeamDisband RequestType = "team_disband"
)

Team-specific request types for P2P team coordination.

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 SafetyLevelChecker added in v0.7.0

type SafetyLevelChecker func(toolName string) (int, bool)

SafetyLevelChecker looks up a tool's safety level by name. Returns the numeric level and true if found, or (dangerous, false) for unknown tools.

type SchemaProposeRequest added in v0.7.0

type SchemaProposeRequest struct {
	// Bundle is the JSON-encoded SchemaBundle to propose for import.
	// Uses json.RawMessage to avoid importing internal/ontology.
	Bundle json.RawMessage `json:"bundle"`

	// Reason describes why the schema elements are being proposed.
	Reason string `json:"reason,omitempty"`
}

SchemaProposeRequest proposes ontology schema elements for import.

type SchemaProposeResponse added in v0.7.0

type SchemaProposeResponse struct {
	// Action is the outcome: OntologyActionAccepted, OntologyActionPartial, or OntologyActionRejected.
	Action string `json:"action"`

	// Accepted lists the names of schema elements that were accepted.
	Accepted []string `json:"accepted,omitempty"`

	// Rejected lists the names of schema elements that were rejected.
	Rejected []string `json:"rejected,omitempty"`

	// Result is the JSON-encoded ImportResult from the ontology package.
	// Uses json.RawMessage to avoid importing internal/ontology.
	Result json.RawMessage `json:"result,omitempty"`
}

SchemaProposeResponse reports the result of a schema proposal.

type SchemaQueryRequest added in v0.7.0

type SchemaQueryRequest struct {
	// RequestedTypes filters the response to specific entity type names.
	// Empty means return all types.
	RequestedTypes []string `json:"requestedTypes,omitempty"`

	// IncludePredicates controls whether predicate definitions are included.
	IncludePredicates bool `json:"includePredicates"`
}

SchemaQueryRequest requests a peer's ontology schema bundle.

type SchemaQueryResponse added in v0.7.0

type SchemaQueryResponse struct {
	// Bundle is the JSON-encoded SchemaBundle from the ontology package.
	// Uses json.RawMessage to avoid importing internal/ontology.
	Bundle json.RawMessage `json:"bundle"`
}

SchemaQueryResponse returns the peer's ontology schema bundle.

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 TeamAcceptHandler added in v0.6.0

type TeamAcceptHandler func(ctx context.Context, peerDID string, payload TeamAcceptPayload) (map[string]interface{}, error)

TeamAcceptHandler handles team acceptance responses.

type TeamAcceptPayload added in v0.4.0

type TeamAcceptPayload struct {
	TeamID    string `json:"teamId"`
	MemberDID string `json:"memberDid"`
	Accepted  bool   `json:"accepted"`
	Reason    string `json:"reason,omitempty"`
}

TeamAcceptPayload is the payload for accepting a team invitation.

type TeamDisbandHandler added in v0.6.0

type TeamDisbandHandler func(ctx context.Context, peerDID string, payload TeamDisbandPayload) (map[string]interface{}, error)

TeamDisbandHandler handles team disband notifications.

type TeamDisbandPayload added in v0.4.0

type TeamDisbandPayload struct {
	TeamID string `json:"teamId"`
	Reason string `json:"reason"`
}

TeamDisbandPayload is the payload for disbanding a team.

type TeamHandler added in v0.6.0

type TeamHandler func(ctx context.Context, peerDID string, reqType RequestType, payload map[string]interface{}) (map[string]interface{}, error)

TeamHandler processes team-related protocol messages.

type TeamInviteHandler added in v0.6.0

type TeamInviteHandler func(ctx context.Context, peerDID string, payload TeamInvitePayload) (map[string]interface{}, error)

TeamInviteHandler handles team invitation requests.

type TeamInvitePayload added in v0.4.0

type TeamInvitePayload struct {
	TeamID       string   `json:"teamId"`
	TeamName     string   `json:"teamName"`
	Goal         string   `json:"goal"`
	LeaderDID    string   `json:"leaderDid"`
	Role         string   `json:"role"`
	Capabilities []string `json:"capabilities"`
}

TeamInvitePayload is the payload for a team invitation.

type TeamResultHandler added in v0.6.0

type TeamResultHandler func(ctx context.Context, peerDID string, payload TeamResultPayload) (map[string]interface{}, error)

TeamResultHandler handles team task results.

type TeamResultPayload added in v0.4.0

type TeamResultPayload struct {
	TeamID    string                 `json:"teamId"`
	TaskID    string                 `json:"taskId"`
	MemberDID string                 `json:"memberDid"`
	Result    map[string]interface{} `json:"result,omitempty"`
	Error     string                 `json:"error,omitempty"`
	Duration  int64                  `json:"durationMs"`
}

TeamResultPayload is the payload for reporting a task result.

type TeamRouter added in v0.6.0

type TeamRouter struct {
	OnInvite  TeamInviteHandler
	OnAccept  TeamAcceptHandler
	OnTask    TeamTaskHandler
	OnResult  TeamResultHandler
	OnDisband TeamDisbandHandler
}

TeamRouter dispatches team messages to type-specific handlers.

func (*TeamRouter) Handle added in v0.6.0

func (r *TeamRouter) Handle(ctx context.Context, peerDID string, reqType RequestType, payload map[string]interface{}) (map[string]interface{}, error)

Handle routes a team request to the appropriate handler based on request type.

type TeamTaskHandler added in v0.6.0

type TeamTaskHandler func(ctx context.Context, peerDID string, payload TeamTaskPayload) (map[string]interface{}, error)

TeamTaskHandler handles team task delegation.

type TeamTaskPayload added in v0.4.0

type TeamTaskPayload struct {
	TeamID   string                 `json:"teamId"`
	TaskID   string                 `json:"taskId"`
	ToolName string                 `json:"toolName"`
	Params   map[string]interface{} `json:"params"`
	Deadline time.Time              `json:"deadline,omitempty"`
}

TeamTaskPayload is the payload for delegating a task to a team member.

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