Skip to content

Agent Mesh

refactor to use proto

Antonio Ojea9aae56aacf41
diff --git a/Makefile b/Makefile
index 92e58fb1..fc940cb8 100644
--- a/Makefile
+++ b/Makefile
@@ -9,6 +9,10 @@ build:
go build -v -o "$(OUT_DIR)/sam-node" ./cmd/sam-node
go build -v -o "$(OUT_DIR)/sam-hub" ./cmd/sam-hub
+.PHONY: proto
+proto:
+ ./hack/gen-proto.sh
+
clean:
rm -rf "$(OUT_DIR)/"
diff --git a/api/hub_client.go b/api/hub_client.go
new file mode 100644
index 00000000..49e16b05
--- /dev/null
+++ b/api/hub_client.go
@@ -0,0 +1,105 @@
+package api
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/multiformats/go-multiaddr"
+ "google.golang.org/protobuf/encoding/protojson"
+)
+
+// FetchConfig fetches the hub configuration from the given URL.
+func FetchConfig(ctx context.Context, hubBaseURL string) (ed25519.PublicKey, []multiaddr.Multiaddr, error) {
+ configURL := strings.TrimRight(hubBaseURL, "/") + "/api/v1/config"
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, configURL, nil)
+ if err != nil {
+ return nil, nil, fmt.Errorf("creating hub config request: %w", err)
+ }
+
+ resp, err := (&http.Client{}).Do(req)
+ if err != nil {
+ return nil, nil, fmt.Errorf("requesting hub config: %w", err)
+ }
+ defer func() {
+ _ = resp.Body.Close()
+ }()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, nil, fmt.Errorf("hub config returned status %d", resp.StatusCode)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, nil, fmt.Errorf("reading hub config body: %w", err)
+ }
+
+ var cfg HubConfig
+ if err := protojson.Unmarshal(body, &cfg); err != nil {
+ return nil, nil, fmt.Errorf("decoding hub config response: %w", err)
+ }
+
+ pubBytes, err := hex.DecodeString(strings.TrimSpace(cfg.PublicKeyHex))
+ if err != nil {
+ return nil, nil, fmt.Errorf("decoding hub public key: %w", err)
+ }
+ if len(pubBytes) != ed25519.PublicKeySize {
+ return nil, nil, fmt.Errorf("invalid hub public key length: %d", len(pubBytes))
+ }
+
+ var hubAddrs []multiaddr.Multiaddr
+ for _, raw := range cfg.BootstrapNodes {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ continue
+ }
+ ma, err := multiaddr.NewMultiaddr(raw)
+ if err != nil {
+ continue
+ }
+ hubAddrs = append(hubAddrs, ma)
+ }
+ if len(hubAddrs) == 0 {
+ return nil, nil, fmt.Errorf("hub config did not provide valid bootstrap addresses")
+ }
+
+ return ed25519.PublicKey(pubBytes), hubAddrs, nil
+}
+
+// FetchPeers fetches the enrolled peers from the hub.
+func FetchPeers(ctx context.Context, hubBaseURL string, token string) (*PeerRegistry, error) {
+ peersURL := strings.TrimRight(hubBaseURL, "/") + "/api/v1/peers"
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, peersURL, nil)
+ if err != nil {
+ return nil, fmt.Errorf("creating hub peers request: %w", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+
+ resp, err := (&http.Client{}).Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("requesting hub peers: %w", err)
+ }
+ defer func() {
+ _ = resp.Body.Close()
+ }()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("hub peers returned status %d", resp.StatusCode)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("reading hub peers body: %w", err)
+ }
+
+ var registry PeerRegistry
+ if err := protojson.Unmarshal(body, &registry); err != nil {
+ return nil, fmt.Errorf("decoding hub peers response: %w", err)
+ }
+
+ return &registry, nil
+}
diff --git a/api/sam.pb.go b/api/sam.pb.go
new file mode 100644
index 00000000..fe74a39c
--- /dev/null
+++ b/api/sam.pb.go
@@ -0,0 +1,561 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.36.11
+// protoc v3.21.12
+// source: api/sam.proto
+
+package api
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+ unsafe "unsafe"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type AuthEnvelope struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Biscuit []byte `protobuf:"bytes,1,opt,name=biscuit,proto3" json:"biscuit,omitempty"`
+ Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"`
+ Proof []byte `protobuf:"bytes,3,opt,name=proof,proto3" json:"proof,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *AuthEnvelope) Reset() {
+ *x = AuthEnvelope{}
+ mi := &file_api_sam_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *AuthEnvelope) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*AuthEnvelope) ProtoMessage() {}
+
+func (x *AuthEnvelope) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[0]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use AuthEnvelope.ProtoReflect.Descriptor instead.
+func (*AuthEnvelope) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *AuthEnvelope) GetBiscuit() []byte {
+ if x != nil {
+ return x.Biscuit
+ }
+ return nil
+}
+
+func (x *AuthEnvelope) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
+func (x *AuthEnvelope) GetProof() []byte {
+ if x != nil {
+ return x.Proof
+ }
+ return nil
+}
+
+type HubConfig struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ PublicKeyHex string `protobuf:"bytes,1,opt,name=public_key_hex,json=publicKeyHex,proto3" json:"public_key_hex,omitempty"`
+ MeshId string `protobuf:"bytes,2,opt,name=mesh_id,json=meshId,proto3" json:"mesh_id,omitempty"`
+ BootstrapNodes []string `protobuf:"bytes,3,rep,name=bootstrap_nodes,json=bootstrapNodes,proto3" json:"bootstrap_nodes,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *HubConfig) Reset() {
+ *x = HubConfig{}
+ mi := &file_api_sam_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *HubConfig) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*HubConfig) ProtoMessage() {}
+
+func (x *HubConfig) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use HubConfig.ProtoReflect.Descriptor instead.
+func (*HubConfig) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *HubConfig) GetPublicKeyHex() string {
+ if x != nil {
+ return x.PublicKeyHex
+ }
+ return ""
+}
+
+func (x *HubConfig) GetMeshId() string {
+ if x != nil {
+ return x.MeshId
+ }
+ return ""
+}
+
+func (x *HubConfig) GetBootstrapNodes() []string {
+ if x != nil {
+ return x.BootstrapNodes
+ }
+ return nil
+}
+
+type PeerProfile struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
+ Groups []string `protobuf:"bytes,2,rep,name=groups,proto3" json:"groups,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PeerProfile) Reset() {
+ *x = PeerProfile{}
+ mi := &file_api_sam_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PeerProfile) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PeerProfile) ProtoMessage() {}
+
+func (x *PeerProfile) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[2]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PeerProfile.ProtoReflect.Descriptor instead.
+func (*PeerProfile) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *PeerProfile) GetEmail() string {
+ if x != nil {
+ return x.Email
+ }
+ return ""
+}
+
+func (x *PeerProfile) GetGroups() []string {
+ if x != nil {
+ return x.Groups
+ }
+ return nil
+}
+
+type PeerRegistry struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Peers map[string]*PeerProfile `protobuf:"bytes,1,rep,name=peers,proto3" json:"peers,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PeerRegistry) Reset() {
+ *x = PeerRegistry{}
+ mi := &file_api_sam_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PeerRegistry) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PeerRegistry) ProtoMessage() {}
+
+func (x *PeerRegistry) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PeerRegistry.ProtoReflect.Descriptor instead.
+func (*PeerRegistry) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *PeerRegistry) GetPeers() map[string]*PeerProfile {
+ if x != nil {
+ return x.Peers
+ }
+ return nil
+}
+
+type ModelProperty struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ ContextWindow int32 `protobuf:"varint,2,opt,name=context_window,json=contextWindow,proto3" json:"context_window,omitempty"`
+ Quantization string `protobuf:"bytes,3,opt,name=quantization,proto3" json:"quantization,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ModelProperty) Reset() {
+ *x = ModelProperty{}
+ mi := &file_api_sam_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ModelProperty) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ModelProperty) ProtoMessage() {}
+
+func (x *ModelProperty) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ModelProperty.ProtoReflect.Descriptor instead.
+func (*ModelProperty) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *ModelProperty) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *ModelProperty) GetContextWindow() int32 {
+ if x != nil {
+ return x.ContextWindow
+ }
+ return 0
+}
+
+func (x *ModelProperty) GetQuantization() string {
+ if x != nil {
+ return x.Quantization
+ }
+ return ""
+}
+
+type AgentCard struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ PeerId string `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
+ Skills []string `protobuf:"bytes,3,rep,name=skills,proto3" json:"skills,omitempty"`
+ Models []*ModelProperty `protobuf:"bytes,4,rep,name=models,proto3" json:"models,omitempty"`
+ McpTools []string `protobuf:"bytes,5,rep,name=mcp_tools,json=mcpTools,proto3" json:"mcp_tools,omitempty"`
+ Metadata map[string]string `protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Signature []byte `protobuf:"bytes,7,opt,name=signature,proto3" json:"signature,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *AgentCard) Reset() {
+ *x = AgentCard{}
+ mi := &file_api_sam_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *AgentCard) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*AgentCard) ProtoMessage() {}
+
+func (x *AgentCard) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[5]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use AgentCard.ProtoReflect.Descriptor instead.
+func (*AgentCard) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *AgentCard) GetPeerId() string {
+ if x != nil {
+ return x.PeerId
+ }
+ return ""
+}
+
+func (x *AgentCard) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *AgentCard) GetSkills() []string {
+ if x != nil {
+ return x.Skills
+ }
+ return nil
+}
+
+func (x *AgentCard) GetModels() []*ModelProperty {
+ if x != nil {
+ return x.Models
+ }
+ return nil
+}
+
+func (x *AgentCard) GetMcpTools() []string {
+ if x != nil {
+ return x.McpTools
+ }
+ return nil
+}
+
+func (x *AgentCard) GetMetadata() map[string]string {
+ if x != nil {
+ return x.Metadata
+ }
+ return nil
+}
+
+func (x *AgentCard) GetSignature() []byte {
+ if x != nil {
+ return x.Signature
+ }
+ return nil
+}
+
+type RevocationMsg struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ TargetPeerId string `protobuf:"bytes,1,opt,name=target_peer_id,json=targetPeerId,proto3" json:"target_peer_id,omitempty"`
+ Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"`
+ Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
+ Signature []byte `protobuf:"bytes,4,opt,name=signature,proto3" json:"signature,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RevocationMsg) Reset() {
+ *x = RevocationMsg{}
+ mi := &file_api_sam_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RevocationMsg) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RevocationMsg) ProtoMessage() {}
+
+func (x *RevocationMsg) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[6]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RevocationMsg.ProtoReflect.Descriptor instead.
+func (*RevocationMsg) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{6}
+}
+
+func (x *RevocationMsg) GetTargetPeerId() string {
+ if x != nil {
+ return x.TargetPeerId
+ }
+ return ""
+}
+
+func (x *RevocationMsg) GetReason() string {
+ if x != nil {
+ return x.Reason
+ }
+ return ""
+}
+
+func (x *RevocationMsg) GetTimestamp() int64 {
+ if x != nil {
+ return x.Timestamp
+ }
+ return 0
+}
+
+func (x *RevocationMsg) GetSignature() []byte {
+ if x != nil {
+ return x.Signature
+ }
+ return nil
+}
+
+var File_api_sam_proto protoreflect.FileDescriptor
+
+const file_api_sam_proto_rawDesc = "" +
+ "\n" +
+ "\rapi/sam.proto\x12\x06sam.v1\"X\n" +
+ "\fAuthEnvelope\x12\x18\n" +
+ "\abiscuit\x18\x01 \x01(\fR\abiscuit\x12\x18\n" +
+ "\aversion\x18\x02 \x01(\tR\aversion\x12\x14\n" +
+ "\x05proof\x18\x03 \x01(\fR\x05proof\"s\n" +
+ "\tHubConfig\x12$\n" +
+ "\x0epublic_key_hex\x18\x01 \x01(\tR\fpublicKeyHex\x12\x17\n" +
+ "\amesh_id\x18\x02 \x01(\tR\x06meshId\x12'\n" +
+ "\x0fbootstrap_nodes\x18\x03 \x03(\tR\x0ebootstrapNodes\";\n" +
+ "\vPeerProfile\x12\x14\n" +
+ "\x05email\x18\x01 \x01(\tR\x05email\x12\x16\n" +
+ "\x06groups\x18\x02 \x03(\tR\x06groups\"\x94\x01\n" +
+ "\fPeerRegistry\x125\n" +
+ "\x05peers\x18\x01 \x03(\v2\x1f.sam.v1.PeerRegistry.PeersEntryR\x05peers\x1aM\n" +
+ "\n" +
+ "PeersEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12)\n" +
+ "\x05value\x18\x02 \x01(\v2\x13.sam.v1.PeerProfileR\x05value:\x028\x01\"n\n" +
+ "\rModelProperty\x12\x12\n" +
+ "\x04name\x18\x01 \x01(\tR\x04name\x12%\n" +
+ "\x0econtext_window\x18\x02 \x01(\x05R\rcontextWindow\x12\"\n" +
+ "\fquantization\x18\x03 \x01(\tR\fquantization\"\xb4\x02\n" +
+ "\tAgentCard\x12\x17\n" +
+ "\apeer_id\x18\x01 \x01(\tR\x06peerId\x12\x12\n" +
+ "\x04name\x18\x02 \x01(\tR\x04name\x12\x16\n" +
+ "\x06skills\x18\x03 \x03(\tR\x06skills\x12-\n" +
+ "\x06models\x18\x04 \x03(\v2\x15.sam.v1.ModelPropertyR\x06models\x12\x1b\n" +
+ "\tmcp_tools\x18\x05 \x03(\tR\bmcpTools\x12;\n" +
+ "\bmetadata\x18\x06 \x03(\v2\x1f.sam.v1.AgentCard.MetadataEntryR\bmetadata\x12\x1c\n" +
+ "\tsignature\x18\a \x01(\fR\tsignature\x1a;\n" +
+ "\rMetadataEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x89\x01\n" +
+ "\rRevocationMsg\x12$\n" +
+ "\x0etarget_peer_id\x18\x01 \x01(\tR\ftargetPeerId\x12\x16\n" +
+ "\x06reason\x18\x02 \x01(\tR\x06reason\x12\x1c\n" +
+ "\ttimestamp\x18\x03 \x01(\x03R\ttimestamp\x12\x1c\n" +
+ "\tsignature\x18\x04 \x01(\fR\tsignatureB\x1bZ\x19github.com/google/sam/apib\x06proto3"
+
+var (
+ file_api_sam_proto_rawDescOnce sync.Once
+ file_api_sam_proto_rawDescData []byte
+)
+
+func file_api_sam_proto_rawDescGZIP() []byte {
+ file_api_sam_proto_rawDescOnce.Do(func() {
+ file_api_sam_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)))
+ })
+ return file_api_sam_proto_rawDescData
+}
+
+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
+var file_api_sam_proto_goTypes = []any{
+ (*AuthEnvelope)(nil), // 0: sam.v1.AuthEnvelope
+ (*HubConfig)(nil), // 1: sam.v1.HubConfig
+ (*PeerProfile)(nil), // 2: sam.v1.PeerProfile
+ (*PeerRegistry)(nil), // 3: sam.v1.PeerRegistry
+ (*ModelProperty)(nil), // 4: sam.v1.ModelProperty
+ (*AgentCard)(nil), // 5: sam.v1.AgentCard
+ (*RevocationMsg)(nil), // 6: sam.v1.RevocationMsg
+ nil, // 7: sam.v1.PeerRegistry.PeersEntry
+ nil, // 8: sam.v1.AgentCard.MetadataEntry
+}
+var file_api_sam_proto_depIdxs = []int32{
+ 7, // 0: sam.v1.PeerRegistry.peers:type_name -> sam.v1.PeerRegistry.PeersEntry
+ 4, // 1: sam.v1.AgentCard.models:type_name -> sam.v1.ModelProperty
+ 8, // 2: sam.v1.AgentCard.metadata:type_name -> sam.v1.AgentCard.MetadataEntry
+ 2, // 3: sam.v1.PeerRegistry.PeersEntry.value:type_name -> sam.v1.PeerProfile
+ 4, // [4:4] is the sub-list for method output_type
+ 4, // [4:4] is the sub-list for method input_type
+ 4, // [4:4] is the sub-list for extension type_name
+ 4, // [4:4] is the sub-list for extension extendee
+ 0, // [0:4] is the sub-list for field type_name
+}
+
+func init() { file_api_sam_proto_init() }
+func file_api_sam_proto_init() {
+ if File_api_sam_proto != nil {
+ return
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),
+ NumEnums: 0,
+ NumMessages: 9,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_api_sam_proto_goTypes,
+ DependencyIndexes: file_api_sam_proto_depIdxs,
+ MessageInfos: file_api_sam_proto_msgTypes,
+ }.Build()
+ File_api_sam_proto = out.File
+ file_api_sam_proto_goTypes = nil
+ file_api_sam_proto_depIdxs = nil
+}
diff --git a/api/sam.proto b/api/sam.proto
new file mode 100644
index 00000000..84e6b50a
--- /dev/null
+++ b/api/sam.proto
@@ -0,0 +1,47 @@
+syntax = "proto3";
+package sam.v1;
+option go_package = "github.com/google/sam/api";
+
+message AuthEnvelope {
+ bytes biscuit = 1;
+ string version = 2;
+ bytes proof = 3;
+}
+
+message HubConfig {
+ string public_key_hex = 1;
+ string mesh_id = 2;
+ repeated string bootstrap_nodes = 3;
+}
+
+message PeerProfile {
+ string email = 1;
+ repeated string groups = 2;
+}
+
+message PeerRegistry {
+ map<string, PeerProfile> peers = 1;
+}
+
+message ModelProperty {
+ string name = 1;
+ int32 context_window = 2;
+ string quantization = 3;
+}
+
+message AgentCard {
+ string peer_id = 1;
+ string name = 2;
+ repeated string skills = 3;
+ repeated ModelProperty models = 4;
+ repeated string mcp_tools = 5;
+ map<string, string> metadata = 6;
+ bytes signature = 7;
+}
+
+message RevocationMsg {
+ string target_peer_id = 1;
+ string reason = 2;
+ int64 timestamp = 3;
+ bytes signature = 4;
+}
diff --git a/cmd/sam-hub/http.go b/cmd/sam-hub/http.go
index 293f8148..4c0fdf81 100644
--- a/cmd/sam-hub/http.go
+++ b/cmd/sam-hub/http.go
@@ -18,15 +18,16 @@ import (
"crypto/ed25519"
"encoding/base64"
"encoding/hex"
- "encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/google/sam/api"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
+ "google.golang.org/protobuf/encoding/protojson"
)
// authMiddleware protects HTTP endpoints by requiring a valid Hub-issued Biscuit
@@ -150,14 +151,19 @@ func (h *Hub) handleConfig(w http.ResponseWriter, r *http.Request) {
pubKey := h.BiscuitKey.Public().(ed25519.PublicKey)
- config := map[string]interface{}{
- "public_key": hex.EncodeToString(pubKey),
- "mesh_id": h.MeshID,
- "bootstrap_nodes": addrStrs,
+ config := &api.HubConfig{
+ PublicKeyHex: hex.EncodeToString(pubKey),
+ MeshId: h.MeshID,
+ BootstrapNodes: addrStrs,
+ }
+ b, err := protojson.Marshal(config)
+ if err != nil {
+ http.Error(w, "Failed to marshal config", http.StatusInternalServerError)
+ return
}
w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(config); err != nil {
- log.Printf("encoding config response: %v", err)
+ if _, err := w.Write(b); err != nil {
+ log.Printf("writing config response: %v", err)
}
}
@@ -171,10 +177,19 @@ func (h *Hub) handlePeers(w http.ResponseWriter, r *http.Request) {
peers = append(peers, pID.String())
}
+ registry := &api.PeerRegistry{
+ Peers: make(map[string]*api.PeerProfile),
+ }
+ for _, pID := range peers {
+ registry.Peers[pID] = &api.PeerProfile{}
+ }
+ b, err := protojson.Marshal(registry)
+ if err != nil {
+ http.Error(w, "Failed to marshal peers", http.StatusInternalServerError)
+ return
+ }
w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(map[string]interface{}{
- "enrolled_peers": peers,
- }); err != nil {
- log.Printf("encoding peers response: %v", err)
+ if _, err := w.Write(b); err != nil {
+ log.Printf("writing peers response: %v", err)
}
}
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index cac8c251..0bdc4680 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -17,17 +17,13 @@ package main
import (
"bufio"
"context"
- "crypto/ed25519"
- "encoding/hex"
- "encoding/json"
"fmt"
"log"
- "net/http"
"os"
"strings"
+ "github.com/google/sam/api"
"github.com/libp2p/go-libp2p/core/crypto"
- "github.com/multiformats/go-multiaddr"
"github.com/spf13/cobra"
)
@@ -37,63 +33,6 @@ var (
tokenFlag string
)
-type hubConfigResponse struct {
- PublicKey string `json:"public_key"`
- MeshID string `json:"mesh_id"`
- BootstrapNodes []string `json:"bootstrap_nodes"`
-}
-
-func fetchHubConfig(ctx context.Context, hubBaseURL string) (ed25519.PublicKey, []multiaddr.Multiaddr, error) {
- configURL := strings.TrimRight(hubBaseURL, "/") + "/api/v1/config"
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, configURL, nil)
- if err != nil {
- return nil, nil, fmt.Errorf("creating hub config request: %w", err)
- }
-
- resp, err := (&http.Client{}).Do(req)
- if err != nil {
- return nil, nil, fmt.Errorf("requesting hub config: %w", err)
- }
- defer func() {
- _ = resp.Body.Close()
- }()
-
- if resp.StatusCode != http.StatusOK {
- return nil, nil, fmt.Errorf("hub config returned status %d", resp.StatusCode)
- }
-
- var cfg hubConfigResponse
- if err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil {
- return nil, nil, fmt.Errorf("decoding hub config response: %w", err)
- }
-
- pubBytes, err := hex.DecodeString(strings.TrimSpace(cfg.PublicKey))
- if err != nil {
- return nil, nil, fmt.Errorf("decoding hub public key: %w", err)
- }
- if len(pubBytes) != ed25519.PublicKeySize {
- return nil, nil, fmt.Errorf("invalid hub public key length: %d", len(pubBytes))
- }
-
- var hubAddrs []multiaddr.Multiaddr
- for _, raw := range cfg.BootstrapNodes {
- raw = strings.TrimSpace(raw)
- if raw == "" {
- continue
- }
- ma, err := multiaddr.NewMultiaddr(raw)
- if err != nil {
- log.Printf("ignoring invalid bootstrap multiaddr %q: %v", raw, err)
- continue
- }
- hubAddrs = append(hubAddrs, ma)
- }
- if len(hubAddrs) == 0 {
- return nil, nil, fmt.Errorf("hub config did not provide valid bootstrap addresses")
- }
-
- return ed25519.PublicKey(pubBytes), hubAddrs, nil
-}
func main() {
rootCmd := &cobra.Command{
@@ -121,7 +60,7 @@ func main() {
}
}()
- hubPubKey, hubAddrs, err := fetchHubConfig(context.Background(), hubAddr)
+ hubPubKey, hubAddrs, err := api.FetchConfig(context.Background(), hubAddr)
if err != nil {
log.Fatalf("Failed to fetch hub config: %v", err)
}
@@ -193,7 +132,7 @@ func main() {
return
}
- hubPubKey, hubAddrs, err := fetchHubConfig(context.Background(), hubAddr)
+ hubPubKey, hubAddrs, err := api.FetchConfig(context.Background(), hubAddr)
if err != nil {
log.Fatalf("Failed to fetch hub config: %v", err)
}
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 2d069a39..bb808f78 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -17,11 +17,12 @@ package main
import (
"context"
"crypto/ed25519"
- "encoding/json"
"fmt"
"github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
+ "google.golang.org/protobuf/proto"
dht "github.com/libp2p/go-libp2p-kad-dht"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/crypto"
@@ -38,11 +39,7 @@ import (
const AuthProtocolID = protocol.ID("/sam/auth/1.0.0")
-// IdentityExchange is the "Auth Envelope"
-type IdentityExchange struct {
- Biscuit []byte `json:"biscuit"`
- Version string `json:"version"`
-}
+
type SamNode struct {
Host host.Host
@@ -124,9 +121,12 @@ func (n *SamNode) listenForHubEvents(ctx context.Context) {
if err != nil {
return
}
- // In a full implementation, parse the event (e.g. {"action": "LEFT", "peer": "Qm..."})
- // and verify the Hub's signature on the payload to prevent forged kicks.
- fmt.Printf("[Mesh Event] Received Hub update from %s\n", msg.ReceivedFrom)
+ var revMsg api.RevocationMsg
+ if err := proto.Unmarshal(msg.Data, &revMsg); err != nil {
+ fmt.Printf("[Mesh Event] Failed to unmarshal revocation message from %s: %v\n", msg.ReceivedFrom, err)
+ continue
+ }
+ fmt.Printf("[Mesh Event] Received Hub update from %s for target %s\n", msg.ReceivedFrom, revMsg.TargetPeerId)
}
}
@@ -148,9 +148,9 @@ func (n *SamNode) HandleAuthHandshake(s network.Stream) {
}
defer reader.ReleaseMsg(msg)
- var exchange IdentityExchange
- if err := json.Unmarshal(msg, &exchange); err != nil {
- fmt.Printf("[AuthN] Invalid JSON from %s\n", remotePeer)
+ var exchange api.AuthEnvelope
+ if err := proto.Unmarshal(msg, &exchange); err != nil {
+ fmt.Printf("[AuthN] Invalid protobuf from %s\n", remotePeer)
return
}
diff --git a/hack/gen-proto.sh b/hack/gen-proto.sh
new file mode 100755
index 00000000..2ed5ea65
--- /dev/null
+++ b/hack/gen-proto.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+set -e
+
+echo "Installing protobuf Go plugins..."
+go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
+
+echo "Generating Go protobuf code..."
+mkdir -p api
+protoc --go_out=paths=source_relative:. api/sam.proto
+
+echo "Protobuf generation complete."
diff --git a/tests/e2e/sam.bats b/tests/e2e/sam.bats
index 404cb9dc..cd49a0b8 100644
--- a/tests/e2e/sam.bats
+++ b/tests/e2e/sam.bats
@@ -16,9 +16,38 @@ setup() {
export HOME="$TEST_TMPDIR/home"
export XDG_CONFIG_HOME="$HOME/.config"
mkdir -p "$XDG_CONFIG_HOME"
+
+ # Start mock hub config server
+ python3 -c '
+import http.server
+import socketserver
+import sys
+
+PORT = 8080
+
+class Handler(http.server.SimpleHTTPRequestHandler):
+ def do_GET(self):
+ if self.path == "/api/v1/config":
+ self.send_response(200)
+ self.send_header("Content-type", "application/json")
+ self.end_headers()
+ self.wfile.write(b"{\"public_key_hex\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"mesh_id\":\"test-mesh\",\"bootstrap_nodes\":[\"/ip4/127.0.0.1/tcp/4002/p2p/QmYyQSo1sn1GjUuQwca9AdvV8Zeyvmxrww8dDnewPrfJs9\"]}")
+ else:
+ self.send_response(404)
+ self.end_headers()
+
+socketserver.TCPServer.allow_reuse_address = True
+with socketserver.TCPServer(("", PORT), Handler) as httpd:
+ httpd.serve_forever()
+' &
+ MOCK_HUB_PID=$!
+ export MOCK_HUB_PID
+ sleep 0.5
}
teardown() {
+ kill "$MOCK_HUB_PID" || true
+ wait "$MOCK_HUB_PID" 2>/dev/null || true
rm -rf "$TEST_TMPDIR"
}
diff --git a/tests/e2e/watch.bats b/tests/e2e/watch.bats
index 7da8bf10..60fc37f0 100644
--- a/tests/e2e/watch.bats
+++ b/tests/e2e/watch.bats
@@ -11,9 +11,38 @@ setup() {
export HOME="$TEST_TMPDIR/home"
export XDG_CONFIG_HOME="$HOME/.config"
mkdir -p "$XDG_CONFIG_HOME"
+
+ # Start mock hub config server
+ python3 -c '
+import http.server
+import socketserver
+import sys
+
+PORT = 8080
+
+class Handler(http.server.SimpleHTTPRequestHandler):
+ def do_GET(self):
+ if self.path == "/api/v1/config":
+ self.send_response(200)
+ self.send_header("Content-type", "application/json")
+ self.end_headers()
+ self.wfile.write(b"{\"public_key_hex\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"mesh_id\":\"test-mesh\",\"bootstrap_nodes\":[\"/ip4/127.0.0.1/tcp/4002/p2p/QmYyQSo1sn1GjUuQwca9AdvV8Zeyvmxrww8dDnewPrfJs9\"]}")
+ else:
+ self.send_response(404)
+ self.end_headers()
+
+socketserver.TCPServer.allow_reuse_address = True
+with socketserver.TCPServer(("", PORT), Handler) as httpd:
+ httpd.serve_forever()
+' &
+ MOCK_HUB_PID=$!
+ export MOCK_HUB_PID
+ sleep 0.5
}
teardown() {
+ kill "$MOCK_HUB_PID" || true
+ wait "$MOCK_HUB_PID" 2>/dev/null || true
rm -rf "$TEST_TMPDIR"
}
diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.go
index d8e5d87b..e37556c9 100644
--- a/tests/integration/minimal_helpers_test.go
+++ b/tests/integration/minimal_helpers_test.go
@@ -113,7 +113,7 @@ func startMockHubConfigServer(t *testing.T) string {
case "/api/v1/config":
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
- "public_key": hex.EncodeToString(pubKey),
+ "public_key_hex": hex.EncodeToString(pubKey),
"mesh_id": "test-mesh",
"bootstrap_nodes": []string{bootstrapAddr},
})