Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat: support mobile integration via Dart FFI and cgo shared libraries
Antonio Ojea5ced27626100
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yamlindex 8748f4cb..88727a61 100644--- a/.github/workflows/test.yaml+++ b/.github/workflows/test.yaml@@ -54,3 +54,12 @@ jobs:- name: Install protocrun: sudo apt-get update && sudo apt-get install -y protobuf-compiler- run: make verify++ build-mobile:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6+ with:+ go-version: ${{ env.GO_VERSION }}+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6+ - run: make mobile-ffi-hostdiff --git a/Makefile b/Makefileindex e7ed7847..8463a12f 100644--- a/Makefile+++ b/Makefile@@ -10,6 +10,19 @@ build:go build -v -o "$(OUT_DIR)/sam-hub" ./cmd/sam-hubgo build -v -o "$(OUT_DIR)/mcp-client" ./cmd/mcp-client+.PHONY: mobile-ffi-host mobile-ffi-android mobile-ffi-ios+mobile-ffi-host:+ mkdir -p "$(OUT_DIR)"+ CGO_ENABLED=1 go build -v -buildmode=c-shared -o "$(OUT_DIR)/libsam.so" ./mobile/sam-node-ffi++mobile-ffi-android:+ mkdir -p "$(OUT_DIR)/android"+ GOOS=android GOARCH=arm64 CGO_ENABLED=1 go build -v -buildmode=c-shared -o "$(OUT_DIR)/android/libsam.so" ./mobile/sam-node-ffi++mobile-ffi-ios:+ mkdir -p "$(OUT_DIR)/ios"+ GOOS=ios GOARCH=arm64 CGO_ENABLED=1 go build -v -buildmode=c-archive -o "$(OUT_DIR)/ios/libsam.a" ./mobile/sam-node-ffi+.PHONY: protoproto:./hack/gen-proto.shdiff --git a/internal/node/node.go b/internal/node/node.goindex de1adc9e..70b823c1 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -239,9 +239,9 @@ func NewSamNode(cfg Options) (*SamNode, error) {authenticatedHubs: make(map[peer.ID]bool),LocalPolicy: cfg.NodeConfig,AllowLoopback: cfg.AllowLoopback,- authSuccess: make(chan struct{}),- reprovideTrigger: make(chan struct{}, 1),- logger: golog.Logger("sam-node"),+ authSuccess: make(chan struct{}),+ reprovideTrigger: make(chan struct{}, 1),+ logger: golog.Logger("sam-node"),}node.BiscuitTimeout = cfg.BiscuitTimeoutdiff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.gonew file mode 100644index 00000000..40a9dd6b--- /dev/null+++ b/mobile/sam-node-ffi/ffi/ffi.go@@ -0,0 +1,285 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package ffi++import (+ "context"+ "crypto/ed25519"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/google/sam/internal/node"+ "github.com/multiformats/go-multiaddr"+)++var (+ activeNode *node.SamNode+ activeStore *node.Store+ cancelFunc context.CancelFunc+ sidecarSrv *http.Server+ unauthSrv *http.Server+ mu sync.Mutex+)++// MobileConfig holds simple configuration options for the mobile agent.+type MobileConfig struct {+ DataDir string `json:"dataDir"`+ HubURL string `json:"hubURL"`+ MeshID string `json:"meshID"`+ BindAddr string `json:"bindAddr"`+ ApiToken string `json:"apiToken"`+ LogLevel string `json:"logLevel"`+ DiscoveryInterval string `json:"discoveryInterval"`+ ListenAddrs string `json:"listenAddrs"` // comma-separated+ AllowLoopback bool `json:"allowLoopback"`+ EnableRelay bool `json:"enableRelay"`+}++// StartNode starts the mesh node and the local sidecar API server.+func StartNode(configJSON string) error {+ mu.Lock()+ defer mu.Unlock()++ if activeNode != nil || unauthSrv != nil {+ return errors.New("node is already running")+ }++ var config MobileConfig+ if err := json.Unmarshal([]byte(configJSON), &config); err != nil {+ return fmt.Errorf("failed to parse config JSON: %w", err)+ }++ store, err := node.NewStore(config.DataDir)+ if err != nil {+ return fmt.Errorf("failed to open store: %w", err)+ }+ activeStore = store++ token, _ := store.LoadIdentity()+ if len(token) == 0 {+ displayHub := config.HubURL+ if displayHub == "" {+ if h, err := store.LoadHubURL(); err == nil && h != "" {+ displayHub = h+ } else {+ displayHub = "https://bananas.sam-mesh.dev"+ }+ }+ bindAddr := config.BindAddr+ if bindAddr == "" {+ bindAddr = "127.0.0.1:8080"+ }+ srv, err := node.StartUnauthSidecarServer(displayHub, bindAddr, "", "")+ if err != nil {+ _ = store.Close()+ activeStore = nil+ return fmt.Errorf("failed to start unauthenticated sidecar server: %w", err)+ }+ unauthSrv = srv+ return nil+ }++ var hubPubKey ed25519.PublicKey+ var hubAddrs []multiaddr.Multiaddr++ // Sync config from stored/synced configuration+ storedPubKey, syncedAddrs, err := node.SyncHubConfig(context.Background(), store)+ if err == nil && len(storedPubKey) > 0 {+ hubPubKey = storedPubKey+ hubAddrs = syncedAddrs+ }++ priv := node.GetOrGenerateKey(store)++ var listenAddrs []string+ if config.ListenAddrs != "" {+ listenAddrs = strings.Split(config.ListenAddrs, ",")+ } else {+ // On mobile, let OS allocate random free ports+ listenAddrs = []string{"/ip4/0.0.0.0/udp/0/quic-v1", "/ip4/0.0.0.0/tcp/0"}+ }++ discoveryInterval := config.DiscoveryInterval+ if discoveryInterval == "" {+ discoveryInterval = node.DefaultDiscoveryInterval+ }++ meshID := config.MeshID+ if meshID == "" {+ meshID = node.DefaultMeshName+ }++ // Create and initialize the node+ samNode, err := node.NewSamNode(node.Options{+ PrivKey: priv,+ HubPubKey: hubPubKey,+ HubAddrs: hubAddrs,+ Store: store,+ MeshID: meshID,+ DiscoveryInterval: discoveryInterval,+ ListenAddrs: listenAddrs,+ EnableRelay: config.EnableRelay,+ AllowLoopback: config.AllowLoopback,+ MonitorBootstrap: 2 * time.Minute,+ MonitorInterval: 1 * time.Minute,+ AutoRelayMinInterval: 30 * time.Second,+ AutoRelayBootDelay: 0 * time.Second,+ AutoRelayBackoff: 3 * time.Second,+ })+ if err != nil {+ _ = store.Close()+ activeStore = nil+ return fmt.Errorf("failed to initialize node: %w", err)+ }++ ctx, cancel := context.WithCancel(context.Background())+ cancelFunc = cancel++ if err := samNode.Start(ctx); err != nil {+ cancel()+ _ = store.Close()+ activeStore = nil+ return fmt.Errorf("failed to start node: %w", err)+ }+ activeNode = samNode++ // Start Sidecar API Server+ bindAddr := config.BindAddr+ if bindAddr == "" {+ bindAddr = "127.0.0.1:8080"+ }+ sidecarSrv, err = node.StartSidecarServer(samNode, bindAddr, config.ApiToken, "", "", "")+ if err != nil {+ _ = stopNodeInternal()+ return fmt.Errorf("failed to start sidecar server: %w", err)+ }++ return nil+}++// StopNode stops the node.+func StopNode() error {+ mu.Lock()+ defer mu.Unlock()+ return stopNodeInternal()+}++func stopNodeInternal() error {+ if activeNode == nil && unauthSrv == nil {+ return errors.New("node is not running")+ }++ if sidecarSrv != nil {+ _ = sidecarSrv.Close()+ sidecarSrv = nil+ }++ if unauthSrv != nil {+ _ = unauthSrv.Close()+ unauthSrv = nil+ }++ if cancelFunc != nil {+ cancelFunc()+ cancelFunc = nil+ }++ var err error+ if activeNode != nil {+ err = activeNode.Teardown()+ activeNode = nil+ }++ if activeStore != nil {+ _ = activeStore.Close()+ activeStore = nil+ }++ return err+}++// GetNodeID returns the P2P peer ID.+func GetNodeID() string {+ mu.Lock()+ defer mu.Unlock()++ if activeNode != nil && activeNode.Host != nil {+ return activeNode.Host.ID().String()+ }+ if unauthSrv != nil {+ return "unauthenticated"+ }+ return ""+}++// EnrollNode enrolls a node.+func EnrollNode(dataDir string, hubURL string, jwt string, allowLoopback bool) error {+ store, err := node.NewStore(dataDir)+ if err != nil {+ return fmt.Errorf("failed to open store: %w", err)+ }+ defer func() { _ = store.Close() }()++ priv := node.GetOrGenerateKey(store)++ var initHubAddrs []multiaddr.Multiaddr+ if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {+ ma, err := multiaddr.NewMultiaddr(hubURL)+ if err == nil {+ initHubAddrs = []multiaddr.Multiaddr{ma}+ }+ }++ enrollCtx, enrollCancel := context.WithCancel(context.Background())+ defer enrollCancel()++ meshNode, err := node.NewSamNode(node.Options{+ PrivKey: priv,+ HubAddrs: initHubAddrs,+ Store: store,+ AllowLoopback: allowLoopback,+ })+ if err != nil {+ return fmt.Errorf("failed to create node for enrollment: %w", err)+ }++ if err := meshNode.Start(enrollCtx); err != nil {+ return fmt.Errorf("failed to start node for enrollment: %w", err)+ }+ defer func() {+ _ = meshNode.Teardown()+ }()++ err = meshNode.Enroll(enrollCtx, hubURL, jwt)+ if err != nil {+ return fmt.Errorf("enrollment failed: %w", err)+ }++ if err := store.SaveHubURL(hubURL); err != nil {+ return fmt.Errorf("failed to save hub URL: %w", err)+ }++ _, _, err = node.SyncHubConfig(enrollCtx, store)+ if err != nil {+ return fmt.Errorf("failed to sync hub config post-enrollment: %w", err)+ }++ return nil+}diff --git a/mobile/sam-node-ffi/ffi/ffi_test.go b/mobile/sam-node-ffi/ffi/ffi_test.gonew file mode 100644index 00000000..b3c82dc1--- /dev/null+++ b/mobile/sam-node-ffi/ffi/ffi_test.go@@ -0,0 +1,116 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package ffi++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/google/sam/api"+ "github.com/libp2p/go-libp2p"+ dht "github.com/libp2p/go-libp2p-kad-dht"+ "github.com/libp2p/go-libp2p/core/network"+ "github.com/libp2p/go-msgio"+ "google.golang.org/protobuf/proto"+)++func TestMobileFFILifecycle(t *testing.T) {+ // 1. Setup Mock Hub+ hubHost, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = hubHost.Close() }()++ hubDHT, err := dht.New(context.Background(), hubHost, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = hubDHT.Close() }()++ hubHost.SetStreamHandler(api.AuthProtocolID, func(s network.Stream) {+ defer func() { _ = s.Close() }()+ resp := &api.AuthResponse{Success: true}+ data, _ := proto.Marshal(resp)+ writer := msgio.NewVarintWriter(s)+ _ = writer.WriteMsg(data)+ })++ mux := http.NewServeMux()+ mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ var req api.EnrollRequest+ _ = proto.Unmarshal(body, &req)++ resp := &api.EnrollResponse{+ BiscuitToken: []byte("mock-biscuit-token"),+ HubPublicKey: make([]byte, 32),+ HubAddresses: []string{hubHost.Addrs()[0].String() + "/p2p/" + hubHost.ID().String()},+ }+ data, _ := proto.Marshal(resp)+ w.Header().Set("Content-Type", "application/x-protobuf")+ _, _ = w.Write(data)+ })+ mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {+ resp := &api.HubInfoResponse{+ OidcIssuer: "http://mock-issuer",+ ClientId: "mock-client",+ Audience: "mock-audience",+ }+ data, _ := proto.Marshal(resp)+ w.Header().Set("Content-Type", "application/x-protobuf")+ _, _ = w.Write(data)+ })++ httpServer := httptest.NewServer(mux)+ defer httpServer.Close()++ // 2. Mobile Enrollment+ tmpDir := t.TempDir()+ err = EnrollNode(tmpDir, httpServer.URL, "dummy-jwt", true)+ if err != nil {+ t.Fatalf("EnrollNode failed: %v", err)+ }++ // 3. Mobile Node Start+ cfg := MobileConfig{+ DataDir: tmpDir,+ HubURL: httpServer.URL,+ MeshID: "test-mesh",+ BindAddr: "127.0.0.1:0", // random free port+ ApiToken: "test-token",+ AllowLoopback: true,+ }+ cfgBytes, _ := json.Marshal(cfg)++ err = StartNode(string(cfgBytes))+ if err != nil {+ t.Fatalf("StartNode failed: %v", err)+ }++ if GetNodeID() == "" || GetNodeID() == "unauthenticated" {+ t.Fatalf("Expected valid peer ID, got %q", GetNodeID())+ }++ // Stop Node+ err = StopNode()+ if err != nil {+ t.Fatalf("StopNode failed: %v", err)+ }+}diff --git a/mobile/sam-node-ffi/main.go b/mobile/sam-node-ffi/main.gonew file mode 100644index 00000000..8eafc31d--- /dev/null+++ b/mobile/sam-node-ffi/main.go@@ -0,0 +1,74 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++/*+#include <stdlib.h>+*/+import "C"+import (+ "unsafe"++ "github.com/google/sam/mobile/sam-node-ffi/ffi"+)++func main() {}++//export StartNode+func StartNode(configJSON *C.char) *C.char {+ goConfigJSON := C.GoString(configJSON)+ err := ffi.StartNode(goConfigJSON)+ if err != nil {+ return C.CString(err.Error())+ }+ return nil+}++//export StopNode+func StopNode() *C.char {+ err := ffi.StopNode()+ if err != nil {+ return C.CString(err.Error())+ }+ return nil+}++//export GetNodeID+func GetNodeID() *C.char {+ nodeID := ffi.GetNodeID()+ if nodeID != "" {+ return C.CString(nodeID)+ }+ return nil+}++//export EnrollNode+func EnrollNode(dataDir *C.char, hubURL *C.char, jwt *C.char, allowLoopback C.char) *C.char {+ goDataDir := C.GoString(dataDir)+ goHubURL := C.GoString(hubURL)+ goJWT := C.GoString(jwt)+ goAllowLoopback := allowLoopback != 0++ err := ffi.EnrollNode(goDataDir, goHubURL, goJWT, goAllowLoopback)+ if err != nil {+ return C.CString(err.Error())+ }+ return nil+}++//export FreeString+func FreeString(str *C.char) {+ C.free(unsafe.Pointer(str))+}