core

package
v1.0.0 Latest Latest
Warning

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

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

Documentation

Overview

Package core provides the fundamental types, encoding, and protocol logic for the Agent Semantic Protocol semantic agent communication protocol.

Index

Constants

View Source
const ProtocolVersion = "1.0.0"

ProtocolVersion is the current Agent Semantic Protocol wire-protocol version.

Variables

View Source
var ErrNoPrivateKey = fmt.Errorf("did: private key not available")

ErrNoPrivateKey is returned when signing is attempted without a private key.

Functions

func CapabilitySetDiff

func CapabilitySetDiff(required, available []string) (present, absent []string)

CapabilitySetDiff computes which of required are absent from available.

func CosineSimilarity

func CosineSimilarity(a, b []float32) float64

CosineSimilarity returns the cosine similarity of two equal-length vectors. Returns 0 if either vector is zero-length or their lengths differ.

func Decode

func Decode(msgType MessageType, data []byte) (interface{}, error)

Decode dispatches to the appropriate Decode* function based on msgType.

func FinishHandshake

func FinishHandshake(originalChallenge []byte, response *HandshakeMessage) error

FinishHandshake verifies the responder's signature over our original challenge. originalChallenge is the nonce sent in the initiator's HandshakeMessage.

func Frame

func Frame(msgType MessageType, payload []byte) []byte

Frame wraps encoded message bytes with a 4-byte big-endian length prefix and a 1-byte message type, ready to be sent over a stream.

Layout: [4 bytes: uint32 frame length] [1 byte: MessageType] [N bytes: payload]

func LogIntentMessage

func LogIntentMessage(intent *IntentMessage) error

LogIntentMessage logs an intent message.

func SummariseRegistry

func SummariseRegistry(r *DiscoveryRegistry) string

SummariseRegistry returns a human-readable summary for logging.

func VerifyIntentSignature

func VerifyIntentSignature(intent *IntentMessage, pubKey []byte) bool

VerifyIntentSignature returns true if intent.Signature is a valid Ed25519 signature of (intent.ID + intent.Payload) by the owner of pubKey. Returns true when Signature is empty (unsigned messages are accepted).

func VerifyResponseSignature

func VerifyResponseSignature(resp *NegotiationResponse, pubKey []byte) bool

VerifyResponseSignature returns true if resp.Signature is a valid Ed25519 signature of (resp.RequestID + resp.Reason) by the owner of pubKey. Returns true when Signature is empty (unsigned messages are accepted).

Types

type Agent

type Agent struct {
	ID           string
	DID          *DID
	Capabilities []string
	// contains filtered or unexported fields
}

Agent holds an agent's public identity and capability profile. Private key material is kept separate (see DID).

func NewAgent

func NewAgent(id string, capabilities []string) (*Agent, error)

NewAgent creates an Agent, generating a fresh Ed25519 key-pair and DID.

func (*Agent) PublicKey

func (a *Agent) PublicKey() []byte

PublicKey returns the raw Ed25519 public key bytes.

func (*Agent) Sign

func (a *Agent) Sign(data []byte) ([]byte, error)

Sign signs data with the agent's private key.

type AgentProfile

type AgentProfile struct {
	AgentID         string
	DID             string
	Capabilities    []string
	EmbeddingVector []float32 // Optional representative vector for the agent
	PublicKey       []byte    // Ed25519 public key; set after a handshake
}

AgentProfile holds a peer agent's public capability profile for ranking.

func RankCandidates

func RankCandidates(intentVector []float32, candidates []AgentProfile) []AgentProfile

RankCandidates sorts a list of agents by cosine similarity to the intent vector, highest first. Agents without a registered embedding vector are ranked last.

type CapabilityAnnouncement

type CapabilityAnnouncement struct {
	AgentID      string
	DID          string
	Capabilities []string
	Timestamp    int64
	TTL          int64 // seconds; 0 = indefinite
}

CapabilityAnnouncement broadcasts capabilities to nearby peers.

func BuildAnnouncement

func BuildAnnouncement(agent *Agent, ttlSeconds int64) *CapabilityAnnouncement

BuildAnnouncement creates a CapabilityAnnouncement for the given agent.

func DecodeCapabilityAnnouncement

func DecodeCapabilityAnnouncement(data []byte) (*CapabilityAnnouncement, error)

DecodeCapabilityAnnouncement deserialises a CapabilityAnnouncement from wire bytes.

func (*CapabilityAnnouncement) Encode

func (m *CapabilityAnnouncement) Encode() ([]byte, error)

Encode serialises m into the Protobuf wire format.

func (*CapabilityAnnouncement) MsgType

func (m *CapabilityAnnouncement) MsgType() MessageType

type DID

type DID struct {
	Method string // always "agent-semantic-protocol" for Agent Semantic Protocol DIDs
	ID     string // hex(sha256(pubkey))
	// contains filtered or unexported fields
}

DID represents a Agent Semantic Protocol Decentralized Identifier.

func DIDFromPublicKey

func DIDFromPublicKey(pubKey []byte) (*DID, error)

DIDFromPublicKey derives a DID from a raw Ed25519 public key (no private key). Use this when you only know a remote peer's public key.

func NewDID

func NewDID() (*DID, error)

NewDID generates a fresh Ed25519 key-pair and derives a DID from it.

func ParseDID

func ParseDID(s string) (*DID, error)

ParseDID parses a "did:agent-semantic-protocol:<id>" string.

func (*DID) PublicKey

func (d *DID) PublicKey() []byte

PublicKey returns a copy of the raw Ed25519 public key (32 bytes), if available.

func (*DID) Sign

func (d *DID) Sign(data []byte) ([]byte, error)

Sign signs data with the DID's private key. Returns ErrNoPrivateKey if only the public half is available.

func (*DID) String

func (d *DID) String() string

String returns the canonical DID string ("did:agent-semantic-protocol:<id>").

func (*DID) ValidateBinding

func (d *DID) ValidateBinding(pubKey []byte) bool

ValidateBinding confirms that a raw public key matches this DID's embedded ID. Call this after receiving a HandshakeMessage to ensure the peer's DID is genuine.

func (*DID) Verify

func (d *DID) Verify(data, sig []byte) bool

Verify checks that sig is a valid Ed25519 signature of data made with the key embedded in this DID.

type DiscoveryRegistry

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

DiscoveryRegistry stores announced capability profiles from peer agents. All methods are concurrency-safe.

func NewDiscoveryRegistry

func NewDiscoveryRegistry() *DiscoveryRegistry

NewDiscoveryRegistry creates an empty registry.

func (*DiscoveryRegistry) All

func (r *DiscoveryRegistry) All() []AgentProfile

All returns a snapshot of all live profiles.

func (*DiscoveryRegistry) Announce

func (r *DiscoveryRegistry) Announce(profile AgentProfile, ttlSeconds int64)

Announce registers or updates an agent's capability profile. ttlSeconds == 0 means the entry never expires.

func (*DiscoveryRegistry) AnnounceFromMessage

func (r *DiscoveryRegistry) AnnounceFromMessage(msg *CapabilityAnnouncement)

AnnounceFromMessage registers the agent described by a CapabilityAnnouncement.

func (*DiscoveryRegistry) Evict

func (r *DiscoveryRegistry) Evict() int

Evict removes all expired entries and returns the count removed.

func (*DiscoveryRegistry) FindByCapability

func (r *DiscoveryRegistry) FindByCapability(required ...string) []AgentProfile

FindByCapability returns all live agents that declare ALL of required capabilities.

func (*DiscoveryRegistry) FindByDID

func (r *DiscoveryRegistry) FindByDID(did string) (AgentProfile, bool)

FindByDID returns the profile registered for a specific DID, or false.

func (*DiscoveryRegistry) Remove

func (r *DiscoveryRegistry) Remove(agentID string)

Remove deletes an agent's entry from the registry.

func (*DiscoveryRegistry) StartEvictionLoop

func (r *DiscoveryRegistry) StartEvictionLoop(interval time.Duration, done <-chan struct{})

StartEvictionLoop runs a background goroutine that periodically evicts expired entries. Cancel ctx to stop it.

type Encoder

type Encoder interface {
	Encode() ([]byte, error)
	MsgType() MessageType
}

Encoder is implemented by every Agent Semantic Protocol message type.

type HandshakeMessage

type HandshakeMessage struct {
	AgentID           string
	DID               string
	Capabilities      []string
	Version           string
	Timestamp         int64
	PublicKey         []byte // Ed25519 public key
	Challenge         []byte // Random nonce sent to peer
	ChallengeResponse []byte // Signature of peer's challenge with own private key
}

HandshakeMessage establishes agent identity and exchanges capabilities.

func DecodeHandshakeMessage

func DecodeHandshakeMessage(data []byte) (*HandshakeMessage, error)

DecodeHandshakeMessage deserialises a HandshakeMessage from wire bytes.

func RespondHandshake

func RespondHandshake(responder *Agent, incoming *HandshakeMessage) (*HandshakeMessage, error)

RespondHandshake processes an incoming HandshakeMessage and builds the response. It verifies the sender's DID/key binding and signs the nonce.

func StartHandshake

func StartHandshake(agent *Agent) (*HandshakeMessage, error)

StartHandshake builds the initiator's HandshakeMessage. It embeds a random challenge nonce that the responder must sign.

func (*HandshakeMessage) Encode

func (m *HandshakeMessage) Encode() ([]byte, error)

Encode serialises m into the Protobuf wire format.

func (*HandshakeMessage) MsgType

func (m *HandshakeMessage) MsgType() MessageType

type HandshakeResult

type HandshakeResult struct {
	PeerAgentID      string
	PeerDID          string
	PeerCapabilities []string
	PeerPublicKey    []byte
	ProtocolVersion  string
	CompletedAt      time.Time
}

HandshakeResult collects the outcome of a completed handshake.

func NewHandshakeResult

func NewHandshakeResult(resp *HandshakeMessage) HandshakeResult

NewHandshakeResult extracts a HandshakeResult from the responder's message after FinishHandshake succeeds.

type IntentMessage

type IntentMessage struct {
	ID           string
	IntentVector []float32         // Semantic embedding (e.g. 384-dim sentence-transformer)
	Capabilities []string          // Capabilities required to fulfil this intent
	DID          string            // Sender DID string ("did:agent-semantic-protocol:<id>")
	Payload      string            // Optional payload (plain text or JSON)
	Timestamp    int64             // Unix nanoseconds
	TrustScore   float32           // Sender trust score [0.0, 1.0]
	Metadata     map[string]string // Arbitrary extension metadata
	Signature    []byte            // Ed25519 signature of ID+Payload by sender DID key
	Logger       *Logger           // Logger instance for auditable logs
}

IntentMessage carries a semantic intent between agents.

func CreateIntent

func CreateIntent(
	sender *Agent,
	intentVector []float32,
	requiredCapabilities []string,
	payload string,
) (*IntentMessage, error)

CreateIntent constructs an IntentMessage ready to be sent.

func DecodeIntentMessage

func DecodeIntentMessage(data []byte) (*IntentMessage, error)

DecodeIntentMessage deserialises an IntentMessage from wire bytes.

func (*IntentMessage) Encode

func (m *IntentMessage) Encode() ([]byte, error)

Encode serialises m into the Protobuf wire format.

func (*IntentMessage) MsgType

func (m *IntentMessage) MsgType() MessageType

type Logger

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

Logger provides functionality for auditable logging.

func NewLogger

func NewLogger(filePath string) (*Logger, error)

NewLogger initializes a new Logger instance.

func (*Logger) Close

func (l *Logger) Close() error

Close closes the log file.

func (*Logger) LogMessage

func (l *Logger) LogMessage(messageID string, messageType string, details string) error

LogMessage writes a log entry for a processed message.

type MessageType

type MessageType byte

MessageType identifies the kind of a framed Agent Semantic Protocol message.

const (
	MsgHandshake   MessageType = 0x01
	MsgIntent      MessageType = 0x02
	MsgNegotiation MessageType = 0x03
	MsgWorkflow    MessageType = 0x04
	MsgCapability  MessageType = 0x05
)

func Unframe

func Unframe(frame []byte) (MessageType, []byte, error)

Unframe reads one framed message, returning the type and raw payload. The caller must supply at least 5 bytes (4-byte header + type byte).

type NegotiationBus

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

NegotiationBus enables in-process agents to negotiate without a real network, suitable for tests and examples.

func NewNegotiationBus

func NewNegotiationBus() *NegotiationBus

NewNegotiationBus creates an empty NegotiationBus.

func (*NegotiationBus) Negotiate

func (b *NegotiationBus) Negotiate(targetAgentID string, intent *IntentMessage) (*NegotiationResponse, error)

Negotiate sends an intent to targetAgentID and returns the response.

func (*NegotiationBus) Register

func (b *NegotiationBus) Register(agentID string, h NegotiationHandler)

Register attaches a handler for the given agentID.

type NegotiationHandler

type NegotiationHandler func(intent *IntentMessage) (*NegotiationResponse, error)

NegotiationHandler is a callback invoked when an agent receives an intent. Return (response, nil) to accept or reject; return (nil, err) on failure.

func DefaultNegotiationHandler

func DefaultNegotiationHandler(agent *Agent) NegotiationHandler

DefaultNegotiationHandler builds a NegotiationHandler that accepts any intent whose required capabilities are all present in provided.

type NegotiationResponse

type NegotiationResponse struct {
	RequestID      string
	AgentID        string
	Accepted       bool
	WorkflowSteps  []string
	DID            string
	ResponseVector []float32
	Timestamp      int64
	Reason         string
	TrustDelta     float32
	Signature      []byte // Ed25519 signature of RequestID+Reason by responder DID key
}

NegotiationResponse answers an IntentMessage.

func DecodeNegotiationResponse

func DecodeNegotiationResponse(data []byte) (*NegotiationResponse, error)

DecodeNegotiationResponse deserialises a NegotiationResponse from wire bytes.

func (*NegotiationResponse) Encode

func (m *NegotiationResponse) Encode() ([]byte, error)

Encode serialises m into the Protobuf wire format.

func (*NegotiationResponse) MsgType

func (m *NegotiationResponse) MsgType() MessageType

type TrustGraph

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

TrustGraph stores peer-to-peer trust scores in memory. It is concurrency-safe — lock before read/write.

func NewTrustGraph

func NewTrustGraph() *TrustGraph

NewTrustGraph creates an empty TrustGraph.

func (*TrustGraph) Apply

func (tg *TrustGraph) Apply(from, to string, delta float32)

Apply adds delta to the existing score (clamped to [0,1]).

func (*TrustGraph) Get

func (tg *TrustGraph) Get(from, to string) float32

Get returns the trust score that `from` has assigned to `to`. Returns 0 if no entry exists.

func (*TrustGraph) Set

func (tg *TrustGraph) Set(from, to string, score float32)

Set stores the trust score that `from` assigns to `to`.

type WorkflowMessage

type WorkflowMessage struct {
	WorkflowID string
	StepID     string
	NextStepID string
	AgentID    string
	DID        string
	Action     string
	Params     map[string]string
	ResultChan string
	Timestamp  int64
}

WorkflowMessage carries one step of a distributed workflow.

func (*WorkflowMessage) Encode

func (m *WorkflowMessage) Encode() ([]byte, error)

Encode serialises m into the Protobuf wire format.

func (*WorkflowMessage) MsgType

func (m *WorkflowMessage) MsgType() MessageType

Jump to

Keyboard shortcuts

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