Skip to content

Agent Mesh

start from scratch

Antonio Ojea3002d9149df6
diff --git a/Makefile b/Makefile
index c3913152..cf485110 100644
--- a/Makefile
+++ b/Makefile
@@ -6,7 +6,7 @@ CGO_ENABLED=0
export GOROOT GO111MODULE CGO_ENABLED
build:
- go build -v -o "$(OUT_DIR)/sam-agent" ./cmd/sam-agent
+ go build -v -o "$(OUT_DIR)/sam-node" ./cmd/sam-node
go build -v -o "$(OUT_DIR)/sam-hub" ./cmd/sam-hub
clean:
@@ -30,7 +30,7 @@ test-e2e: build
exit 1; \
fi; \
}
- SAM_BINARY=$(OUT_DIR)/sam-agent bats --verbose-run tests/e2e/
+ SAM_BINARY=$(OUT_DIR)/sam-node bats --verbose-run tests/e2e/
# code linters
lint:
diff --git a/cmd/sam-agent/agent_discovery.go b/cmd/sam-agent/agent_discovery.go
deleted file mode 100644
index 27dfda63..00000000
--- a/cmd/sam-agent/agent_discovery.go
+++ /dev/null
@@ -1,156 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strings"
- "time"
-
- samnet "sam/pkg/net"
- protocol "sam/pkg/protocol/discovery"
-)
-
-func newAgentDiscoverer(node samnet.Node, federation string, maxDHTCardAge time.Duration) (samnet.AgentDiscoverFunc, error) {
- svc, err := protocol.NewDiscoveryService(node, protocol.WithMaxDHTCardAge(maxDHTCardAge))
- if err != nil {
- return nil, fmt.Errorf("creating discovery service: %w", err)
- }
- return func(ctx context.Context) ([]samnet.DiscoveredAgent, error) {
- seen := map[string]samnet.DiscoveredAgent{}
- const dhtLookupTimeout = 1200 * time.Millisecond
-
- connectedCtx, cancelConnected := context.WithTimeout(ctx, 2*time.Second)
- connected, err := svc.DiscoverAll(connectedCtx)
- cancelConnected()
- if err == nil {
- for _, card := range connected {
- if record, ok := discoveredAgentFromCard(card); ok {
- seen[record.PeerID] = record
- }
- }
- }
-
- for _, id := range node.Host().Peerstore().Peers() {
- if id == "" || id == node.PeerID() {
- continue
- }
- lookupCtx, cancelLookup := context.WithTimeout(ctx, dhtLookupTimeout)
- raw, getErr := node.GetValue(lookupCtx, protocol.DHTPeerCardKey(id.String()))
- cancelLookup()
- if getErr != nil {
- continue
- }
- card, decodeErr := decodeAgentCardRaw(raw)
- if decodeErr != nil {
- continue
- }
- if record, ok := discoveredAgentFromCard(card); ok {
- seen[record.PeerID] = record
- }
- }
-
- for _, id := range node.Host().Network().Peers() {
- lookupCtx, cancelLookup := context.WithTimeout(ctx, dhtLookupTimeout)
- raw, getErr := node.GetValue(lookupCtx, protocol.DHTPeerCardKey(id.String()))
- cancelLookup()
- if getErr != nil {
- continue
- }
- card, decodeErr := decodeAgentCardRaw(raw)
- if decodeErr != nil {
- continue
- }
- if record, ok := discoveredAgentFromCard(card); ok {
- seen[record.PeerID] = record
- }
- }
-
- capabilities, err := samnet.CachedCapabilities(federation)
- if err == nil {
- for _, capability := range capabilities {
- discoverCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
- cards, discoverErr := svc.Discover(discoverCtx, capability)
- cancel()
- if discoverErr != nil {
- continue
- }
- for _, card := range cards {
- if record, ok := discoveredAgentFromCard(card); ok {
- seen[record.PeerID] = record
- }
- }
- }
- }
-
- out := make([]samnet.DiscoveredAgent, 0, len(seen))
- for _, record := range seen {
- out = append(out, record)
- }
- return out, nil
- }, nil
-}
-
-func discoveredAgentFromCard(card *protocol.AgentCard) (samnet.DiscoveredAgent, bool) {
- if card == nil || strings.TrimSpace(card.PeerID) == "" {
- return samnet.DiscoveredAgent{}, false
- }
- raw, err := json.Marshal(card)
- if err != nil {
- return samnet.DiscoveredAgent{}, false
- }
- return samnet.DiscoveredAgent{
- PeerID: card.PeerID,
- Card: raw,
- Capabilities: card.CapabilityNames(),
- }, true
-}
-
-func decodeCachedAgentCards(federation string) ([]*protocol.AgentCard, error) {
- records, err := samnet.LoadCachedAgentRecords(federation)
- if err != nil {
- return nil, err
- }
- out := make([]*protocol.AgentCard, 0, len(records))
- for _, record := range records {
- card, err := decodeAgentCardRaw(record.Card)
- if err != nil {
- continue
- }
- out = append(out, card)
- }
- return out, nil
-}
-
-func upsertAgentCardRecord(federation string, card *protocol.AgentCard) error {
- record, ok := discoveredAgentFromCard(card)
- if !ok {
- return nil
- }
- return samnet.UpsertCachedAgentRecord(federation, record)
-}
-
-func decodeAgentCardRaw(raw []byte) (*protocol.AgentCard, error) {
- var card protocol.AgentCard
- if err := json.Unmarshal(raw, &card); err != nil {
- return nil, fmt.Errorf("decoding agent card: %w", err)
- }
- if err := protocol.VerifyAgentCard(&card); err != nil {
- return nil, fmt.Errorf("validating agent card: %w", err)
- }
- return &card, nil
-}
diff --git a/cmd/sam-agent/call.go b/cmd/sam-agent/call.go
deleted file mode 100644
index 636aef79..00000000
--- a/cmd/sam-agent/call.go
+++ /dev/null
@@ -1,243 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "os"
- "strings"
- "time"
-
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/spf13/cobra"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
- samnet "sam/pkg/net"
- a2aprotocol "sam/pkg/protocol/a2a"
- protocol "sam/pkg/protocol/discovery"
-)
-
-func newCallCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "call <peer-id|capability>",
- Short: "Execute an A2A task against a remote SAM agent",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- return runCall(cmd.Context(), cfg, strings.TrimSpace(args[0]))
- },
- }
-
- f := cmd.Flags()
- f.StringVar(&cfg.callMessage, "message", "", "natural-language prompt sent to the remote agent")
- f.StringVar(&cfg.callBiscuit, "biscuit", "dev-biscuit", "Biscuit token sent in A2A call headers")
- f.Int64Var(&cfg.callAmount, "amount", 1, "micropayment amount sent in A2A call headers")
- f.StringVar(&cfg.callAsset, "asset", "sam-credit", "micropayment asset sent in A2A call headers")
- f.StringVar(&cfg.callNonce, "nonce", "", "optional micropayment nonce (auto-generated when empty)")
- f.DurationVar(&cfg.callTimeout, "timeout", 20*time.Second, "A2A call timeout")
- f.StringVar(&cfg.dryRun, "dry-run", "", "dry-run mode: 'client' (no network) or 'server' (skip A2A execute)")
- _ = cmd.MarkFlagRequired("message")
-
- return cmd
-}
-
-func runCall(parent context.Context, cfg *runConfig, targetArg string) error {
- if strings.TrimSpace(cfg.callMessage) == "" {
- return fmt.Errorf("--message is required")
- }
- if cfg.callAmount <= 0 {
- return fmt.Errorf("--amount must be positive")
- }
- if strings.TrimSpace(cfg.callAsset) == "" {
- return fmt.Errorf("--asset is required")
- }
- if cfg.callTimeout <= 0 {
- cfg.callTimeout = 20 * time.Second
- }
-
- // For dry-run=client mode, validate the request without network
- if cfg.dryRun == "client" {
- return runCallDryRunClient(cfg, targetArg)
- }
-
- node, _, err := buildNode(cfg)
- if err != nil {
- return err
- }
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
-
- ctx, cancel := context.WithTimeout(parent, cfg.callTimeout)
- defer cancel()
-
- target, capability, err := resolveCallTarget(ctx, node, targetArg)
- if err != nil {
- return err
- }
-
- passport, err := loadLocalIdentityAuth()
- if err != nil {
- return err
- }
- if err := identity.SetLocalPassport(node.Host(), defaultFederationID, passport); err != nil {
- return fmt.Errorf("configuring local passport auth: %w", err)
- }
-
- observer, err := a2aprotocol.NewBoltObserverWithFallback(defaultFederationID)
- if err != nil {
- return fmt.Errorf("creating reputation observer: %w", err)
- }
- defer func() { _ = observer.Close() }()
-
- nonce := strings.TrimSpace(cfg.callNonce)
- if nonce == "" {
- nonce = fmt.Sprintf("%d", time.Now().UnixNano())
- }
- if capability == "" {
- capability = targetArg
- }
- requestJSON, err := buildCallRequest(cfg.callMessage)
- if err != nil {
- return err
- }
-
- resp, err := a2aprotocol.Execute(ctx, node.Host(), a2aprotocol.ExecuteRequest{
- Target: target,
- Capability: capability,
- Biscuit: cfg.callBiscuit,
- Payment: economy.Micropayment{
- Amount: cfg.callAmount,
- Asset: cfg.callAsset,
- Nonce: nonce,
- Capability: capability,
- },
- Request: requestJSON,
- }, observer)
- if err != nil {
- return fmt.Errorf("A2A call failed: %w", err)
- }
-
- var out any
- if err := json.Unmarshal(resp, &out); err != nil {
- _, _ = os.Stdout.Write(append(resp, '\n'))
- return nil
- }
- enc := json.NewEncoder(os.Stdout)
- enc.SetIndent("", " ")
- return enc.Encode(out)
-}
-
-func resolveCallTarget(ctx context.Context, node samnet.Node, targetArg string) (peer.AddrInfo, string, error) {
- targetArg = strings.TrimSpace(targetArg)
- if targetArg == "" {
- return peer.AddrInfo{}, "", fmt.Errorf("target peer ID or capability is required")
- }
-
- if pid, err := peer.Decode(targetArg); err == nil {
- return peer.AddrInfo{ID: pid, Addrs: node.Host().Peerstore().Addrs(pid)}, "", nil
- }
-
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- return peer.AddrInfo{}, "", fmt.Errorf("creating discovery service: %w", err)
- }
- peers, err := svc.DiscoverPeers(ctx, targetArg)
- if err != nil {
- return peer.AddrInfo{}, "", fmt.Errorf("discovering capability %q: %w", targetArg, err)
- }
- if len(peers) == 0 {
- return peer.AddrInfo{}, "", fmt.Errorf("no peers found for capability %q", targetArg)
- }
- return peers[0], targetArg, nil
-}
-
-func loadLocalIdentityAuth() (string, error) {
- const loginHint = "identity passport not found; run 'sam-agent identity login --hub <url>' first"
- store, err := identity.DefaultCredentialStore()
- if err != nil {
- return "", fmt.Errorf("opening credential store: %w", err)
- }
- defer func() { _ = store.Close() }()
- creds, err := store.Load()
- if err != nil {
- return "", fmt.Errorf("loading credentials: %w", err)
- }
- if creds == nil {
- return "", errors.New(loginHint)
- }
- pass := strings.TrimSpace(creds.PassportBiscuit)
- if pass != "" {
- return pass, nil
- }
- return "", errors.New(loginHint)
-}
-
-func buildCallRequest(message string) (json.RawMessage, error) {
- payload, err := json.Marshal(map[string]any{
- "jsonrpc": "2.0",
- "id": "sam-call",
- "method": "message",
- "params": map[string]any{
- "message": strings.TrimSpace(message),
- },
- })
- if err != nil {
- return nil, fmt.Errorf("encoding call payload: %w", err)
- }
- return json.RawMessage(payload), nil
-}
-
-// runCallDryRunClient validates a call request without network activity
-func runCallDryRunClient(cfg *runConfig, targetArg string) error {
- if strings.TrimSpace(targetArg) == "" {
- return fmt.Errorf("target peer ID or capability is required")
- }
-
- nonce := strings.TrimSpace(cfg.callNonce)
- if nonce == "" {
- nonce = fmt.Sprintf("%d", time.Now().UnixNano())
- }
-
- capability := targetArg
-
- // Build the call request structure
- callReq := map[string]any{
- "target": targetArg,
- "capability": capability,
- "biscuit": cfg.callBiscuit,
- "payment": map[string]any{
- "amount": cfg.callAmount,
- "asset": cfg.callAsset,
- "nonce": nonce,
- "capability": capability,
- },
- "message": cfg.callMessage,
- }
-
- // Output format
- if cfg.outputFormat == "json" {
- return json.NewEncoder(os.Stdout).Encode(callReq)
- }
-
- // Default human-readable format
- data, _ := json.MarshalIndent(callReq, "", " ")
- fmt.Println(string(data))
- return nil
-}
diff --git a/cmd/sam-agent/identity.go b/cmd/sam-agent/identity.go
deleted file mode 100644
index 1ee7b315..00000000
--- a/cmd/sam-agent/identity.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// 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
-
-import "github.com/spf13/cobra"
-
-// newIdentityCmd creates the "sam identity" group command.
-func newIdentityCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "identity",
- Short: "Manage SAM node identity and Hub credentials",
- }
- cmd.AddCommand(newIdentityLoginCmd(cfg))
- cmd.AddCommand(newIdentityWhoamiCmd(cfg))
- return cmd
-}
diff --git a/cmd/sam-agent/identity_login.go b/cmd/sam-agent/identity_login.go
deleted file mode 100644
index ad004bbd..00000000
--- a/cmd/sam-agent/identity_login.go
+++ /dev/null
@@ -1,152 +0,0 @@
-// 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
-
-import (
- "context"
- "fmt"
- "os"
- "strings"
-
- "github.com/spf13/cobra"
-
- "sam/pkg/identity"
-)
-
-const (
- defaultClientID = "sam-cli"
-)
-
-func newIdentityLoginCmd(cfg *runConfig) *cobra.Command {
- var clientID string
-
- cmd := &cobra.Command{
- Use: "login",
- Short: "Authenticate with a Hub using the OAuth2 Device Authorization Grant",
- Long: `Authenticate with a SAM Hub using the OAuth2 Device Authorization Grant.
-
-The CLI prints a short URL and a user code. Open the URL in any browser,
-enter the code, and complete the sign-in. The CLI polls until you finish,
-then saves credentials to ~/.config/sam/state.db.
-
-The Hub URL defaults to --hub (global flag) or the SAM_HUB environment
-variable. Any Hub that implements OIDC Device Flow is supported:
-
- sam-agent identity login --hub https://hub.internal.bank
- sam-agent identity login --hub https://hub.example.com --client-id my-app`,
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runIdentityLogin(cmd.Context(), cfg, clientID)
- },
- }
- cmd.Flags().StringVar(&clientID, "client-id", defaultClientID,
- "OAuth2 client ID registered with the Hub")
- return cmd
-}
-
-func runIdentityLogin(parent context.Context, cfg *runConfig, clientID string) error {
- hubURL := resolveHubURL(cfg)
- if hubURL == "" {
- return fmt.Errorf("hub URL is required: set --hub, SAM_HUB env var, or use a stored identity")
- }
-
- fmt.Fprintf(os.Stderr, "Fetching Hub discovery document from %s …\n", hubURL)
- disc, err := identity.FetchHubDiscovery(parent, hubURL)
- if err != nil {
- return fmt.Errorf("hub discovery: %w (make sure the Hub is reachable and implements OIDC discovery)", err)
- }
-
- flowCfg := identity.DeviceFlowConfig{ClientID: clientID}
- auth, err := identity.StartDeviceFlow(parent, disc.DeviceAuthEndpoint, flowCfg)
- if err != nil {
- return fmt.Errorf("starting device flow: %w", err)
- }
-
- // Present the code to the user.
- verifyURL := auth.VerificationURIComplete
- if verifyURL == "" {
- verifyURL = auth.VerificationURI
- }
- fmt.Fprintf(os.Stderr, "\n")
- fmt.Fprintf(os.Stderr, " Open this URL in your browser:\n\n")
- fmt.Fprintf(os.Stderr, " %s\n\n", verifyURL)
- if auth.VerificationURIComplete == "" {
- fmt.Fprintf(os.Stderr, " And enter code: %s\n\n", auth.UserCode)
- }
- fmt.Fprintf(os.Stderr, "Waiting for authorization (expires in %ds) …\n", auth.ExpiresIn)
-
- result, err := identity.PollDeviceToken(parent, disc.TokenEndpoint, auth, flowCfg)
- if err != nil {
- return fmt.Errorf("device flow: %w", err)
- }
-
- fmt.Fprintf(os.Stderr, "Authorization successful. Issuing identity passport …\n")
-
- // Build the node to obtain our stable PeerID.
- node, _, err := buildNode(cfg)
- if err != nil {
- return err
- }
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
- peerID := node.PeerID().String()
-
- issueReq := identity.PassportIssueRequest{
- PeerID: peerID,
- FederationID: defaultFederationID,
- Subject: peerID,
- Claims: map[string]string{"hub": hubURL},
- }
- passportEndpoint := strings.TrimRight(hubURL, "/") + "/issue-passport"
- passportBiscuit, err := identity.FetchPassportBiscuit(parent, passportEndpoint, result.AccessToken, issueReq)
- if err != nil {
- return fmt.Errorf("fetching hub-issued passport biscuit: %w", err)
- }
-
- store, err := identity.DefaultCredentialStore()
- if err != nil {
- return fmt.Errorf("opening credential store: %w", err)
- }
- defer func() { _ = store.Close() }()
-
- creds := &identity.StoredCredentials{
- PeerID: peerID,
- HubURL: hubURL,
- AccessToken: result.AccessToken,
- RefreshToken: result.RefreshToken,
- TokenExpiry: result.TokenExpiry,
- PassportBiscuit: passportBiscuit,
- }
- if err := store.Save(creds); err != nil {
- return fmt.Errorf("saving credentials: %w", err)
- }
-
- fmt.Fprintf(os.Stderr, "\nLogged in as peer %s\n", peerID)
- if claims, pErr := identity.ValidatePassportBiscuit(parent, passportBiscuit, peerID, defaultFederationID); pErr == nil {
- fmt.Fprintf(os.Stderr, "Subject: %s\n", claims.Subject)
- fmt.Fprintf(os.Stderr, "Federation: %s\n", claims.FederationID)
- }
- fmt.Fprintf(os.Stderr, "Credentials saved to %s\n", store.Path())
- return nil
-}
-
-// resolveHubURL returns the hub URL from the flag, then the environment.
-func resolveHubURL(cfg *runConfig) string {
- if cfg.hub != "" {
- return cfg.hub
- }
- return os.Getenv("SAM_HUB")
-}
diff --git a/cmd/sam-agent/identity_whoami.go b/cmd/sam-agent/identity_whoami.go
deleted file mode 100644
index 2305b830..00000000
--- a/cmd/sam-agent/identity_whoami.go
+++ /dev/null
@@ -1,88 +0,0 @@
-// 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
-
-import (
- "context"
- "fmt"
- "os"
- "time"
-
- "github.com/spf13/cobra"
-
- "sam/pkg/identity"
-)
-
-func newIdentityWhoamiCmd(_ *runConfig) *cobra.Command {
- return &cobra.Command{
- Use: "whoami",
- Short: "Show the currently stored identity and Hub credentials",
- Long: `Print the Hub-issued identity stored in ~/.config/sam/state.db.
-
-Displays the bound PeerID, OIDC claims, and credential expiry. If no login
-has been performed, prints a helpful message.`,
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runIdentityWhoami()
- },
- }
-}
-
-func runIdentityWhoami() error {
- store, err := identity.DefaultCredentialStore()
- if err != nil {
- return fmt.Errorf("opening credential store: %w", err)
- }
- defer func() { _ = store.Close() }()
-
- creds, err := store.Load()
- if err != nil {
- return fmt.Errorf("loading credentials: %w", err)
- }
- if creds == nil {
- _, _ = fmt.Fprintln(os.Stdout, "Not logged in. Run `sam identity login --hub <url>` to authenticate.")
- return nil
- }
-
- _, _ = fmt.Fprintf(os.Stdout, "Hub : %s\n", creds.HubURL)
- if creds.PeerID != "" {
- _, _ = fmt.Fprintf(os.Stdout, "PeerID : %s\n", creds.PeerID)
- }
-
- if !creds.TokenExpiry.IsZero() {
- if time.Now().After(creds.TokenExpiry) {
- _, _ = fmt.Fprintf(os.Stdout, "Token : EXPIRED (was %s)\n", creds.TokenExpiry.Format(time.RFC3339))
- } else {
- _, _ = fmt.Fprintf(os.Stdout, "Token : valid until %s\n", creds.TokenExpiry.Format(time.RFC3339))
- }
- }
-
- passport := creds.PassportBiscuit
- if passport == "" {
- _, _ = fmt.Fprintln(os.Stdout, "Passport : none")
- return nil
- }
- claims, err := identity.ValidatePassportBiscuit(context.Background(), passport, creds.PeerID, "")
- if err != nil {
- _, _ = fmt.Fprintf(os.Stdout, "Passport : INVALID (%v)\n", err)
- return nil
- }
- _, _ = fmt.Fprintf(os.Stdout, "Passport : present\n")
- _, _ = fmt.Fprintf(os.Stdout, "Subject : %s\n", claims.Subject)
- _, _ = fmt.Fprintf(os.Stdout, "Audience : %s\n", claims.FederationID)
- if email := claims.Claims["email"]; email != "" {
- _, _ = fmt.Fprintf(os.Stdout, "Email : %s\n", email)
- }
- return nil
-}
diff --git a/cmd/sam-agent/inspect.go b/cmd/sam-agent/inspect.go
deleted file mode 100644
index 60707cce..00000000
--- a/cmd/sam-agent/inspect.go
+++ /dev/null
@@ -1,169 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strings"
-
- "github.com/spf13/cobra"
-
- "sam/pkg/economy"
- protocol "sam/pkg/protocol/discovery"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-// newInspectCmd creates the "sam inspect" command for decoding SAM artifacts.
-func newInspectCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "inspect",
- Short: "Decode and explain SAM artifacts (biscuit, card)",
- Long: `Inspect and decode SAM artifacts for auditing and transparency.
-
-Usage:
- sam inspect biscuit <token> Decode a Biscuit token and explain caveats
- sam inspect card <peer-id|json> Decode an Agent Card and display metadata`,
- }
-
- cmd.AddCommand(newInspectBiscuitCmd(cfg))
- cmd.AddCommand(newInspectCardCmd(cfg))
- return cmd
-}
-
-// newInspectBiscuitCmd decodes a Biscuit token and displays its caveats.
-func newInspectBiscuitCmd(cfg *runConfig) *cobra.Command {
- return &cobra.Command{
- Use: "biscuit <token>",
- Short: "Decode and explain a Biscuit token",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- return runInspectBiscuit(cfg, strings.TrimSpace(args[0]))
- },
- }
-}
-
-func runInspectBiscuit(cfg *runConfig, token string) error {
- if token == "" {
- return fmt.Errorf("token is required")
- }
-
- // Parse the token using BiscuitSkillGate logic
- parser := economy.SimpleBiscuitParser{}
- parsed, err := parser.Parse(context.Background(), token)
- if err != nil {
- return fmt.Errorf("parsing biscuit: %w", err)
- }
-
- // Build human-readable explanation
- explanation := buildBiscuitExplanation(parsed)
-
- // Output format
- if cfg.outputFormat == "json" {
- result := map[string]interface{}{
- "subject": parsed.Subject,
- "allowed_skills": parsed.AllowedSkills,
- "explanation": explanation,
- }
- data, _ := json.MarshalIndent(result, "", " ")
- fmt.Println(string(data))
- } else {
- fmt.Printf("Subject: %s\n", parsed.Subject)
- if len(parsed.AllowedSkills) > 0 {
- fmt.Printf("Allowed Skills: %s\n", strings.Join(parsed.AllowedSkills, ", "))
- } else {
- fmt.Println("Allowed Skills: (unrestricted)")
- }
- fmt.Printf("\nHuman Language Summary:\n%s\n", explanation)
- }
- return nil
-}
-
-// buildBiscuitExplanation generates a human-readable explanation of a Biscuit.
-func buildBiscuitExplanation(parsed *economy.ParsedBiscuit) string {
- subject := parsed.Subject
- if len(parsed.AllowedSkills) == 0 {
- return fmt.Sprintf("This token issued to '%s' grants unrestricted access to all skills.", subject)
- }
-
- if len(parsed.AllowedSkills) == 1 {
- return fmt.Sprintf("This token issued to '%s' allows the '%s' skill.", subject, parsed.AllowedSkills[0])
- }
-
- skills := strings.Join(parsed.AllowedSkills, "', '")
- return fmt.Sprintf("This token issued to '%s' allows the following skills: '%s'.", subject, skills)
-}
-
-// newInspectCardCmd decodes an Agent Card from JSON or peer ID.
-func newInspectCardCmd(cfg *runConfig) *cobra.Command {
- return &cobra.Command{
- Use: "card <peer-id|json>",
- Short: "Decode and display an Agent Card",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- return runInspectCard(cfg, strings.TrimSpace(args[0]))
- },
- }
-}
-
-func runInspectCard(cfg *runConfig, input string) error {
- if input == "" {
- return fmt.Errorf("peer-id or JSON is required")
- }
-
- // Try to parse as JSON first
- var card protocol.AgentCard
- if err := json.Unmarshal([]byte(input), &card); err != nil {
- // If JSON parsing fails, return helpful error message
- return fmt.Errorf("input must be valid JSON: %w", err)
- }
-
- // Output format
- if cfg.outputFormat == "json" {
- data, _ := json.MarshalIndent(card, "", " ")
- fmt.Println(string(data))
- } else {
- fmt.Printf("Peer ID: %s\n", card.PeerID)
- fmt.Printf("Algorithm: %s\n", card.Algorithm)
- fmt.Printf("Issued At: %s\n", card.IssuedAt.Format("2006-01-02T15:04:05Z07:00"))
-
- if len(card.Capabilities) > 0 {
- fmt.Println("\nCapabilities:")
- for _, capability := range card.Capabilities {
- fmt.Printf(" - %s\n", capability)
- }
- }
-
- resources := mcpprotocol.ResourcesFromCard(&card)
- if len(resources) > 0 {
- fmt.Println("\nResources:")
- for _, res := range resources {
- fmt.Printf(" - %s (%s): %s\n", res.Name, res.Kind, res.Endpoint)
- }
- }
-
- fmt.Printf("\nSignature: %s\n", truncateString(card.Signature, 20))
- }
- return nil
-}
-
-// truncateString limits a string to n characters and adds ellipsis.
-func truncateString(s string, n int) string {
- if len(s) <= n {
- return s
- }
- return s[:n] + "..."
-}
diff --git a/cmd/sam-agent/main.go b/cmd/sam-agent/main.go
deleted file mode 100644
index dd39b2e4..00000000
--- a/cmd/sam-agent/main.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package main
-
-import (
- "fmt"
- "os"
-)
-
-func main() {
- cfg := &runConfig{}
- cmd := newRootCmd(cfg)
- if err := cmd.Execute(); err != nil {
- fmt.Fprintf(os.Stderr, "sam-agent: %v\n", err)
- os.Exit(1)
- }
-}
diff --git a/cmd/sam-agent/mesh.go b/cmd/sam-agent/mesh.go
deleted file mode 100644
index aa1738e9..00000000
--- a/cmd/sam-agent/mesh.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// 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
-
-import "github.com/spf13/cobra"
-
-// newMeshCmd creates the "sam mesh" group command and its subcommands.
-func newMeshCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "mesh",
- Short: "Inspect and interact with the SAM agent mesh",
- }
- cmd.AddCommand(newMeshGetCmd(cfg))
- return cmd
-}
-
-// newMeshGetCmd creates the "sam mesh get" sub-group.
-func newMeshGetCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "get",
- Short: "Retrieve resources from the mesh",
- }
- // -o / --output is a persistent flag so every "get" leaf inherits it.
- cmd.PersistentFlags().StringVarP(&cfg.outputFormat, "output", "o", "table",
- "output format: table|json")
-
- cmd.AddCommand(newMeshGetAgentsCmd(cfg))
- return cmd
-}
diff --git a/cmd/sam-agent/mesh_get_agents.go b/cmd/sam-agent/mesh_get_agents.go
deleted file mode 100644
index 3e8faf04..00000000
--- a/cmd/sam-agent/mesh_get_agents.go
+++ /dev/null
@@ -1,237 +0,0 @@
-// 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
-
-import (
- "bufio"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "log/slog"
- "net/http"
- "net/http/httptest"
- "os"
- "strings"
- "time"
-
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/spf13/cobra"
-
- samnet "sam/pkg/net"
- protocol "sam/pkg/protocol/discovery"
-)
-
-func newMeshGetAgentsCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "agents",
- Short: "List agent cards visible in the mesh",
- Long: `List agent cards visible in the SAM mesh.
-
-With no filter the command queries every currently-connected peer for its
-AgentCard. Use --capability to narrow the result to agents that advertise a
-specific skill via DHT discovery.
-
-Examples:
- sam mesh get agents -o json
- sam mesh get agents --capability agent.summarize
- sam mesh get agents --capability agent.chat -o json | jq '.[].peer_id'`,
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runMeshGetAgents(cmd.Context(), cfg)
- },
- }
- cmd.Flags().StringVar(&cfg.capability, "capability", "",
- "filter by capability (DHT discovery); omit to list all connected agents")
- cmd.Flags().StringVar(&cfg.skill, "skill", "", "alias of --capability")
- cmd.Flags().DurationVar(&cfg.discoverTimeout, "timeout", 10*time.Second,
- "how long to wait for DHT discovery when --capability is set")
- cmd.Flags().DurationVar(&cfg.dhtCardMaxAge, "dht-card-max-age", 15*time.Minute,
- "maximum accepted age for DHT-fetched cards (<=0 disables freshness check)")
- cmd.Flags().BoolVar(&cfg.meshWatch, "watch", false, "watch for newly discovered agents and append them live")
- return cmd
-}
-
-func runMeshGetAgents(parent context.Context, cfg *runConfig) error {
- format, err := parseOutputFormat(cfg.outputFormat)
- if err != nil {
- return err
- }
-
- node, _, err := buildNode(cfg)
- if err != nil {
- return err
- }
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
-
- if cfg.meshWatch {
- return runMeshGetAgentsWatch(parent, cfg, format, node)
- }
-
- svc, err := protocol.NewDiscoveryService(node, protocol.WithMaxDHTCardAge(cfg.dhtCardMaxAge))
- if err != nil {
- return fmt.Errorf("creating discovery service: %w", err)
- }
-
- ctx, cancel := context.WithTimeout(parent, cfg.discoverTimeout)
- defer cancel()
-
- filter := cfg.capability
- if filter == "" {
- filter = cfg.skill
- }
-
- var cards []*protocol.AgentCard
- if filter != "" {
- // DHT-based capability-filtered discovery.
- cards, err = svc.Discover(ctx, filter)
- } else {
- // List AgentCards from all currently-connected peers.
- cards, err = svc.DiscoverAll(ctx)
- }
- if err != nil {
- return fmt.Errorf("discovering agents: %w", err)
- }
-
- latencyByPeer := map[string]time.Duration{}
- for _, c := range cards {
- if id, decodeErr := peer.Decode(c.PeerID); decodeErr == nil {
- latencyByPeer[c.PeerID] = node.Host().Peerstore().LatencyEWMA(id)
- }
- }
-
- return printAgents(os.Stdout, cards, format, latencyByPeer)
-}
-
-func runMeshGetAgentsWatch(parent context.Context, cfg *runConfig, format outputFormat, node samnet.Node) error {
- watchManager, err := newInventoryWatchManager(node, defaultFederationID)
- if err != nil {
- return fmt.Errorf("creating inventory watch manager: %w", err)
- }
- defer func() {
- if closeErr := watchManager.Close(); closeErr != nil {
- slog.Warn("closing inventory watch manager", "err", closeErr)
- }
- }()
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/.sam/watch/inventory" {
- http.NotFound(w, r)
- return
- }
- watchManager.ServeInventoryWatch(w, r)
- }))
- defer server.Close()
-
- req, err := http.NewRequestWithContext(parent, http.MethodGet, server.URL+"/.sam/watch/inventory", nil)
- if err != nil {
- return fmt.Errorf("building watch request: %w", err)
- }
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return fmt.Errorf("opening watch stream: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode != http.StatusOK {
- body, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("watch stream failed: %s: %s", resp.Status, strings.TrimSpace(string(body)))
- }
-
- discoverer, err := newAgentDiscoverer(node, defaultFederationID, cfg.dhtCardMaxAge)
- if err != nil {
- return fmt.Errorf("creating informer discoverer: %w", err)
- }
- informer, err := samnet.NewLocalInformer(node, defaultFederationID, samnet.WithInformerDiscoverer(discoverer))
- if err != nil {
- return fmt.Errorf("creating local informer: %w", err)
- }
- informer.Start(parent)
-
- if format == outputTable {
- if err := printAgentsTableHeader(os.Stdout); err != nil {
- return err
- }
- }
-
- seen := map[string]struct{}{}
- return consumeInventorySSE(resp.Body, func(evt samnet.AgentWatchEvent) error {
- if evt.Type != samnet.AgentWatchEventAdded || len(evt.Card) == 0 {
- return nil
- }
- card, err := decodeAgentCardRaw(evt.Card)
- if err != nil {
- return nil
- }
- if _, ok := seen[card.PeerID]; ok {
- return nil
- }
- seen[card.PeerID] = struct{}{}
-
- latencyByPeer := map[string]time.Duration{}
- if id, err := peer.Decode(card.PeerID); err == nil {
- latencyByPeer[card.PeerID] = node.Host().Peerstore().LatencyEWMA(id)
- }
- rows := toAgentRows([]*protocol.AgentCard{card}, latencyByPeer)
- if format == outputJSON {
- enc := json.NewEncoder(os.Stdout)
- return enc.Encode(rows[0])
- }
- return printAgentRows(os.Stdout, rows)
- })
-}
-
-func consumeInventorySSE(body io.Reader, onEvent func(samnet.AgentWatchEvent) error) error {
- scanner := bufio.NewScanner(body)
- var eventName string
- var dataLines []string
- for scanner.Scan() {
- line := scanner.Text()
- if line == "" {
- if strings.EqualFold(eventName, "HEARTBEAT") {
- eventName = ""
- dataLines = nil
- continue
- }
- if len(dataLines) > 0 {
- var evt samnet.AgentWatchEvent
- if err := json.Unmarshal([]byte(strings.Join(dataLines, "\n")), &evt); err != nil {
- return fmt.Errorf("decoding watch event: %w", err)
- }
- if evt.Type == "" {
- evt.Type = samnet.AgentWatchEventType(eventName)
- }
- if err := onEvent(evt); err != nil {
- return err
- }
- }
- eventName = ""
- dataLines = nil
- continue
- }
- if strings.HasPrefix(line, "event: ") {
- eventName = strings.TrimSpace(strings.TrimPrefix(line, "event: "))
- continue
- }
- if strings.HasPrefix(line, "data: ") {
- dataLines = append(dataLines, strings.TrimPrefix(line, "data: "))
- }
- }
- if err := scanner.Err(); err != nil {
- return err
- }
- return nil
-}
diff --git a/cmd/sam-agent/node.go b/cmd/sam-agent/node.go
deleted file mode 100644
index 80495614..00000000
--- a/cmd/sam-agent/node.go
+++ /dev/null
@@ -1,225 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "encoding/pem"
- "fmt"
- "log/slog"
- "net/http"
- "net/url"
- "os"
- "os/signal"
- "strings"
- "syscall"
- "time"
-
- "github.com/libp2p/go-libp2p/core/crypto"
- libp2ppeer "github.com/libp2p/go-libp2p/core/peer"
- "github.com/multiformats/go-multiaddr"
-
- samnet "sam/pkg/net"
-)
-
-// buildNode constructs a SAM mesh node from the shared runConfig flags.
-// --hub is mandatory: the hub provides OIDC-backed passport issuance and
-// acts as the mandatory P2P rendezvous/bootstrap point for the mesh.
-// It also returns the hub's libp2p peer ID so callers can register it as
-// a trusted peer (exempt from passport auth) before joining the mesh.
-func buildNode(cfg *runConfig) (samnet.Node, libp2ppeer.ID, error) {
- hubURL := strings.TrimSpace(resolveHubURL(cfg))
- if hubURL == "" {
- return nil, "", fmt.Errorf("--hub (or SAM_HUB env) is required: the hub is the rendezvous point and passport issuer for the mesh")
- }
-
- listen, err := parseMultiaddrs(cfg.listenAddrs)
- if err != nil {
- return nil, "", fmt.Errorf("parsing --listen: %w", err)
- }
-
- key, err := loadOrGenerateKey(cfg.identityPath)
- if err != nil {
- return nil, "", fmt.Errorf("loading identity key: %w", err)
- }
-
- // Resolve hub hostname for rendezvous namespace and relay hint.
- hubHost := hubHostFromURL(hubURL)
-
- // Fetch hub P2P bootstrap addresses from the hub's well-known endpoint.
- // This is the primary rendezvous mechanism: all agents bootstrap through
- // the hub, which acts as DHT server and relay.
- hubBootstrap, hubPeerID, err := fetchHubP2PInfo(hubURL)
- if err != nil {
- slog.Default().Warn("could not fetch hub P2P addresses; hub may not be running in P2P mode", "hub", hubURL, "err", err)
- }
-
- opts := []samnet.Option{
- samnet.WithListenAddrs(listen...),
- samnet.WithBootstrapPeers(hubBootstrap...),
- samnet.WithDHTMode(parseDHTMode(cfg.dhtMode)),
- samnet.WithFederation(defaultFederationID),
- samnet.WithUserAgent(cfg.userAgent),
- samnet.WithLogger(slog.Default()),
- samnet.WithPrivateKey(key),
- samnet.WithRendezvousNamespace(hubHost),
- samnet.WithRelayFallbackHost(hubHost),
- }
- if cfg.withRelay {
- opts = append(opts, samnet.WithRelayService())
- }
-
- node, err := samnet.New(opts...)
- if err != nil {
- return nil, "", err
- }
- return node, hubPeerID, nil
-}
-
-// fetchHubP2PAddrs contacts the hub's /.well-known/sam-hub-p2p endpoint and
-// returns the hub's libp2p multiaddrs for use as bootstrap/rendezvous peers.
-// fetchHubP2PInfo contacts the hub's /.well-known/sam-hub-p2p endpoint and
-// returns the hub's libp2p multiaddrs and peer ID.
-func fetchHubP2PInfo(hubURL string) ([]multiaddr.Multiaddr, libp2ppeer.ID, error) {
- endpoint := strings.TrimRight(hubURL, "/") + "/.well-known/sam-hub-p2p"
- resp, err := http.Get(endpoint) //nolint:gosec // hubURL is user-supplied and validated
- if err != nil {
- return nil, "", fmt.Errorf("fetching hub P2P info: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode != http.StatusOK {
- return nil, "", fmt.Errorf("hub P2P info returned %d", resp.StatusCode)
- }
- var info struct {
- PeerID string `json:"peer_id"`
- Addrs []string `json:"addrs"`
- }
- if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
- return nil, "", fmt.Errorf("decoding hub P2P info: %w", err)
- }
- var out []multiaddr.Multiaddr
- for _, s := range info.Addrs {
- ma, err := multiaddr.NewMultiaddr(s)
- if err != nil {
- continue // skip malformed entries
- }
- out = append(out, ma)
- }
- hubPeer, _ := libp2ppeer.Decode(info.PeerID) // empty string if hub has no P2P mode
- return out, hubPeer, nil
-}
-
-func hubHostFromURL(hubURL string) string {
- u, err := url.Parse(strings.TrimSpace(hubURL))
- if err != nil {
- return ""
- }
- return strings.TrimSpace(u.Hostname())
-}
-
-// loadOrGenerateKey loads a PEM-encoded libp2p Ed25519 private key from path.
-//
-// - If path is empty an ephemeral key is generated.
-// - If path names an existing file the key is read from it.
-// - If path names a non-existent file a fresh key is generated and written
-// there (0600) so subsequent invocations are deterministic.
-func loadOrGenerateKey(path string) (crypto.PrivKey, error) {
- if path == "" {
- return samnet.GenerateKey()
- }
-
- data, err := os.ReadFile(path)
- if err == nil {
- block, _ := pem.Decode(data)
- if block == nil {
- return nil, fmt.Errorf("no PEM block found in %s", path)
- }
- return crypto.UnmarshalPrivateKey(block.Bytes)
- }
- if !os.IsNotExist(err) {
- return nil, fmt.Errorf("reading identity file: %w", err)
- }
-
- // File does not exist — generate and persist.
- key, err := samnet.GenerateKey()
- if err != nil {
- return nil, fmt.Errorf("generating key: %w", err)
- }
- raw, err := crypto.MarshalPrivateKey(key)
- if err != nil {
- return nil, fmt.Errorf("marshaling key: %w", err)
- }
- block := &pem.Block{Type: "LIBP2P PRIVATE KEY", Bytes: raw}
- if err := os.WriteFile(path, pem.EncodeToMemory(block), 0o600); err != nil {
- return nil, fmt.Errorf("writing identity file: %w", err)
- }
- slog.Default().Info("identity key created", "path", path)
- return key, nil
-}
-
-// parseMultiaddrs converts a slice of multiaddr strings into typed values.
-func parseMultiaddrs(values []string) ([]multiaddr.Multiaddr, error) {
- if len(values) == 0 {
- return nil, nil
- }
- out := make([]multiaddr.Multiaddr, 0, len(values))
- for _, value := range values {
- ma, err := multiaddr.NewMultiaddr(strings.TrimSpace(value))
- if err != nil {
- return nil, err
- }
- out = append(out, ma)
- }
- return out, nil
-}
-
-// parseDHTMode maps a flag string to the samnet.DHTMode constant.
-func parseDHTMode(mode string) samnet.DHTMode {
- switch strings.ToLower(strings.TrimSpace(mode)) {
- case "server":
- return samnet.DHTModeServer
- case "auto":
- return samnet.DHTModeAuto
- default:
- return samnet.DHTModeClient
- }
-}
-
-// waitForShutdown blocks until either the context is cancelled, a OS signal is
-// received, or the optional runFor timer fires.
-func waitForShutdown(parent context.Context, runFor time.Duration) error {
- if runFor > 0 {
- t := time.NewTimer(runFor)
- defer func() { _ = t.Stop() }()
- select {
- case <-parent.Done():
- return parent.Err()
- case <-t.C:
- return nil
- }
- }
-
- sigCh := make(chan os.Signal, 1)
- signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
- defer signal.Stop(sigCh)
-
- select {
- case <-parent.Done():
- return parent.Err()
- case <-sigCh:
- return nil
- }
-}
diff --git a/cmd/sam-agent/output.go b/cmd/sam-agent/output.go
deleted file mode 100644
index 7764360d..00000000
--- a/cmd/sam-agent/output.go
+++ /dev/null
@@ -1,134 +0,0 @@
-// 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
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "strings"
- "text/tabwriter"
- "time"
-
- protocol "sam/pkg/protocol/discovery"
-)
-
-// outputFormat controls how command results are rendered.
-type outputFormat string
-
-const (
- outputTable outputFormat = "table"
- outputJSON outputFormat = "json"
-)
-
-// parseOutputFormat validates and normalises the -o flag value.
-func parseOutputFormat(s string) (outputFormat, error) {
- switch strings.ToLower(strings.TrimSpace(s)) {
- case "table", "":
- return outputTable, nil
- case "json":
- return outputJSON, nil
- default:
- return "", fmt.Errorf("unsupported output format %q: must be table or json", s)
- }
-}
-
-// agentRow is the flat representation used for both table and JSON output.
-type agentRow struct {
- PeerID string `json:"peer_id"`
- Identity string `json:"identity"`
- Capability string `json:"capability"`
- Latency string `json:"latency"`
- IssuedAt time.Time `json:"issued_at"`
-}
-
-func toAgentRows(cards []*protocol.AgentCard, latencyByPeer map[string]time.Duration) []agentRow {
- rows := make([]agentRow, 0, len(cards))
- for _, c := range cards {
- identity := c.PeerID
- caps := c.CapabilityNames()
- capability := ""
- if len(caps) > 0 {
- capability = caps[0]
- }
- latency := "n/a"
- if d, ok := latencyByPeer[c.PeerID]; ok {
- latency = d.Round(time.Millisecond).String()
- }
- rows = append(rows, agentRow{
- PeerID: c.PeerID,
- Identity: identity,
- Capability: capability,
- Latency: latency,
- IssuedAt: c.IssuedAt,
- })
- }
- return rows
-}
-
-// printAgents writes agent cards to w in the requested format.
-func printAgents(w io.Writer, cards []*protocol.AgentCard, format outputFormat, latencyByPeer map[string]time.Duration) error {
- rows := toAgentRows(cards, latencyByPeer)
- switch format {
- case outputJSON:
- enc := json.NewEncoder(w)
- enc.SetIndent("", " ")
- return enc.Encode(rows)
- default:
- return printAgentsTable(w, rows)
- }
-}
-
-func printAgentsTable(w io.Writer, rows []agentRow) error {
- tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
- _, _ = fmt.Fprintln(tw, "PEER ID\tIDENTITY\tCAPABILITY\tLATENCY\tISSUED AT")
- for _, r := range rows {
- _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n",
- truncate(r.PeerID, 20),
- r.Identity,
- r.Capability,
- r.Latency,
- r.IssuedAt.Format(time.RFC3339),
- )
- }
- return tw.Flush()
-}
-
-func printAgentsTableHeader(w io.Writer) error {
- tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
- _, _ = fmt.Fprintln(tw, "PEER ID\tIDENTITY\tCAPABILITY\tLATENCY\tISSUED AT")
- return tw.Flush()
-}
-
-func printAgentRows(w io.Writer, rows []agentRow) error {
- tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
- for _, r := range rows {
- _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n",
- truncate(r.PeerID, 20),
- r.Identity,
- r.Capability,
- r.Latency,
- r.IssuedAt.Format(time.RFC3339),
- )
- }
- return tw.Flush()
-}
-
-func truncate(s string, n int) string {
- if len(s) <= n {
- return s
- }
- return s[:n-1] + "…"
-}
diff --git a/cmd/sam-agent/proxy.go b/cmd/sam-agent/proxy.go
deleted file mode 100644
index c2ac63ae..00000000
--- a/cmd/sam-agent/proxy.go
+++ /dev/null
@@ -1,581 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "log/slog"
- "math/big"
- "net/http"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/spf13/cobra"
-
- "sam/pkg/identity"
- samnet "sam/pkg/net"
- a2aprotocol "sam/pkg/protocol/a2a"
- protocol "sam/pkg/protocol/discovery"
- httpprotocol "sam/pkg/protocol/http"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-func newProxyCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "proxy",
- Short: "Start a local HTTP proxy tunnel over libp2p",
- Long: `Listen on a local HTTP port and forward requests through SAM.
-
-The destination must be set on each request via X-SAM-Target:
- - PeerID: routes directly to a specific peer
- - Capability: discovers the closest provider via DHT and routes there`,
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runProxy(cmd.Context(), cfg)
- },
- }
-
- f := cmd.Flags()
- f.IntVar(&cfg.proxyPort, "port", 0, "local HTTP listen port")
- f.StringVar(&cfg.proxyTargetHdr, "target-header", "X-SAM-Target", "request header used to select peer-id or capability")
- f.StringVar(&cfg.proxyBiscuit, "biscuit", "dev-biscuit", "biscuit token forwarded in tunnel metadata")
- f.DurationVar(&cfg.proxyTimeout, "timeout", 30*time.Second, "per-request tunnel timeout")
- _ = cmd.MarkFlagRequired("port")
-
- return cmd
-}
-
-func runProxy(parent context.Context, cfg *runConfig) error {
- if cfg.proxyPort <= 0 {
- return fmt.Errorf("--port must be a positive integer")
- }
- if strings.TrimSpace(cfg.proxyTargetHdr) == "" {
- cfg.proxyTargetHdr = "X-SAM-Target"
- }
- if cfg.proxyTimeout <= 0 {
- cfg.proxyTimeout = 30 * time.Second
- }
-
- node, _, err := buildNode(cfg)
- if err != nil {
- return err
- }
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
-
- discoverer, err := newAgentDiscoverer(node, defaultFederationID, 15*time.Minute)
- if err != nil {
- return fmt.Errorf("creating informer discoverer: %w", err)
- }
- informer, err := samnet.NewLocalInformer(node, defaultFederationID, samnet.WithInformerDiscoverer(discoverer))
- if err != nil {
- return fmt.Errorf("creating local informer: %w", err)
- }
- informer.Start(parent)
-
- watchManager, err := newInventoryWatchManager(node, defaultFederationID)
- if err != nil {
- return fmt.Errorf("creating inventory watch manager: %w", err)
- }
- defer func() {
- if closeErr := watchManager.Close(); closeErr != nil {
- slog.Warn("closing inventory watch manager", "err", closeErr)
- }
- }()
-
- handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if strings.HasPrefix(r.URL.Path, "/.sam/") {
- handleSAMReservedWithWatcher(w, r, node, cfg, watchManager)
- return
- }
-
- if _, authErr := extractBearerToken(r.Header.Get("Authorization")); authErr != nil {
- http.Error(w, fmt.Sprintf("unauthorized: %v", authErr), http.StatusUnauthorized)
- return
- }
-
- start := time.Now()
- observer, err := a2aprotocol.NewBoltObserverWithFallback(defaultFederationID)
- if err != nil {
- http.Error(w, "reputation observer unavailable", http.StatusInternalServerError)
- return
- }
- defer func() { _ = observer.Close() }()
-
- passport, vErr := loadLocalIdentityAuth()
- if vErr != nil {
- http.Error(w, "unauthorized: local identity login required", http.StatusUnauthorized)
- return
- }
- if err := identity.SetLocalPassport(node.Host(), defaultFederationID, passport); err != nil {
- http.Error(w, fmt.Sprintf("passport auth unavailable: %v", err), http.StatusInternalServerError)
- return
- }
-
- targetArg := strings.TrimSpace(r.Header.Get(cfg.proxyTargetHdr))
- if targetArg == "" {
- http.Error(w, fmt.Sprintf("missing %s header", cfg.proxyTargetHdr), http.StatusBadRequest)
- return
- }
-
- ctx, cancel := context.WithTimeout(r.Context(), cfg.proxyTimeout)
- defer cancel()
-
- target, capability, err := resolveProxyTarget(ctx, node, targetArg)
- if err != nil {
- http.Error(w, fmt.Sprintf("target resolution failed: %v", err), http.StatusBadGateway)
- return
- }
-
- body, err := io.ReadAll(r.Body)
- if err != nil {
- observer.OnFailure(target.ID.String(), a2aprotocol.FailureTypeProtocol)
- http.Error(w, fmt.Sprintf("reading request body: %v", err), http.StatusBadRequest)
- return
- }
-
- requestHeaders := r.Header.Clone()
- requestHeaders.Del(cfg.proxyTargetHdr)
-
- tunnelReq := httpprotocol.HTTPTunnelRequest{
- Method: r.Method,
- Path: r.URL.RequestURI(),
- Headers: requestHeaders,
- Body: body,
- }
-
- if cfg.debug {
- slog.Default().Info("proxy hop", "path", "[Local HTTP] -> ["+target.ID.String()+"] -> [Remote Service]")
- }
-
- if len(target.Addrs) > 0 {
- _ = node.Connect(ctx, target)
- }
-
- resp, err := httpprotocol.TunnelHTTP(ctx, node.Host(), target.ID, httpprotocol.HTTPTunnelOpenRequest{
- Biscuit: strings.TrimSpace(cfg.proxyBiscuit),
- Capability: capability,
- Request: tunnelReq,
- })
- if err != nil {
- observer.OnFailure(target.ID.String(), a2aprotocol.FailureTypeLiveness)
- http.Error(w, fmt.Sprintf("tunnel request failed: %v", err), http.StatusBadGateway)
- return
- }
- if resp.Error != "" {
- observer.OnFailure(target.ID.String(), a2aprotocol.FailureTypeRemote)
- status := resp.StatusCode
- if status == 0 {
- status = http.StatusBadGateway
- }
- http.Error(w, resp.Error, status)
- return
- }
-
- for key, vals := range resp.Headers {
- for _, val := range vals {
- w.Header().Add(key, val)
- }
- }
- status := resp.StatusCode
- if status == 0 {
- status = http.StatusOK
- }
- w.WriteHeader(status)
- _, _ = w.Write(resp.Body)
-
- observer.OnSuccess(target.ID.String(), time.Since(start))
- })
-
- addr := ":" + strconv.Itoa(cfg.proxyPort)
- srv := &http.Server{Addr: addr, Handler: handler}
- go func() {
- <-parent.Done()
- shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- _ = srv.Shutdown(shutdownCtx)
- }()
-
- slog.Default().Info("SAM HTTP proxy is up", "peer_id", node.PeerID(), "listen", addr, "target_header", cfg.proxyTargetHdr)
- if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
- return fmt.Errorf("starting local proxy HTTP server: %w", err)
- }
- return nil
-}
-
-func extractBearerToken(header string) (string, error) {
- header = strings.TrimSpace(header)
- if header == "" {
- return "", fmt.Errorf("missing Authorization header")
- }
- parts := strings.SplitN(header, " ", 2)
- if len(parts) != 2 || !strings.EqualFold(strings.TrimSpace(parts[0]), "Bearer") {
- return "", errors.New("authorization must use Bearer scheme")
- }
- token := strings.TrimSpace(parts[1])
- if token == "" {
- return "", fmt.Errorf("bearer token is empty")
- }
- return token, nil
-}
-
-func handleSAMReserved(w http.ResponseWriter, r *http.Request, node samnet.Node, cfg *runConfig) {
- handleSAMReservedWithWatcher(w, r, node, cfg, nil)
-}
-
-func handleSAMReservedWithWatcher(w http.ResponseWriter, r *http.Request, node samnet.Node, cfg *runConfig, watchManager *inventoryWatchManager) {
- ctx, cancel := context.WithTimeout(r.Context(), cfg.proxyTimeout)
- defer cancel()
-
- switch r.URL.Path {
- case "/.sam/watch/inventory":
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- if watchManager == nil {
- http.Error(w, "watch manager unavailable", http.StatusServiceUnavailable)
- return
- }
- watchManager.ServeInventoryWatch(w, r)
- return
- case "/.sam/inventory":
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- cards, err := aggregateInventory(ctx, node, defaultFederationID)
- if err != nil {
- http.Error(w, fmt.Sprintf("inventory lookup failed: %v", err), http.StatusBadGateway)
- return
- }
- writeJSON(w, cards)
- case "/.sam/mcp/inventory":
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- cards, err := aggregateInventory(ctx, node, defaultFederationID)
- if err != nil {
- http.Error(w, fmt.Sprintf("inventory lookup failed: %v", err), http.StatusBadGateway)
- return
- }
- writeJSON(w, buildGlobalMCPCatalog(cards))
- case "/.sam/search":
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- skill := strings.TrimSpace(r.URL.Query().Get("skill"))
- if skill == "" {
- http.Error(w, "missing skill query parameter", http.StatusBadRequest)
- return
- }
- cards, err := searchInventoryBySkill(ctx, node, defaultFederationID, skill)
- if err != nil {
- http.Error(w, fmt.Sprintf("search failed: %v", err), http.StatusBadGateway)
- return
- }
- writeJSON(w, cards)
- default:
- http.NotFound(w, r)
- }
-}
-
-func aggregateInventory(ctx context.Context, node samnet.Node, federation string) ([]*protocol.AgentCard, error) {
- cached, err := decodeCachedAgentCards(federation)
- if err != nil {
- return nil, err
- }
-
- byPeer := make(map[string]*protocol.AgentCard, len(cached))
- capabilities := map[string]struct{}{}
- for _, card := range cached {
- if card == nil || strings.TrimSpace(card.PeerID) == "" {
- continue
- }
- byPeer[card.PeerID] = card
- for _, capName := range card.CapabilityNames() {
- capabilities[capName] = struct{}{}
- }
- }
-
- for capability := range capabilities {
- liveCards, err := discoverCardsByCapability(ctx, node, capability)
- if err != nil {
- continue
- }
- for _, card := range liveCards {
- if card == nil || strings.TrimSpace(card.PeerID) == "" {
- continue
- }
- byPeer[card.PeerID] = card
- _ = upsertAgentCardRecord(federation, card)
- }
- }
-
- out := make([]*protocol.AgentCard, 0, len(byPeer))
- for _, card := range byPeer {
- out = append(out, card)
- }
- sort.Slice(out, func(i, j int) bool { return out[i].PeerID < out[j].PeerID })
- return out, nil
-}
-
-func searchInventoryBySkill(ctx context.Context, node samnet.Node, federation, skill string) ([]*protocol.AgentCard, error) {
- byPeer := map[string]*protocol.AgentCard{}
-
- cached, _ := decodeCachedAgentCards(federation)
- for _, card := range cached {
- if cardHasCapability(card, skill) {
- byPeer[card.PeerID] = card
- }
- }
-
- liveCards, err := discoverCardsByCapability(ctx, node, skill)
- if err != nil {
- if len(byPeer) == 0 {
- return nil, err
- }
- } else {
- for _, card := range liveCards {
- if card == nil || strings.TrimSpace(card.PeerID) == "" {
- continue
- }
- byPeer[card.PeerID] = card
- _ = upsertAgentCardRecord(federation, card)
- }
- }
-
- out := make([]*protocol.AgentCard, 0, len(byPeer))
- for _, card := range byPeer {
- out = append(out, card)
- }
- sort.Slice(out, func(i, j int) bool { return out[i].PeerID < out[j].PeerID })
- return out, nil
-}
-
-func discoverCardsByCapability(ctx context.Context, node samnet.Node, capability string) ([]*protocol.AgentCard, error) {
- ns := protocol.AgentCapabilityNamespace(capability)
- peerInfos, err := findProvidersForNamespace(ctx, node, ns)
- if err != nil {
- return nil, err
- }
-
- seen := map[string]struct{}{}
- cards := make([]*protocol.AgentCard, 0, len(peerInfos))
- for _, pi := range peerInfos {
- if pi.ID == "" {
- continue
- }
- pid := pi.ID.String()
- if _, ok := seen[pid]; ok {
- continue
- }
- seen[pid] = struct{}{}
-
- if len(pi.Addrs) > 0 {
- _ = node.Connect(ctx, pi)
- }
- card, err := fetchCardFromDHT(ctx, node, pid)
- if err != nil {
- continue
- }
- if !cardHasCapability(card, capability) {
- continue
- }
- cards = append(cards, card)
- }
- return cards, nil
-}
-
-func findProvidersForNamespace(ctx context.Context, node samnet.Node, namespace string) ([]peer.AddrInfo, error) {
- ch, err := node.Discover(ctx, namespace)
- if err != nil {
- return nil, err
- }
-
- results := make([]peer.AddrInfo, 0)
- seen := map[string]struct{}{}
- for info := range ch {
- if info.ID == "" || info.ID == node.PeerID() {
- continue
- }
- if _, ok := seen[info.ID.String()]; ok {
- continue
- }
- seen[info.ID.String()] = struct{}{}
- results = append(results, info)
- }
- return results, nil
-}
-
-func fetchCardFromDHT(ctx context.Context, node samnet.Node, peerID string) (*protocol.AgentCard, error) {
- raw, err := node.GetValue(ctx, protocol.DHTPeerCardKey(peerID))
- if err != nil {
- return nil, err
- }
- var card protocol.AgentCard
- if err := json.Unmarshal(raw, &card); err != nil {
- return nil, fmt.Errorf("decoding agent card: %w", err)
- }
- if err := protocol.VerifyAgentCard(&card); err != nil {
- return nil, fmt.Errorf("validating agent card: %w", err)
- }
- return &card, nil
-}
-
-func cardHasCapability(card *protocol.AgentCard, capability string) bool {
- if card == nil {
- return false
- }
- want := strings.ToLower(strings.TrimSpace(capability))
- if want == "" {
- return false
- }
- for _, c := range card.CapabilityNames() {
- if strings.EqualFold(c, want) {
- return true
- }
- }
- return false
-}
-
-type meshToolEntry struct {
- URI string `json:"uri"`
- PeerID string `json:"peer_id"`
- Name string `json:"name"`
- Kind string `json:"kind,omitempty"`
- Capability string `json:"capability,omitempty"`
- Description string `json:"description,omitempty"`
-}
-
-func buildGlobalMCPCatalog(cards []*protocol.AgentCard) []meshToolEntry {
- out := make([]meshToolEntry, 0)
- for _, card := range cards {
- if card == nil || strings.TrimSpace(card.PeerID) == "" {
- continue
- }
- resources := mcpprotocol.ResourcesFromCard(card)
- for _, res := range resources {
- name := strings.TrimSpace(res.Name)
- if name == "" {
- continue
- }
- out = append(out, meshToolEntry{
- URI: fmt.Sprintf("mesh://%s/%s", card.PeerID, name),
- PeerID: card.PeerID,
- Name: name,
- Kind: strings.TrimSpace(res.Kind),
- Description: strings.TrimSpace(res.Description),
- })
- }
- if len(resources) > 0 {
- continue
- }
- for _, capability := range card.CapabilityNames() {
- out = append(out, meshToolEntry{
- URI: fmt.Sprintf("mesh://%s/%s", card.PeerID, capability),
- PeerID: card.PeerID,
- Name: capability,
- Capability: capability,
- })
- }
- }
- sort.Slice(out, func(i, j int) bool {
- if out[i].PeerID == out[j].PeerID {
- return out[i].Name < out[j].Name
- }
- return out[i].PeerID < out[j].PeerID
- })
- return out
-}
-
-func writeJSON(w http.ResponseWriter, v any) {
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(v); err != nil {
- http.Error(w, fmt.Sprintf("encoding response: %v", err), http.StatusInternalServerError)
- }
-}
-
-func resolveProxyTarget(ctx context.Context, node samnet.Node, targetArg string) (peer.AddrInfo, string, error) {
- targetArg = strings.TrimSpace(targetArg)
- if targetArg == "" {
- return peer.AddrInfo{}, "", fmt.Errorf("target peer ID or capability is required")
- }
-
- if pid, err := peer.Decode(targetArg); err == nil {
- return peer.AddrInfo{ID: pid, Addrs: node.Host().Peerstore().Addrs(pid)}, "", nil
- }
-
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- return peer.AddrInfo{}, "", fmt.Errorf("creating discovery service: %w", err)
- }
- peers, err := svc.DiscoverPeers(ctx, targetArg)
- if err != nil {
- return peer.AddrInfo{}, "", fmt.Errorf("discovering capability %q: %w", targetArg, err)
- }
- if len(peers) == 0 {
- return peer.AddrInfo{}, "", fmt.Errorf("no peers found for capability %q", targetArg)
- }
-
- closest := closestPeer(node.PeerID(), peers)
- return closest, targetArg, nil
-}
-
-func closestPeer(local peer.ID, peers []peer.AddrInfo) peer.AddrInfo {
- if len(peers) == 1 {
- return peers[0]
- }
- localBytes := []byte(local)
- best := peers[0]
- bestDistance := xorDistance(localBytes, []byte(best.ID))
- for i := 1; i < len(peers); i++ {
- d := xorDistance(localBytes, []byte(peers[i].ID))
- if d.Cmp(bestDistance) < 0 {
- best = peers[i]
- bestDistance = d
- }
- }
- return best
-}
-
-func xorDistance(a, b []byte) *big.Int {
- max := len(a)
- if len(b) > max {
- max = len(b)
- }
- buf := make([]byte, max)
- for i := 0; i < max; i++ {
- var av, bv byte
- if i < len(a) {
- av = a[i]
- }
- if i < len(b) {
- bv = b[i]
- }
- buf[i] = av ^ bv
- }
- return new(big.Int).SetBytes(buf)
-}
diff --git a/cmd/sam-agent/proxy_reserved_test.go b/cmd/sam-agent/proxy_reserved_test.go
deleted file mode 100644
index 266bcadc..00000000
--- a/cmd/sam-agent/proxy_reserved_test.go
+++ /dev/null
@@ -1,233 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "net/http/httptest"
- "path/filepath"
- "testing"
- "time"
-
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/multiformats/go-multiaddr"
-
- "sam/pkg/identity"
- samnet "sam/pkg/net"
- protocol "sam/pkg/protocol/discovery"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-func TestExtractBearerToken(t *testing.T) {
- tests := []struct {
- name string
- header string
- wantErr bool
- }{
- {name: "valid bearer", header: "Bearer abc.def.ghi", wantErr: false},
- {name: "valid bearer lowercase", header: "bearer token", wantErr: false},
- {name: "missing header", header: "", wantErr: true},
- {name: "wrong scheme", header: "Basic xyz", wantErr: true},
- {name: "empty token", header: "Bearer ", wantErr: true},
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- _, err := extractBearerToken(tc.header)
- if tc.wantErr && err == nil {
- t.Fatalf("expected error, got nil")
- }
- if !tc.wantErr && err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- })
- }
-}
-
-func TestSAMReservedSearchReturnsPublishedWriterCard(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- tmpHome := t.TempDir()
- t.Setenv("HOME", tmpHome)
- t.Setenv("XDG_CONFIG_HOME", filepath.Join(tmpHome, ".config"))
-
- nodeB, err := newProxyReservedNode(0, nil)
- if err != nil {
- t.Fatalf("creating proxy/search node: %v", err)
- }
- if err := nodeB.Start(ctx); err != nil {
- t.Fatalf("starting proxy/search node: %v", err)
- }
- defer func() { _ = nodeB.Stop(context.Background()) }()
-
- // Set passport on nodeB
- passportB, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{
- PeerID: nodeB.PeerID().String(),
- FederationID: "default",
- Subject: nodeB.PeerID().String(),
- })
- if err != nil {
- t.Fatalf("issuing nodeB passport: %v", err)
- }
- if err := identity.SetLocalPassport(nodeB.Host(), "default", passportB); err != nil {
- t.Fatalf("setting nodeB passport: %v", err)
- }
-
- bootstrap := []multiaddr.Multiaddr{nodeB.Addrs()[0].Encapsulate(multiaddr.StringCast("/p2p/" + nodeB.PeerID().String()))}
- nodeA, err := newProxyReservedNode(0, bootstrap)
- if err != nil {
- t.Fatalf("creating publisher node: %v", err)
- }
- if err := nodeA.Start(ctx); err != nil {
- t.Fatalf("starting publisher node: %v", err)
- }
- defer func() { _ = nodeA.Stop(context.Background()) }()
-
- // Set passport on nodeA
- passportA, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{
- PeerID: nodeA.PeerID().String(),
- FederationID: "default",
- Subject: nodeA.PeerID().String(),
- })
- if err != nil {
- t.Fatalf("issuing nodeA passport: %v", err)
- }
- if err := identity.SetLocalPassport(nodeA.Host(), "default", passportA); err != nil {
- t.Fatalf("setting nodeA passport: %v", err)
- }
-
- if err := connectProxyReservedWithRetry(ctx, nodeA, peer.AddrInfo{ID: nodeB.PeerID(), Addrs: nodeB.Addrs()}); err != nil {
- t.Fatalf("connecting publisher to search node: %v", err)
- }
- if err := connectProxyReservedWithRetry(ctx, nodeB, peer.AddrInfo{ID: nodeA.PeerID(), Addrs: nodeA.Addrs()}); err != nil {
- t.Fatalf("connecting search node to publisher: %v", err)
- }
-
- priv := nodeA.Host().Peerstore().PrivKey(nodeA.PeerID())
- if priv == nil {
- t.Fatalf("publisher private key missing")
- }
- card, err := protocol.NewAgentCard(nodeA.PeerID(), []string{"writer"}, []mcpprotocol.Resource{{Name: "writer", Kind: "tool", Endpoint: "mcp://writer"}}, priv)
- if err != nil {
- t.Fatalf("creating writer card: %v", err)
- }
- pub, err := protocol.NewPublisher(nodeA)
- if err != nil {
- t.Fatalf("creating publisher: %v", err)
- }
- if err := publishProxyReservedWithRetry(ctx, pub, card); err != nil {
- t.Fatalf("publishing writer card: %v", err)
- }
-
- cfg := &runConfig{proxyTimeout: 3 * time.Second}
-
- deadline := time.Now().Add(20 * time.Second)
- for {
- // Re-publish while polling to handle DHT provider propagation races in short-lived tests.
- _ = pub.Publish(ctx, card)
-
- req := httptest.NewRequest(http.MethodGet, "/.sam/search?skill=writer", nil)
- rr := httptest.NewRecorder()
- handleSAMReserved(rr, req, nodeB, cfg)
-
- if rr.Code == http.StatusOK {
- var cards []*protocol.AgentCard
- if err := json.Unmarshal(rr.Body.Bytes(), &cards); err != nil {
- t.Fatalf("decoding search response: %v", err)
- }
- for _, got := range cards {
- if got != nil && got.PeerID == nodeA.PeerID().String() {
- return
- }
- }
- }
-
- if time.Now().After(deadline) {
- t.Fatalf("writer card not discovered in /.sam/search response before timeout")
- }
- time.Sleep(250 * time.Millisecond)
- }
-}
-
-func newProxyReservedNode(port int, bootstrap []multiaddr.Multiaddr) (samnet.Node, error) {
- listen, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/127.0.0.1/udp/%d/quic-v1", port))
- if err != nil {
- return nil, fmt.Errorf("building listen address: %w", err)
- }
- key, err := samnet.GenerateKey()
- if err != nil {
- return nil, fmt.Errorf("generating node key: %w", err)
- }
- node, err := samnet.New(
- samnet.WithPrivateKey(key),
- samnet.WithListenAddrs(listen),
- samnet.WithBootstrapPeers(bootstrap...),
- samnet.WithDHTMode(samnet.DHTModeServer),
- )
- if err != nil {
- return nil, err
- }
-
- // Set a test passport so the node can authenticate with other peers.
- // Note: Must be done after node creation but the actual SetLocalPassport
- // happens after Start in the test that calls this.
- return node, nil
-}
-
-func connectProxyReservedWithRetry(ctx context.Context, node samnet.Node, pi peer.AddrInfo) error {
- ticker := time.NewTicker(250 * time.Millisecond)
- defer ticker.Stop()
- var last error
- for {
- if err := node.Connect(ctx, pi); err == nil {
- return nil
- } else {
- last = err
- }
- select {
- case <-ctx.Done():
- if last != nil {
- return last
- }
- return ctx.Err()
- case <-ticker.C:
- }
- }
-}
-
-func publishProxyReservedWithRetry(ctx context.Context, pub *protocol.Publisher, card *protocol.AgentCard) error {
- ticker := time.NewTicker(250 * time.Millisecond)
- defer ticker.Stop()
- var last error
- for {
- if err := pub.Publish(ctx, card); err == nil {
- return nil
- } else {
- last = err
- }
- select {
- case <-ctx.Done():
- if last != nil {
- return last
- }
- return ctx.Err()
- case <-ticker.C:
- }
- }
-}
diff --git a/cmd/sam-agent/proxy_watch.go b/cmd/sam-agent/proxy_watch.go
deleted file mode 100644
index 03dbdcfb..00000000
--- a/cmd/sam-agent/proxy_watch.go
+++ /dev/null
@@ -1,184 +0,0 @@
-// 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
-
-import (
- "encoding/json"
- "fmt"
- "net/http"
- "sync"
- "time"
-
- "github.com/libp2p/go-libp2p/core/event"
-
- samnet "sam/pkg/net"
-)
-
-const proxyWatchHeartbeatInterval = 15 * time.Second
-
-type inventoryWatchManager struct {
- federation string
- sub event.Subscription
-
- mu sync.Mutex
- nextID uint64
- watchers map[uint64]chan samnet.AgentWatchEvent
- closed bool
-}
-
-func newInventoryWatchManager(node samnet.Node, federation string) (*inventoryWatchManager, error) {
- sub, err := node.Host().EventBus().Subscribe(new(samnet.AgentWatchEvent))
- if err != nil {
- return nil, fmt.Errorf("subscribing to agent watch events: %w", err)
- }
- mgr := &inventoryWatchManager{
- federation: federation,
- sub: sub,
- watchers: map[uint64]chan samnet.AgentWatchEvent{},
- }
- go mgr.run()
- return mgr, nil
-}
-
-func (m *inventoryWatchManager) Close() error {
- m.mu.Lock()
- if m.closed {
- m.mu.Unlock()
- return nil
- }
- m.closed = true
- watchers := m.watchers
- m.watchers = map[uint64]chan samnet.AgentWatchEvent{}
- m.mu.Unlock()
- for id, ch := range watchers {
- close(ch)
- delete(watchers, id)
- }
- return m.sub.Close()
-}
-
-func (m *inventoryWatchManager) run() {
- for evt := range m.sub.Out() {
- switch agentEvent := evt.(type) {
- case samnet.AgentWatchEvent:
- m.broadcast(agentEvent)
- case *samnet.AgentWatchEvent:
- if agentEvent != nil {
- m.broadcast(*agentEvent)
- }
- }
- }
-}
-
-func (m *inventoryWatchManager) register() (uint64, <-chan samnet.AgentWatchEvent) {
- m.mu.Lock()
- defer m.mu.Unlock()
- id := m.nextID
- m.nextID++
- ch := make(chan samnet.AgentWatchEvent, 32)
- m.watchers[id] = ch
- return id, ch
-}
-
-func (m *inventoryWatchManager) unregister(id uint64) {
- m.mu.Lock()
- defer m.mu.Unlock()
- if ch, ok := m.watchers[id]; ok {
- delete(m.watchers, id)
- close(ch)
- }
-}
-
-func (m *inventoryWatchManager) broadcast(evt samnet.AgentWatchEvent) {
- m.mu.Lock()
- defer m.mu.Unlock()
- for _, ch := range m.watchers {
- select {
- case ch <- evt:
- default:
- }
- }
-}
-
-func (m *inventoryWatchManager) ServeInventoryWatch(w http.ResponseWriter, r *http.Request) {
- flusher, ok := w.(http.Flusher)
- if !ok {
- http.Error(w, "streaming not supported", http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Content-Type", "text/event-stream")
- w.Header().Set("Cache-Control", "no-cache")
- w.Header().Set("Connection", "keep-alive")
- w.Header().Set("X-Accel-Buffering", "no")
- id, ch := m.register()
- defer m.unregister(id)
-
- if err := writeSSEHeartbeat(w); err != nil {
- return
- }
- flusher.Flush()
-
- records, _ := samnet.LoadCachedAgentRecords(m.federation)
- for _, record := range records {
- if err := writeSSEEvent(w, samnet.AgentWatchEvent{Type: samnet.AgentWatchEventAdded, PeerID: record.PeerID, Card: record.Card}); err != nil {
- return
- }
- flusher.Flush()
- }
-
- heartbeat := time.NewTicker(proxyWatchHeartbeatInterval)
- defer heartbeat.Stop()
-
- for {
- select {
- case <-r.Context().Done():
- return
- case evt, ok := <-ch:
- if !ok {
- return
- }
- if err := writeSSEEvent(w, evt); err != nil {
- return
- }
- flusher.Flush()
- case <-heartbeat.C:
- if err := writeSSEHeartbeat(w); err != nil {
- return
- }
- flusher.Flush()
- }
- }
-}
-func writeSSEEvent(w http.ResponseWriter, evt samnet.AgentWatchEvent) error {
- data, err := json.Marshal(evt)
- if err != nil {
- return err
- }
- if _, err := fmt.Fprintf(w, "event: %s\n", evt.Type); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(w, "data: %s\n\n", data); err != nil {
- return err
- }
- return nil
-}
-
-func writeSSEHeartbeat(w http.ResponseWriter) error {
- if _, err := fmt.Fprint(w, "event: HEARTBEAT\ndata: {}\n\n"); err != nil {
- return err
- }
- return nil
-}
diff --git a/cmd/sam-agent/publish.go b/cmd/sam-agent/publish.go
deleted file mode 100644
index 655821ec..00000000
--- a/cmd/sam-agent/publish.go
+++ /dev/null
@@ -1,277 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "os"
- "strings"
- "time"
-
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/spf13/cobra"
-
- "sam/pkg/economy"
- samnet "sam/pkg/net"
- a2aprotocol "sam/pkg/protocol/a2a"
- protocol "sam/pkg/protocol/discovery"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-// newPublishCmd creates the "sam publish" group command and attaches its
-// subcommands. It owns the flags that are shared between publish card and
-// publish mcp.
-func newPublishCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "publish",
- Short: "Publish an agent card to DHT namespaces",
- Long: `Publish a signed SAM AgentCard into the DHT and keep re-providing it.
-
-Quick usage:
- sam publish --skill weather-bot --mcp-port 8080
-
-Advanced usage remains available via subcommands:
- sam publish card ...
- sam publish mcp ...`,
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runPublish(cmd.Context(), cfg)
- },
- }
-
- // Shared flags inherited by both publish subcommands.
- f := cmd.PersistentFlags()
- f.StringSliceVar(&cfg.capabilities, "capability", nil, "capability to publish (repeatable)")
- f.StringVar(&cfg.skill, "skill", "", "single skill to publish (alias for one --capability)")
- f.StringVar(&cfg.resourceName, "resource-name", "", "MCP resource name")
- f.StringVar(&cfg.resourceKind, "resource-kind", "tool", "MCP resource kind")
- f.StringVar(&cfg.resourceEP, "resource-endpoint", "", "MCP resource endpoint")
- f.StringVar(&cfg.resourceDesc, "resource-description", "", "MCP resource description")
- f.DurationVar(&cfg.republishEvery, "republish-every", 2*time.Minute, "interval to refresh DHT announcements")
- f.StringVar(&cfg.dryRun, "dry-run", "", "dry-run mode: 'client' (no network) or 'server' (skip DHT commit)")
-
- cmd.Flags().IntVar(&cfg.mcpPort, "mcp-port", 0, "local MCP port for quick publish mode")
-
- cmd.AddCommand(newPublishCardCmd(cfg))
- cmd.AddCommand(newPublishMCPCmd(cfg))
- return cmd
-}
-
-func runPublish(parent context.Context, cfg *runConfig) error {
- if cfg.skill == "" && len(cfg.capabilities) == 0 {
- return fmt.Errorf("quick mode requires --skill (or use a publish subcommand)")
- }
- if cfg.mcpPort <= 0 {
- return fmt.Errorf("quick mode requires --mcp-port (or use sam publish mcp --port)")
- }
-
- capabilities := append([]string{}, cfg.capabilities...)
- if cfg.skill != "" {
- capabilities = append(capabilities, cfg.skill)
- }
- cfg.capabilities = normalizeValues(capabilities)
- if len(cfg.capabilities) == 0 {
- return fmt.Errorf("at least one non-empty skill/capability is required")
- }
- if err := ensureSecurePublishPreflight(); err != nil {
- return err
- }
-
- // For dry-run=client mode, skip network and just build the card
- if cfg.dryRun == "client" {
- return runPublishDryRunClient(cfg)
- }
-
- node, _, err := buildNode(cfg)
- if err != nil {
- return err
- }
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
-
- priv := node.Host().Peerstore().PrivKey(node.PeerID())
- if priv == nil {
- return fmt.Errorf("local node private key unavailable")
- }
-
- resourceName := strings.TrimSpace(cfg.resourceName)
- if resourceName == "" {
- resourceName = cfg.capabilities[0]
- }
- resource := mcpprotocol.Resource{
- Name: resourceName,
- Kind: strings.TrimSpace(cfg.resourceKind),
- Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),
- Description: strings.TrimSpace(cfg.resourceDesc),
- }
-
- card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, []mcpprotocol.Resource{resource}, priv)
- if err != nil {
- return fmt.Errorf("building agent card: %w", err)
- }
- if err := registerLocalAgentCard(node, card); err != nil {
- return err
- }
-
- // For dry-run=server mode, skip DHT but still build network
- if cfg.dryRun == "server" {
- return outputCard(card, cfg.outputFormat)
- }
-
- connector := &httpMCPConnector{
- client: &http.Client{Timeout: 30 * time.Second},
- addr: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),
- }
- if _, err := mcpprotocol.NewMCPBridge(node.Host(), economy.AllowAllVerifier{}, connector); err != nil {
- return fmt.Errorf("creating MCP bridge: %w", err)
- }
-
- pub, err := protocol.NewPublisher(node)
- if err != nil {
- return fmt.Errorf("creating publisher: %w", err)
- }
- if err := publishLoop(parent, pub, card, cfg.republishEvery); err != nil {
- return err
- }
-
- if err := json.NewEncoder(os.Stdout).Encode(card); err != nil {
- return fmt.Errorf("encoding published card: %w", err)
- }
- return waitForShutdown(parent, cfg.runFor)
-}
-
-func ensureSecurePublishPreflight() error {
- gate, closeFn, err := a2aprotocol.NewPassportGateWithCleanup()
- if err != nil {
- return fmt.Errorf("publish security preflight failed: %w", err)
- }
- defer func() { _ = closeFn() }()
- if a2aprotocol.IsAllowAllGate(gate) {
- return fmt.Errorf("refusing publish: A2A authentication middleware is permissive (AllowAllGate)")
- }
- return nil
-}
-
-func registerLocalAgentCard(node samnet.Node, card *protocol.AgentCard) error {
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- return fmt.Errorf("creating local discovery service: %w", err)
- }
- if err := svc.RegisterLocalCard(card); err != nil {
- return fmt.Errorf("registering local agent card stream: %w", err)
- }
- return nil
-}
-
-func publishLoop(parent context.Context, pub *protocol.Publisher, card *protocol.AgentCard, every time.Duration) error {
- if every <= 0 {
- every = 2 * time.Minute
- }
- retryTicker := time.NewTicker(250 * time.Millisecond)
- defer retryTicker.Stop()
- for {
- if err := pub.Publish(parent, card); err == nil {
- break
- } else {
- select {
- case <-parent.Done():
- return fmt.Errorf("initial publish failed: %w", err)
- case <-retryTicker.C:
- }
- }
- }
- go func() {
- ticker := time.NewTicker(every)
- defer ticker.Stop()
- for {
- select {
- case <-parent.Done():
- return
- case <-ticker.C:
- _ = pub.Publish(parent, card)
- }
- }
- }()
- return nil
-}
-
-func normalizeValues(items []string) []string {
- seen := map[string]struct{}{}
- out := make([]string, 0, len(items))
- for _, item := range items {
- v := strings.TrimSpace(item)
- if v == "" {
- continue
- }
- if _, ok := seen[v]; ok {
- continue
- }
- seen[v] = struct{}{}
- out = append(out, v)
- }
- return out
-}
-
-// runPublishDryRunClient builds a card without any network activity
-func runPublishDryRunClient(cfg *runConfig) error {
- // Generate a temporary identity for card signing
- privKey, err := samnet.GenerateKey()
- if err != nil {
- return fmt.Errorf("generating key: %w", err)
- }
-
- // Create a peer ID from the key
- peerID, err := peer.IDFromPrivateKey(privKey)
- if err != nil {
- return fmt.Errorf("creating peer ID: %w", err)
- }
-
- resourceName := strings.TrimSpace(cfg.resourceName)
- if resourceName == "" {
- resourceName = cfg.capabilities[0]
- }
- resource := mcpprotocol.Resource{
- Name: resourceName,
- Kind: strings.TrimSpace(cfg.resourceKind),
- Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),
- Description: strings.TrimSpace(cfg.resourceDesc),
- }
-
- card, err := protocol.NewAgentCard(peerID, cfg.capabilities, []mcpprotocol.Resource{resource}, privKey)
- if err != nil {
- return fmt.Errorf("building agent card: %w", err)
- }
-
- return outputCard(card, cfg.outputFormat)
-}
-
-// outputCard prints an agent card in the requested format
-func outputCard(card *protocol.AgentCard, format string) error {
- if format == "json" {
- return json.NewEncoder(os.Stdout).Encode(card)
- }
-
- // Default human-readable format
- data, err := json.MarshalIndent(card, "", " ")
- if err != nil {
- return fmt.Errorf("formatting card: %w", err)
- }
- fmt.Println(string(data))
- return nil
-}
diff --git a/cmd/sam-agent/publish_card.go b/cmd/sam-agent/publish_card.go
deleted file mode 100644
index ada4e753..00000000
--- a/cmd/sam-agent/publish_card.go
+++ /dev/null
@@ -1,94 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
- "strings"
-
- "github.com/spf13/cobra"
-
- protocol "sam/pkg/protocol/discovery"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-func newPublishCardCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "card",
- Short: "Sign and publish an A2A agent card to the DHT",
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runPublishCard(cmd.Context(), cfg)
- },
- }
- _ = cmd.MarkPersistentFlagRequired("capability")
- _ = cmd.MarkPersistentFlagRequired("resource-name")
- return cmd
-}
-
-func runPublishCard(parent context.Context, cfg *runConfig) error {
- if len(cfg.capabilities) == 0 {
- return fmt.Errorf("at least one --capability is required")
- }
-
- node, _, err := buildNode(cfg)
- if err != nil {
- return err
- }
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
-
- priv := node.Host().Peerstore().PrivKey(node.PeerID())
- if priv == nil {
- return fmt.Errorf("local node private key unavailable")
- }
-
- resource := mcpprotocol.Resource{
- Name: strings.TrimSpace(cfg.resourceName),
- Kind: strings.TrimSpace(cfg.resourceKind),
- Endpoint: strings.TrimSpace(cfg.resourceEP),
- Description: strings.TrimSpace(cfg.resourceDesc),
- }
- card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, []mcpprotocol.Resource{resource}, priv)
- if err != nil {
- return fmt.Errorf("building agent card: %w", err)
- }
- if err := registerLocalAgentCard(node, card); err != nil {
- return err
- }
-
- pub, err := protocol.NewPublisher(node)
- if err != nil {
- return fmt.Errorf("creating publisher: %w", err)
- }
- if err := publishLoop(parent, pub, card, cfg.republishEvery); err != nil {
- return fmt.Errorf("publishing agent card: %w", err)
- }
-
- if err := json.NewEncoder(os.Stdout).Encode(card); err != nil {
- return fmt.Errorf("encoding published card: %w", err)
- }
-
- slog.Default().Info("agent card published",
- "peer_id", node.PeerID(),
- "capabilities", cfg.capabilities,
- )
- return waitForShutdown(parent, cfg.runFor)
-}
diff --git a/cmd/sam-agent/publish_mcp.go b/cmd/sam-agent/publish_mcp.go
deleted file mode 100644
index d3361490..00000000
--- a/cmd/sam-agent/publish_mcp.go
+++ /dev/null
@@ -1,140 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "io"
- "log/slog"
- "net/http"
- "os"
- "strings"
- "time"
-
- "github.com/modelcontextprotocol/go-sdk/mcp"
- "github.com/spf13/cobra"
-
- "sam/pkg/economy"
- protocol "sam/pkg/protocol/discovery"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-func newPublishMCPCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "mcp",
- Short: "Expose a local MCP endpoint via libp2p and publish its agent card",
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runPublishMCP(cmd.Context(), cfg)
- },
- }
- cmd.Flags().IntVar(&cfg.mcpPort, "port", 0, "local TCP port serving the MCP JSON-RPC endpoint")
- _ = cmd.MarkFlagRequired("port")
- _ = cmd.MarkPersistentFlagRequired("capability")
- return cmd
-}
-
-func runPublishMCP(parent context.Context, cfg *runConfig) error {
- if len(cfg.capabilities) == 0 {
- return fmt.Errorf("at least one --capability is required")
- }
- if cfg.mcpPort <= 0 {
- return fmt.Errorf("--port must be a positive integer")
- }
-
- node, _, err := buildNode(cfg)
- if err != nil {
- return err
- }
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
-
- priv := node.Host().Peerstore().PrivKey(node.PeerID())
- if priv == nil {
- return fmt.Errorf("local node private key unavailable")
- }
-
- resource := mcpprotocol.Resource{
- Name: strings.TrimSpace(cfg.resourceName),
- Kind: strings.TrimSpace(cfg.resourceKind),
- Endpoint: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),
- }
- card, err := protocol.NewAgentCard(node.PeerID(), cfg.capabilities, []mcpprotocol.Resource{resource}, priv)
- if err != nil {
- return fmt.Errorf("building agent card: %w", err)
- }
- if err := registerLocalAgentCard(node, card); err != nil {
- return err
- }
-
- connector := &httpMCPConnector{
- client: &http.Client{Timeout: 30 * time.Second},
- addr: fmt.Sprintf("http://127.0.0.1:%d", cfg.mcpPort),
- }
- if _, err := mcpprotocol.NewMCPBridge(node.Host(), economy.AllowAllVerifier{}, connector); err != nil {
- return fmt.Errorf("creating MCP bridge: %w", err)
- }
-
- pub, err := protocol.NewPublisher(node)
- if err != nil {
- return fmt.Errorf("creating publisher: %w", err)
- }
- if err := publishLoop(parent, pub, card, cfg.republishEvery); err != nil {
- return fmt.Errorf("publishing agent card: %w", err)
- }
-
- if err := json.NewEncoder(os.Stdout).Encode(card); err != nil {
- return fmt.Errorf("encoding published card: %w", err)
- }
-
- slog.Default().Info("MCP bridge published",
- "peer_id", node.PeerID(),
- "mcp_port", cfg.mcpPort,
- "capabilities", cfg.capabilities,
- )
- return waitForShutdown(parent, cfg.runFor)
-}
-
-// httpMCPConnector dials a local HTTP MCP server and returns an IOTransport
-// backed by the HTTP request/response body pair.
-type httpMCPConnector struct {
- client *http.Client
- addr string // e.g. "http://127.0.0.1:8080"
-}
-
-// Open establishes a streaming JSON-RPC connection to the local MCP server.
-func (c *httpMCPConnector) Open(ctx context.Context) (mcp.Transport, error) {
- pr, pw := io.Pipe()
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.addr+"/mcp", pr)
- if err != nil {
- return nil, fmt.Errorf("building MCP HTTP request: %w", err)
- }
- req.Header.Set("Content-Type", "application/json")
-
- resp, err := c.client.Do(req)
- if err != nil {
- _ = pw.Close()
- return nil, fmt.Errorf("connecting to local MCP server at %s: %w", c.addr, err)
- }
- if resp.StatusCode != http.StatusOK {
- _ = resp.Body.Close()
- _ = pw.Close()
- return nil, fmt.Errorf("local MCP server returned %s", resp.Status)
- }
- return &mcp.IOTransport{Reader: resp.Body, Writer: pw}, nil
-}
diff --git a/cmd/sam-agent/root.go b/cmd/sam-agent/root.go
deleted file mode 100644
index 6e41b071..00000000
--- a/cmd/sam-agent/root.go
+++ /dev/null
@@ -1,123 +0,0 @@
-// 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
-
-import (
- "log/slog"
- "os"
- "time"
-
- logging "github.com/ipfs/go-log/v2"
- "github.com/spf13/cobra"
-)
-
-// runConfig holds all flag values shared across subcommands.
-type runConfig struct {
- // Node flags (persistent — available to every subcommand).
- listenAddrs []string
- dhtMode string
- withRelay bool
- userAgent string
- runFor time.Duration
- hub string
- identityPath string
- debug bool
-
- // sam up
- tunnelHTTPEndpoint string
-
- // sam publish (shared by card and mcp subcommands)
- capabilities []string
- skill string
- resourceName string
- resourceKind string
- resourceEP string
- resourceDesc string
- republishEvery time.Duration
-
- // sam publish mcp
- mcpPort int
-
- // sam mesh get
- outputFormat string
- capability string
- discoverTimeout time.Duration
- dhtCardMaxAge time.Duration
- meshWatch bool
-
- // sam call
- callMessage string
- callBiscuit string
- callAmount int64
- callAsset string
- callNonce string
- callTimeout time.Duration
-
- // sam proxy
- proxyPort int
- proxyTargetHdr string
- proxyBiscuit string
- proxyTimeout time.Duration
-
- // dry-run modes: "", "client", "server"
- dryRun string
-}
-
-const defaultFederationID = "default"
-
-// newRootCmd builds the top-level "sam-agent" command and attaches subcommands.
-func newRootCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "sam-agent",
- Short: "SAM agent runtime and mesh CLI",
- PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
- return applyLogging(cfg.debug)
- },
- }
-
- // Persistent flags visible to every subcommand.
- pf := cmd.PersistentFlags()
- pf.StringSliceVar(&cfg.listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/0/quic-v1"}, "libp2p listen multiaddrs")
- pf.StringVar(&cfg.dhtMode, "dht-mode", "client", "DHT mode: client|server|auto")
- pf.BoolVar(&cfg.withRelay, "relay-service", false, "enable relay service")
- pf.StringVar(&cfg.userAgent, "user-agent", "sam/0.1.0", "libp2p user-agent")
- pf.DurationVar(&cfg.runFor, "run-for", 0, "optional duration before graceful shutdown (0 = wait for signal)")
- pf.StringVar(&cfg.hub, "hub", "", "OIDC hub URL for passport issuance and identity login")
- pf.StringVar(&cfg.identityPath, "identity", "", "path to PEM-encoded Ed25519 private key (generated and saved if absent)")
- pf.BoolVar(&cfg.debug, "debug", false, "enable debug logging (slog + libp2p subsystems)")
-
- cmd.AddCommand(newUpCmd(cfg))
- cmd.AddCommand(newPublishCmd(cfg))
- cmd.AddCommand(newMeshCmd(cfg))
- cmd.AddCommand(newCallCmd(cfg))
- cmd.AddCommand(newProxyCmd(cfg))
- cmd.AddCommand(newIdentityCmd(cfg))
- cmd.AddCommand(newInspectCmd(cfg))
- return cmd
-}
-
-// applyLogging configures the default slog handler and, when debug is true,
-// sets every libp2p/IPFS subsystem logger to DEBUG as well.
-func applyLogging(debug bool) error {
- level := slog.LevelInfo
- if debug {
- level = slog.LevelDebug
- if err := logging.SetLogLevel("*", "debug"); err != nil {
- slog.Warn("could not set libp2p log level", "err", err)
- }
- }
- slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})))
- return nil
-}
diff --git a/cmd/sam-agent/up.go b/cmd/sam-agent/up.go
deleted file mode 100644
index 113ea3a0..00000000
--- a/cmd/sam-agent/up.go
+++ /dev/null
@@ -1,135 +0,0 @@
-// 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
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "os"
-
- "github.com/spf13/cobra"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
- httpprotocol "sam/pkg/protocol/http"
-)
-
-func newUpCmd(cfg *runConfig) *cobra.Command {
- cmd := &cobra.Command{
- Use: "up",
- Short: "Start a SAM node",
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runUp(cmd.Context(), cfg)
- },
- }
- cmd.Flags().StringVar(&cfg.tunnelHTTPEndpoint, "tunnel-http-endpoint", "", "optional local HTTP endpoint exposed via /sam/tunnel/http/1.0 (for example http://127.0.0.1:11434)")
- return cmd
-}
-
-func runUp(parent context.Context, cfg *runConfig) error {
- log := slog.Default()
-
- // Require a hub-issued passport biscuit before joining the mesh.
- // Agents must authenticate via the hub's OIDC flow first:
- // sam-agent identity login --hub <hub-url>
- creds, err := loadRequiredPassport(cfg)
- if err != nil {
- return err
- }
-
- node, hubPeerID, err := buildNode(cfg)
- if err != nil {
- return err
- }
-
- // Register the hub as a trusted peer before starting the node.
- // The hub is infrastructure — it doesn't run passport auth — so we
- // must exempt it from the connection-close-on-auth-failure gate.
- if hubPeerID != "" {
- identity.RegisterTrustedPeer(node.Host(), hubPeerID)
- }
-
- if err := node.Start(parent); err != nil {
- return fmt.Errorf("starting node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
-
- // Set the local passport so this node can prove its hub-issued identity
- // to every peer it connects to. No biscuit = no mesh participation.
- if err := identity.SetLocalPassport(node.Host(), defaultFederationID, creds.PassportBiscuit); err != nil {
- return fmt.Errorf("installing passport: %w", err)
- }
- log.Info("hub configured", "url", cfg.hub, "peer_id", creds.PeerID)
-
- var tunnel *httpprotocol.HTTPTunnelService
- if cfg.tunnelHTTPEndpoint != "" {
- tunnel, err = httpprotocol.NewHTTPTunnelService(
- node.Host(),
- cfg.tunnelHTTPEndpoint,
- httpprotocol.WithHTTPTunnelSkillGate(economy.NewBiscuitSkillGate(nil)),
- )
- if err != nil {
- return fmt.Errorf("initializing HTTP tunnel listener: %w", err)
- }
- defer tunnel.Close()
- log.Info("HTTP tunnel listener enabled", "protocol", httpprotocol.HTTPTunnelProtocolID, "endpoint", cfg.tunnelHTTPEndpoint)
- }
-
- addrs := make([]string, 0, len(node.Addrs()))
- for _, a := range node.Addrs() {
- addrs = append(addrs, a.String())
- }
-
- status := map[string]any{
- "peer_id": node.PeerID().String(),
- "addrs": addrs,
- "dht_mode": cfg.dhtMode,
- }
- if err := json.NewEncoder(os.Stdout).Encode(status); err != nil {
- return fmt.Errorf("encoding status: %w", err)
- }
-
- log.Info("SAM node is up",
- "peer_id", node.PeerID(),
- "addrs", addrs,
- "dht_mode", cfg.dhtMode,
- )
-
- return waitForShutdown(parent, cfg.runFor)
-}
-
-// loadRequiredPassport loads stored credentials and returns an error with
-// actionable guidance if no hub-issued passport biscuit is found.
-// Every agent must authenticate via the hub OIDC flow before joining the mesh.
-func loadRequiredPassport(cfg *runConfig) (*identity.StoredCredentials, error) {
- store, err := identity.DefaultCredentialStore()
- if err != nil {
- return nil, fmt.Errorf("opening credential store: %w", err)
- }
- defer func() { _ = store.Close() }()
-
- creds, err := store.Load()
- if err != nil {
- return nil, fmt.Errorf("loading credentials: %w", err)
- }
- hub := resolveHubURL(cfg)
- if creds == nil || creds.PassportBiscuit == "" {
- return nil, fmt.Errorf(
- "no hub-issued passport found — authenticate first: sam-agent identity login --hub %s", hub)
- }
- return creds, nil
-}
diff --git a/cmd/sam-hub/hub.go b/cmd/sam-hub/hub.go
new file mode 100644
index 00000000..056aa9b9
--- /dev/null
+++ b/cmd/sam-hub/hub.go
@@ -0,0 +1,241 @@
+package main
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/hex"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "sync"
+
+ "github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/coreos/go-oidc/v3/oidc"
+ "github.com/libp2p/go-libp2p"
+ p2phttp "github.com/libp2p/go-libp2p-http"
+ dht "github.com/libp2p/go-libp2p-kad-dht"
+ "github.com/libp2p/go-libp2p/core/host"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "github.com/libp2p/go-libp2p/p2p/net/gostream"
+ "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay"
+ libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"
+ libp2pquic "github.com/libp2p/go-libp2p/p2p/transport/quic"
+ "github.com/libp2p/go-libp2p/p2p/transport/tcp"
+ "github.com/spf13/cobra"
+ "golang.org/x/oauth2"
+)
+
+// Hub handles identity bridging and network discovery
+type Hub struct {
+ Host host.Host
+ DHT *dht.IpfsDHT
+ OIDCConfig *oauth2.Config
+ Verifier *oidc.IDTokenVerifier
+ BiscuitKey ed25519.PrivateKey
+ MeshID string
+ Registry map[peer.ID]string
+ mu sync.RWMutex
+}
+
+var (
+ oidcIssuer string
+ clientID string
+ clientSecret string
+ biscuitHex string
+ listenAddrs []string
+ meshName string
+ publicAddr string
+)
+
+// NewHub starts a host supporting both QUIC and TCP (with TLS 1.3)
+func NewHub(ctx context.Context) (*Hub, error) {
+ // Multi-transport setup for firewall traversal
+ h, err := libp2p.New(
+ libp2p.Transport(libp2pquic.NewTransport),
+ libp2p.Transport(tcp.NewTCPTransport),
+ libp2p.ListenAddrStrings(listenAddrs...),
+ // FIPS compliant Security
+ libp2p.Security(libp2ptls.ID, libp2ptls.New),
+ libp2p.EnableRelayService(),
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ _, err = relay.New(h)
+ if err != nil {
+ return nil, err
+ }
+
+ kadDHT, err := dht.New(ctx, h, dht.Mode(dht.ModeServer))
+ if err != nil {
+ return nil, err
+ }
+ if err = kadDHT.Bootstrap(ctx); err != nil {
+ return nil, err
+ }
+
+ provider, err := oidc.NewProvider(ctx, oidcIssuer)
+ if err != nil {
+ return nil, err
+ }
+
+ conf := &oauth2.Config{
+ ClientID: clientID,
+ ClientSecret: clientSecret,
+ Endpoint: provider.Endpoint(),
+ RedirectURL: fmt.Sprintf("%s/callback", publicAddr),
+ Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
+ }
+
+ // SAM_HUB_KEY stores an ed25519 seed as a 32-byte hex value.
+ keyBytes, err := hex.DecodeString(biscuitHex)
+ if err != nil || len(keyBytes) != 32 {
+ return nil, fmt.Errorf("invalid SAM_HUB_KEY: must be 32-byte hex string")
+ }
+ bKey := ed25519.NewKeyFromSeed(keyBytes)
+
+ return &Hub{
+ Host: h,
+ DHT: kadDHT,
+ OIDCConfig: conf,
+ Verifier: provider.Verifier(&oidc.Config{ClientID: clientID}),
+ BiscuitKey: bKey,
+ MeshID: meshName,
+ Registry: make(map[peer.ID]string),
+ }, nil
+}
+
+func (h *Hub) handleLogin(w http.ResponseWriter, r *http.Request) {
+ pID := r.URL.Query().Get("peer_id")
+ if pID == "" {
+ http.Error(w, "Missing peer_id", 400)
+ return
+ }
+ url := h.OIDCConfig.AuthCodeURL(pID)
+ http.Redirect(w, r, url, http.StatusFound)
+}
+
+func (h *Hub) handleCallback(w http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ peerIDStr := r.URL.Query().Get("state")
+ code := r.URL.Query().Get("code")
+
+ token, err := h.OIDCConfig.Exchange(ctx, code)
+ if err != nil {
+ http.Error(w, "Token exchange failed", 500)
+ return
+ }
+
+ rawID, _ := token.Extra("id_token").(string)
+ idToken, err := h.Verifier.Verify(ctx, rawID)
+ if err != nil {
+ http.Error(w, "ID Token verification failed", 401)
+ return
+ }
+
+ var claims struct {
+ Email string `json:"email"`
+ }
+ idToken.Claims(&claims)
+
+ p, err := peer.Decode(peerIDStr)
+ if err != nil {
+ http.Error(w, "Invalid peer_id", 400)
+ return
+ }
+
+ bToken, err := h.issueBiscuit(p, claims.Email)
+ if err != nil {
+ http.Error(w, "Failed to issue Biscuit", 500)
+ return
+ }
+
+ h.mu.Lock()
+ h.Registry[p] = claims.Email
+ h.mu.Unlock()
+
+ fmt.Fprintf(w, "Sovereign Identity Verified!\nUser: %s\nToken: %s", claims.Email, bToken)
+}
+
+func (h *Hub) issueBiscuit(p peer.ID, email string) (string, error) {
+ builder := biscuit.NewBuilder(h.BiscuitKey)
+
+ builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "peer_id",
+ IDs: []biscuit.Term{biscuit.String(p.String())},
+ }})
+ builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "mesh_id",
+ IDs: []biscuit.Term{biscuit.String(h.MeshID)},
+ }})
+ builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "external_id",
+ IDs: []biscuit.Term{biscuit.String(email)},
+ }})
+
+ t, err := builder.Build()
+ if err != nil {
+ return "", err
+ }
+
+ data, err := t.Serialize()
+ if err != nil {
+ return "", err
+ }
+
+ return base64.StdEncoding.EncodeToString(data), nil
+}
+
+func main() {
+ rootCmd := &cobra.Command{
+ Use: "sam-hub",
+ Short: "Sovereign Agent Mesh - Multi-Transport Hub",
+ Run: func(cmd *cobra.Command, args []string) {
+ ctx := context.Background()
+ h, err := NewHub(ctx)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/login", h.handleLogin)
+ mux.HandleFunc("/callback", h.handleCallback)
+
+ // Corrected libp2phttp Serve logic
+ // This allows agents to reach OIDC via libp2p streams
+ listener, err := gostream.Listen(h.Host, p2phttp.DefaultP2PProtocol)
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer listener.Close()
+ go func() {
+ server := &http.Server{
+ Handler: mux,
+ }
+ server.Serve(listener)
+ }()
+
+ fmt.Printf("SAM Hub Online (QUIC + TCP)\n")
+ fmt.Printf("MeshID: %s\n", h.MeshID)
+ fmt.Printf("PeerID: %s\n", h.Host.ID())
+
+ // Still need a port for the Browser to reach the Hub for OIDC redirect
+ log.Fatal(http.ListenAndServe(":8080", mux))
+ },
+ }
+
+ rootCmd.Flags().StringVar(&oidcIssuer, "issuer", os.Getenv("SAM_OIDC_ISSUER"), "OIDC Issuer URL")
+ rootCmd.Flags().StringVar(&clientID, "client-id", os.Getenv("SAM_OIDC_ID"), "OIDC Client ID")
+ rootCmd.Flags().StringVar(&clientSecret, "client-secret", os.Getenv("SAM_OIDC_SECRET"), "OIDC Client Secret")
+ rootCmd.Flags().StringVar(&biscuitHex, "key", os.Getenv("SAM_HUB_KEY"), "Hub Private Key (32-byte Hex)")
+ rootCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/4001/quic-v1", "/ip4/0.0.0.0/tcp/4002"}, "libp2p Listen Addrs")
+ rootCmd.Flags().StringVar(&meshName, "mesh", "public-mesh", "Mesh federation name")
+ rootCmd.Flags().StringVar(&publicAddr, "public-url", "http://localhost:8080", "Public URL for browser OIDC")
+
+ if err := rootCmd.Execute(); err != nil {
+ os.Exit(1)
+ }
+}
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.go
deleted file mode 100644
index c30a13ff..00000000
--- a/cmd/sam-hub/main.go
+++ /dev/null
@@ -1,263 +0,0 @@
-package main
-
-import (
- "context"
- "crypto/ed25519"
- "crypto/rand"
- "encoding/base64"
- "encoding/json"
- "fmt"
- "net/http"
- "os"
- "strings"
-
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/spf13/cobra"
-
- "sam/pkg/identity"
- samnet "sam/pkg/net"
-
- "github.com/multiformats/go-multiaddr"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "sam-hub",
- Short: "SAM hub: passport issuer, key manager, and trust observer",
- }
-
- cmd.AddCommand(newKeygenCmd())
- cmd.AddCommand(newServeCmd())
-
- if err := cmd.Execute(); err != nil {
- fmt.Fprintf(os.Stderr, "sam-hub: %v\n", err)
- os.Exit(1)
- }
-}
-
-func newKeygenCmd() *cobra.Command {
- var includeIdentity bool
- cmd := &cobra.Command{
- Use: "keygen",
- Short: "Generate hub keys (signing and/or peer identity)",
- RunE: func(_ *cobra.Command, _ []string) error {
- // Always generate signing key
- _, signingPriv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- return fmt.Errorf("generating signing key: %w", err)
- }
- signingB64 := base64.RawURLEncoding.EncodeToString(signingPriv)
- signingPub := base64.RawURLEncoding.EncodeToString(signingPriv.Public().(ed25519.PublicKey))
-
- fmt.Printf("\n=== Passport Signing Key ===\n")
- fmt.Printf("Environment: SAM_HUB_KEY\n")
- fmt.Printf("Private (base64):\n%s\n\n", signingB64)
- fmt.Printf("Public (base64):\n%s\n\n", signingPub)
-
- // Optionally generate peer identity key for libp2p
- if includeIdentity {
- idPriv, err := samnet.GenerateKey()
- if err != nil {
- return fmt.Errorf("generating identity key: %w", err)
- }
- idBytes, err := crypto.MarshalPrivateKey(idPriv)
- if err != nil {
- return fmt.Errorf("marshaling identity key: %w", err)
- }
- idB64 := base64.RawURLEncoding.EncodeToString(idBytes)
-
- fmt.Printf("=== Hub Peer Identity Key (for libp2p) ===\n")
- fmt.Printf("Environment: SAM_HUB_IDENTITY_KEY\n")
- fmt.Printf("Private (base64):\n%s\n\n", idB64)
- fmt.Printf("Usage: Configure as bootstrap peer for agents to discover the hub.\n")
- }
-
- return nil
- },
- }
- cmd.Flags().BoolVar(&includeIdentity, "with-identity", false, "also generate peer identity key for libp2p host")
- return cmd
-}
-
-func newServeCmd() *cobra.Command {
- var (
- httpListen string
- p2pListen string
- enableP2P bool
- )
- cmd := &cobra.Command{
- Use: "serve",
- Short: "Start the hub HTTP server (and optionally libp2p host)",
- RunE: func(cmd *cobra.Command, _ []string) error {
- // Optionally start libp2p host for peer discovery/rendezvous
- var node samnet.Node
- if enableP2P {
- idPriv, err := loadOrGenerateIdentityKey()
- if err != nil {
- return fmt.Errorf("loading identity key: %w", err)
- }
- listenAddrs, err := parseMultiaddrs(p2pListen)
- if err != nil {
- return fmt.Errorf("parsing p2p listen addresses: %w", err)
- }
- if len(listenAddrs) == 0 {
- listenAddrs = samnet.DefaultOptions().ListenAddrs
- }
- node, err = samnet.New(
- samnet.WithPrivateKey(idPriv),
- samnet.WithListenAddrs(listenAddrs...),
- samnet.WithDHTMode(samnet.DHTModeServer),
- samnet.WithRelayService(),
- )
- if err != nil {
- return fmt.Errorf("creating libp2p node: %w", err)
- }
- if err := node.Start(context.Background()); err != nil {
- return fmt.Errorf("starting libp2p node: %w", err)
- }
- defer func() { _ = node.Stop(context.Background()) }()
- fmt.Printf("libp2p host listening:\n")
- for _, addr := range node.Addrs() {
- fmt.Printf(" %s/p2p/%s\n", addr, node.PeerID())
- }
- }
-
- // Capture node reference for the P2P info endpoint closure.
- p2pNode := node
-
- mux := http.NewServeMux()
- mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
- w.WriteHeader(http.StatusOK)
- _, _ = w.Write([]byte("ok"))
- })
- mux.HandleFunc("/.well-known/sam-hub-keys", func(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- _ = json.NewEncoder(w).Encode(map[string]any{
- "issuer": identity.DefaultHubIssuer,
- "keys": []map[string]string{{
- "kid": "sam-hub-root-v1",
- "alg": "Ed25519",
- "k": identity.HubPublicKeyBase64(),
- }},
- })
- })
- mux.HandleFunc("/issue-passport", func(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- auth := strings.TrimSpace(r.Header.Get("Authorization"))
- if !strings.HasPrefix(strings.ToLower(auth), "bearer ") || strings.TrimSpace(strings.TrimPrefix(auth, "Bearer ")) == "" {
- http.Error(w, "missing bearer token", http.StatusUnauthorized)
- return
- }
- var req passportRequest
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- http.Error(w, fmt.Sprintf("bad request: %v", err), http.StatusBadRequest)
- return
- }
- meshID := strings.TrimSpace(req.MeshID)
- if meshID == "" {
- meshID = strings.TrimSpace(req.Federation)
- }
- tok, err := identity.IssuePassportBiscuit(context.Background(), identity.PassportIssueRequest{
- PeerID: strings.TrimSpace(req.PeerID),
- FederationID: meshID,
- Subject: strings.TrimSpace(req.Subject),
- Claims: map[string]string{"email": strings.TrimSpace(req.Email)},
- })
- if err != nil {
- http.Error(w, fmt.Sprintf("issue failed: %v", err), http.StatusBadRequest)
- return
- }
- _ = json.NewEncoder(w).Encode(map[string]string{
- "issuer": identity.DefaultHubIssuer,
- "passport_biscuit": tok,
- })
- })
- // /.well-known/sam-hub-p2p advertises the hub's libp2p peer ID and
- // multiaddrs so agents can bootstrap and rendezvous via the hub
- // without needing out-of-band address configuration.
- mux.HandleFunc("/.well-known/sam-hub-p2p", func(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- if p2pNode == nil {
- http.Error(w, "hub is not running in P2P mode", http.StatusServiceUnavailable)
- return
- }
- addrs := make([]string, 0, len(p2pNode.Addrs()))
- for _, a := range p2pNode.Addrs() {
- addrs = append(addrs, fmt.Sprintf("%s/p2p/%s", a, p2pNode.PeerID()))
- }
- w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(map[string]any{
- "peer_id": p2pNode.PeerID().String(),
- "addrs": addrs,
- })
- })
- mux.HandleFunc("/trust-map", func(w http.ResponseWriter, _ *http.Request) {
- _ = json.NewEncoder(w).Encode(map[string]any{"source": "gossipsub", "note": "passive observer endpoint"})
- })
- srv := &http.Server{Addr: httpListen, Handler: mux}
- go func() {
- <-cmd.Context().Done()
- _ = srv.Shutdown(context.Background())
- }()
- fmt.Printf("hub HTTP listening on %s\n", httpListen)
- return srv.ListenAndServe()
- },
- }
- cmd.Flags().StringVar(&httpListen, "http-listen", ":8081", "HTTP server listen address")
- cmd.Flags().StringVar(&p2pListen, "p2p-listen", "", "libp2p listen multiaddrs (comma-separated; default: QUIC+TCP on all interfaces)")
- cmd.Flags().BoolVar(&enableP2P, "enable-p2p", false, "run libp2p host for peer discovery and rendezvous")
- return cmd
-}
-
-type passportRequest struct {
- PeerID string `json:"peer_id"`
- Federation string `json:"federation"`
- MeshID string `json:"mesh_id"`
- Subject string `json:"subject"`
- Email string `json:"email"`
-}
-
-// loadOrGenerateIdentityKey loads the hub's libp2p peer identity from SAM_HUB_IDENTITY_KEY
-// environment variable (base64-encoded private key), or generates a new one.
-func loadOrGenerateIdentityKey() (crypto.PrivKey, error) {
- if keyB64 := strings.TrimSpace(os.Getenv("SAM_HUB_IDENTITY_KEY")); keyB64 != "" {
- keyBytes, err := base64.RawURLEncoding.DecodeString(keyB64)
- if err != nil {
- return nil, fmt.Errorf("decoding SAM_HUB_IDENTITY_KEY: %w", err)
- }
- priv, err := crypto.UnmarshalPrivateKey(keyBytes)
- if err != nil {
- return nil, fmt.Errorf("unmarshaling SAM_HUB_IDENTITY_KEY: %w", err)
- }
- return priv, nil
- }
- return samnet.GenerateKey()
-}
-
-// parseMultiaddrs parses comma-separated multiaddr strings.
-func parseMultiaddrs(addrStr string) ([]multiaddr.Multiaddr, error) {
- if strings.TrimSpace(addrStr) == "" {
- return nil, nil
- }
- var out []multiaddr.Multiaddr
- for _, s := range strings.Split(addrStr, ",") {
- if s = strings.TrimSpace(s); s != "" {
- // This is a stub; actual implementation would use multiaddr.NewMultiaddr
- ma, err := multiaddr.NewMultiaddr(s)
- if err != nil {
- return nil, err
- }
- out = append(out, ma)
- }
- }
- return out, nil
-}
diff --git a/go.mod b/go.mod
index 4a668b99..f9ff9e02 100644
--- a/go.mod
+++ b/go.mod
@@ -3,21 +3,18 @@ module sam
go 1.25.7
require (
- github.com/a2aproject/a2a-go/v2 v2.2.0
- github.com/ipfs/go-cid v0.6.1
- github.com/ipfs/go-log/v2 v2.9.1
+ github.com/biscuit-auth/biscuit-go/v2 v2.2.0
+ github.com/coreos/go-oidc/v3 v3.18.0
github.com/libp2p/go-libp2p v0.48.0
+ github.com/libp2p/go-libp2p-http v0.5.0
github.com/libp2p/go-libp2p-kad-dht v0.39.0
- github.com/libp2p/go-libp2p-pubsub v0.15.0
github.com/modelcontextprotocol/go-sdk v1.5.0
github.com/multiformats/go-multiaddr v0.16.1
- github.com/multiformats/go-multihash v0.2.3
github.com/spf13/cobra v1.10.2
github.com/vishvananda/netlink v1.3.1
github.com/vishvananda/netns v0.0.5
go.etcd.io/bbolt v1.4.3
- go.opentelemetry.io/otel v1.43.0
- go.opentelemetry.io/otel/trace v1.43.0
+ golang.org/x/oauth2 v0.36.0
)
require (
@@ -31,19 +28,20 @@ require (
github.com/dunglas/httpsfv v1.1.0 // indirect
github.com/filecoin-project/go-clock v0.1.0 // indirect
github.com/flynn/noise v1.1.0 // indirect
+ github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
- github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/gopacket v1.1.19 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
- github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/huin/goupnp v1.3.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/ipfs/boxo v0.38.0 // indirect
+ github.com/ipfs/go-cid v0.6.1 // indirect
github.com/ipfs/go-datastore v0.9.1 // indirect
+ github.com/ipfs/go-log/v2 v2.9.1 // indirect
github.com/ipld/go-ipld-prime v0.22.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect
@@ -53,9 +51,9 @@ require (
github.com/libp2p/go-cidranger v1.1.0 // indirect
github.com/libp2p/go-flow-metrics v0.3.0 // indirect
github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect
+ github.com/libp2p/go-libp2p-gostream v0.6.0 // indirect
github.com/libp2p/go-libp2p-kbucket v0.8.0 // indirect
github.com/libp2p/go-libp2p-record v0.3.1 // indirect
- github.com/libp2p/go-libp2p-rendezvous v0.0.0-20250501073202-f082642ffcc8 // indirect
github.com/libp2p/go-libp2p-routing-helpers v0.7.5 // indirect
github.com/libp2p/go-msgio v0.3.0 // indirect
github.com/libp2p/go-netroute v0.4.0 // indirect
@@ -73,6 +71,7 @@ require (
github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect
github.com/multiformats/go-multibase v0.3.0 // indirect
github.com/multiformats/go-multicodec v0.10.0 // indirect
+ github.com/multiformats/go-multihash v0.2.3 // indirect
github.com/multiformats/go-multistream v0.6.1 // indirect
github.com/multiformats/go-varint v0.1.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
@@ -109,7 +108,9 @@ require (
github.com/wlynxg/anet v0.0.5 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
+ go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/metric v1.43.0 // indirect
+ go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.uber.org/dig v1.19.0 // indirect
go.uber.org/fx v1.24.0 // indirect
go.uber.org/mock v0.6.0 // indirect
@@ -120,7 +121,6 @@ require (
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/mod v0.35.0 // indirect
golang.org/x/net v0.53.0 // indirect
- golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.43.0 // indirect
golang.org/x/telemetry v0.0.0-20260414141209-fac6e1c83189 // indirect
diff --git a/go.sum b/go.sum
index 27d72c57..031a542a 100644
--- a/go.sum
+++ b/go.sum
@@ -43,8 +43,8 @@ filippo.io/keygen v0.0.0-20260114151900-8e2790ea4c5b h1:REI1FbdW71yO56Are4XAxD+O
filippo.io/keygen v0.0.0-20260114151900-8e2790ea4c5b/go.mod h1:9nnw1SlYHYuPSo/3wjQzNjSbeHlq2NsKo5iEtfJPWP0=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
-github.com/a2aproject/a2a-go/v2 v2.2.0 h1:eayiNXYpyTOLVhhQrGmIHlcy8GnOdnwaNdYQPvS84Ik=
-github.com/a2aproject/a2a-go/v2 v2.2.0/go.mod h1:htTxMwicNXXXEwwfjuB/Pd1g7UHDrswhSievncmTVcE=
+github.com/alecthomas/participle/v2 v2.0.0 h1:Fgrq+MbuSsJwIkw3fEj9h75vDP0Er5JzepJ0/HNHv0g=
+github.com/alecthomas/participle/v2 v2.0.0/go.mod h1:rAKZdJldHu8084ojcWevWAL8KmEU+AT+Olodb+WoN2Y=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
@@ -54,6 +54,8 @@ github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZx
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
+github.com/biscuit-auth/biscuit-go/v2 v2.2.0 h1:1zBfZ0ZCbxJbhtAhou6Fa07lBlJ+wcphBEPV/sENBvY=
+github.com/biscuit-auth/biscuit-go/v2 v2.2.0/go.mod h1:c7AsMdr816vPd/4Psb3z6Xv2EKciKxSEayI8ueBaJio=
github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM=
github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3 h1:oe6fCvaEpkhyW3qAicT0TnGtyht/UrgvOwMcEgLb7Aw=
github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3/go.mod h1:qdP0gaj0QtgX2RUZhnlVrceJ+Qln8aSlDyJwelLLFeM=
@@ -67,6 +69,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
+github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A=
+github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
@@ -102,6 +106,8 @@ github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeME
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
+github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
+github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
@@ -109,7 +115,6 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
-github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
@@ -206,8 +211,6 @@ github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c=
github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
-github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
-github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
@@ -270,16 +273,16 @@ github.com/libp2p/go-libp2p v0.48.0 h1:h2BrLAgrj7X8bEN05K7qmrjpNHYA+6tnsGRdprjTn
github.com/libp2p/go-libp2p v0.48.0/go.mod h1:Q1fBZNdmC2Hf82husCTfkKJVfHm2we5zk+NWmOGEmWk=
github.com/libp2p/go-libp2p-asn-util v0.4.1 h1:xqL7++IKD9TBFMgnLPZR6/6iYhawHKHl950SO9L6n94=
github.com/libp2p/go-libp2p-asn-util v0.4.1/go.mod h1:d/NI6XZ9qxw67b4e+NgpQexCIiFYJjErASrYW4PFDN8=
+github.com/libp2p/go-libp2p-gostream v0.6.0 h1:QfAiWeQRce6pqnYfmIVWJFXNdDyfiR/qkCnjyaZUPYU=
+github.com/libp2p/go-libp2p-gostream v0.6.0/go.mod h1:Nywu0gYZwfj7Jc91PQvbGU8dIpqbQQkjWgDuOrFaRdA=
+github.com/libp2p/go-libp2p-http v0.5.0 h1:+x0AbLaUuLBArHubbbNRTsgWz0RjNTy6DJLOxQ3/QBc=
+github.com/libp2p/go-libp2p-http v0.5.0/go.mod h1:glh87nZ35XCQyFsdzZps6+F4HYI6DctVFY5u1fehwSg=
github.com/libp2p/go-libp2p-kad-dht v0.39.0 h1:mww38eBYiUvdsu+Xl/GLlBC0Aa8M+5HAwvafkFOygAM=
github.com/libp2p/go-libp2p-kad-dht v0.39.0/go.mod h1:Po2JugFEkDq9Vig/JXtc153ntOi0q58o4j7IuITCOVs=
github.com/libp2p/go-libp2p-kbucket v0.8.0 h1:QAK7RzKJpYe+EuSEATAaaHYMYLkPDGC18m9jxPLnU8s=
github.com/libp2p/go-libp2p-kbucket v0.8.0/go.mod h1:JMlxqcEyKwO6ox716eyC0hmiduSWZZl6JY93mGaaqc4=
-github.com/libp2p/go-libp2p-pubsub v0.15.0 h1:cG7Cng2BT82WttmPFMi50gDNV+58K626m/wR00vGL1o=
-github.com/libp2p/go-libp2p-pubsub v0.15.0/go.mod h1:lr4oE8bFgQaifRcoc2uWhWWiK6tPdOEKpUuR408GFN4=
github.com/libp2p/go-libp2p-record v0.3.1 h1:cly48Xi5GjNw5Wq+7gmjfBiG9HCzQVkiZOUZ8kUl+Fg=
github.com/libp2p/go-libp2p-record v0.3.1/go.mod h1:T8itUkLcWQLCYMqtX7Th6r7SexyUJpIyPgks757td/E=
-github.com/libp2p/go-libp2p-rendezvous v0.0.0-20250501073202-f082642ffcc8 h1:uevPWUmI8M5A2O8rOVrs2GuyyFCGNXEfEPCkNaEhsRU=
-github.com/libp2p/go-libp2p-rendezvous v0.0.0-20250501073202-f082642ffcc8/go.mod h1:iZc7ET+Ej2aDYXbt3bakWP9++1/XenDDMFVDlVFDS5Y=
github.com/libp2p/go-libp2p-routing-helpers v0.7.5 h1:HdwZj9NKovMx0vqq6YNPTh6aaNzey5zHD7HeLJtq6fI=
github.com/libp2p/go-libp2p-routing-helpers v0.7.5/go.mod h1:3YaxrwP0OBPDD7my3D0KxfR89FlcX/IEbxDEDfAmj98=
github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA=
@@ -625,8 +628,8 @@ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ
golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
-golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
-golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
+golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
+golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
diff --git a/internal/db/bolt.go b/internal/db/bolt.go
deleted file mode 100644
index 8a1aea72..00000000
--- a/internal/db/bolt.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// 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 db
-
-import (
- "context"
- "errors"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "time"
-
- "go.etcd.io/bbolt"
-)
-
-// DefaultStatePath returns ~/.config/sam/state.db.
-func DefaultStatePath() (string, error) {
- cfgDir, err := os.UserConfigDir()
- if err != nil {
- return "", fmt.Errorf("resolving user config dir: %w", err)
- }
- return filepath.Join(cfgDir, "sam", "state.db"), nil
-}
-
-type BoltStore struct {
- db *bbolt.DB
-}
-
-// OpenDefault opens the default bbolt state DB and initializes required buckets.
-func OpenDefault() (*BoltStore, error) {
- path, err := DefaultStatePath()
- if err != nil {
- return nil, err
- }
- return Open(path)
-}
-
-// Open opens a bbolt store at the given path and initializes required buckets.
-func Open(path string) (*BoltStore, error) {
- path = strings.TrimSpace(path)
- if path == "" {
- return nil, fmt.Errorf("store path is required")
- }
- if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
- return nil, fmt.Errorf("creating state directory: %w", err)
- }
- db, err := bbolt.Open(path, 0o600, &bbolt.Options{Timeout: 2 * time.Second})
- if err != nil {
- return nil, fmt.Errorf("opening bbolt store: %w", err)
- }
- s := &BoltStore{db: db}
- if err := s.initBuckets(); err != nil {
- _ = db.Close()
- return nil, err
- }
- return s, nil
-}
-
-func (s *BoltStore) initBuckets() error {
- return s.db.Update(func(tx *bbolt.Tx) error {
- for _, bucket := range requiredBuckets {
- if _, err := tx.CreateBucketIfNotExists([]byte(bucket)); err != nil {
- return fmt.Errorf("creating bucket %q: %w", bucket, err)
- }
- }
- return nil
- })
-}
-
-func (s *BoltStore) Get(ctx context.Context, bucket, key string) ([]byte, error) {
- if err := ctx.Err(); err != nil {
- return nil, err
- }
- var out []byte
- err := s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucket))
- if b == nil {
- return fmt.Errorf("bucket %q does not exist", bucket)
- }
- value := b.Get([]byte(key))
- if value == nil {
- return os.ErrNotExist
- }
- out = append([]byte(nil), value...)
- return nil
- })
- if err != nil {
- if errors.Is(err, os.ErrNotExist) {
- return nil, os.ErrNotExist
- }
- return nil, fmt.Errorf("get %s/%s: %w", bucket, key, err)
- }
- return out, nil
-}
-
-func (s *BoltStore) Put(ctx context.Context, bucket, key string, value []byte) error {
- if err := ctx.Err(); err != nil {
- return err
- }
- if len(value) == 0 {
- return fmt.Errorf("value is required")
- }
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucket))
- if b == nil {
- return fmt.Errorf("bucket %q does not exist", bucket)
- }
- return b.Put([]byte(key), value)
- })
-}
-
-func (s *BoltStore) Delete(ctx context.Context, bucket, key string) error {
- if err := ctx.Err(); err != nil {
- return err
- }
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucket))
- if b == nil {
- return fmt.Errorf("bucket %q does not exist", bucket)
- }
- return b.Delete([]byte(key))
- })
-}
-
-func (s *BoltStore) Close() error {
- if s == nil || s.db == nil {
- return nil
- }
- return s.db.Close()
-}
diff --git a/internal/db/codec.go b/internal/db/codec.go
deleted file mode 100644
index 42ff2a00..00000000
--- a/internal/db/codec.go
+++ /dev/null
@@ -1,116 +0,0 @@
-// 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 db
-
-import (
- "encoding/json"
- "fmt"
- "time"
-)
-
-// Codec keeps serialization pluggable while defaulting to JSON.
-type Codec interface {
- Marshal(version int, v any) ([]byte, error)
- Unmarshal(data []byte, currentVersion int, v any, transform MigrationFunc) error
-}
-
-type JSONCodec struct{}
-
-type versionedEnvelope struct {
- Metadata Metadata `json:"metadata"`
- Payload json.RawMessage `json:"payload"`
-}
-
-// MigrationFunc can mutate payload map in-memory when older versions are read.
-// It receives the raw payload map and source version.
-type MigrationFunc func(payload map[string]any, fromVersion int) map[string]any
-
-func (JSONCodec) Marshal(version int, v any) ([]byte, error) {
- payload, err := json.Marshal(v)
- if err != nil {
- return nil, fmt.Errorf("marshal payload: %w", err)
- }
- env := versionedEnvelope{
- Metadata: Metadata{Version: version, Updated: time.Now().UTC()},
- Payload: payload,
- }
- out, err := json.Marshal(env)
- if err != nil {
- return nil, fmt.Errorf("marshal envelope: %w", err)
- }
- return out, nil
-}
-
-func (JSONCodec) Unmarshal(data []byte, currentVersion int, v any, transform MigrationFunc) error {
- var original versionedEnvelope
- if err := json.Unmarshal(data, &original); err != nil {
- return fmt.Errorf("unmarshal envelope: %w", err)
- }
- fromVersion := original.Metadata.Version
-
- migrated := migrate(data, currentVersion)
- var env versionedEnvelope
- if err := json.Unmarshal(migrated, &env); err != nil {
- return fmt.Errorf("unmarshal migrated envelope: %w", err)
- }
- payload := env.Payload
- if transform != nil && fromVersion < currentVersion {
- var m map[string]any
- if err := json.Unmarshal(payload, &m); err != nil {
- return fmt.Errorf("unmarshal legacy payload map: %w", err)
- }
- m = transform(m, fromVersion)
- updatedPayload, err := json.Marshal(m)
- if err != nil {
- return fmt.Errorf("marshal migrated payload map: %w", err)
- }
- payload = updatedPayload
- }
- if err := json.Unmarshal(payload, v); err != nil {
- return fmt.Errorf("unmarshal payload: %w", err)
- }
- return nil
-}
-
-// migrate upgrades envelope metadata lazily at read-time.
-func migrate(data []byte, currentVersion int) []byte {
- var raw map[string]any
- if err := json.Unmarshal(data, &raw); err != nil {
- return data
- }
- meta, ok := raw["metadata"].(map[string]any)
- if !ok {
- meta = map[string]any{}
- raw["metadata"] = meta
- }
- version := 0
- if v, ok := meta["version"]; ok {
- switch typed := v.(type) {
- case float64:
- version = int(typed)
- case int:
- version = typed
- }
- }
- if version < currentVersion {
- meta["version"] = currentVersion
- meta["updated_at"] = time.Now().UTC().Format(time.RFC3339Nano)
- }
- out, err := json.Marshal(raw)
- if err != nil {
- return data
- }
- return out
-}
diff --git a/internal/db/codec_test.go b/internal/db/codec_test.go
deleted file mode 100644
index 62145425..00000000
--- a/internal/db/codec_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// 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 db
-
-import (
- "testing"
-)
-
-type v2Record struct {
- Name string `json:"name"`
- Scope string `json:"scope"`
-}
-
-func TestJSONCodecLazyMigrationV1ToV2(t *testing.T) {
- legacy := []byte(`{"metadata":{"version":1,"updated_at":"2026-01-01T00:00:00Z"},"payload":{"name":"alice"}}`)
- codec := JSONCodec{}
-
- var out v2Record
- err := codec.Unmarshal(legacy, 2, &out, func(payload map[string]any, fromVersion int) map[string]any {
- if fromVersion < 2 {
- if _, ok := payload["scope"]; !ok {
- payload["scope"] = "default"
- }
- }
- return payload
- })
- if err != nil {
- t.Fatalf("Unmarshal() error = %v", err)
- }
- if out.Name != "alice" {
- t.Fatalf("Name = %q, want %q", out.Name, "alice")
- }
- if out.Scope != "default" {
- t.Fatalf("Scope = %q, want %q", out.Scope, "default")
- }
-}
diff --git a/internal/db/manager.go b/internal/db/manager.go
deleted file mode 100644
index edaebc00..00000000
--- a/internal/db/manager.go
+++ /dev/null
@@ -1,209 +0,0 @@
-// 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 db
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "sync"
-)
-
-const defaultFederation = "default"
-
-// Manager owns a pool of per-federation bbolt stores under a shared base directory.
-// Each federation gets a physically isolated file: <baseDir>/<name>.db.
-// The master identity store (state.db) is intentionally kept separate and is
-// NOT managed here.
-type Manager struct {
- mu sync.Mutex
- stores map[string]*BoltStore
- baseDir string
-}
-
-// FederationsDir returns the default directory for federation databases:
-// ~/.config/sam/federations/
-func FederationsDir() (string, error) {
- cfgDir, err := os.UserConfigDir()
- if err != nil {
- return "", fmt.Errorf("resolving user config dir: %w", err)
- }
- return filepath.Join(cfgDir, "sam", "federations"), nil
-}
-
-// NewManager creates a Manager rooted at the default federations directory.
-func NewManager() (*Manager, error) {
- dir, err := FederationsDir()
- if err != nil {
- return nil, err
- }
- return NewManagerAt(dir)
-}
-
-// NewManagerAt creates a Manager rooted at the given directory.
-// The directory is created lazily when the first federation is opened.
-func NewManagerAt(dir string) (*Manager, error) {
- dir = strings.TrimSpace(dir)
- if dir == "" {
- return nil, fmt.Errorf("manager base directory must not be empty")
- }
- return &Manager{
- stores: make(map[string]*BoltStore),
- baseDir: dir,
- }, nil
-}
-
-// Store returns (opening lazily if needed) the Store for the given federation.
-// Name must be non-empty and contain only safe filesystem characters (letters,
-// digits, hyphens, underscores, dots). Use the constant DefaultFederation for
-// the standard "default" federation.
-func (m *Manager) Store(fedID string) (Store, error) {
- fedID = strings.TrimSpace(fedID)
- if fedID == "" {
- fedID = defaultFederation
- }
- if err := validateFedID(fedID); err != nil {
- return nil, err
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- if s, ok := m.stores[fedID]; ok {
- return s, nil
- }
-
- path := filepath.Join(m.baseDir, fedID+".db")
- s, err := Open(path)
- if err != nil {
- return nil, fmt.Errorf("opening federation %q: %w", fedID, err)
- }
- m.stores[fedID] = s
- return s, nil
-}
-
-// DefaultStore is shorthand for Store(defaultFederation).
-func (m *Manager) DefaultStore() (Store, error) {
- return m.Store(defaultFederation)
-}
-
-// DropFederation closes the store for the given federation and deletes its
-// physical file from disk. Calling this while other goroutines are actively
-// using the returned Store is unsafe.
-func (m *Manager) DropFederation(name string) error {
- name = strings.TrimSpace(name)
- if name == "" {
- return fmt.Errorf("federation name must not be empty")
- }
- if err := validateFedID(name); err != nil {
- return err
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- if s, ok := m.stores[name]; ok {
- if err := s.Close(); err != nil {
- return fmt.Errorf("closing federation %q: %w", name, err)
- }
- delete(m.stores, name)
- }
-
- path := filepath.Join(m.baseDir, name+".db")
- if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
- return fmt.Errorf("deleting federation db %q: %w", name, err)
- }
- return nil
-}
-
-// ListFederations returns the names of all federation databases that exist on
-// disk under the manager's base directory (including those not yet opened).
-func (m *Manager) ListFederations() ([]string, error) {
- entries, err := os.ReadDir(m.baseDir)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, nil
- }
- return nil, fmt.Errorf("listing federations dir %q: %w", m.baseDir, err)
- }
-
- var names []string
- for _, e := range entries {
- if e.IsDir() {
- continue
- }
- if strings.HasSuffix(e.Name(), ".db") {
- names = append(names, strings.TrimSuffix(e.Name(), ".db"))
- }
- }
- return names, nil
-}
-
-// Close closes all open federation stores.
-func (m *Manager) Close() error {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- var firstErr error
- for name, s := range m.stores {
- if err := s.Close(); err != nil && firstErr == nil {
- firstErr = fmt.Errorf("closing federation %q: %w", name, err)
- }
- delete(m.stores, name)
- }
- return firstErr
-}
-
-// BaseDir returns the directory where federation databases are stored.
-func (m *Manager) BaseDir() string { return m.baseDir }
-
-// validateFedID rejects names that could be used for path traversal.
-func validateFedID(name string) error {
- if strings.ContainsAny(name, `/\:*?"<>|`) || strings.Contains(name, "..") {
- return fmt.Errorf("federation name %q contains invalid characters", name)
- }
- return nil
-}
-
-// FederatedGet is a convenience wrapper that opens the federation store and
-// performs a single Get. Useful for one-off lookups; prefer Store() when
-// making multiple calls to avoid repeated open overhead.
-func (m *Manager) FederatedGet(ctx context.Context, fedID, bucket, key string) ([]byte, error) {
- s, err := m.Store(fedID)
- if err != nil {
- return nil, err
- }
- return s.Get(ctx, bucket, key)
-}
-
-// FederatedPut is a convenience wrapper; see FederatedGet.
-func (m *Manager) FederatedPut(ctx context.Context, fedID, bucket, key string, value []byte) error {
- s, err := m.Store(fedID)
- if err != nil {
- return err
- }
- return s.Put(ctx, bucket, key, value)
-}
-
-// FederatedDelete is a convenience wrapper; see FederatedGet.
-func (m *Manager) FederatedDelete(ctx context.Context, fedID, bucket, key string) error {
- s, err := m.Store(fedID)
- if err != nil {
- return err
- }
- return s.Delete(ctx, bucket, key)
-}
diff --git a/internal/db/store.go b/internal/db/store.go
deleted file mode 100644
index 7e6f6fd5..00000000
--- a/internal/db/store.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// 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 db
-
-import (
- "context"
- "time"
-)
-
-const (
- BucketIdentities = "identities"
- BucketReputation = "reputation"
- BucketCache = "cache"
-)
-
-var requiredBuckets = []string{
- BucketIdentities,
- BucketReputation,
- BucketCache,
-}
-
-// Metadata is attached to every versioned blob persisted in the store.
-type Metadata struct {
- Version int `json:"version"`
- Updated time.Time `json:"updated_at"`
-}
-
-// Store is the unified persistence interface used by SAM subsystems.
-// Every mutation and lookup requires a context so callers can enforce
-// deadlines and propagate cancellation.
-type Store interface {
- Get(ctx context.Context, bucket, key string) ([]byte, error)
- Put(ctx context.Context, bucket, key string, value []byte) error
- Delete(ctx context.Context, bucket, key string) error
- Close() error
-}
diff --git a/pkg/economy/biscuit.go b/pkg/economy/biscuit.go
deleted file mode 100644
index 6ef68fc5..00000000
--- a/pkg/economy/biscuit.go
+++ /dev/null
@@ -1,265 +0,0 @@
-// 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 economy
-
-import (
- "context"
- "errors"
- "fmt"
- "strings"
-)
-
-// ErrSkillCaveatDenied is returned when the Biscuit token does not authorize
-// the requested skill (allow_skill caveat mismatch).
-var ErrSkillCaveatDenied = errors.New("biscuit skill caveat denied")
-
-// ErrProtocolPolicyDenied indicates claim-based protocol authorization failure.
-var ErrProtocolPolicyDenied = errors.New("protocol authz policy denied")
-
-// ErrCapabilityDenied is returned when a token's action/resource caveats deny
-// a requested operation.
-var ErrCapabilityDenied = errors.New("biscuit capability denied")
-
-// ParsedBiscuit holds the claims extracted from a raw Biscuit token.
-// In this simplified implementation the token itself encodes caveats as a
-// structured string of the form:
-//
-// <subject>;<allow_skill=skill1,skill2,...>
-//
-// A full implementation would parse a cryptographically-verified Biscuit using
-// the biscuit-go library. This interface keeps the contract stable for that
-// future migration.
-type ParsedBiscuit struct {
- Subject string
- AllowedSkills []string // empty means "allow all"
- AllowedActions []string // empty means "allow all"
- AllowedResources []string // empty means "allow all"
-}
-
-// BiscuitParser extracts claims from a raw token string.
-type BiscuitParser interface {
- Parse(ctx context.Context, token string) (*ParsedBiscuit, error)
-}
-
-// SimpleBiscuitParser parses the lightweight plain-text format used in the
-// SAM reference implementation:
-//
-// <subject>;<allow_skill=weather-bot,risk-audit>
-//
-// Tokens with no caveat section allow all skills.
-type SimpleBiscuitParser struct{}
-
-func (SimpleBiscuitParser) Parse(_ context.Context, token string) (*ParsedBiscuit, error) {
- token = strings.TrimSpace(token)
- if token == "" {
- return nil, fmt.Errorf("empty token")
- }
- parts := strings.SplitN(token, ";", 2)
- p := &ParsedBiscuit{Subject: parts[0]}
- if len(parts) < 2 {
- return p, nil // no caveats → allow all
- }
- caveat := strings.TrimSpace(parts[1])
- const skillPrefix = "allow_skill="
- const actionPrefix = "allow_operation="
- const resourcePrefix = "allow_resource="
- if strings.HasPrefix(caveat, skillPrefix) {
- raw := strings.TrimPrefix(caveat, skillPrefix)
- for _, s := range strings.Split(raw, ",") {
- if s = strings.TrimSpace(s); s != "" {
- p.AllowedSkills = append(p.AllowedSkills, s)
- }
- }
- return p, nil
- }
- if strings.HasPrefix(caveat, actionPrefix) {
- raw := strings.TrimPrefix(caveat, actionPrefix)
- for _, s := range strings.Split(raw, ",") {
- if s = strings.TrimSpace(s); s != "" {
- p.AllowedActions = append(p.AllowedActions, s)
- }
- }
- return p, nil
- }
- if strings.HasPrefix(caveat, resourcePrefix) {
- raw := strings.TrimPrefix(caveat, resourcePrefix)
- for _, s := range strings.Split(raw, ",") {
- if s = strings.TrimSpace(s); s != "" {
- p.AllowedResources = append(p.AllowedResources, s)
- }
- }
- return p, nil
- }
- // Parse multiple caveats separated by ';' when present.
- for _, clause := range strings.Split(parts[1], ";") {
- clause = strings.TrimSpace(clause)
- switch {
- case strings.HasPrefix(clause, skillPrefix):
- raw := strings.TrimPrefix(clause, skillPrefix)
- for _, s := range strings.Split(raw, ",") {
- if s = strings.TrimSpace(s); s != "" {
- p.AllowedSkills = append(p.AllowedSkills, s)
- }
- }
- case strings.HasPrefix(clause, actionPrefix):
- raw := strings.TrimPrefix(clause, actionPrefix)
- for _, s := range strings.Split(raw, ",") {
- if s = strings.TrimSpace(s); s != "" {
- p.AllowedActions = append(p.AllowedActions, s)
- }
- }
- case strings.HasPrefix(clause, resourcePrefix):
- raw := strings.TrimPrefix(clause, resourcePrefix)
- for _, s := range strings.Split(raw, ",") {
- if s = strings.TrimSpace(s); s != "" {
- p.AllowedResources = append(p.AllowedResources, s)
- }
- }
- }
- }
- return p, nil
-}
-
-// BiscuitSkillGate is an A2A-layer guard that verifies the requested skill
-// appears in the token's allow_skill caveat list before forwarding the stream.
-//
-// It is designed to be composed with A2AService via FederationGate or
-// directly called from the A2A header validation path.
-type BiscuitSkillGate struct {
- parser BiscuitParser
-}
-
-// NewBiscuitSkillGate creates a gate using the given parser.
-// Pass nil to use SimpleBiscuitParser.
-func NewBiscuitSkillGate(parser BiscuitParser) *BiscuitSkillGate {
- if parser == nil {
- parser = SimpleBiscuitParser{}
- }
- return &BiscuitSkillGate{parser: parser}
-}
-
-// CheckSkill returns nil if the token authorises the given skill, or a
-// typed ErrSkillCaveatDenied error when the caveat is violated.
-func (g *BiscuitSkillGate) CheckSkill(ctx context.Context, token, skill string) error {
- parsed, err := g.parser.Parse(ctx, token)
- if err != nil {
- return fmt.Errorf("parsing biscuit: %w", err)
- }
- // No caveats means unrestricted.
- if len(parsed.AllowedSkills) == 0 {
- return nil
- }
- for _, allowed := range parsed.AllowedSkills {
- if strings.EqualFold(allowed, skill) {
- return nil
- }
- }
- return fmt.Errorf("%w: token for %q does not allow skill %q (allowed: %s)",
- ErrSkillCaveatDenied, parsed.Subject, skill,
- strings.Join(parsed.AllowedSkills, ", "))
-}
-
-// EvaluateProtocolPolicies enforces Datalog-like claim predicates for a protocol.
-//
-// Policies are keyed by protocol ID and contain required claim key/value pairs.
-// A wildcard "*" policy applies to every protocol and is merged with protocol-specific
-// requirements.
-func EvaluateProtocolPolicies(protocol string, claims map[string]string, policies map[string]map[string]string) error {
- protocol = strings.TrimSpace(protocol)
- if protocol == "" || len(policies) == 0 {
- return nil
- }
- required := map[string]string{}
- for k, v := range policies["*"] {
- required[k] = v
- }
- for k, v := range policies[protocol] {
- required[k] = v
- }
- if len(required) == 0 {
- return nil
- }
- if claims == nil {
- claims = map[string]string{}
- }
- for key, want := range required {
- key = strings.TrimSpace(key)
- want = strings.TrimSpace(want)
- if key == "" {
- continue
- }
- got := strings.TrimSpace(claims[key])
- if !strings.EqualFold(got, want) {
- return fmt.Errorf("%w: protocol %q requires %s=%q", ErrProtocolPolicyDenied, protocol, key, want)
- }
- }
- return nil
-}
-
-// CheckCapability validates action/resource caveats for an operation.
-// Empty caveat lists are treated as unrestricted for that dimension.
-func CheckCapability(ctx context.Context, parser BiscuitParser, token, action, resource string) error {
- action = strings.TrimSpace(action)
- resource = strings.TrimSpace(resource)
- if parser == nil {
- parser = SimpleBiscuitParser{}
- }
- parsed, err := parser.Parse(ctx, token)
- if err != nil {
- return fmt.Errorf("parsing biscuit: %w", err)
- }
- if len(parsed.AllowedActions) > 0 {
- allowed := false
- for _, a := range parsed.AllowedActions {
- if strings.EqualFold(strings.TrimSpace(a), action) {
- allowed = true
- break
- }
- }
- if !allowed {
- return fmt.Errorf("%w: token for %q does not allow action %q", ErrCapabilityDenied, parsed.Subject, action)
- }
- }
- if len(parsed.AllowedResources) > 0 {
- allowed := false
- for _, r := range parsed.AllowedResources {
- if strings.EqualFold(strings.TrimSpace(r), resource) {
- allowed = true
- break
- }
- }
- if !allowed {
- return fmt.Errorf("%w: token for %q does not allow resource %q", ErrCapabilityDenied, parsed.Subject, resource)
- }
- }
- return nil
-}
-
-// Restriction templates that agents can append to attenuate delegated tokens.
-const (
- RestrictionTemplateOperationRead = "allow_operation=read"
- RestrictionTemplateOperationWrite = "allow_operation=write"
- RestrictionTemplateResourcePattern = "allow_resource=%s"
-)
-
-// RestrictionTemplateOperation returns a clause that limits token usage to an operation.
-func RestrictionTemplateOperation(operation string) string {
- return "allow_operation=" + strings.TrimSpace(operation)
-}
-
-// RestrictionTemplateResource returns a clause that limits token usage to one resource.
-func RestrictionTemplateResource(resource string) string {
- return fmt.Sprintf(RestrictionTemplateResourcePattern, strings.TrimSpace(resource))
-}
diff --git a/pkg/economy/economy.go b/pkg/economy/economy.go
deleted file mode 100644
index 41c8d784..00000000
--- a/pkg/economy/economy.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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 economy
-
-import (
- "context"
- "errors"
- "time"
-)
-
-// Micropayment contains normalized payment metadata extracted from request headers.
-type Micropayment struct {
- Amount int64
- Asset string
- Nonce string
- Payer string
- Payee string
- Capability string
-}
-
-// VerifyRequest is passed to a Biscuit verifier for offline authorization.
-type VerifyRequest struct {
- Token string
- Method string
- Path string
- Payment Micropayment
-}
-
-// VerifyDecision is returned by a verifier on successful authorization.
-type VerifyDecision struct {
- Subject string
- Policy string
- AttenuationDepth int
- ExpiresAt time.Time
- Metadata map[string]string
-}
-
-// Verifier verifies Biscuit tokens and request-bound micropayment metadata.
-type Verifier interface {
- Verify(ctx context.Context, req VerifyRequest) (*VerifyDecision, error)
-}
-
-var (
- ErrMissingBiscuitToken = errors.New("missing Biscuit token header")
- ErrMissingMicropayAmount = errors.New("missing micropayment amount header")
- ErrMissingMicropayAsset = errors.New("missing micropayment asset header")
- ErrMissingMicropayNonce = errors.New("missing micropayment nonce header")
- ErrInvalidMicropayAmount = errors.New("invalid micropayment amount")
- ErrVerifierDeniedRequest = errors.New("biscuit verifier denied request")
- ErrVerifierUnavailable = errors.New("biscuit verifier unavailable")
- ErrMiddlewareMisconfigured = errors.New("economy middleware misconfigured")
-)
-
-// AllowAllVerifier is a Verifier that unconditionally approves every request.
-// Useful for local development and bridges that do not require micropayment gating.
-type AllowAllVerifier struct{}
-
-func (AllowAllVerifier) Verify(_ context.Context, _ VerifyRequest) (*VerifyDecision, error) {
- return &VerifyDecision{Subject: "anonymous"}, nil
-}
diff --git a/pkg/economy/middleware.go b/pkg/economy/middleware.go
deleted file mode 100644
index b9e35058..00000000
--- a/pkg/economy/middleware.go
+++ /dev/null
@@ -1,274 +0,0 @@
-// 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 economy
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "net/http"
- "strconv"
- "strings"
-
- "go.opentelemetry.io/otel"
- "go.opentelemetry.io/otel/attribute"
- "go.opentelemetry.io/otel/trace"
-)
-
-var tracer = otel.Tracer("sam/economy")
-
-const (
- DefaultBiscuitTokenHeader = "X-SAM-Biscuit"
- DefaultMicropaymentAmountHeader = "X-SAM-Micropayment-Amount"
- DefaultMicropaymentAssetHeader = "X-SAM-Micropayment-Asset"
- DefaultMicropaymentNonceHeader = "X-SAM-Micropayment-Nonce"
- DefaultMicropaymentPayerHeader = "X-SAM-Micropayment-Payer"
- DefaultMicropaymentPayeeHeader = "X-SAM-Micropayment-Payee"
- DefaultA2ACapabilityHeader = "X-SAM-A2A-Capability"
-)
-
-type contextKey string
-
-const (
- decisionContextKey contextKey = "sam.economy.decision"
- paymentContextKey contextKey = "sam.economy.payment"
-)
-
-// Middleware validates Biscuit-based micropayment headers for A2A requests.
-type Middleware struct {
- verifier Verifier
- opts Options
-}
-
-// Options controls middleware behavior and wire format.
-type Options struct {
- TokenHeader string
- AmountHeader string
- AssetHeader string
- NonceHeader string
- PayerHeader string
- PayeeHeader string
- CapabilityHeader string
-}
-
-// Option mutates middleware options.
-type Option func(*Options)
-
-// DefaultOptions returns production-safe defaults.
-func DefaultOptions() Options {
- return Options{
- TokenHeader: DefaultBiscuitTokenHeader,
- AmountHeader: DefaultMicropaymentAmountHeader,
- AssetHeader: DefaultMicropaymentAssetHeader,
- NonceHeader: DefaultMicropaymentNonceHeader,
- PayerHeader: DefaultMicropaymentPayerHeader,
- PayeeHeader: DefaultMicropaymentPayeeHeader,
- CapabilityHeader: DefaultA2ACapabilityHeader,
- }
-}
-
-// WithTokenHeader configures the Biscuit token header.
-func WithTokenHeader(name string) Option {
- return func(o *Options) { o.TokenHeader = name }
-}
-
-// WithAmountHeader configures the micropayment amount header.
-func WithAmountHeader(name string) Option {
- return func(o *Options) { o.AmountHeader = name }
-}
-
-// WithAssetHeader configures the micropayment asset header.
-func WithAssetHeader(name string) Option {
- return func(o *Options) { o.AssetHeader = name }
-}
-
-// WithNonceHeader configures the micropayment nonce header.
-func WithNonceHeader(name string) Option {
- return func(o *Options) { o.NonceHeader = name }
-}
-
-// WithPayerHeader configures the micropayment payer header.
-func WithPayerHeader(name string) Option {
- return func(o *Options) { o.PayerHeader = name }
-}
-
-// WithPayeeHeader configures the micropayment payee header.
-func WithPayeeHeader(name string) Option {
- return func(o *Options) { o.PayeeHeader = name }
-}
-
-// WithCapabilityHeader configures the A2A capability header.
-func WithCapabilityHeader(name string) Option {
- return func(o *Options) { o.CapabilityHeader = name }
-}
-
-// NewMiddleware creates a new Biscuit middleware for inbound A2A requests.
-func NewMiddleware(verifier Verifier, opts ...Option) (*Middleware, error) {
- if verifier == nil {
- return nil, fmt.Errorf("%w: verifier is nil", ErrMiddlewareMisconfigured)
- }
-
- o := DefaultOptions()
- for _, fn := range opts {
- fn(&o)
- }
-
- if err := o.validate(); err != nil {
- return nil, err
- }
-
- return &Middleware{verifier: verifier, opts: o}, nil
-}
-
-// Wrap applies Biscuit verification to each inbound request.
-func (m *Middleware) Wrap(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx, span := tracer.Start(r.Context(), "economy.middleware",
- trace.WithAttributes(
- attribute.String("http.method", r.Method),
- attribute.String("http.path", r.URL.Path),
- ),
- )
- defer span.End()
-
- token, payment, err := m.extract(r)
- if err != nil {
- span.RecordError(err)
- writeError(w, statusForExtractError(err), err)
- return
- }
-
- span.SetAttributes(
- attribute.Int64("sam.payment.amount", payment.Amount),
- attribute.String("sam.payment.asset", payment.Asset),
- attribute.String("sam.a2a.capability", payment.Capability),
- )
-
- decision, err := m.verifier.Verify(ctx, VerifyRequest{
- Token: token,
- Method: r.Method,
- Path: r.URL.Path,
- Payment: payment,
- })
- if err != nil {
- span.RecordError(err)
- status := http.StatusPaymentRequired
- if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
- status = http.StatusGatewayTimeout
- }
- writeError(w, status, fmt.Errorf("%w: %v", ErrVerifierDeniedRequest, err))
- return
- }
-
- span.SetAttributes(
- attribute.String("sam.auth.subject", decision.Subject),
- attribute.Int("sam.auth.attenuation_depth", decision.AttenuationDepth),
- )
-
- ctx = context.WithValue(ctx, paymentContextKey, payment)
- ctx = context.WithValue(ctx, decisionContextKey, decision)
- next.ServeHTTP(w, r.WithContext(ctx))
- })
-}
-
-// DecisionFromContext retrieves a verifier decision placed by middleware.
-func DecisionFromContext(ctx context.Context) (*VerifyDecision, bool) {
- v, ok := ctx.Value(decisionContextKey).(*VerifyDecision)
- return v, ok
-}
-
-// MicropaymentFromContext retrieves normalized payment metadata from request context.
-func MicropaymentFromContext(ctx context.Context) (Micropayment, bool) {
- v, ok := ctx.Value(paymentContextKey).(Micropayment)
- return v, ok
-}
-
-func (m *Middleware) extract(r *http.Request) (string, Micropayment, error) {
- token := strings.TrimSpace(r.Header.Get(m.opts.TokenHeader))
- if token == "" {
- return "", Micropayment{}, ErrMissingBiscuitToken
- }
-
- amountRaw := strings.TrimSpace(r.Header.Get(m.opts.AmountHeader))
- if amountRaw == "" {
- return "", Micropayment{}, ErrMissingMicropayAmount
- }
- amount, err := strconv.ParseInt(amountRaw, 10, 64)
- if err != nil || amount <= 0 {
- return "", Micropayment{}, ErrInvalidMicropayAmount
- }
-
- asset := strings.TrimSpace(r.Header.Get(m.opts.AssetHeader))
- if asset == "" {
- return "", Micropayment{}, ErrMissingMicropayAsset
- }
-
- nonce := strings.TrimSpace(r.Header.Get(m.opts.NonceHeader))
- if nonce == "" {
- return "", Micropayment{}, ErrMissingMicropayNonce
- }
-
- payment := Micropayment{
- Amount: amount,
- Asset: asset,
- Nonce: nonce,
- Payer: strings.TrimSpace(r.Header.Get(m.opts.PayerHeader)),
- Payee: strings.TrimSpace(r.Header.Get(m.opts.PayeeHeader)),
- Capability: strings.TrimSpace(r.Header.Get(m.opts.CapabilityHeader)),
- }
-
- return token, payment, nil
-}
-
-func (o Options) validate() error {
- if strings.TrimSpace(o.TokenHeader) == "" {
- return fmt.Errorf("%w: token header is required", ErrMiddlewareMisconfigured)
- }
- if strings.TrimSpace(o.AmountHeader) == "" {
- return fmt.Errorf("%w: amount header is required", ErrMiddlewareMisconfigured)
- }
- if strings.TrimSpace(o.AssetHeader) == "" {
- return fmt.Errorf("%w: asset header is required", ErrMiddlewareMisconfigured)
- }
- if strings.TrimSpace(o.NonceHeader) == "" {
- return fmt.Errorf("%w: nonce header is required", ErrMiddlewareMisconfigured)
- }
- if strings.TrimSpace(o.PayerHeader) == "" {
- return fmt.Errorf("%w: payer header is required", ErrMiddlewareMisconfigured)
- }
- if strings.TrimSpace(o.PayeeHeader) == "" {
- return fmt.Errorf("%w: payee header is required", ErrMiddlewareMisconfigured)
- }
- if strings.TrimSpace(o.CapabilityHeader) == "" {
- return fmt.Errorf("%w: capability header is required", ErrMiddlewareMisconfigured)
- }
- return nil
-}
-
-func statusForExtractError(err error) int {
- if errors.Is(err, ErrMissingBiscuitToken) {
- return http.StatusUnauthorized
- }
- return http.StatusBadRequest
-}
-
-func writeError(w http.ResponseWriter, status int, err error) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- _ = json.NewEncoder(w).Encode(struct {
- Error string `json:"error"`
- }{Error: err.Error()})
-}
diff --git a/pkg/economy/middleware_test.go b/pkg/economy/middleware_test.go
deleted file mode 100644
index de36ae35..00000000
--- a/pkg/economy/middleware_test.go
+++ /dev/null
@@ -1,241 +0,0 @@
-// 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 economy_test
-
-import (
- "context"
- "errors"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
-
- "sam/pkg/economy"
-)
-
-type fakeVerifier struct {
- decision *economy.VerifyDecision
- err error
- lastReq economy.VerifyRequest
- called bool
-}
-
-func (f *fakeVerifier) Verify(_ context.Context, req economy.VerifyRequest) (*economy.VerifyDecision, error) {
- f.called = true
- f.lastReq = req
- if f.err != nil {
- return nil, f.err
- }
- return f.decision, nil
-}
-
-func TestMiddlewareRejectsMissingHeaders(t *testing.T) {
- tests := []struct {
- name string
- headers map[string]string
- wantStatus int
- wantErrSub string
- verifierCall bool
- }{
- {
- name: "missing token",
- headers: validHeaders(),
- wantStatus: http.StatusUnauthorized,
- wantErrSub: economy.ErrMissingBiscuitToken.Error(),
- },
- {
- name: "missing amount",
- headers: drop(validHeaders(), economy.DefaultMicropaymentAmountHeader),
- wantStatus: http.StatusBadRequest,
- wantErrSub: economy.ErrMissingMicropayAmount.Error(),
- },
- {
- name: "invalid amount",
- headers: set(validHeaders(), economy.DefaultMicropaymentAmountHeader, "abc"),
- wantStatus: http.StatusBadRequest,
- wantErrSub: economy.ErrInvalidMicropayAmount.Error(),
- },
- {
- name: "missing asset",
- headers: drop(validHeaders(), economy.DefaultMicropaymentAssetHeader),
- wantStatus: http.StatusBadRequest,
- wantErrSub: economy.ErrMissingMicropayAsset.Error(),
- },
- {
- name: "missing nonce",
- headers: drop(validHeaders(), economy.DefaultMicropaymentNonceHeader),
- wantStatus: http.StatusBadRequest,
- wantErrSub: economy.ErrMissingMicropayNonce.Error(),
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- v := &fakeVerifier{decision: &economy.VerifyDecision{Subject: "peer:alice"}}
- mw, err := economy.NewMiddleware(v)
- if err != nil {
- t.Fatalf("NewMiddleware() error = %v", err)
- }
-
- h := mw.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.WriteHeader(http.StatusNoContent)
- }))
-
- req := httptest.NewRequest(http.MethodPost, "/a2a/call", nil)
- for k, val := range tt.headers {
- req.Header.Set(k, val)
- }
- if tt.name == "missing token" {
- req.Header.Del(economy.DefaultBiscuitTokenHeader)
- }
-
- rr := httptest.NewRecorder()
- h.ServeHTTP(rr, req)
-
- if rr.Code != tt.wantStatus {
- t.Fatalf("status = %d, want %d", rr.Code, tt.wantStatus)
- }
- if !strings.Contains(rr.Body.String(), tt.wantErrSub) {
- t.Fatalf("body = %q, want substring %q", rr.Body.String(), tt.wantErrSub)
- }
- if v.called {
- t.Fatal("verifier should not be called for malformed requests")
- }
- })
- }
-}
-
-func TestMiddlewarePassesDecisionAndPaymentInContext(t *testing.T) {
- v := &fakeVerifier{decision: &economy.VerifyDecision{Subject: "peer:alice", AttenuationDepth: 2}}
- mw, err := economy.NewMiddleware(v)
- if err != nil {
- t.Fatalf("NewMiddleware() error = %v", err)
- }
-
- called := false
- h := mw.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- called = true
-
- decision, ok := economy.DecisionFromContext(r.Context())
- if !ok {
- t.Fatal("decision missing from context")
- }
- if decision.Subject != "peer:alice" {
- t.Fatalf("decision subject = %q, want %q", decision.Subject, "peer:alice")
- }
-
- payment, ok := economy.MicropaymentFromContext(r.Context())
- if !ok {
- t.Fatal("payment missing from context")
- }
- if payment.Amount != 42 || payment.Asset != "sam-credit" || payment.Nonce != "n-1" {
- t.Fatalf("unexpected payment = %#v", payment)
- }
-
- w.WriteHeader(http.StatusAccepted)
- }))
-
- req := httptest.NewRequest(http.MethodPost, "/a2a/call", nil)
- for k, val := range validHeaders() {
- req.Header.Set(k, val)
- }
-
- rr := httptest.NewRecorder()
- h.ServeHTTP(rr, req)
-
- if !called {
- t.Fatal("next handler was not called")
- }
- if rr.Code != http.StatusAccepted {
- t.Fatalf("status = %d, want %d", rr.Code, http.StatusAccepted)
- }
- if !v.called {
- t.Fatal("verifier was not called")
- }
- if v.lastReq.Token != "biscuit-token" {
- t.Fatalf("token = %q, want %q", v.lastReq.Token, "biscuit-token")
- }
- if v.lastReq.Payment.Capability != "agent.chat" {
- t.Fatalf("capability = %q, want %q", v.lastReq.Payment.Capability, "agent.chat")
- }
-}
-
-func TestMiddlewareMapsVerifierFailure(t *testing.T) {
- v := &fakeVerifier{err: errors.New("insufficient funds")}
- mw, err := economy.NewMiddleware(v)
- if err != nil {
- t.Fatalf("NewMiddleware() error = %v", err)
- }
-
- h := mw.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.WriteHeader(http.StatusNoContent)
- }))
-
- req := httptest.NewRequest(http.MethodPost, "/a2a/call", nil)
- for k, val := range validHeaders() {
- req.Header.Set(k, val)
- }
-
- rr := httptest.NewRecorder()
- h.ServeHTTP(rr, req)
-
- if rr.Code != http.StatusPaymentRequired {
- t.Fatalf("status = %d, want %d", rr.Code, http.StatusPaymentRequired)
- }
- if !strings.Contains(rr.Body.String(), economy.ErrVerifierDeniedRequest.Error()) {
- t.Fatalf("body = %q, want substring %q", rr.Body.String(), economy.ErrVerifierDeniedRequest.Error())
- }
-}
-
-func TestNewMiddlewareValidation(t *testing.T) {
- if _, err := economy.NewMiddleware(nil); !errors.Is(err, economy.ErrMiddlewareMisconfigured) {
- t.Fatalf("NewMiddleware(nil) error = %v, want ErrMiddlewareMisconfigured", err)
- }
-
- v := &fakeVerifier{decision: &economy.VerifyDecision{Subject: "peer:alice"}}
- if _, err := economy.NewMiddleware(v, economy.WithTokenHeader("")); !errors.Is(err, economy.ErrMiddlewareMisconfigured) {
- t.Fatalf("NewMiddleware(empty header) error = %v, want ErrMiddlewareMisconfigured", err)
- }
-}
-
-func validHeaders() map[string]string {
- return map[string]string{
- economy.DefaultBiscuitTokenHeader: "biscuit-token",
- economy.DefaultMicropaymentAmountHeader: "42",
- economy.DefaultMicropaymentAssetHeader: "sam-credit",
- economy.DefaultMicropaymentNonceHeader: "n-1",
- economy.DefaultMicropaymentPayerHeader: "peer:alice",
- economy.DefaultMicropaymentPayeeHeader: "peer:bob",
- economy.DefaultA2ACapabilityHeader: "agent.chat",
- }
-}
-
-func drop(headers map[string]string, key string) map[string]string {
- cloned := make(map[string]string, len(headers))
- for k, v := range headers {
- cloned[k] = v
- }
- delete(cloned, key)
- return cloned
-}
-
-func set(headers map[string]string, key, val string) map[string]string {
- cloned := make(map[string]string, len(headers))
- for k, v := range headers {
- cloned[k] = v
- }
- cloned[key] = val
- return cloned
-}
diff --git a/pkg/identity/credentials.go b/pkg/identity/credentials.go
deleted file mode 100644
index 5df7cbb8..00000000
--- a/pkg/identity/credentials.go
+++ /dev/null
@@ -1,192 +0,0 @@
-// 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 identity
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "os"
- "strings"
- "time"
-
- internaldb "sam/internal/db"
-)
-
-// StoredCredentials is the persisted identity state in the SAM key-value store.
-type StoredCredentials struct {
- PeerID string `json:"peer_id,omitempty"`
- // HubURL is the hub the user authenticated against.
- HubURL string `json:"hub_url"`
- // AccessToken is the OAuth2 access token returned by the Hub.
- AccessToken string `json:"access_token"`
- // RefreshToken allows silent token refresh.
- RefreshToken string `json:"refresh_token,omitempty"`
- // TokenExpiry is when the access token expires.
- TokenExpiry time.Time `json:"token_expiry,omitempty"`
- // PassportBiscuit is the hub-issued biscuit binding identity to peer/federation.
- PassportBiscuit string `json:"passport_biscuit,omitempty"`
-}
-
-const (
- credentialsBucketKey = "local"
- credentialsCurrentVersion = 2
-)
-
-type credentialsRecord struct {
- PeerID string `json:"peer_id,omitempty"`
- HubURL string `json:"hub_url"`
- AccessToken string `json:"access_token"`
- RefreshToken string `json:"refresh_token,omitempty"`
- TokenExpiry time.Time `json:"token_expiry,omitempty"`
- Passport string `json:"passport_biscuit,omitempty"`
-}
-
-// CredentialStore reads and writes SAM credentials from the local state DB.
-type CredentialStore struct {
- path string
- store internaldb.Store
- codec internaldb.Codec
-}
-
-// DefaultCredentialStore returns a store that uses ~/.config/sam/state.db.
-func DefaultCredentialStore() (*CredentialStore, error) {
- path, err := internaldb.DefaultStatePath()
- if err != nil {
- return nil, err
- }
- return NewCredentialStore(path)
-}
-
-// NewCredentialStore creates a store backed by the given bbolt file path.
-func NewCredentialStore(path string) (*CredentialStore, error) {
- if path == "" {
- return nil, errors.New("credential store path must not be empty")
- }
- store, err := internaldb.Open(path)
- if err != nil {
- return nil, fmt.Errorf("opening state store: %w", err)
- }
- return &CredentialStore{path: path, store: store, codec: internaldb.JSONCodec{}}, nil
-}
-
-// Path returns the resolved path to the state DB file.
-func (s *CredentialStore) Path() string { return s.path }
-
-// Close releases store resources.
-func (s *CredentialStore) Close() error {
- if s == nil || s.store == nil {
- return nil
- }
- return s.store.Close()
-}
-
-// Load reads stored credentials. Returns nil, nil when no identity exists.
-func (s *CredentialStore) Load() (*StoredCredentials, error) {
- data, err := s.store.Get(context.Background(), internaldb.BucketIdentities, credentialsBucketKey)
- if errors.Is(err, os.ErrNotExist) {
- return nil, nil
- }
- if err != nil {
- return nil, fmt.Errorf("reading identity record: %w", err)
- }
-
- var rec credentialsRecord
- if err := s.codec.Unmarshal(data, credentialsCurrentVersion, &rec, func(payload map[string]any, fromVersion int) map[string]any {
- if fromVersion < 2 {
- if _, ok := payload["peer_id"]; !ok {
- payload["peer_id"] = ""
- }
- }
- return payload
- }); err != nil {
- return nil, fmt.Errorf("decoding identity record: %w", err)
- }
-
- creds := &StoredCredentials{
- PeerID: rec.PeerID,
- HubURL: rec.HubURL,
- AccessToken: rec.AccessToken,
- RefreshToken: rec.RefreshToken,
- TokenExpiry: rec.TokenExpiry,
- PassportBiscuit: rec.Passport,
- }
- return creds, nil
-}
-
-// Save writes creds to the identities bucket.
-func (s *CredentialStore) Save(creds *StoredCredentials) error {
- if creds == nil {
- return errors.New("cannot save nil credentials")
- }
- rec := credentialsRecord{
- PeerID: strings.TrimSpace(creds.PeerID),
- HubURL: creds.HubURL,
- AccessToken: creds.AccessToken,
- RefreshToken: creds.RefreshToken,
- TokenExpiry: creds.TokenExpiry,
- Passport: strings.TrimSpace(creds.PassportBiscuit),
- }
-
- encodedRec, err := s.codec.Marshal(credentialsCurrentVersion, rec)
- if err != nil {
- return fmt.Errorf("encoding identity record: %w", err)
- }
- if err := s.store.Put(context.Background(), internaldb.BucketIdentities, credentialsBucketKey, encodedRec); err != nil {
- return fmt.Errorf("writing identity record: %w", err)
- }
- return nil
-}
-
-// Clear removes stored credentials.
-func (s *CredentialStore) Clear() error {
- if err := s.store.Delete(context.Background(), internaldb.BucketIdentities, credentialsBucketKey); err != nil && !errors.Is(err, os.ErrNotExist) {
- return fmt.Errorf("removing identity record: %w", err)
- }
- return nil
-}
-
-// HubDiscoveryDoc is the subset of OIDC provider metadata that SAM needs.
-type HubDiscoveryDoc struct {
- Issuer string `json:"issuer"`
- DeviceAuthEndpoint string `json:"device_authorization_endpoint"`
- TokenEndpoint string `json:"token_endpoint"`
- UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`
- JWKsURI string `json:"jwks_uri,omitempty"`
-}
-
-// FetchHubDiscovery retrieves the OIDC discovery document from hubURL.
-// hubURL should be the base URL of the Hub (e.g. "https://hub.example.com").
-// The document is fetched from <hubURL>/.well-known/openid-configuration.
-func FetchHubDiscovery(ctx context.Context, hubURL string) (*HubDiscoveryDoc, error) {
- discoveryURL := strings.TrimRight(hubURL, "/") + "/.well-known/openid-configuration"
- req, err := newGetRequest(ctx, discoveryURL)
- if err != nil {
- return nil, err
- }
- body, err := doHTTPRequest(req)
- if err != nil {
- return nil, fmt.Errorf("fetching hub discovery doc from %s: %w", discoveryURL, err)
- }
- var doc HubDiscoveryDoc
- if err := json.Unmarshal(body, &doc); err != nil {
- return nil, fmt.Errorf("parsing hub discovery doc: %w", err)
- }
- if doc.DeviceAuthEndpoint == "" {
- return nil, fmt.Errorf("hub at %s does not advertise device_authorization_endpoint", hubURL)
- }
- return &doc, nil
-}
diff --git a/pkg/identity/device_flow.go b/pkg/identity/device_flow.go
deleted file mode 100644
index 74377073..00000000
--- a/pkg/identity/device_flow.go
+++ /dev/null
@@ -1,262 +0,0 @@
-// 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 identity
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "strings"
- "time"
-)
-
-const (
- // DefaultDevicePollInterval is how often the client polls the token endpoint.
- DefaultDevicePollInterval = 5 * time.Second
- // DefaultDeviceGrantType is the OAuth2 Device Authorization Grant type.
- DefaultDeviceGrantType = "urn:ietf:params:oauth2:grant-type:device_code"
-)
-
-// DeviceAuthResponse is the response from the Device Authorization endpoint.
-type DeviceAuthResponse struct {
- DeviceCode string `json:"device_code"`
- UserCode string `json:"user_code"`
- VerificationURI string `json:"verification_uri"`
- VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
- ExpiresIn int `json:"expires_in"`
- Interval int `json:"interval"`
-}
-
-// TokenResponse is the OAuth2 token endpoint response.
-type TokenResponse struct {
- AccessToken string `json:"access_token"`
- TokenType string `json:"token_type"`
- ExpiresIn int `json:"expires_in"`
- RefreshToken string `json:"refresh_token,omitempty"`
- IDToken string `json:"id_token,omitempty"`
- // OAuth2 error fields.
- Error string `json:"error,omitempty"`
- ErrorDescription string `json:"error_description,omitempty"`
-}
-
-// DeviceFlowConfig holds the parameters for the Device Authorization Grant.
-type DeviceFlowConfig struct {
- // ClientID is the OAuth2 client ID registered with the Hub.
- ClientID string
- // Scopes requested from the Hub. Defaults to ["openid", "profile", "email"].
- Scopes []string
- // PollInterval overrides the server-suggested polling interval.
- PollInterval time.Duration
- // HTTPClient allows injecting a custom client (useful in tests).
- HTTPClient *http.Client
-}
-
-// DeviceFlowResult is the outcome of a successful Device Authorization Grant.
-type DeviceFlowResult struct {
- AccessToken string
- RefreshToken string
- TokenExpiry time.Time
- IDToken string
-}
-
-// StartDeviceFlow initiates a Device Authorization Grant against the Hub.
-// It returns a DeviceAuthResponse that the caller must present to the user
-// (VerificationURI + UserCode).
-func StartDeviceFlow(ctx context.Context, deviceEndpoint string, cfg DeviceFlowConfig) (*DeviceAuthResponse, error) {
- scopes := cfg.Scopes
- if len(scopes) == 0 {
- scopes = []string{"openid", "profile", "email"}
- }
-
- form := url.Values{}
- form.Set("client_id", cfg.ClientID)
- form.Set("scope", strings.Join(scopes, " "))
-
- body, err := postForm(ctx, deviceEndpoint, form, cfg.HTTPClient)
- if err != nil {
- return nil, fmt.Errorf("device authorization request: %w", err)
- }
-
- var resp DeviceAuthResponse
- if err := json.Unmarshal(body, &resp); err != nil {
- return nil, fmt.Errorf("parsing device authorization response: %w", err)
- }
- if resp.DeviceCode == "" {
- return nil, fmt.Errorf("hub did not return a device_code")
- }
- return &resp, nil
-}
-
-// PollDeviceToken polls the token endpoint until the user completes the Device
-// Authorization flow, the device code expires, or ctx is cancelled.
-//
-// Returns ErrDeviceAuthPending while waiting for the user, ErrDeviceAuthSlowDown
-// if the Hub requests a longer polling interval, and ErrDeviceAuthExpired if the
-// code has expired.
-func PollDeviceToken(ctx context.Context, tokenEndpoint string, auth *DeviceAuthResponse, cfg DeviceFlowConfig) (*DeviceFlowResult, error) {
- interval := cfg.PollInterval
- if interval == 0 {
- if auth.Interval > 0 {
- interval = time.Duration(auth.Interval) * time.Second
- } else {
- interval = DefaultDevicePollInterval
- }
- }
-
- deadline := time.Now().Add(time.Duration(auth.ExpiresIn) * time.Second)
- ticker := time.NewTicker(interval)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return nil, ctx.Err()
- case <-ticker.C:
- }
-
- if time.Now().After(deadline) {
- return nil, ErrDeviceAuthExpired
- }
-
- result, pending, err := exchangeDeviceCode(ctx, tokenEndpoint, auth.DeviceCode, cfg)
- if err != nil {
- return nil, err
- }
- if pending {
- continue
- }
- if result != nil {
- return result, nil
- }
- }
-}
-
-// exchangeDeviceCode does one polling request to the token endpoint.
-// Returns (result, false, nil) on success, (nil, true, nil) when still pending,
-// and (nil, false, err) on a terminal error.
-func exchangeDeviceCode(ctx context.Context, tokenEndpoint, deviceCode string, cfg DeviceFlowConfig) (*DeviceFlowResult, bool, error) {
- form := url.Values{}
- form.Set("grant_type", DefaultDeviceGrantType)
- form.Set("device_code", deviceCode)
- form.Set("client_id", cfg.ClientID)
-
- body, err := postForm(ctx, tokenEndpoint, form, cfg.HTTPClient)
- if err != nil {
- return nil, false, fmt.Errorf("token exchange request: %w", err)
- }
-
- var tr TokenResponse
- if err := json.Unmarshal(body, &tr); err != nil {
- return nil, false, fmt.Errorf("parsing token response: %w", err)
- }
-
- switch tr.Error {
- case "":
- // Success.
- case "authorization_pending":
- return nil, true, nil
- case "slow_down":
- return nil, true, nil // caller will retry on next tick
- case "expired_token", "access_denied":
- return nil, false, ErrDeviceAuthExpired
- default:
- return nil, false, fmt.Errorf("token error %q: %s", tr.Error, tr.ErrorDescription)
- }
-
- if tr.AccessToken == "" {
- return nil, false, fmt.Errorf("token endpoint returned no access_token")
- }
-
- expiry := time.Time{}
- if tr.ExpiresIn > 0 {
- expiry = time.Now().Add(time.Duration(tr.ExpiresIn) * time.Second)
- }
-
- return &DeviceFlowResult{
- AccessToken: tr.AccessToken,
- RefreshToken: tr.RefreshToken,
- TokenExpiry: expiry,
- IDToken: tr.IDToken,
- }, false, nil
-}
-
-// Device flow sentinel errors.
-var (
- ErrDeviceAuthPending = fmt.Errorf("device authorization pending")
- ErrDeviceAuthSlowDown = fmt.Errorf("device authorization: slow down")
- ErrDeviceAuthExpired = fmt.Errorf("device authorization code expired or denied")
-)
-
-// ---------------------------------------------------------------------------
-// Internal HTTP helpers
-// ---------------------------------------------------------------------------
-
-func postForm(ctx context.Context, endpoint string, form url.Values, client *http.Client) ([]byte, error) {
- if client == nil {
- client = http.DefaultClient
- }
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint,
- strings.NewReader(form.Encode()))
- if err != nil {
- return nil, fmt.Errorf("building request for %s: %w", endpoint, err)
- }
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Set("Accept", "application/json")
-
- resp, err := client.Do(req)
- if err != nil {
- return nil, fmt.Errorf("POST %s: %w", endpoint, err)
- }
- defer func() { _ = resp.Body.Close() }()
- return io.ReadAll(io.LimitReader(resp.Body, 1<<16))
-}
-
-func newGetRequest(ctx context.Context, u string) (*http.Request, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
- if err != nil {
- return nil, fmt.Errorf("building GET request for %s: %w", u, err)
- }
- req.Header.Set("Accept", "application/json")
- return req, nil
-}
-
-func newPostJSONRequest(ctx context.Context, u string, body []byte) (*http.Request, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, strings.NewReader(string(body)))
- if err != nil {
- return nil, fmt.Errorf("building POST request for %s: %w", u, err)
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Accept", "application/json")
- return req, nil
-}
-
-func doHTTPRequest(req *http.Request) ([]byte, error) {
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("%s %s: %w", req.Method, req.URL, err)
- }
- defer func() { _ = resp.Body.Close() }()
- body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
- if err != nil {
- return nil, fmt.Errorf("reading response body: %w", err)
- }
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return nil, fmt.Errorf("unexpected status %s: %s", resp.Status, body)
- }
- return body, nil
-}
diff --git a/pkg/identity/libp2p_passport.go b/pkg/identity/libp2p_passport.go
deleted file mode 100644
index 9d0c3809..00000000
--- a/pkg/identity/libp2p_passport.go
+++ /dev/null
@@ -1,221 +0,0 @@
-package identity
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "sync"
-
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/network"
- "github.com/libp2p/go-libp2p/core/peer"
- coreprotocol "github.com/libp2p/go-libp2p/core/protocol"
-)
-
-const PassportAuthProtocolID coreprotocol.ID = "/sam/auth/1.0.0"
-
-type passportAuthRequest struct {
- Passport string `json:"passport"`
-}
-
-type passportAuthResponse struct {
- OK bool `json:"ok"`
- Error string `json:"error,omitempty"`
-}
-
-type passportAuthManager struct {
- host host.Host
- federationID string
-
- mu sync.RWMutex
- localPassport string
- peerClaims map[string]*PassportClaims
- trustedPeers map[peer.ID]struct{} // hub, relays — exempt from passport auth
- installed bool
-}
-
-var passportAuthManagers sync.Map
-
-func EnsurePassportAuth(h host.Host, _ string) error {
- if h == nil {
- return fmt.Errorf("host is nil")
- }
- mgr := getOrCreatePassportAuthManager(h)
- mgr.mu.Lock()
- mgr.federationID = "default"
- if mgr.installed {
- mgr.mu.Unlock()
- return nil
- }
- mgr.installed = true
- mgr.mu.Unlock()
-
- h.SetStreamHandler(PassportAuthProtocolID, mgr.handleStream)
- h.Network().Notify(&network.NotifyBundle{
- ConnectedF: func(_ network.Network, conn network.Conn) {
- go func() {
- remote := conn.RemotePeer()
- mgr.mu.RLock()
- _, trusted := mgr.trustedPeers[remote]
- mgr.mu.RUnlock()
- if trusted {
- return
- }
- if err := AuthenticatePeerPassport(context.Background(), h, remote); err != nil {
- // Peer could not present a valid hub-issued passport.
- // Close the connection to prevent unauthenticated mesh participation.
- _ = conn.Close()
- }
- }()
- },
- DisconnectedF: func(_ network.Network, conn network.Conn) {
- mgr.mu.Lock()
- delete(mgr.peerClaims, conn.RemotePeer().String())
- mgr.mu.Unlock()
- },
- })
- return nil
-}
-
-// RegisterTrustedPeer marks a peer as infrastructure (e.g. the hub) that is
-// exempt from passport authentication. Connections to/from trusted peers are
-// never closed due to a missing biscuit. Must be called before the node starts
-// making connections.
-func RegisterTrustedPeer(h host.Host, p peer.ID) {
- if h == nil || p == "" {
- return
- }
- mgr := getOrCreatePassportAuthManager(h)
- mgr.mu.Lock()
- mgr.trustedPeers[p] = struct{}{}
- mgr.mu.Unlock()
-}
-
-func SetLocalPassport(h host.Host, _ string, passport string) error {
- if err := EnsurePassportAuth(h, "default"); err != nil {
- return err
- }
- mgr := getOrCreatePassportAuthManager(h)
- mgr.mu.Lock()
- mgr.localPassport = passport
- mgr.mu.Unlock()
- return nil
-}
-
-func AuthenticatePeerPassport(ctx context.Context, h host.Host, target peer.ID) error {
- if h == nil {
- return fmt.Errorf("host is nil")
- }
- if target == "" {
- return fmt.Errorf("target peer id is required")
- }
- mgr := getOrCreatePassportAuthManager(h)
- if _, ok := mgr.claimsFor(target); ok {
- return nil
- }
- mgr.mu.RLock()
- localPassport := mgr.localPassport
- mgr.mu.RUnlock()
- if localPassport == "" {
- return fmt.Errorf("local passport is not configured")
- }
-
- stream, err := h.NewStream(ctx, target, PassportAuthProtocolID)
- if err != nil {
- return fmt.Errorf("opening passport auth stream: %w", err)
- }
- defer func() { _ = stream.Close() }()
-
- if err := json.NewEncoder(stream).Encode(passportAuthRequest{Passport: localPassport}); err != nil {
- return fmt.Errorf("writing passport auth request: %w", err)
- }
- var resp passportAuthResponse
- if err := json.NewDecoder(stream).Decode(&resp); err != nil {
- return fmt.Errorf("reading passport auth response: %w", err)
- }
- if !resp.OK {
- if resp.Error == "" {
- resp.Error = "passport authentication rejected"
- }
- return fmt.Errorf("%s", resp.Error)
- }
- mgr.mu.Lock()
- if _, ok := mgr.peerClaims[target.String()]; !ok {
- mgr.peerClaims[target.String()] = &PassportClaims{
- PeerID: target.String(),
- FederationID: mgr.federationID,
- Subject: target.String(),
- Claims: map[string]string{},
- }
- }
- mgr.mu.Unlock()
- return nil
-}
-
-func AuthenticatedPeerPassport(h host.Host, target peer.ID) (*PassportClaims, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- if target == "" {
- return nil, fmt.Errorf("target peer id is required")
- }
- mgr := getOrCreatePassportAuthManager(h)
- claims, ok := mgr.claimsFor(target)
- if !ok {
- return nil, fmt.Errorf("peer %s has not completed passport authentication", target)
- }
- return claims, nil
-}
-
-// EnsureAuthenticatedPeer blocks protocol usage until the passport auth hook
-// completes successfully for the target peer.
-func EnsureAuthenticatedPeer(ctx context.Context, h host.Host, target peer.ID) (*PassportClaims, error) {
- claims, err := AuthenticatedPeerPassport(h, target)
- if err == nil {
- return claims, nil
- }
- if authErr := AuthenticatePeerPassport(ctx, h, target); authErr != nil {
- return nil, authErr
- }
- return AuthenticatedPeerPassport(h, target)
-}
-
-func getOrCreatePassportAuthManager(h host.Host) *passportAuthManager {
- if mgr, ok := passportAuthManagers.Load(h); ok {
- return mgr.(*passportAuthManager)
- }
- mgr := &passportAuthManager{
- host: h,
- federationID: "default",
- peerClaims: map[string]*PassportClaims{},
- trustedPeers: map[peer.ID]struct{}{},
- }
- actual, _ := passportAuthManagers.LoadOrStore(h, mgr)
- return actual.(*passportAuthManager)
-}
-
-func (m *passportAuthManager) claimsFor(target peer.ID) (*PassportClaims, bool) {
- m.mu.RLock()
- defer m.mu.RUnlock()
- claims, ok := m.peerClaims[target.String()]
- return claims, ok
-}
-
-func (m *passportAuthManager) handleStream(stream network.Stream) {
- defer func() { _ = stream.Close() }()
-
- var req passportAuthRequest
- if err := json.NewDecoder(stream).Decode(&req); err != nil {
- _ = json.NewEncoder(stream).Encode(passportAuthResponse{Error: fmt.Sprintf("invalid passport auth request: %v", err)})
- return
- }
- claims, err := ValidatePassportBiscuit(context.Background(), req.Passport, stream.Conn().RemotePeer().String(), m.federationID)
- if err != nil {
- _ = json.NewEncoder(stream).Encode(passportAuthResponse{Error: fmt.Sprintf("invalid passport: %v", err)})
- return
- }
- m.mu.Lock()
- m.peerClaims[stream.Conn().RemotePeer().String()] = claims
- m.mu.Unlock()
- _ = json.NewEncoder(stream).Encode(passportAuthResponse{OK: true})
-}
diff --git a/pkg/identity/passport.go b/pkg/identity/passport.go
deleted file mode 100644
index 1282452e..00000000
--- a/pkg/identity/passport.go
+++ /dev/null
@@ -1,233 +0,0 @@
-package identity
-
-import (
- "context"
- "crypto/ed25519"
- "crypto/sha256"
- "encoding/base64"
- "encoding/json"
- "fmt"
- "os"
- "strings"
- "sync"
- "time"
-
- "sam/pkg/economy"
-)
-
-// PassportIssueRequest binds OIDC identity material to a peer and federation.
-type PassportIssueRequest struct {
- PeerID string
- FederationID string
- Subject string
- Claims map[string]string
-}
-
-// PassportClaims are extracted from a passport biscuit.
-type PassportClaims struct {
- Token string
- PeerID string
- FederationID string
- Subject string
- Claims map[string]string
- IssuedAt time.Time
- Issuer string
-}
-
-const DefaultHubIssuer = "app.sam-mesh.dev"
-
-var (
- hubKeyMu sync.RWMutex
- hubKeyCache ed25519.PrivateKey
-)
-
-type signedPassportPayload struct {
- Issuer string `json:"issuer"`
- PeerID string `json:"peer_id"`
- FederationID string `json:"federation_id"`
- MeshID string `json:"mesh_id"`
- Subject string `json:"subject"`
- Claims map[string]string `json:"claims,omitempty"`
- IssuedAt time.Time `json:"issued_at"`
-}
-
-// SetHubSigningKey overrides the hub's signing key (for testing or secure key injection).
-func SetHubSigningKey(priv ed25519.PrivateKey) {
- hubKeyMu.Lock()
- defer hubKeyMu.Unlock()
- hubKeyCache = priv
-}
-
-// hubSigningKey returns the hub's Ed25519 signing key.
-// Priority: environment variable SAM_HUB_KEY (base64-encoded private key),
-// then cached value, then deterministic seed (development default).
-func hubSigningKey() ed25519.PrivateKey {
- hubKeyMu.RLock()
- if hubKeyCache != nil {
- defer hubKeyMu.RUnlock()
- return hubKeyCache
- }
- hubKeyMu.RUnlock()
-
- // Check environment variable for externally configured key
- if keyB64 := strings.TrimSpace(os.Getenv("SAM_HUB_KEY")); keyB64 != "" {
- if keyBytes, err := base64.RawURLEncoding.DecodeString(keyB64); err == nil && len(keyBytes) == ed25519.PrivateKeySize {
- priv := ed25519.PrivateKey(keyBytes)
- hubKeyMu.Lock()
- hubKeyCache = priv
- hubKeyMu.Unlock()
- return priv
- }
- }
-
- // Development default: deterministic seed
- seed := sha256.Sum256([]byte("sam-hub-root-key-v1"))
- priv := ed25519.NewKeyFromSeed(seed[:])
- hubKeyMu.Lock()
- hubKeyCache = priv
- hubKeyMu.Unlock()
- return priv
-}
-
-func HubPublicKeyBytes() []byte {
- pub := hubSigningKey().Public().(ed25519.PublicKey)
- out := make([]byte, len(pub))
- copy(out, pub)
- return out
-}
-
-func HubPublicKeyBase64() string {
- return base64.RawURLEncoding.EncodeToString(HubPublicKeyBytes())
-}
-
-// IssuePassportBiscuit issues a compact passport biscuit token.
-// Token wire format keeps compatibility with SimpleBiscuitParser by placing
-// identity binding data in the subject segment and caveats after ';'.
-func IssuePassportBiscuit(_ context.Context, req PassportIssueRequest) (string, error) {
- req.PeerID = strings.TrimSpace(req.PeerID)
- req.FederationID = strings.TrimSpace(req.FederationID)
- req.Subject = strings.TrimSpace(req.Subject)
- if req.PeerID == "" || req.FederationID == "" || req.Subject == "" {
- return "", fmt.Errorf("peer_id, federation_id and subject are required")
- }
- if req.Claims == nil {
- req.Claims = map[string]string{}
- }
- payload := signedPassportPayload{
- Issuer: DefaultHubIssuer,
- PeerID: req.PeerID,
- FederationID: req.FederationID,
- MeshID: req.FederationID,
- Subject: req.Subject,
- Claims: req.Claims,
- IssuedAt: time.Now().UTC(),
- }
- rawPayload, err := json.Marshal(payload)
- if err != nil {
- return "", fmt.Errorf("marshal payload: %w", err)
- }
- sig := ed25519.Sign(hubSigningKey(), rawPayload)
- subject := fmt.Sprintf("passportv1|payload=%s|sig=%s",
- base64.RawURLEncoding.EncodeToString(rawPayload),
- base64.RawURLEncoding.EncodeToString(sig),
- )
- return subject + ";allow_skill=*", nil
-}
-
-func FetchPassportBiscuit(ctx context.Context, issueEndpoint string, accessToken string, req PassportIssueRequest) (string, error) {
- body, err := json.Marshal(map[string]string{
- "peer_id": strings.TrimSpace(req.PeerID),
- "federation": strings.TrimSpace(req.FederationID),
- "mesh_id": strings.TrimSpace(req.FederationID),
- "subject": strings.TrimSpace(req.Subject),
- "email": strings.TrimSpace(req.Claims["email"]),
- })
- if err != nil {
- return "", fmt.Errorf("marshal passport request: %w", err)
- }
- httpReq, err := newPostJSONRequest(ctx, strings.TrimSpace(issueEndpoint), body)
- if err != nil {
- return "", err
- }
- if token := strings.TrimSpace(accessToken); token != "" {
- httpReq.Header.Set("Authorization", "Bearer "+token)
- }
- respBody, err := doHTTPRequest(httpReq)
- if err != nil {
- return "", fmt.Errorf("requesting passport biscuit: %w", err)
- }
- var out struct {
- PassportBiscuit string `json:"passport_biscuit"`
- }
- if err := json.Unmarshal(respBody, &out); err != nil {
- return "", fmt.Errorf("parse passport response: %w", err)
- }
- if strings.TrimSpace(out.PassportBiscuit) == "" {
- return "", fmt.Errorf("passport_biscuit missing in response")
- }
- return strings.TrimSpace(out.PassportBiscuit), nil
-}
-
-func ValidatePassportBiscuit(ctx context.Context, token string, expectedPeerID string, expectedFederationID string) (*PassportClaims, error) {
- p, err := economy.SimpleBiscuitParser{}.Parse(ctx, token)
- if err != nil {
- return nil, fmt.Errorf("parse passport biscuit: %w", err)
- }
- parts := strings.Split(p.Subject, "|")
- if len(parts) != 3 || parts[0] != "passportv1" {
- return nil, fmt.Errorf("invalid passport biscuit subject")
- }
- var rawPayload []byte
- var signature []byte
- for _, item := range parts[1:] {
- kv := strings.SplitN(item, "=", 2)
- if len(kv) != 2 {
- continue
- }
- key, value := kv[0], kv[1]
- switch key {
- case "payload":
- rawPayload, err = base64.RawURLEncoding.DecodeString(value)
- if err != nil {
- return nil, fmt.Errorf("invalid passport payload encoding")
- }
- case "sig":
- signature, err = base64.RawURLEncoding.DecodeString(value)
- if err != nil {
- return nil, fmt.Errorf("invalid passport signature encoding")
- }
- }
- }
- if len(rawPayload) == 0 || len(signature) == 0 {
- return nil, fmt.Errorf("invalid passport biscuit envelope")
- }
- if !ed25519.Verify(ed25519.PublicKey(HubPublicKeyBytes()), rawPayload, signature) {
- return nil, fmt.Errorf("passport signature verification failed")
- }
- var payload signedPassportPayload
- if err := json.Unmarshal(rawPayload, &payload); err != nil {
- return nil, fmt.Errorf("invalid passport payload")
- }
- claims := &PassportClaims{
- Token: token,
- PeerID: payload.PeerID,
- FederationID: payload.FederationID,
- Subject: payload.Subject,
- Claims: payload.Claims,
- IssuedAt: payload.IssuedAt,
- Issuer: payload.Issuer,
- }
- if strings.TrimSpace(claims.FederationID) == "" {
- claims.FederationID = strings.TrimSpace(payload.MeshID)
- }
- if claims.Claims == nil {
- claims.Claims = map[string]string{}
- }
- if strings.TrimSpace(expectedPeerID) != "" && claims.PeerID != strings.TrimSpace(expectedPeerID) {
- return nil, fmt.Errorf("passport peer mismatch")
- }
- if strings.TrimSpace(expectedFederationID) != "" && claims.FederationID != strings.TrimSpace(expectedFederationID) {
- return nil, fmt.Errorf("passport federation mismatch")
- }
- return claims, nil
-}
diff --git a/pkg/net/informer.go b/pkg/net/informer.go
deleted file mode 100644
index 0b31f6b0..00000000
--- a/pkg/net/informer.go
+++ /dev/null
@@ -1,292 +0,0 @@
-// 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 samnet
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "time"
-
- "github.com/libp2p/go-libp2p/core/event"
- "go.etcd.io/bbolt"
-
- internaldb "sam/internal/db"
-)
-
-const (
- agentCacheRecordVersion = 1
- agentCacheCardPrefix = "agent-card/"
- defaultInformerPeriod = 2 * time.Second
-)
-
-type AgentWatchEventType string
-
-const (
- AgentWatchEventAdded AgentWatchEventType = "ADDED"
-)
-
-type AgentWatchEvent struct {
- Type AgentWatchEventType `json:"type"`
- PeerID string `json:"peer_id,omitempty"`
- Card json.RawMessage `json:"card,omitempty"`
-}
-
-type DiscoveredAgent struct {
- PeerID string
- Card []byte
- Capabilities []string
-}
-
-type AgentDiscoverFunc func(context.Context) ([]DiscoveredAgent, error)
-
-type LocalInformer struct {
- node Node
- federation string
- interval time.Duration
- emitter event.Emitter
- discover AgentDiscoverFunc
-
- mu sync.Mutex
- knownByID map[string]string
-}
-
-type LocalInformerOption func(*LocalInformer)
-
-func WithInformerInterval(interval time.Duration) LocalInformerOption {
- return func(informer *LocalInformer) {
- informer.interval = interval
- }
-}
-
-func WithInformerDiscoverer(discover AgentDiscoverFunc) LocalInformerOption {
- return func(informer *LocalInformer) {
- informer.discover = discover
- }
-}
-
-func NewLocalInformer(node Node, federation string, opts ...LocalInformerOption) (*LocalInformer, error) {
- if node == nil || node.Host() == nil {
- return nil, fmt.Errorf("node host is required")
- }
- emitter, err := node.Host().EventBus().Emitter(new(AgentWatchEvent))
- if err != nil {
- return nil, fmt.Errorf("creating agent event emitter: %w", err)
- }
- informer := &LocalInformer{
- node: node,
- federation: strings.TrimSpace(federation),
- interval: defaultInformerPeriod,
- emitter: emitter,
- knownByID: map[string]string{},
- }
- for _, opt := range opts {
- opt(informer)
- }
- if informer.interval <= 0 {
- informer.interval = defaultInformerPeriod
- }
- if informer.discover == nil {
- return nil, fmt.Errorf("informer discoverer is required")
- }
- cached, err := LoadCachedAgentRecords(informer.federation)
- if err != nil {
- return nil, err
- }
- for _, record := range cached {
- if strings.TrimSpace(record.PeerID) == "" {
- continue
- }
- informer.knownByID[record.PeerID] = informer.fingerprint(record.PeerID, record.Card)
- }
- return informer, nil
-}
-
-func (i *LocalInformer) Start(ctx context.Context) {
- go func() {
- _ = i.Sync(ctx)
- ticker := time.NewTicker(i.interval)
- defer ticker.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- _ = i.Sync(ctx)
- }
- }
- }()
-}
-
-func (i *LocalInformer) Sync(ctx context.Context) error {
- records, err := i.discover(ctx)
- if err != nil {
- return err
- }
- for _, record := range records {
- if err := UpsertCachedAgentRecord(i.federation, record); err != nil {
- continue
- }
- if i.markSeen(record) {
- _ = i.emitter.Emit(AgentWatchEvent{Type: AgentWatchEventAdded, PeerID: record.PeerID, Card: append([]byte(nil), record.Card...)})
- }
- }
- return nil
-}
-
-func (i *LocalInformer) markSeen(record DiscoveredAgent) bool {
- fingerprint := i.fingerprint(record.PeerID, record.Card)
- i.mu.Lock()
- defer i.mu.Unlock()
- if known, ok := i.knownByID[record.PeerID]; ok && known == fingerprint {
- return false
- }
- i.knownByID[record.PeerID] = fingerprint
- return true
-}
-
-func (i *LocalInformer) fingerprint(peerID string, card []byte) string {
- return strings.TrimSpace(peerID) + "|" + string(card)
-}
-
-type CachedAgentRecord struct {
- PeerID string `json:"peer_id"`
- Card json.RawMessage `json:"card"`
- Capabilities []string `json:"capabilities,omitempty"`
-}
-
-func LoadCachedAgentRecords(federation string) ([]CachedAgentRecord, error) {
- path, err := federationDBPath(federation)
- if err != nil {
- return nil, err
- }
- if _, err := os.Stat(path); err != nil {
- if os.IsNotExist(err) {
- return nil, nil
- }
- return nil, err
- }
- db, err := bbolt.Open(path, 0o600, &bbolt.Options{Timeout: 2 * time.Second, ReadOnly: true})
- if err != nil {
- return nil, err
- }
- defer func() { _ = db.Close() }()
-
- codec := internaldb.JSONCodec{}
- seen := map[string]struct{}{}
- out := make([]CachedAgentRecord, 0)
- err = db.View(func(tx *bbolt.Tx) error {
- bucket := tx.Bucket([]byte(internaldb.BucketCache))
- if bucket == nil {
- return nil
- }
- return bucket.ForEach(func(key, value []byte) error {
- if !strings.HasPrefix(string(key), agentCacheCardPrefix) {
- return nil
- }
- var record CachedAgentRecord
- if err := codec.Unmarshal(value, agentCacheRecordVersion, &record, nil); err != nil {
- return nil
- }
- if strings.TrimSpace(record.PeerID) == "" {
- return nil
- }
- if _, ok := seen[record.PeerID]; ok {
- return nil
- }
- seen[record.PeerID] = struct{}{}
- out = append(out, record)
- return nil
- })
- })
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func CachedCapabilities(federation string) ([]string, error) {
- records, err := LoadCachedAgentRecords(federation)
- if err != nil {
- return nil, err
- }
- seen := map[string]struct{}{}
- out := make([]string, 0)
- for _, record := range records {
- for _, capability := range record.Capabilities {
- capability = strings.TrimSpace(capability)
- if capability == "" {
- continue
- }
- if _, ok := seen[capability]; ok {
- continue
- }
- seen[capability] = struct{}{}
- out = append(out, capability)
- }
- }
- return out, nil
-}
-
-func UpsertCachedAgentRecord(federation string, record DiscoveredAgent) error {
- if strings.TrimSpace(record.PeerID) == "" || len(record.Card) == 0 {
- return nil
- }
- path, err := federationDBPath(federation)
- if err != nil {
- return err
- }
- db, err := bbolt.Open(path, 0o600, &bbolt.Options{Timeout: 2 * time.Second})
- if err != nil {
- return err
- }
- defer func() { _ = db.Close() }()
-
- codec := internaldb.JSONCodec{}
- payload, err := codec.Marshal(agentCacheRecordVersion, CachedAgentRecord{
- PeerID: record.PeerID,
- Card: append([]byte(nil), record.Card...),
- Capabilities: append([]string(nil), record.Capabilities...),
- })
- if err != nil {
- return err
- }
- return db.Update(func(tx *bbolt.Tx) error {
- bucket, err := tx.CreateBucketIfNotExists([]byte(internaldb.BucketCache))
- if err != nil {
- return fmt.Errorf("ensuring cache bucket: %w", err)
- }
- return bucket.Put([]byte(agentCacheCardPrefix+record.PeerID), payload)
- })
-}
-
-func federationDBPath(federation string) (string, error) {
- baseDir, err := internaldb.FederationsDir()
- if err != nil {
- return "", err
- }
- name := strings.TrimSpace(federation)
- if name == "" {
- name = "default"
- }
- if err := os.MkdirAll(baseDir, 0o700); err != nil {
- return "", err
- }
- return filepath.Join(baseDir, name+".db"), nil
-}
diff --git a/pkg/net/middleware.go b/pkg/net/middleware.go
deleted file mode 100644
index 02f644cb..00000000
--- a/pkg/net/middleware.go
+++ /dev/null
@@ -1,141 +0,0 @@
-// 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 samnet
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strings"
-
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/network"
- coreprotocol "github.com/libp2p/go-libp2p/core/protocol"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
-)
-
-const (
- a2aProtocolID = "/sam/a2a/1.0.0"
- mcpProtocolID = "/sam/mcp/1.0.0"
-)
-
-// Middleware wraps stream handlers registered on a host.
-type Middleware func(h host.Host, pid coreprotocol.ID, next network.StreamHandler) network.StreamHandler
-
-// AuthMiddlewareConfig controls global authn/authz behavior for all registered protocols.
-type AuthMiddlewareConfig struct {
- // AttemptAuthWhenMissing attempts /sam/auth/1.0.0 when a peer is not yet validated.
- AttemptAuthWhenMissing bool
- // ProtocolPolicies stores Datalog-like required facts per protocol, for example:
- // "/sam/a2a/1.0.0" -> {"mesh_membership":"finance"}
- ProtocolPolicies map[string]map[string]string
-}
-
-// WrapHost returns a host that applies middleware to every subsequently registered stream handler.
-func WrapHost(h host.Host, middlewares ...Middleware) host.Host {
- if h == nil || len(middlewares) == 0 {
- return h
- }
- return &middlewareHost{Host: h, middlewares: middlewares}
-}
-
-type middlewareHost struct {
- host.Host
- middlewares []Middleware
-}
-
-func (h *middlewareHost) SetStreamHandler(pid coreprotocol.ID, handler network.StreamHandler) {
- wrapped := handler
- for i := len(h.middlewares) - 1; i >= 0; i-- {
- wrapped = h.middlewares[i](h, pid, wrapped)
- }
- h.Host.SetStreamHandler(pid, wrapped)
-}
-
-func (h *middlewareHost) SetStreamHandlerMatch(pid coreprotocol.ID, m func(coreprotocol.ID) bool, handler network.StreamHandler) {
- wrapped := handler
- for i := len(h.middlewares) - 1; i >= 0; i-- {
- wrapped = h.middlewares[i](h, pid, wrapped)
- }
- h.Host.SetStreamHandlerMatch(pid, m, wrapped)
-}
-
-// NewAuthMiddleware creates a protocol-independent auth middleware that enforces
-// authenticated connections and optional claim-based authorization policies.
-func NewAuthMiddleware(cfg AuthMiddlewareConfig) Middleware {
- return func(h host.Host, pid coreprotocol.ID, next network.StreamHandler) network.StreamHandler {
- return func(stream network.Stream) {
- protocolName := string(pid)
- if bypassAuthMiddleware(pid) {
- next(stream)
- return
- }
-
- if err := identity.EnsurePassportAuth(h, "default"); err != nil {
- writeUnauthorizedAndReset(stream, protocolName, fmt.Sprintf("failed to initialize auth middleware: %v", err))
- return
- }
-
- remote := stream.Conn().RemotePeer()
- claims, err := identity.AuthenticatedPeerPassport(h, remote)
- if err != nil && cfg.AttemptAuthWhenMissing {
- if authErr := identity.AuthenticatePeerPassport(context.Background(), h, remote); authErr == nil {
- claims, err = identity.AuthenticatedPeerPassport(h, remote)
- } else {
- err = authErr
- }
- }
- if err != nil {
- writeUnauthorizedAndReset(stream, protocolName, fmt.Sprintf("passport auth required: %v", err))
- return
- }
-
- if policyErr := economy.EvaluateProtocolPolicies(protocolName, claims.Claims, cfg.ProtocolPolicies); policyErr != nil {
- writeUnauthorizedAndReset(stream, protocolName, policyErr.Error())
- return
- }
-
- next(stream)
- }
- }
-}
-
-func bypassAuthMiddleware(pid coreprotocol.ID) bool {
- p := string(pid)
- if p == string(identity.PassportAuthProtocolID) {
- return true
- }
- return !strings.HasPrefix(p, "/sam/")
-}
-
-func writeUnauthorizedAndReset(stream network.Stream, protocolName, reason string) {
- resp := map[string]string{
- "error": "Unauthorized",
- "code": "unauthorized",
- "protocol": protocolName,
- "reason": strings.TrimSpace(reason),
- }
-
- switch protocolName {
- case a2aProtocolID, mcpProtocolID:
- _ = json.NewEncoder(stream).Encode(resp)
- _ = stream.Close()
- return
- }
-
- _ = stream.Reset()
-}
diff --git a/pkg/net/net.go b/pkg/net/net.go
deleted file mode 100644
index 0c4ce7ee..00000000
--- a/pkg/net/net.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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 samnet provides the core networking substrate for SAM (Sovereign Agent Mesh).
-//
-// It wraps go-libp2p to deliver a zero-config, NAT-traversing, end-to-end encrypted
-// mesh with Kademlia DHT discovery, Relay v2, and DCUtR hole-punching over QUIC.
-// All relay traffic is E2E encrypted via TLS (QUIC-native), ensuring zero-knowledge
-// relay semantics — relay nodes see only opaque ciphertext.
-package samnet
-
-import (
- "context"
-
- dht "github.com/libp2p/go-libp2p-kad-dht"
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/multiformats/go-multiaddr"
-)
-
-// Node represents a SAM mesh node. It manages a libp2p host with QUIC transport,
-// Kademlia DHT discovery, and NAT traversal via AutoNAT, Relay v2, and DCUtR
-// hole-punching.
-type Node interface {
- // Start initializes the libp2p host, connects to bootstrap peers,
- // and begins participating in the DHT.
- Start(ctx context.Context) error
-
- // Stop gracefully shuts down the node and releases all resources.
- Stop(ctx context.Context) error
-
- // Host returns the underlying libp2p host.
- Host() host.Host
-
- // DHT returns the Kademlia DHT instance.
- DHT() *dht.IpfsDHT
-
- // PeerID returns this node's peer identity.
- PeerID() peer.ID
-
- // Addrs returns the multiaddresses this node is listening on.
- Addrs() []multiaddr.Multiaddr
-
- // Announce advertises a named capability to the DHT so other
- // peers can discover this node as a provider.
- Announce(ctx context.Context, capability string) error
-
- // Discover returns a channel of peers providing the given capability.
- Discover(ctx context.Context, capability string) (<-chan peer.AddrInfo, error)
-
- // PutValue stores a signed value under a DHT key using content routing.
- // Keys should be namespaced, for example: /sam/capability/weather-bot.
- PutValue(ctx context.Context, key string, value []byte) error
-
- // GetValue retrieves a value previously stored under a DHT key.
- GetValue(ctx context.Context, key string) ([]byte, error)
-
- // Connect establishes a connection to the given peer, using relay
- // fallback and hole-punching for NAT traversal.
- Connect(ctx context.Context, pi peer.AddrInfo) error
-}
diff --git a/pkg/net/node.go b/pkg/net/node.go
deleted file mode 100644
index bee402be..00000000
--- a/pkg/net/node.go
+++ /dev/null
@@ -1,483 +0,0 @@
-// 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 samnet
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "log/slog"
- "strings"
- "sync"
- "time"
-
- "github.com/libp2p/go-libp2p"
- dht "github.com/libp2p/go-libp2p-kad-dht"
- pubsub "github.com/libp2p/go-libp2p-pubsub"
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/peer"
- coreprotocol "github.com/libp2p/go-libp2p/core/protocol"
- "github.com/libp2p/go-libp2p/core/routing"
- drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing"
- relayv2 "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay"
- libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"
- "github.com/multiformats/go-multiaddr"
- "go.opentelemetry.io/otel"
- "go.opentelemetry.io/otel/attribute"
- "go.opentelemetry.io/otel/trace"
-
- "sam/pkg/reputation"
-)
-
-var tracer = otel.Tracer("sam/net")
-
-// Compile-time interface assertion.
-var _ Node = (*node)(nil)
-
-// node is the concrete implementation of the Node interface.
-type node struct {
- opts Options
-
- mu sync.RWMutex
- host host.Host
- kdht *dht.IpfsDHT
- relay *relayv2.Relay
- disc *drouting.RoutingDiscovery
- gsub *pubsub.PubSub
- trust *reputation.TrustStore
- started bool
- logger *slog.Logger
-}
-
-// New creates a new SAM mesh node. Call Start to initialize networking.
-func New(opts ...Option) (Node, error) {
- o := DefaultOptions()
- for _, fn := range opts {
- fn(&o)
- }
- if err := o.validate(); err != nil {
- return nil, fmt.Errorf("invalid node options: %w", err)
- }
- return &node{
- opts: o,
- logger: o.Logger,
- }, nil
-}
-
-// Start initializes the libp2p host with QUIC transport, Kademlia DHT,
-// relay v2 client, and DCUtR hole-punching. It connects to bootstrap
-// peers and begins DHT participation.
-func (n *node) Start(ctx context.Context) error {
- ctx, span := tracer.Start(ctx, "node.Start")
- defer span.End()
-
- n.mu.Lock()
- defer n.mu.Unlock()
-
- if n.started {
- return fmt.Errorf("node already started")
- }
-
- // Build the libp2p host. The Routing callback creates the DHT during
- // host construction, resolving the circular host↔DHT dependency.
- var kdht *dht.IpfsDHT
- h, err := libp2p.New(
- libp2p.Identity(n.opts.PrivateKey),
- libp2p.ListenAddrs(n.opts.ListenAddrs...),
- libp2p.UserAgent(n.opts.UserAgent),
- // Force TLS security transport only. QUIC uses TLS 1.3 natively,
- // and TCP falls back to libp2p TLS.
- libp2p.Security(libp2ptls.ID, libp2ptls.New),
- // QUIC is included in default transports; all QUIC traffic is
- // TLS-encrypted natively, providing zero-knowledge relay semantics.
- libp2p.NATPortMap(),
- libp2p.EnableRelay(),
- libp2p.EnableHolePunching(),
- libp2p.Routing(func(h host.Host) (routing.PeerRouting, error) {
- var dhtErr error
- kdht, dhtErr = n.newDHT(ctx, h)
- return kdht, dhtErr
- }),
- )
- if err != nil {
- return fmt.Errorf("creating libp2p host: %w", err)
- }
-
- middlewares := []Middleware{
- NewAuthMiddleware(AuthMiddlewareConfig{
- AttemptAuthWhenMissing: n.opts.AttemptAuthWhenMissing,
- ProtocolPolicies: n.opts.ProtocolPolicies,
- }),
- }
- middlewares = append(middlewares, n.opts.StreamMiddlewares...)
- n.host = WrapHost(h, middlewares...)
- n.kdht = kdht
-
- span.SetAttributes(
- attribute.String("peer_id", n.host.ID().String()),
- attribute.Int("listen_addrs", len(n.host.Addrs())),
- )
-
- // Start relay v2 service if configured, allowing other peers to
- // relay through this node.
- if n.opts.EnableRelayService {
- n.relay, err = relayv2.New(n.host)
- if err != nil {
- _ = n.host.Close()
- return fmt.Errorf("starting relay service: %w", err)
- }
- n.logger.Info("relay v2 service enabled")
- }
-
- // Bootstrap the DHT routing table.
- if err := n.kdht.Bootstrap(ctx); err != nil {
- _ = n.host.Close()
- return fmt.Errorf("bootstrapping DHT: %w", err)
- }
-
- // Connect to bootstrap peers concurrently.
- if err := n.connectBootstrapPeers(ctx); err != nil {
- n.logger.Warn("partial bootstrap failure", "error", err)
- }
-
- // Initialize routing-based discovery backed by the DHT.
- n.disc = drouting.NewRoutingDiscovery(n.kdht)
- gs, err := pubsub.NewGossipSub(ctx, n.host)
- if err != nil {
- _ = n.host.Close()
- return fmt.Errorf("initializing gossipsub: %w", err)
- }
- n.gsub = gs
- trust, err := reputation.NewTrustStore(n.host, gs)
- if err != nil {
- _ = n.host.Close()
- return fmt.Errorf("initializing reputation trust store: %w", err)
- }
- if err := trust.Start(ctx); err != nil {
- _ = n.host.Close()
- return fmt.Errorf("starting reputation trust store: %w", err)
- }
- n.trust = trust
- reputation.SetDefaultEvaluator(trust)
- reputation.SetDefaultAttestor(trust)
- n.started = true
-
- n.logger.Info("node started",
- "peer_id", n.host.ID(),
- "addrs", n.host.Addrs(),
- "relay_fallback", n.opts.RelayFallbackHost,
- "rendezvous_namespace", n.opts.RendezvousNamespace,
- )
- return nil
-}
-
-// Stop gracefully shuts down the relay, DHT, and host in order.
-func (n *node) Stop(ctx context.Context) error {
- _, span := tracer.Start(ctx, "node.Stop")
- defer span.End()
-
- n.mu.Lock()
- defer n.mu.Unlock()
-
- if !n.started {
- return nil
- }
-
- var errs []error
- if n.relay != nil {
- if err := n.relay.Close(); err != nil {
- errs = append(errs, fmt.Errorf("closing relay: %w", err))
- }
- }
- if err := n.kdht.Close(); err != nil {
- errs = append(errs, fmt.Errorf("closing DHT: %w", err))
- }
- if n.trust != nil {
- if err := n.trust.Close(); err != nil {
- errs = append(errs, fmt.Errorf("closing trust cache: %w", err))
- }
- }
- if err := n.host.Close(); err != nil {
- errs = append(errs, fmt.Errorf("closing host: %w", err))
- }
-
- n.started = false
- reputation.SetDefaultEvaluator(nil)
- reputation.SetDefaultAttestor(nil)
- n.logger.Info("node stopped")
- return errors.Join(errs...)
-}
-
-func (n *node) Host() host.Host {
- n.mu.RLock()
- defer n.mu.RUnlock()
- return n.host
-}
-
-func (n *node) DHT() *dht.IpfsDHT {
- n.mu.RLock()
- defer n.mu.RUnlock()
- return n.kdht
-}
-
-func (n *node) PeerID() peer.ID {
- n.mu.RLock()
- defer n.mu.RUnlock()
- if n.host == nil {
- return ""
- }
- return n.host.ID()
-}
-
-func (n *node) Addrs() []multiaddr.Multiaddr {
- n.mu.RLock()
- defer n.mu.RUnlock()
- if n.host == nil {
- return nil
- }
- return n.host.Addrs()
-}
-
-// Announce advertises a capability to the DHT. The call is synchronous:
-// when it returns, the provider record has been stored in the DHT.
-func (n *node) Announce(ctx context.Context, capability string) error {
- ctx, span := tracer.Start(ctx, "node.Announce",
- trace.WithAttributes(attribute.String("capability", capability)),
- )
- defer span.End()
-
- n.mu.RLock()
- disc := n.disc
- n.mu.RUnlock()
-
- if disc == nil {
- return fmt.Errorf("node not started")
- }
- ns := n.discoveryNamespace(capability)
- if _, err := disc.Advertise(ctx, ns); err != nil {
- return fmt.Errorf("advertising capability %q: %w", capability, err)
- }
-
- n.logger.Info("capability announced", "capability", capability, "namespace", ns)
- return nil
-}
-
-// Discover returns a channel of peers that provide the named capability.
-// The channel is closed when the context expires or no more peers are found.
-func (n *node) Discover(ctx context.Context, capability string) (<-chan peer.AddrInfo, error) {
- ctx, span := tracer.Start(ctx, "node.Discover",
- trace.WithAttributes(attribute.String("capability", capability)),
- )
- defer span.End()
-
- n.mu.RLock()
- disc := n.disc
- n.mu.RUnlock()
-
- if disc == nil {
- return nil, fmt.Errorf("node not started")
- }
- ns := n.discoveryNamespace(capability)
- ch, err := disc.FindPeers(ctx, ns)
- if err != nil {
- return nil, fmt.Errorf("discovering capability %q: %w", capability, err)
- }
- return ch, nil
-}
-
-func (n *node) discoveryNamespace(capability string) string {
- capability = strings.TrimSpace(capability)
- ns := strings.TrimSpace(n.opts.RendezvousNamespace)
- if ns == "" {
- ns = DefaultRendezvousNamespace
- }
- if capability == "" {
- return ns
- }
- return ns + "/" + capability
-}
-
-// Connect establishes a direct connection to the given peer. libp2p will
-// automatically attempt relay and hole-punching for NAT traversal.
-func (n *node) Connect(ctx context.Context, pi peer.AddrInfo) error {
- ctx, span := tracer.Start(ctx, "node.Connect",
- trace.WithAttributes(attribute.String("target", pi.ID.String())),
- )
- defer span.End()
-
- n.mu.RLock()
- h := n.host
- n.mu.RUnlock()
-
- if h == nil {
- return fmt.Errorf("node not started")
- }
-
- if err := h.Connect(ctx, pi); err != nil {
- return fmt.Errorf("connecting to %s: %w", pi.ID, err)
- }
-
- n.logger.Info("connected to peer", "peer_id", pi.ID)
- return nil
-}
-
-// newDHT initializes the Kademlia DHT with the configured mode.
-// SAM uses a single fixed federation namespace for DHT protocol traffic.
-func (n *node) newDHT(ctx context.Context, h host.Host) (*dht.IpfsDHT, error) {
- prefix := "/sam/fed/default"
- var opts []dht.Option
- opts = append(opts, dht.ProtocolPrefix(coreprotocol.ID(prefix)))
- opts = append(opts, dht.NamespacedValidator("sam", samRecordValidator{}))
- switch n.opts.DHTMode {
- case DHTModeServer:
- opts = append(opts, dht.Mode(dht.ModeServer))
- case DHTModeClient:
- opts = append(opts, dht.Mode(dht.ModeClient))
- default:
- opts = append(opts, dht.Mode(dht.ModeAutoServer))
- }
- return dht.New(ctx, h, opts...)
-}
-
-// PutValue stores opaque bytes in the DHT under a namespaced key.
-func (n *node) PutValue(ctx context.Context, key string, value []byte) error {
- ctx, span := tracer.Start(ctx, "node.PutValue",
- trace.WithAttributes(attribute.String("key", key)),
- )
- defer span.End()
-
- n.mu.RLock()
- k := n.kdht
- n.mu.RUnlock()
-
- if k == nil {
- return fmt.Errorf("node not started")
- }
- if strings.TrimSpace(key) == "" {
- return fmt.Errorf("key is required")
- }
- if len(value) == 0 {
- return fmt.Errorf("value is required")
- }
- if !strings.HasPrefix(key, "/") {
- key = "/" + key
- }
- if err := k.PutValue(ctx, key, value); err != nil {
- return fmt.Errorf("put DHT value for %q: %w", key, err)
- }
- return nil
-}
-
-// GetValue fetches bytes from the DHT using a namespaced key.
-func (n *node) GetValue(ctx context.Context, key string) ([]byte, error) {
- ctx, span := tracer.Start(ctx, "node.GetValue",
- trace.WithAttributes(attribute.String("key", key)),
- )
- defer span.End()
-
- n.mu.RLock()
- k := n.kdht
- n.mu.RUnlock()
-
- if k == nil {
- return nil, fmt.Errorf("node not started")
- }
- if strings.TrimSpace(key) == "" {
- return nil, fmt.Errorf("key is required")
- }
- if !strings.HasPrefix(key, "/") {
- key = "/" + key
- }
- value, err := k.GetValue(ctx, key)
- if err != nil {
- return nil, fmt.Errorf("get DHT value for %q: %w", key, err)
- }
- return value, nil
-}
-
-type samRecordValidator struct{}
-
-func (samRecordValidator) Validate(_ string, value []byte) error {
- if len(value) == 0 {
- return fmt.Errorf("empty SAM record")
- }
- return nil
-}
-
-func (samRecordValidator) Select(_ string, values [][]byte) (int, error) {
- if len(values) == 0 {
- return -1, fmt.Errorf("no SAM records")
- }
-
- best := 0
- bestIssuedAt := parseIssuedAt(values[0])
- for i := 1; i < len(values); i++ {
- issuedAt := parseIssuedAt(values[i])
- if issuedAt.After(bestIssuedAt) {
- best = i
- bestIssuedAt = issuedAt
- }
- }
- return best, nil
-}
-
-func parseIssuedAt(value []byte) time.Time {
- var payload struct {
- IssuedAt time.Time `json:"issued_at"`
- }
- if err := json.Unmarshal(value, &payload); err != nil {
- return time.Time{}
- }
- return payload.IssuedAt
-}
-
-// connectBootstrapPeers connects to all configured bootstrap peers concurrently.
-func (n *node) connectBootstrapPeers(ctx context.Context) error {
- if len(n.opts.BootstrapPeers) == 0 {
- return nil
- }
-
- var (
- wg sync.WaitGroup
- mu sync.Mutex
- errs []error
- )
-
- for _, addr := range n.opts.BootstrapPeers {
- pi, err := peer.AddrInfoFromP2pAddr(addr)
- if err != nil {
- mu.Lock()
- errs = append(errs, fmt.Errorf("parsing bootstrap addr %s: %w", addr, err))
- mu.Unlock()
- continue
- }
-
- wg.Add(1)
- go func(pi peer.AddrInfo) {
- defer wg.Done()
- if err := n.host.Connect(ctx, pi); err != nil {
- mu.Lock()
- errs = append(errs, fmt.Errorf("bootstrap peer %s: %w", pi.ID, err))
- mu.Unlock()
- return
- }
- n.logger.Debug("bootstrap peer connected", "peer_id", pi.ID)
- }(*pi)
- }
-
- wg.Wait()
- return errors.Join(errs...)
-}
diff --git a/pkg/net/node_test.go b/pkg/net/node_test.go
deleted file mode 100644
index 1ec327ff..00000000
--- a/pkg/net/node_test.go
+++ /dev/null
@@ -1,269 +0,0 @@
-// 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 samnet_test
-
-import (
- "context"
- "testing"
- "time"
-
- samnet "sam/pkg/net"
-
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/multiformats/go-multiaddr"
-)
-
-func TestGenerateKey(t *testing.T) {
- k1, err := samnet.GenerateKey()
- if err != nil {
- t.Fatalf("GenerateKey() error = %v", err)
- }
- if k1 == nil {
- t.Fatal("GenerateKey() returned nil key")
- }
-
- // Verify the key produces a valid peer ID.
- id1, err := peer.IDFromPrivateKey(k1)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
- if id1 == "" {
- t.Fatal("derived empty peer ID")
- }
-
- // Two keys must produce distinct identities.
- k2, err := samnet.GenerateKey()
- if err != nil {
- t.Fatalf("second GenerateKey() error = %v", err)
- }
- id2, _ := peer.IDFromPrivateKey(k2)
- if id1 == id2 {
- t.Error("two generated keys produced the same peer ID")
- }
-}
-
-func TestNew(t *testing.T) {
- tests := []struct {
- name string
- opts []samnet.Option
- wantErr bool
- }{
- {
- name: "defaults",
- opts: nil,
- },
- {
- name: "custom key",
- opts: func() []samnet.Option {
- k, _ := samnet.GenerateKey()
- return []samnet.Option{samnet.WithPrivateKey(k)}
- }(),
- },
- {
- name: "custom user agent",
- opts: []samnet.Option{samnet.WithUserAgent("test/1.0")},
- },
- {
- name: "server DHT mode",
- opts: []samnet.Option{samnet.WithDHTMode(samnet.DHTModeServer)},
- },
- {
- name: "with relay service",
- opts: []samnet.Option{samnet.WithRelayService()},
- },
- {
- name: "empty listen addrs rejected",
- opts: []samnet.Option{samnet.WithListenAddrs()},
- wantErr: true,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- n, err := samnet.New(tt.opts...)
- if (err != nil) != tt.wantErr {
- t.Fatalf("New() error = %v, wantErr %v", err, tt.wantErr)
- }
- if !tt.wantErr && n == nil {
- t.Fatal("New() returned nil node")
- }
- })
- }
-}
-
-func TestNodeStartStop(t *testing.T) {
- quic, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/udp/0/quic-v1")
- n, err := samnet.New(
- samnet.WithListenAddrs(quic),
- samnet.WithDHTMode(samnet.DHTModeServer),
- )
- if err != nil {
- t.Fatalf("New() error = %v", err)
- }
-
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- if err := n.Start(ctx); err != nil {
- t.Fatalf("Start() error = %v", err)
- }
-
- if n.PeerID() == "" {
- t.Error("PeerID() is empty after Start")
- }
- if len(n.Addrs()) == 0 {
- t.Error("Addrs() is empty after Start")
- }
- if n.Host() == nil {
- t.Error("Host() is nil after Start")
- }
- if n.DHT() == nil {
- t.Error("DHT() is nil after Start")
- }
-
- // Double start must error.
- if err := n.Start(ctx); err == nil {
- t.Error("second Start() should return error")
- }
-
- if err := n.Stop(ctx); err != nil {
- t.Fatalf("Stop() error = %v", err)
- }
-
- // Double stop must be safe (idempotent).
- if err := n.Stop(ctx); err != nil {
- t.Fatalf("second Stop() should not error, got %v", err)
- }
-}
-
-func TestDHTRouting(t *testing.T) {
- tests := []struct {
- name string
- capability string
- announce bool
- wantFound bool
- }{
- {
- name: "announced capability is discoverable",
- capability: "llm/gpt4",
- announce: true,
- wantFound: true,
- },
- {
- name: "unannounced capability returns no peers",
- capability: "llm/nonexistent",
- announce: false,
- wantFound: false,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
-
- quic, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/udp/0/quic-v1")
-
- // Create and start the provider node.
- provider, err := samnet.New(
- samnet.WithListenAddrs(quic),
- samnet.WithDHTMode(samnet.DHTModeServer),
- )
- if err != nil {
- t.Fatalf("creating provider: %v", err)
- }
- if err := provider.Start(ctx); err != nil {
- t.Fatalf("starting provider: %v", err)
- }
- defer func() { _ = provider.Stop(ctx) }()
-
- // Create and start the consumer node.
- consumer, err := samnet.New(
- samnet.WithListenAddrs(quic),
- samnet.WithDHTMode(samnet.DHTModeServer),
- )
- if err != nil {
- t.Fatalf("creating consumer: %v", err)
- }
- if err := consumer.Start(ctx); err != nil {
- t.Fatalf("starting consumer: %v", err)
- }
- defer func() { _ = consumer.Stop(ctx) }()
-
- // Connect the two nodes so the DHT can route between them.
- providerInfo := peer.AddrInfo{
- ID: provider.PeerID(),
- Addrs: provider.Addrs(),
- }
- if err := consumer.Connect(ctx, providerInfo); err != nil {
- t.Fatalf("connecting consumer to provider: %v", err)
- }
-
- // Wait for DHT routing tables to populate after connection.
- // The DHT processes connection events asynchronously.
- waitForDHT(t, ctx, provider)
- waitForDHT(t, ctx, consumer)
-
- // Announce if the test case requires it.
- if tt.announce {
- if err := provider.Announce(ctx, tt.capability); err != nil {
- t.Fatalf("Announce() error = %v", err)
- }
- }
-
- // Discover with a bounded timeout.
- discoverCtx, discoverCancel := context.WithTimeout(ctx, 5*time.Second)
- defer discoverCancel()
-
- ch, err := consumer.Discover(discoverCtx, tt.capability)
- if err != nil {
- t.Fatalf("Discover() error = %v", err)
- }
-
- var found bool
- for pi := range ch {
- if pi.ID == provider.PeerID() {
- found = true
- break
- }
- }
-
- if found != tt.wantFound {
- t.Errorf("found = %v, want %v", found, tt.wantFound)
- }
- })
- }
-}
-
-// waitForDHT polls until the node's DHT routing table has at least one peer,
-// or the context expires.
-func waitForDHT(t *testing.T, ctx context.Context, n samnet.Node) {
- t.Helper()
- ticker := time.NewTicker(50 * time.Millisecond)
- defer ticker.Stop()
- deadline := time.After(10 * time.Second)
- for {
- if n.DHT().RoutingTable().Size() > 0 {
- return
- }
- select {
- case <-deadline:
- t.Fatalf("DHT routing table empty after 10s (peer %s)", n.PeerID())
- case <-ctx.Done():
- t.Fatal("context cancelled waiting for DHT peers")
- case <-ticker.C:
- }
- }
-}
diff --git a/pkg/net/options.go b/pkg/net/options.go
deleted file mode 100644
index 77fafbff..00000000
--- a/pkg/net/options.go
+++ /dev/null
@@ -1,216 +0,0 @@
-// 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 samnet
-
-import (
- cryptorand "crypto/rand"
- "fmt"
- "log/slog"
-
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/multiformats/go-multiaddr"
-)
-
-// DHTMode controls how the node participates in the Kademlia DHT.
-type DHTMode int
-
-const (
- // DHTModeAuto automatically switches between client and server based on
- // the node's reachability (NAT status).
- DHTModeAuto DHTMode = iota
- // DHTModeServer always participates as a full DHT server.
- DHTModeServer
- // DHTModeClient always participates as a DHT client only.
- DHTModeClient
-
- DefaultRelayFallbackHost = "app.sam-mesh.dev"
- DefaultRendezvousNamespace = "app.sam-mesh.dev"
-)
-
-// Options configures a SAM mesh node.
-type Options struct {
- // PrivateKey is the Ed25519 identity key. Generated if nil.
- PrivateKey crypto.PrivKey
- // ListenAddrs are the multiaddresses to listen on.
- ListenAddrs []multiaddr.Multiaddr
- // BootstrapPeers are the initial peers to connect to on startup.
- // Each address must include the /p2p/<peerID> component.
- BootstrapPeers []multiaddr.Multiaddr
- // DHTMode controls DHT participation level.
- DHTMode DHTMode
- // EnableRelayService runs a circuit relay v2 service, allowing other
- // peers to relay through this node.
- EnableRelayService bool
- // UserAgent is the libp2p user-agent string.
- UserAgent string
- // Logger is the structured logger. Defaults to slog.Default().
- Logger *slog.Logger
- // FederationID scopes DHT participation to the single SAM namespace.
- // Runtime enforces the default value for all nodes.
- FederationID string
- // RelayFallbackHost is the default host hint for relay bootstrap.
- RelayFallbackHost string
- // RendezvousNamespace scopes capability discovery advertisements.
- RendezvousNamespace string
- // AttemptAuthWhenMissing triggers a /sam/auth/1.0.0 exchange when a stream
- // arrives from an unvalidated peer before rejecting it.
- AttemptAuthWhenMissing bool
- // ProtocolPolicies defines required claims per protocol ID.
- // Example: {"/sam/a2a/1.0.0": {"mesh_membership": "finance"}}
- ProtocolPolicies map[string]map[string]string
- // StreamMiddlewares are additional wrappers applied to every stream handler.
- StreamMiddlewares []Middleware
-}
-
-// Option is a functional option for node configuration.
-type Option func(*Options)
-
-// DefaultOptions returns production defaults: QUIC on all interfaces,
-// auto DHT mode, and standard user-agent.
-func DefaultOptions() Options {
- quicV1, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0/udp/0/quic-v1")
- quicV1v6, _ := multiaddr.NewMultiaddr("/ip6/::/udp/0/quic-v1")
- tcpV4, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0/tcp/0")
- tcpV6, _ := multiaddr.NewMultiaddr("/ip6/::/tcp/0")
- return Options{
- ListenAddrs: []multiaddr.Multiaddr{quicV1, quicV1v6, tcpV4, tcpV6},
- DHTMode: DHTModeAuto,
- UserAgent: "sam/0.1.0",
- Logger: slog.Default(),
- FederationID: "default",
- RelayFallbackHost: DefaultRelayFallbackHost,
- RendezvousNamespace: DefaultRendezvousNamespace,
- AttemptAuthWhenMissing: true,
- ProtocolPolicies: map[string]map[string]string{},
- }
-}
-
-func (o *Options) validate() error {
- if o.PrivateKey == nil {
- key, err := GenerateKey()
- if err != nil {
- return fmt.Errorf("generating default key: %w", err)
- }
- o.PrivateKey = key
- }
- if len(o.ListenAddrs) == 0 {
- return fmt.Errorf("at least one listen address required")
- }
- if o.Logger == nil {
- o.Logger = slog.Default()
- }
- if o.FederationID == "" {
- o.FederationID = "default"
- }
- if o.RelayFallbackHost == "" {
- o.RelayFallbackHost = DefaultRelayFallbackHost
- }
- if o.RendezvousNamespace == "" {
- o.RendezvousNamespace = DefaultRendezvousNamespace
- }
- if o.ProtocolPolicies == nil {
- o.ProtocolPolicies = map[string]map[string]string{}
- }
- return nil
-}
-
-// GenerateKey creates a new Ed25519 private key suitable for use as a peer identity.
-func GenerateKey() (crypto.PrivKey, error) {
- priv, _, err := crypto.GenerateEd25519Key(cryptorand.Reader)
- if err != nil {
- return nil, fmt.Errorf("generating ed25519 key: %w", err)
- }
- return priv, nil
-}
-
-// WithPrivateKey sets the node's Ed25519 identity key.
-func WithPrivateKey(key crypto.PrivKey) Option {
- return func(o *Options) { o.PrivateKey = key }
-}
-
-// WithListenAddrs sets the multiaddresses to listen on.
-func WithListenAddrs(addrs ...multiaddr.Multiaddr) Option {
- return func(o *Options) { o.ListenAddrs = addrs }
-}
-
-// WithBootstrapPeers sets initial peers to connect during Start.
-func WithBootstrapPeers(addrs ...multiaddr.Multiaddr) Option {
- return func(o *Options) { o.BootstrapPeers = addrs }
-}
-
-// WithDHTMode sets the DHT participation mode.
-func WithDHTMode(mode DHTMode) Option {
- return func(o *Options) { o.DHTMode = mode }
-}
-
-// WithRelayService enables the circuit relay v2 service.
-func WithRelayService() Option {
- return func(o *Options) { o.EnableRelayService = true }
-}
-
-// WithFederation keeps API compatibility but federation is fixed at runtime.
-func WithFederation(_ string) Option {
- return func(o *Options) { o.FederationID = "default" }
-}
-
-// WithLogger sets a structured logger for the node.
-
-func WithLogger(l *slog.Logger) Option {
- return func(o *Options) { o.Logger = l }
-}
-
-// WithUserAgent sets the libp2p user-agent string.
-func WithUserAgent(ua string) Option {
- return func(o *Options) { o.UserAgent = ua }
-}
-
-// WithRendezvousNamespace sets the discovery rendezvous namespace.
-func WithRendezvousNamespace(ns string) Option {
- return func(o *Options) { o.RendezvousNamespace = ns }
-}
-
-// WithRelayFallbackHost sets the relay host hint used in logs and defaults.
-func WithRelayFallbackHost(host string) Option {
- return func(o *Options) { o.RelayFallbackHost = host }
-}
-
-// WithAttemptAuthWhenMissing configures whether global middleware attempts
-// /sam/auth/1.0.0 when the peer is not yet validated.
-func WithAttemptAuthWhenMissing(enabled bool) Option {
- return func(o *Options) { o.AttemptAuthWhenMissing = enabled }
-}
-
-// WithProtocolPolicy requires claim=value for the given protocol ID.
-func WithProtocolPolicy(protocolID, claim, value string) Option {
- return func(o *Options) {
- if o.ProtocolPolicies == nil {
- o.ProtocolPolicies = map[string]map[string]string{}
- }
- if _, ok := o.ProtocolPolicies[protocolID]; !ok {
- o.ProtocolPolicies[protocolID] = map[string]string{}
- }
- o.ProtocolPolicies[protocolID][claim] = value
- }
-}
-
-// WithStreamMiddleware appends a custom global stream middleware wrapper.
-func WithStreamMiddleware(m Middleware) Option {
- return func(o *Options) {
- if m == nil {
- return
- }
- o.StreamMiddlewares = append(o.StreamMiddlewares, m)
- }
-}
diff --git a/pkg/protocol/a2a/a2a.go b/pkg/protocol/a2a/a2a.go
deleted file mode 100644
index 6bdcf392..00000000
--- a/pkg/protocol/a2a/a2a.go
+++ /dev/null
@@ -1,511 +0,0 @@
-// 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 a2a
-
-import (
- "bufio"
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "strings"
- "time"
-
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/network"
- "github.com/libp2p/go-libp2p/core/peer"
- coreprotocol "github.com/libp2p/go-libp2p/core/protocol"
- "github.com/modelcontextprotocol/go-sdk/jsonrpc"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
- "sam/pkg/protocol/middleware"
- "sam/pkg/reputation"
-)
-
-const A2AProtocolID coreprotocol.ID = "/sam/a2a/1.0.0"
-
-const (
- FailureTypeLiveness = "Liveness"
- FailureTypeProtocol = "Protocol"
- FailureTypeRemote = "Remote"
- FailureTypeInternal = "Internal"
-)
-
-// JSONRPCConnector opens a local backend JSON-RPC transport endpoint.
-type JSONRPCConnector interface {
- Open(ctx context.Context) (mcp.Transport, error)
-}
-
-// Observer receives task health callbacks after every A2A attempt.
-type Observer interface {
- OnSuccess(peerID string, latency time.Duration)
- OnFailure(peerID string, errorType string)
-}
-
-// NopObserver intentionally drops all callbacks.
-type NopObserver struct{}
-
-func (NopObserver) OnSuccess(string, time.Duration) {}
-func (NopObserver) OnFailure(string, string) {}
-
-// LivenessError reports that the remote peer was unreachable or dropped during call.
-type LivenessError struct {
- PeerID string
- Err error
-}
-
-func (e *LivenessError) Error() string {
- if e == nil {
- return "liveness error"
- }
- if strings.TrimSpace(e.PeerID) == "" {
- return fmt.Sprintf("peer unreachable: %v", e.Err)
- }
- return fmt.Sprintf("peer %s unreachable: %v", e.PeerID, e.Err)
-}
-
-func (e *LivenessError) Unwrap() error {
- if e == nil {
- return nil
- }
- return e.Err
-}
-
-// ExecuteRequest contains all data needed for one outbound A2A task.
-type ExecuteRequest struct {
- Target peer.AddrInfo
- Capability string
- Biscuit string
- Payment economy.Micropayment
- Request json.RawMessage
-}
-
-type a2aHeader struct {
- Biscuit string `json:"biscuit"`
- Capability string `json:"capability,omitempty"`
- Payment economy.Micropayment `json:"payment"`
-}
-
-// FederationGate controls which inbound peers are allowed to execute A2A tasks.
-// It is called with the requester's peer ID and the requested capability.
-// Return nil to allow the stream; return an error to drop it.
-type FederationGate interface {
- Allow(ctx context.Context, peerID string, capability string) error
-}
-
-// AllowAllGate is a FederationGate that accepts every peer (default, open mesh).
-type AllowAllGate struct{}
-
-func (AllowAllGate) Allow(_ context.Context, _ string, _ string) error {
- return nil
-}
-
-// IsAllowAllGate reports whether g is the permissive default gate implementation.
-func IsAllowAllGate(g FederationGate) bool {
- switch g.(type) {
- case AllowAllGate, *AllowAllGate:
- return true
- default:
- return false
- }
-}
-
-// A2AService serves /sam/a2a/1.0 and forwards JSON-RPC over a local backend connector.
-type A2AService struct {
- host host.Host
- observer Observer
- backend JSONRPCConnector
- gate FederationGate
- skillGate *economy.BiscuitSkillGate
-}
-
-// A2AServiceOption configures an A2AService.
-type A2AServiceOption func(*A2AService)
-
-// WithFederationGate installs an identity gate that filters inbound streams by
-// requester PeerID before processing any A2A payload.
-func WithFederationGate(g FederationGate) A2AServiceOption {
- return func(s *A2AService) { s.gate = g }
-}
-
-// WithSkillGate installs a Biscuit skill-caveat gate that drops streams whose
-// token does not include an allow_skill caveat matching the requested capability.
-func WithSkillGate(g *economy.BiscuitSkillGate) A2AServiceOption {
- return func(s *A2AService) { s.skillGate = g }
-}
-
-// NewA2AService registers a handler for /sam/a2a/1.0 on host h.
-func NewA2AService(h host.Host, connector JSONRPCConnector, observer Observer, opts ...A2AServiceOption) (*A2AService, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- if connector == nil {
- return nil, fmt.Errorf("backend connector is nil")
- }
- if observer == nil {
- observer = NopObserver{}
- }
- s := &A2AService{host: h, observer: observer, backend: connector, gate: AllowAllGate{}}
- for _, o := range opts {
- o(s)
- }
- h.SetStreamHandler(A2AProtocolID, s.handleStream)
- return s, nil
-}
-
-// Close unregisters the A2A handler from the host.
-func (s *A2AService) Close() {
- if s == nil || s.host == nil {
- return
- }
- s.host.RemoveStreamHandler(A2AProtocolID)
-}
-
-// Preflight performs liveness and quick protocol-negotiation checks.
-func Preflight(ctx context.Context, h host.Host, target peer.AddrInfo) error {
- if h == nil {
- return fmt.Errorf("host is nil")
- }
- if target.ID == "" {
- return fmt.Errorf("target peer ID is required")
- }
- if err := h.Connect(ctx, target); err != nil {
- return &LivenessError{PeerID: target.ID.String(), Err: err}
- }
- probe, err := h.NewStream(ctx, target.ID, A2AProtocolID)
- if err != nil {
- return &LivenessError{PeerID: target.ID.String(), Err: err}
- }
- _ = probe.Close()
- return nil
-}
-
-// Execute performs one outbound A2A task and returns the remote JSON-RPC response.
-func Execute(ctx context.Context, h host.Host, req ExecuteRequest, observer Observer) (json.RawMessage, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- if req.Target.ID == "" {
- return nil, fmt.Errorf("target peer ID is required")
- }
- if strings.TrimSpace(req.Biscuit) == "" {
- return nil, fmt.Errorf("biscuit token is required")
- }
- payload := []byte(strings.TrimSpace(string(req.Request)))
- if len(payload) == 0 {
- return nil, fmt.Errorf("json-rpc request is required")
- }
- if _, err := jsonrpc.DecodeMessage(payload); err != nil {
- return nil, fmt.Errorf("invalid A2A JSON-RPC payload: %w", err)
- }
-
- if observer == nil {
- observer = NopObserver{}
- }
- peerID := req.Target.ID.String()
- started := time.Now()
- if err := h.Connect(ctx, req.Target); err != nil {
- observer.OnFailure(peerID, FailureTypeLiveness)
- return nil, &LivenessError{PeerID: peerID, Err: err}
- }
- if err := identity.AuthenticatePeerPassport(ctx, h, req.Target.ID); err != nil {
- observer.OnFailure(peerID, FailureTypeProtocol)
- return nil, fmt.Errorf("passport authentication failed for %s: %w", peerID, err)
- }
-
- if err := Preflight(ctx, h, req.Target); err != nil {
- observer.OnFailure(peerID, FailureTypeLiveness)
- return nil, err
- }
- if eval := reputation.DefaultEvaluator(); eval != nil && eval.IsNegative(peerID) {
- observer.OnFailure(peerID, FailureTypeProtocol)
- return nil, fmt.Errorf("refusing A2A call to negatively-rated peer %s", peerID)
- }
-
- stream, err := h.NewStream(ctx, req.Target.ID, A2AProtocolID)
- if err != nil {
- observer.OnFailure(peerID, FailureTypeLiveness)
- return nil, &LivenessError{PeerID: peerID, Err: err}
- }
- defer func() { _ = stream.Close() }()
-
- // Propagate the caller's deadline to the stream so that all subsequent
- // reads and writes respect the context timeout even after the stream is
- // open (bufio reads don't accept a context directly).
- if deadline, ok := ctx.Deadline(); ok {
- _ = stream.SetDeadline(deadline)
- }
- // Also wire up context cancellation so a manual cancel (no deadline) also
- // kills the stream promptly.
- ctx, streamCancel := context.WithCancel(ctx)
- defer streamCancel()
- go func() {
- <-ctx.Done()
- _ = stream.SetDeadline(time.Now())
- }()
-
- header := a2aHeader{
- Biscuit: strings.TrimSpace(req.Biscuit),
- Capability: strings.TrimSpace(req.Capability),
- Payment: req.Payment,
- }
- if strings.TrimSpace(header.Payment.Capability) == "" {
- header.Payment.Capability = header.Capability
- }
-
- w := bufio.NewWriter(stream)
- if err := json.NewEncoder(w).Encode(header); err != nil {
- observer.OnFailure(peerID, FailureTypeProtocol)
- return nil, fmt.Errorf("writing A2A header: %w", err)
- }
- if _, err := w.Write(append(payload, '\n')); err != nil {
- observer.OnFailure(peerID, classifyFailure(err))
- return nil, wrapRuntimeLiveness(req.Target.ID, err)
- }
- if err := w.Flush(); err != nil {
- observer.OnFailure(peerID, classifyFailure(err))
- return nil, wrapRuntimeLiveness(req.Target.ID, err)
- }
-
- r := bufio.NewReader(stream)
- line, err := r.ReadBytes('\n')
- if err != nil {
- observer.OnFailure(peerID, classifyFailure(err))
- return nil, wrapRuntimeLiveness(req.Target.ID, err)
- }
- resp := bytesTrimSpace(line)
- if len(resp) == 0 {
- observer.OnFailure(peerID, FailureTypeProtocol)
- return nil, fmt.Errorf("empty A2A response from %s", peerID)
- }
- if remoteErr := decodeA2AError(resp); remoteErr != "" {
- observer.OnFailure(peerID, FailureTypeRemote)
- return nil, fmt.Errorf("remote A2A error from %s: %s", peerID, remoteErr)
- }
- if _, err := jsonrpc.DecodeMessage(resp); err != nil {
- observer.OnFailure(peerID, FailureTypeProtocol)
- return nil, fmt.Errorf("invalid A2A response JSON-RPC payload from %s: %w", peerID, err)
- }
-
- observer.OnSuccess(peerID, time.Since(started))
- if att := reputation.DefaultAttestor(); att != nil {
- _ = att.Publish(context.Background(), peerID, 1)
- }
- return json.RawMessage(resp), nil
-}
-
-func (s *A2AService) handleStream(stream network.Stream) {
- defer func() { _ = stream.Close() }()
-
- peerID := stream.Conn().RemotePeer().String()
- started := time.Now()
- fail := func(errType string, err error) {
- s.observer.OnFailure(peerID, errType)
- if err != nil {
- _ = writeA2AError(stream, err)
- }
- }
-
- reader := bufio.NewReader(stream)
-
- headerLine, err := reader.ReadBytes('\n')
- if err != nil {
- // Liveness preflight opens and closes a probe stream without payload.
- if errors.Is(err, io.EOF) {
- return
- }
- fail(classifyFailure(err), fmt.Errorf("reading A2A header: %w", err))
- return
- }
- var header a2aHeader
- if err := json.Unmarshal(bytesTrimSpace(headerLine), &header); err != nil {
- fail(FailureTypeProtocol, fmt.Errorf("invalid A2A header: %w", err))
- return
- }
- if strings.TrimSpace(header.Biscuit) == "" {
- fail(FailureTypeProtocol, fmt.Errorf("missing biscuit token"))
- return
- }
- if err := (middleware.PassportAuthz{}).CheckCapability(context.Background(), header.Biscuit, "a2a.negotiate", strings.TrimSpace(header.Capability)); err != nil {
- fail(FailureTypeProtocol, err)
- return
- }
- claims, err := identity.AuthenticatedPeerPassport(s.host, stream.Conn().RemotePeer())
- if err != nil {
- fail(FailureTypeProtocol, fmt.Errorf("passport authentication required: %w", err))
- return
- }
-
- // Identity gate: verify the requester's PeerID is allowed in this federation
- // before forwarding any payload to the local agent backend.
- authCtx := withAuthenticatedPassportClaims(context.Background(), claims)
- if err := s.gate.Allow(authCtx, peerID, strings.TrimSpace(header.Capability)); err != nil {
- fail(FailureTypeProtocol, fmt.Errorf("federation gate denied peer %s: %w", peerID, err))
- return
- }
-
- requestLine, err := reader.ReadBytes('\n')
-
- // Zero-Trust Biscuit: verify the token's allow_skill caveat before processing.
- if s.skillGate != nil {
- capability := strings.TrimSpace(header.Capability)
- if skillErr := s.skillGate.CheckSkill(context.Background(), header.Biscuit, capability); skillErr != nil {
- fail(FailureTypeProtocol, fmt.Errorf("skill caveat check failed: %w", skillErr))
- return
- }
- }
-
- if err != nil {
- fail(classifyFailure(err), fmt.Errorf("reading MCP request frame: %w", err))
- return
- }
- requestBytes := bytesTrimSpace(requestLine)
- msg, err := jsonrpc.DecodeMessage(requestBytes)
- if err != nil {
- fail(FailureTypeProtocol, fmt.Errorf("decoding MCP JSON-RPC request: %w", err))
- return
- }
-
- transport, err := s.backend.Open(context.Background())
- if err != nil {
- fail(FailureTypeInternal, fmt.Errorf("opening local backend transport: %w", err))
- return
- }
- conn, err := transport.Connect(context.Background())
- if err != nil {
- fail(FailureTypeInternal, fmt.Errorf("connecting local backend transport: %w", err))
- return
- }
- defer func() { _ = conn.Close() }()
-
- if err := conn.Write(context.Background(), msg); err != nil {
- fail(FailureTypeInternal, fmt.Errorf("writing local backend request: %w", err))
- return
- }
- respMsg, err := conn.Read(context.Background())
- if err != nil {
- fail(FailureTypeInternal, fmt.Errorf("reading local backend response: %w", err))
- return
- }
- respBytes, err := jsonrpc.EncodeMessage(respMsg)
- if err != nil {
- fail(FailureTypeInternal, fmt.Errorf("encoding MCP JSON-RPC response: %w", err))
- return
- }
-
- writer := bufio.NewWriter(stream)
- if _, err := writer.Write(append(respBytes, '\n')); err != nil {
- fail(classifyFailure(err), fmt.Errorf("writing A2A response: %w", err))
- return
- }
- if err := writer.Flush(); err != nil {
- fail(classifyFailure(err), fmt.Errorf("flushing A2A response: %w", err))
- return
- }
-
- s.observer.OnSuccess(peerID, time.Since(started))
- if att := reputation.DefaultAttestor(); att != nil {
- _ = att.PublishWithProtocol(context.Background(), peerID, 1, string(A2AProtocolID))
- }
-}
-
-func writeA2AError(w io.Writer, err error) error {
- if err == nil {
- err = fmt.Errorf("a2a request failed")
- }
- return json.NewEncoder(w).Encode(struct {
- JSONRPC string `json:"jsonrpc"`
- Error struct {
- Code int `json:"code"`
- Message string `json:"message"`
- } `json:"error"`
- ID any `json:"id"`
- }{
- JSONRPC: "2.0",
- Error: struct {
- Code int `json:"code"`
- Message string `json:"message"`
- }{Code: -32001, Message: err.Error()},
- ID: nil,
- })
-}
-
-func wrapRuntimeLiveness(pid peer.ID, err error) error {
- if err == nil {
- return nil
- }
- if classifyFailure(err) == FailureTypeLiveness {
- return &LivenessError{PeerID: pid.String(), Err: err}
- }
- return err
-}
-
-func classifyFailure(err error) string {
- if err == nil {
- return FailureTypeInternal
- }
- var livenessErr *LivenessError
- if errors.As(err, &livenessErr) {
- return FailureTypeLiveness
- }
- msg := strings.ToLower(err.Error())
- switch {
- case strings.Contains(msg, "connection refused"):
- return FailureTypeLiveness
- case strings.Contains(msg, "connection reset"):
- return FailureTypeLiveness
- case strings.Contains(msg, "stream reset"):
- return FailureTypeLiveness
- case strings.Contains(msg, "broken pipe"):
- return FailureTypeLiveness
- case strings.Contains(msg, "no good addresses"):
- return FailureTypeLiveness
- case strings.Contains(msg, "deadline exceeded"):
- return FailureTypeLiveness
- case strings.Contains(msg, "eof"):
- return FailureTypeLiveness
- default:
- return FailureTypeProtocol
- }
-}
-
-func decodeA2AError(payload []byte) string {
- var rpcOut struct {
- Error struct {
- Message string `json:"message"`
- } `json:"error"`
- }
- if err := json.Unmarshal(payload, &rpcOut); err == nil {
- if msg := strings.TrimSpace(rpcOut.Error.Message); msg != "" {
- return msg
- }
- }
-
- var out struct {
- Error string `json:"error"`
- }
- if err := json.Unmarshal(payload, &out); err != nil {
- return ""
- }
- return strings.TrimSpace(out.Error)
-}
-
-func bytesTrimSpace(in []byte) []byte {
- return bytes.TrimSpace(in)
-}
diff --git a/pkg/protocol/a2a/a2a_test.go b/pkg/protocol/a2a/a2a_test.go
deleted file mode 100644
index a39cae82..00000000
--- a/pkg/protocol/a2a/a2a_test.go
+++ /dev/null
@@ -1,223 +0,0 @@
-// 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 a2a
-
-import (
- "context"
- "errors"
- "sync"
- "testing"
- "time"
-
- "github.com/libp2p/go-libp2p"
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/modelcontextprotocol/go-sdk/jsonrpc"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
-)
-
-type testObserver struct {
- mu sync.Mutex
- successCount int
- failureCount int
- lastPeerID string
- lastFailure string
-}
-
-func (o *testObserver) OnSuccess(peerID string, _ time.Duration) {
- o.mu.Lock()
- defer o.mu.Unlock()
- o.successCount++
- o.lastPeerID = peerID
-}
-
-func (o *testObserver) OnFailure(peerID string, errorType string) {
- o.mu.Lock()
- defer o.mu.Unlock()
- o.failureCount++
- o.lastPeerID = peerID
- o.lastFailure = errorType
-}
-
-func (o *testObserver) GetCounts() (success, failure int) {
- o.mu.Lock()
- defer o.mu.Unlock()
- return o.successCount, o.failureCount
-}
-
-func (o *testObserver) GetLastFailure() string {
- o.mu.Lock()
- defer o.mu.Unlock()
- return o.lastFailure
-}
-
-type staticResponseConnector struct{}
-
-func (staticResponseConnector) Open(context.Context) (mcp.Transport, error) {
- return staticResponseTransport{}, nil
-}
-
-type staticResponseTransport struct{}
-
-func (staticResponseTransport) Connect(context.Context) (mcp.Connection, error) {
- msg, err := jsonrpc.DecodeMessage([]byte(`{"jsonrpc":"2.0","id":"sam-call","result":{"ok":true}}`))
- if err != nil {
- return nil, err
- }
- return &staticResponseConn{response: msg}, nil
-}
-
-type staticResponseConn struct {
- response jsonrpc.Message
-}
-
-func (c *staticResponseConn) Read(context.Context) (jsonrpc.Message, error) {
- return c.response, nil
-}
-
-func (c *staticResponseConn) Write(context.Context, jsonrpc.Message) error {
- return nil
-}
-
-func (c *staticResponseConn) Close() error {
- return nil
-}
-
-func (c *staticResponseConn) SessionID() string {
- return "test-session"
-}
-
-func TestExecuteSuccessRecordsObserver(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
-
- serverHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(server) error = %v", err)
- }
- defer func() { _ = serverHost.Close() }()
-
- clientHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(client) error = %v", err)
- }
- defer func() { _ = clientHost.Close() }()
-
- // Set up server passport
- serverPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{
- PeerID: serverHost.ID().String(),
- FederationID: "default",
- Subject: "server-sub",
- })
- if err != nil {
- t.Fatalf("IssuePassportBiscuit(server) error = %v", err)
- }
- if err := identity.SetLocalPassport(serverHost, "default", serverPassport); err != nil {
- t.Fatalf("SetLocalPassport(server) error = %v", err)
- }
-
- serverObserver := &testObserver{}
- svc, err := NewA2AService(serverHost, staticResponseConnector{}, serverObserver)
- if err != nil {
- t.Fatalf("NewA2AService(server) error = %v", err)
- }
- defer svc.Close()
-
- clientObserver := &testObserver{}
- passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{
- PeerID: clientHost.ID().String(),
- FederationID: "default",
- Subject: "sub",
- })
- if err != nil {
- t.Fatalf("IssuePassportBiscuit(client) error = %v", err)
- }
- if err := identity.SetLocalPassport(clientHost, "default", passport); err != nil {
- t.Fatalf("SetLocalPassport(client) error = %v", err)
- }
- resp, err := Execute(ctx, clientHost, ExecuteRequest{
- Target: peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()},
- Biscuit: "test-biscuit",
- Payment: economy.Micropayment{Amount: 1, Asset: "sam-credit", Nonce: "n-1"},
- Request: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"ping"}}`),
- }, clientObserver)
- if err != nil {
- t.Fatalf("Execute() error = %v", err)
- }
- if len(resp) == 0 {
- t.Fatalf("response is empty")
- }
- if success, failure := clientObserver.GetCounts(); success != 1 || failure != 0 {
- t.Fatalf("client observer counts = success:%d failure:%d, want success:1 failure:0", success, failure)
- }
- if success, failure := serverObserver.GetCounts(); success != 1 || failure != 0 {
- t.Fatalf("server observer counts = success:%d failure:%d, want success:1 failure:0", success, failure)
- }
-}
-
-func TestExecuteReturnsLivenessErrorWhenPeerDown(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
-
- serverHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(server) error = %v", err)
- }
-
- clientHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(client) error = %v", err)
- }
- defer func() { _ = clientHost.Close() }()
-
- target := peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()}
- if err := serverHost.Close(); err != nil {
- t.Fatalf("serverHost.Close() error = %v", err)
- }
-
- clientObserver := &testObserver{}
- passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{
- PeerID: clientHost.ID().String(),
- FederationID: "default",
- Subject: "sub",
- })
- if err != nil {
- t.Fatalf("IssuePassportBiscuit() error = %v", err)
- }
- if err := identity.SetLocalPassport(clientHost, "default", passport); err != nil {
- t.Fatalf("SetLocalPassport() error = %v", err)
- }
- _, err = Execute(ctx, clientHost, ExecuteRequest{
- Target: target,
- Biscuit: "test-biscuit",
- Payment: economy.Micropayment{Amount: 1, Asset: "sam-credit", Nonce: "n-2"},
- Request: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"ping"}}`),
- }, clientObserver)
- if err == nil {
- t.Fatalf("Execute() error = nil, want liveness error")
- }
- var liveErr *LivenessError
- if !errors.As(err, &liveErr) {
- t.Fatalf("Execute() error = %v, want LivenessError", err)
- }
- if clientObserver.failureCount == 0 {
- t.Fatalf("expected failure hook to be called")
- }
- if clientObserver.lastFailure != FailureTypeLiveness {
- t.Fatalf("failure type = %q, want %q", clientObserver.lastFailure, FailureTypeLiveness)
- }
-}
diff --git a/pkg/protocol/a2a/agent_card_adapter.go b/pkg/protocol/a2a/agent_card_adapter.go
deleted file mode 100644
index a89f3610..00000000
--- a/pkg/protocol/a2a/agent_card_adapter.go
+++ /dev/null
@@ -1,192 +0,0 @@
-// 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 a2a
-
-import (
- "fmt"
- "sort"
- "strings"
- "time"
-
- mcpprotocol "sam/pkg/protocol/mcp"
-
- a2asdk "github.com/a2aproject/a2a-go/v2/a2a"
-
- "sam/pkg/protocol/discovery"
-)
-
-// ToA2ACard converts a generic discovery AgentCard into the official A2A SDK representation.
-func ToA2ACard(card *discovery.AgentCard, interfaceURL string) (*a2asdk.AgentCard, error) {
- if card == nil {
- return nil, fmt.Errorf("agent card is nil")
- }
- if strings.TrimSpace(card.PeerID) == "" {
- return nil, fmt.Errorf("card peer ID is required")
- }
- if len(card.Capabilities) == 0 {
- return nil, fmt.Errorf("at least one capability is required")
- }
-
- out := synthesizeA2ACard(card)
- if strings.TrimSpace(interfaceURL) != "" {
- out.SupportedInterfaces = []*a2asdk.AgentInterface{
- a2asdk.NewAgentInterface(strings.TrimSpace(interfaceURL), a2asdk.TransportProtocolJSONRPC),
- }
- }
- return &out, nil
-}
-
-// AgentCardFromA2A converts an A2A SDK AgentCard into the generic discovery AgentCard.
-func AgentCardFromA2A(peerID string, card *a2asdk.AgentCard, resources []mcpprotocol.Resource) (*discovery.AgentCard, error) {
- if card == nil {
- return nil, fmt.Errorf("a2a agent card is nil")
- }
- peerID = strings.TrimSpace(peerID)
- if peerID == "" {
- return nil, fmt.Errorf("peer ID is required")
- }
-
- capabilities := make([]string, 0, len(card.Skills))
- for _, skill := range card.Skills {
- if id := strings.TrimSpace(skill.ID); id != "" {
- capabilities = append(capabilities, id)
- continue
- }
- if name := strings.TrimSpace(skill.Name); name != "" {
- capabilities = append(capabilities, name)
- }
- }
- if len(capabilities) == 0 {
- return nil, fmt.Errorf("a2a card must contain at least one skill")
- }
-
- out := &discovery.AgentCard{
- Capabilities: capabilitiesFromSkills(card.Skills),
- Tools: append([]discovery.Tool(nil), resources...),
- PeerID: peerID,
- IssuedAt: time.Now().UTC(),
- Algorithm: discovery.AgentCardSignAlgo,
- }
- mcpprotocol.SetResources(out, resources)
- return out, nil
-}
-
-func synthesizeA2ACard(card *discovery.AgentCard) a2asdk.AgentCard {
- out := a2asdk.AgentCard{
- Capabilities: a2asdk.AgentCapabilities{Streaming: true},
- Description: "SAM agent " + strings.TrimSpace(card.PeerID),
- Name: "sam-agent-" + strings.TrimSpace(card.PeerID),
- Skills: skillsFromCapabilities(card.Capabilities),
- Version: discovery.AgentCardVersion,
- }
- return normalizeA2ASDKCard(out)
-}
-
-func skillsFromCapabilities(in []string) []a2asdk.AgentSkill {
- out := make([]a2asdk.AgentSkill, 0, len(in))
- for _, capability := range in {
- identifier := strings.TrimSpace(capability)
- if identifier == "" {
- continue
- }
- out = append(out, a2asdk.AgentSkill{
- ID: identifier,
- Name: identifier,
- Description: "SAM capability " + identifier,
- Tags: []string{"sam"},
- })
- }
- return normalizeSkills(out)
-}
-
-func capabilitiesFromSkills(in []a2asdk.AgentSkill) []string {
- out := make([]string, 0, len(in))
- for _, skill := range in {
- identifier := strings.TrimSpace(skill.ID)
- if identifier == "" {
- identifier = strings.TrimSpace(skill.Name)
- }
- if identifier == "" {
- continue
- }
- out = append(out, identifier)
- }
- return discoveryNormalizeCapabilities(out)
-}
-
-func discoveryNormalizeCapabilities(capabilities []string) []string {
- seen := make(map[string]struct{}, len(capabilities))
- out := make([]string, 0, len(capabilities))
- for _, capability := range capabilities {
- capability = strings.ToLower(strings.TrimSpace(capability))
- if capability == "" {
- continue
- }
- if _, ok := seen[capability]; ok {
- continue
- }
- seen[capability] = struct{}{}
- out = append(out, capability)
- }
- sort.Strings(out)
- return out
-}
-
-func normalizeA2ASDKCard(card a2asdk.AgentCard) a2asdk.AgentCard {
- card.Skills = normalizeSkills(card.Skills)
- card.SupportedInterfaces = normalizeInterfaces(card.SupportedInterfaces)
- card.Signatures = nil
- return card
-}
-
-func normalizeSkills(skills []a2asdk.AgentSkill) []a2asdk.AgentSkill {
- cloned := append([]a2asdk.AgentSkill(nil), skills...)
- for index := range cloned {
- cloned[index].ID = strings.TrimSpace(cloned[index].ID)
- cloned[index].Name = strings.TrimSpace(cloned[index].Name)
- cloned[index].Description = strings.TrimSpace(cloned[index].Description)
- sort.Strings(cloned[index].Tags)
- sort.Strings(cloned[index].Examples)
- sort.Strings(cloned[index].InputModes)
- sort.Strings(cloned[index].OutputModes)
- }
- sort.Slice(cloned, func(i, j int) bool {
- if cloned[i].ID == cloned[j].ID {
- return cloned[i].Name < cloned[j].Name
- }
- return cloned[i].ID < cloned[j].ID
- })
- return cloned
-}
-
-func normalizeInterfaces(in []*a2asdk.AgentInterface) []*a2asdk.AgentInterface {
- cloned := make([]*a2asdk.AgentInterface, 0, len(in))
- for _, item := range in {
- if item == nil {
- continue
- }
- copyItem := *item
- copyItem.URL = strings.TrimSpace(copyItem.URL)
- copyItem.Tenant = strings.TrimSpace(copyItem.Tenant)
- cloned = append(cloned, &copyItem)
- }
- sort.Slice(cloned, func(i, j int) bool {
- if cloned[i].URL == cloned[j].URL {
- return cloned[i].Tenant < cloned[j].Tenant
- }
- return cloned[i].URL < cloned[j].URL
- })
- return cloned
-}
diff --git a/pkg/protocol/a2a/agent_card_adapter_test.go b/pkg/protocol/a2a/agent_card_adapter_test.go
deleted file mode 100644
index 5dc1d93d..00000000
--- a/pkg/protocol/a2a/agent_card_adapter_test.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// 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 a2a
-
-import (
- "testing"
-
- a2asdk "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/peer"
-
- "sam/pkg/protocol/discovery"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-func TestToA2ACard(t *testing.T) {
- priv, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pid, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card, err := discovery.NewAgentCard(
- pid,
- []string{"inference", "search"},
- []mcpprotocol.Resource{{Name: "mcp", Kind: "tool"}},
- priv,
- )
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
-
- a2aCard, err := ToA2ACard(card, "https://example.com/a2a")
- if err != nil {
- t.Fatalf("ToA2ACard() error = %v", err)
- }
- if a2aCard.Version != discovery.AgentCardVersion {
- t.Fatalf("a2a version = %q, want %q", a2aCard.Version, discovery.AgentCardVersion)
- }
- if len(a2aCard.Skills) != 2 {
- t.Fatalf("len(skills) = %d, want 2", len(a2aCard.Skills))
- }
- if len(a2aCard.SupportedInterfaces) != 1 {
- t.Fatalf("len(supportedInterfaces) = %d, want 1", len(a2aCard.SupportedInterfaces))
- }
-}
-
-func TestAgentCardFromA2A(t *testing.T) {
- a2aCard := &a2asdk.AgentCard{
- SupportedInterfaces: []*a2asdk.AgentInterface{a2asdk.NewAgentInterface("https://example.com/a2a", a2asdk.TransportProtocolJSONRPC)},
- Capabilities: a2asdk.AgentCapabilities{Streaming: true},
- DefaultInputModes: []string{"application/json"},
- DefaultOutputModes: []string{"application/json"},
- Description: "test",
- Name: "test-agent",
- Skills: []a2asdk.AgentSkill{
- {ID: "inference", Name: "Inference", Description: "run inference", Tags: []string{"sam"}},
- },
- Version: "a2a.v1",
- }
-
- card, err := AgentCardFromA2A("12D3KooWQK6Jk5hY5YAL3mVyYBVN1w8w5kZdeMNF8f9mJ5JPgX5R", a2aCard, nil)
- if err != nil {
- t.Fatalf("AgentCardFromA2A() error = %v", err)
- }
- resources := mcpprotocol.ResourcesFromCard(card)
- if len(resources) != 0 {
- t.Fatalf("len(resources) = %d, want 0", len(resources))
- }
- capabilities := card.CapabilityNames()
- if len(capabilities) != 1 || capabilities[0] != "inference" {
- t.Fatalf("capabilities = %#v, want [inference]", capabilities)
- }
- if card.Algorithm != discovery.AgentCardSignAlgo {
- t.Fatalf("algorithm = %q, want %q", card.Algorithm, discovery.AgentCardSignAlgo)
- }
-}
diff --git a/pkg/protocol/a2a/federation_gate.go b/pkg/protocol/a2a/federation_gate.go
deleted file mode 100644
index ec45e031..00000000
--- a/pkg/protocol/a2a/federation_gate.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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 a2a
-
-import (
- "context"
- "fmt"
- "strings"
-
- "sam/pkg/identity"
-)
-
-type passportClaimsContextKey struct{}
-
-func withAuthenticatedPassportClaims(ctx context.Context, claims *identity.PassportClaims) context.Context {
- return context.WithValue(ctx, passportClaimsContextKey{}, claims)
-}
-
-func authenticatedPassportClaimsFromContext(ctx context.Context) (*identity.PassportClaims, bool) {
- claims, ok := ctx.Value(passportClaimsContextKey{}).(*identity.PassportClaims)
- if !ok || claims == nil {
- return nil, false
- }
- return claims, true
-}
-
-// PassportGate is a FederationGate that allows a peer only when it presents a
-// valid passport biscuit bound to the peer and federation.
-type PassportGate struct {
- federationID string
-}
-
-// NewPassportGate creates a gate scoped to the default federation.
-func NewPassportGate() *PassportGate {
- return &PassportGate{federationID: "default"}
-}
-
-// NewPassportGateWithCleanup returns a passport gate and a no-op close function
-// for compatibility with setup call-sites expecting a cleanup callback.
-func NewPassportGateWithCleanup() (*PassportGate, func() error, error) {
- return NewPassportGate(), func() error { return nil }, nil
-}
-
-// Allow returns nil when the requester has authenticated passport claims.
-func (g *PassportGate) Allow(ctx context.Context, peerID string, _ string) error {
- if peerID == "" {
- return fmt.Errorf("empty peer ID")
- }
- claims, ok := authenticatedPassportClaimsFromContext(ctx)
- if !ok {
- return fmt.Errorf("authentication error: missing authenticated passport claims")
- }
- if strings.TrimSpace(claims.PeerID) != strings.TrimSpace(peerID) {
- return fmt.Errorf("authentication error: authenticated peer mismatch")
- }
- if strings.TrimSpace(g.federationID) != "" && strings.TrimSpace(claims.FederationID) != strings.TrimSpace(g.federationID) {
- return fmt.Errorf("authentication error: passport federation mismatch")
- }
- return nil
-}
diff --git a/pkg/protocol/a2a/federation_gate_test.go b/pkg/protocol/a2a/federation_gate_test.go
deleted file mode 100644
index fd1c5bf4..00000000
--- a/pkg/protocol/a2a/federation_gate_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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 a2a
-
-import (
- "context"
- "strings"
- "testing"
-
- "sam/pkg/identity"
-)
-
-func TestPassportGateRejectsAudienceMismatch(t *testing.T) {
- passport, err := identity.IssuePassportBiscuit(context.Background(), identity.PassportIssueRequest{
- PeerID: "12D3KooWTestPeer",
- FederationID: "Federation-A",
- Subject: "sub-1",
- })
- if err != nil {
- t.Fatalf("issuing passport: %v", err)
- }
- claims, err := identity.ValidatePassportBiscuit(context.Background(), passport, "12D3KooWTestPeer", "")
- if err != nil {
- t.Fatalf("validating passport: %v", err)
- }
- gate := NewPassportGate()
- err = gate.Allow(withAuthenticatedPassportClaims(context.Background(), claims), "12D3KooWTestPeer", "writer")
- if err == nil {
- t.Fatalf("expected audience mismatch error, got nil")
- }
- if !strings.Contains(err.Error(), "passport federation mismatch") {
- t.Fatalf("unexpected error: %v", err)
- }
-}
diff --git a/pkg/protocol/a2a/observer_db.go b/pkg/protocol/a2a/observer_db.go
deleted file mode 100644
index 0f6af353..00000000
--- a/pkg/protocol/a2a/observer_db.go
+++ /dev/null
@@ -1,120 +0,0 @@
-// 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 a2a
-
-import (
- "context"
- "fmt"
- "strings"
- "sync"
- "time"
-
- internaldb "sam/internal/db"
-)
-
-const reputationRecordVersion = 1
-
-type reputationRecord struct {
- PeerID string `json:"peer_id"`
- OK bool `json:"ok"`
- LatencyMS int64 `json:"latency_ms,omitempty"`
- ErrorType string `json:"error_type,omitempty"`
-}
-
-// BoltObserver persists A2A success/failure events for local reputation tracking.
-type BoltObserver struct {
- mu sync.Mutex
- store internaldb.Store
- codec internaldb.Codec
-}
-
-// DefaultBoltObserver opens ~/.config/sam/state.db.
-func DefaultBoltObserver() (*BoltObserver, error) {
- store, err := internaldb.OpenDefault()
- if err != nil {
- return nil, fmt.Errorf("opening default state store: %w", err)
- }
- return &BoltObserver{store: store, codec: internaldb.JSONCodec{}}, nil
-}
-
-// NewBoltObserver opens or creates an observer database at path.
-func NewBoltObserver(path string) (*BoltObserver, error) {
- store, err := internaldb.Open(path)
- if err != nil {
- return nil, fmt.Errorf("opening state store: %w", err)
- }
- return &BoltObserver{store: store, codec: internaldb.JSONCodec{}}, nil
-}
-
-// NewBoltObserverForFederation opens a reputation observer scoped to the given
-// federation name. The database is stored at
-// ~/.config/sam/federations/<name>.db.
-func NewBoltObserverForFederation(fedID string) (*BoltObserver, error) {
- fedID = strings.TrimSpace(fedID)
- if fedID == "" {
- fedID = "default"
- }
- mgr, err := internaldb.NewManager()
- if err != nil {
- return nil, fmt.Errorf("creating federation manager: %w", err)
- }
- store, err := mgr.Store(fedID)
- if err != nil {
- _ = mgr.Close()
- return nil, fmt.Errorf("opening federation %q store: %w", fedID, err)
- }
- return &BoltObserver{store: store, codec: internaldb.JSONCodec{}}, nil
-}
-
-// NewBoltObserverWithFallback prefers federation-scoped storage and falls back
-// to default state storage when federation manager setup is unavailable.
-func NewBoltObserverWithFallback(fedID string) (*BoltObserver, error) {
- observer, err := NewBoltObserverForFederation(fedID)
- if err == nil {
- return observer, nil
- }
- fallback, fallbackErr := DefaultBoltObserver()
- if fallbackErr != nil {
- return nil, fmt.Errorf("creating federation observer: %v; fallback failed: %w", err, fallbackErr)
- }
- return fallback, nil
-}
-
-func (o *BoltObserver) OnSuccess(peerID string, latency time.Duration) {
- o.writeRecord(peerID, reputationRecord{PeerID: peerID, OK: true, LatencyMS: latency.Milliseconds()})
-}
-
-func (o *BoltObserver) OnFailure(peerID string, errorType string) {
- o.writeRecord(peerID, reputationRecord{PeerID: peerID, OK: false, ErrorType: errorType})
-}
-
-func (o *BoltObserver) writeRecord(peerID string, rec reputationRecord) {
- o.mu.Lock()
- defer o.mu.Unlock()
- key := fmt.Sprintf("%s/%020d", peerID, time.Now().UTC().UnixNano())
- encoded, err := o.codec.Marshal(reputationRecordVersion, rec)
- if err != nil {
- return
- }
- _ = o.store.Put(context.Background(), internaldb.BucketReputation, key, encoded)
-}
-
-// Close closes the underlying store handle.
-func (o *BoltObserver) Close() error {
- if o == nil || o.store == nil {
- return nil
- }
- return o.store.Close()
-}
diff --git a/pkg/protocol/auth/auth.go b/pkg/protocol/auth/auth.go
deleted file mode 100644
index 19ac374b..00000000
--- a/pkg/protocol/auth/auth.go
+++ /dev/null
@@ -1,22 +0,0 @@
-// 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 auth contains shared connection authorization hooks used by mesh
-// protocols (A2A, HTTP tunnel, MCP bridge).
-package auth
-
-import "sam/pkg/protocol/middleware"
-
-type ConnectionAuthz = middleware.ConnectionAuthz
-type PassportAuthz = middleware.PassportAuthz
diff --git a/pkg/protocol/discovery/agent_card.go b/pkg/protocol/discovery/agent_card.go
deleted file mode 100644
index 734fde01..00000000
--- a/pkg/protocol/discovery/agent_card.go
+++ /dev/null
@@ -1,242 +0,0 @@
-// 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 discovery
-
-import (
- "encoding/base64"
- "encoding/json"
- "fmt"
- "sort"
- "strings"
- "time"
-
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/peer"
-)
-
-const (
- AgentCardVersion = "a2a.v1"
- AgentCardSignAlgo = "libp2p-ed25519"
- AgentDHTNamespaceBase = "/sam/v1/agents/"
-)
-
-// Tool describes an advertised local tool endpoint.
-type Tool struct {
- Name string `json:"name"`
- Kind string `json:"kind"`
- Endpoint string `json:"endpoint,omitempty"`
- Description string `json:"description,omitempty"`
-}
-
-// AgentCard is the signed capability document advertised in the SAM mesh.
-//
-// The signature covers all fields except Signature.
-type AgentCard struct {
- PeerID string `json:"peer_id"`
- Capabilities []string `json:"capabilities"`
- Tools []Tool `json:"tools,omitempty"`
- IssuedAt time.Time `json:"issued_at"`
- Algorithm string `json:"alg"`
- Signature string `json:"signature"`
-}
-
-type agentCardPayload struct {
- PeerID string `json:"peer_id"`
- Capabilities []string `json:"capabilities"`
- Tools []Tool `json:"tools,omitempty"`
- IssuedAt time.Time `json:"issued_at"`
- Algorithm string `json:"alg"`
-}
-
-// NewAgentCard builds and signs an AgentCard for DHT advertisement.
-func NewAgentCard(peerID peer.ID, capabilities []string, tools []Tool, privateKey crypto.PrivKey) (*AgentCard, error) {
- if privateKey == nil {
- return nil, fmt.Errorf("private key is required")
- }
- if peerID == "" {
- return nil, fmt.Errorf("peer ID is required")
- }
- normalizedCaps := normalizeCapabilities(capabilities)
- if len(normalizedCaps) == 0 {
- return nil, fmt.Errorf("at least one capability is required")
- }
-
- card := &AgentCard{
- Capabilities: normalizedCaps,
- Tools: normalizeTools(tools),
- PeerID: peerID.String(),
- IssuedAt: time.Now().UTC(),
- Algorithm: AgentCardSignAlgo,
- }
-
- if err := SignAgentCard(card, privateKey); err != nil {
- return nil, err
- }
-
- return card, nil
-}
-
-// SignAgentCard signs the card payload using the node private key.
-func SignAgentCard(card *AgentCard, privateKey crypto.PrivKey) error {
- if card == nil {
- return fmt.Errorf("agent card is nil")
- }
- if privateKey == nil {
- return fmt.Errorf("private key is required")
- }
- if err := card.validateBase(); err != nil {
- return err
- }
-
- payload, err := card.signingPayload()
- if err != nil {
- return fmt.Errorf("encoding card payload: %w", err)
- }
-
- sig, err := privateKey.Sign(payload)
- if err != nil {
- return fmt.Errorf("signing card payload: %w", err)
- }
- card.Signature = base64.RawURLEncoding.EncodeToString(sig)
- return nil
-}
-
-// VerifyAgentCard verifies card integrity and signature against the embedded PeerID.
-func VerifyAgentCard(card *AgentCard) error {
- if card == nil {
- return fmt.Errorf("agent card is nil")
- }
- if err := card.validateBase(); err != nil {
- return err
- }
- if strings.TrimSpace(card.Signature) == "" {
- return fmt.Errorf("card signature is required")
- }
-
- pid, err := peer.Decode(card.PeerID)
- if err != nil {
- return fmt.Errorf("invalid peer ID %q: %w", card.PeerID, err)
- }
- pub, err := pid.ExtractPublicKey()
- if err != nil {
- return fmt.Errorf("extracting public key from peer ID: %w", err)
- }
-
- payload, err := card.signingPayload()
- if err != nil {
- return fmt.Errorf("encoding card payload: %w", err)
- }
-
- sig, err := base64.RawURLEncoding.DecodeString(card.Signature)
- if err != nil {
- return fmt.Errorf("decoding signature: %w", err)
- }
-
- ok, err := pub.Verify(payload, sig)
- if err != nil {
- return fmt.Errorf("verifying signature: %w", err)
- }
- if !ok {
- return fmt.Errorf("agent card signature invalid")
- }
- return nil
-}
-
-// Sign signs the current card payload using the provided private key.
-func (c *AgentCard) Sign(privateKey crypto.PrivKey) error {
- return SignAgentCard(c, privateKey)
-}
-
-// Verify checks card integrity and signature against the embedded PeerID.
-func (c *AgentCard) Verify() error {
- return VerifyAgentCard(c)
-}
-
-func (c *AgentCard) validateBase() error {
- if strings.TrimSpace(c.PeerID) == "" {
- return fmt.Errorf("card peer ID is required")
- }
- if _, err := peer.Decode(c.PeerID); err != nil {
- return fmt.Errorf("invalid peer ID %q: %w", c.PeerID, err)
- }
- if len(normalizeCapabilities(c.Capabilities)) == 0 {
- return fmt.Errorf("at least one capability is required")
- }
- if c.IssuedAt.IsZero() {
- return fmt.Errorf("card issued_at is required")
- }
- if strings.TrimSpace(c.Algorithm) == "" {
- return fmt.Errorf("signature algorithm is required")
- }
- return nil
-}
-
-func (c *AgentCard) signingPayload() ([]byte, error) {
- p := agentCardPayload{
- PeerID: c.PeerID,
- Capabilities: normalizeCapabilities(c.Capabilities),
- Tools: normalizeTools(c.Tools),
- IssuedAt: c.IssuedAt.UTC(),
- Algorithm: c.Algorithm,
- }
- return json.Marshal(p)
-}
-
-// CapabilityNames returns normalized capability identifiers.
-func (c *AgentCard) CapabilityNames() []string {
- if c == nil {
- return nil
- }
- return normalizeCapabilities(c.Capabilities)
-}
-
-func normalizeCapabilities(capabilities []string) []string {
- seen := make(map[string]struct{}, len(capabilities))
- out := make([]string, 0, len(capabilities))
- for _, c := range capabilities {
- n := strings.ToLower(strings.TrimSpace(c))
- if n == "" {
- continue
- }
- if _, ok := seen[n]; ok {
- continue
- }
- seen[n] = struct{}{}
- out = append(out, n)
- }
- sort.Strings(out)
- return out
-}
-
-func normalizeTools(tools []Tool) []Tool {
- out := make([]Tool, 0, len(tools))
- for _, tool := range tools {
- tool.Name = strings.TrimSpace(tool.Name)
- tool.Kind = strings.TrimSpace(tool.Kind)
- tool.Endpoint = strings.TrimSpace(tool.Endpoint)
- tool.Description = strings.TrimSpace(tool.Description)
- if tool.Name == "" {
- continue
- }
- out = append(out, tool)
- }
- sort.Slice(out, func(i, j int) bool {
- if out[i].Name == out[j].Name {
- return out[i].Kind < out[j].Kind
- }
- return out[i].Name < out[j].Name
- })
- return out
-}
diff --git a/pkg/protocol/discovery/agent_card_test.go b/pkg/protocol/discovery/agent_card_test.go
deleted file mode 100644
index 5b10d44e..00000000
--- a/pkg/protocol/discovery/agent_card_test.go
+++ /dev/null
@@ -1,105 +0,0 @@
-// 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 discovery_test
-
-import (
- "testing"
- "time"
-
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/peer"
-
- protocol "sam/pkg/protocol/discovery"
- mcpprotocol "sam/pkg/protocol/mcp"
-)
-
-func TestAgentCardSignVerify(t *testing.T) {
- priv, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pid, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card, err := protocol.NewAgentCard(
- pid,
- []string{"Inference", "search", "search"},
- []mcpprotocol.Resource{{Name: "local-mcp", Kind: "tool", Endpoint: "unix:///tmp/mcp.sock"}},
- priv,
- )
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
-
- if err := protocol.VerifyAgentCard(card); err != nil {
- t.Fatalf("VerifyAgentCard() error = %v", err)
- }
-
- capabilities := card.CapabilityNames()
- if len(capabilities) != 2 || capabilities[0] != "inference" || capabilities[1] != "search" {
- t.Fatalf("normalized capabilities = %#v, want [inference search]", capabilities)
- }
-}
-
-func TestAgentCardVerifyRejectsTamper(t *testing.T) {
- priv, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pid, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card, err := protocol.NewAgentCard(
- pid,
- []string{"inference"},
- nil,
- priv,
- )
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
-
- card.Capabilities = append(card.Capabilities, card.Capabilities[0])
- card.Capabilities[1] = "search"
- if err := protocol.VerifyAgentCard(card); err == nil {
- t.Fatal("VerifyAgentCard() should fail for tampered card")
- }
-}
-
-func TestAgentCardVerifyRejectsMissingSignature(t *testing.T) {
- priv, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pid, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card := &protocol.AgentCard{
- Capabilities: []string{"inference"},
- PeerID: pid.String(),
- IssuedAt: time.Now().UTC(),
- Algorithm: protocol.AgentCardSignAlgo,
- }
-
- if err := protocol.VerifyAgentCard(card); err == nil {
- t.Fatal("VerifyAgentCard() should fail without signature")
- }
-}
diff --git a/pkg/protocol/discovery/discovery.go b/pkg/protocol/discovery/discovery.go
deleted file mode 100644
index dfc4b2e3..00000000
--- a/pkg/protocol/discovery/discovery.go
+++ /dev/null
@@ -1,310 +0,0 @@
-// 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 discovery
-
-import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "sync"
- "time"
-
- "github.com/libp2p/go-libp2p/core/network"
- "github.com/libp2p/go-libp2p/core/peer"
-
- samnet "sam/pkg/net"
-)
-
-const (
- AgentCardProtocolID = "/sam/agentcard/1.0"
- // maxDHTCardAge bounds how old a DHT card can be before we prefer a direct
- // stream fetch from the peer.
- maxDHTCardAge = 15 * time.Minute
-)
-
-type cardFetchSource int
-
-const (
- cardFromDHT cardFetchSource = iota
- cardFromStream
-)
-
-// DiscoveryService discovers and validates AgentCards over DHT and libp2p.
-type DiscoveryService struct {
- node samnet.Node
- // maxDHTCardAge bounds accepted DHT card freshness.
- // When <= 0, freshness checks are disabled.
- maxDHTCardAge time.Duration
-
- mu sync.RWMutex
- localCard *AgentCard
-}
-
-// DiscoveryOption configures DiscoveryService behavior.
-type DiscoveryOption func(*DiscoveryService) error
-
-// WithMaxDHTCardAge sets the freshness bound for DHT-fetched cards.
-// A value <= 0 disables freshness checks.
-func WithMaxDHTCardAge(maxAge time.Duration) DiscoveryOption {
- return func(s *DiscoveryService) error {
- s.maxDHTCardAge = maxAge
- return nil
- }
-}
-
-// NewDiscoveryService creates a discovery service backed by a SAM node.
-func NewDiscoveryService(node samnet.Node, opts ...DiscoveryOption) (*DiscoveryService, error) {
- if node == nil {
- return nil, fmt.Errorf("node is nil")
- }
- if node.Host() == nil {
- return nil, fmt.Errorf("node host is nil")
- }
-
- s := &DiscoveryService{
- node: node,
- maxDHTCardAge: maxDHTCardAge,
- }
- for _, opt := range opts {
- if err := opt(s); err != nil {
- return nil, fmt.Errorf("applying discovery option: %w", err)
- }
- }
- return s, nil
-}
-
-// RegisterLocalCard stores the local card and serves it over AgentCardProtocolID.
-func (s *DiscoveryService) RegisterLocalCard(card *AgentCard) error {
- if card == nil {
- return fmt.Errorf("local card is nil")
- }
- if err := VerifyAgentCard(card); err != nil {
- return fmt.Errorf("invalid local card: %w", err)
- }
- if card.PeerID != s.node.PeerID().String() {
- return fmt.Errorf("local card peer ID %q does not match node peer ID %q", card.PeerID, s.node.PeerID())
- }
-
- s.mu.Lock()
- s.localCard = card
- s.mu.Unlock()
-
- s.node.Host().SetStreamHandler(AgentCardProtocolID, s.handleAgentCardStream)
- return nil
-}
-
-// Discover resolves providers for a capability namespace and returns verified cards.
-func (s *DiscoveryService) Discover(ctx context.Context, capability string) ([]*AgentCard, error) {
- peers, err := s.DiscoverPeers(ctx, capability)
- if err != nil {
- return nil, err
- }
-
- cards := make([]*AgentCard, 0)
- for _, pi := range peers {
- card, src, err := s.fetchCard(ctx, pi)
- if err != nil {
- continue
- }
- if !hasCapability(card, capability) && src == cardFromDHT {
- // DHT can lag behind recent card updates; retry over direct stream.
- streamCard, streamErr := s.fetchCardFromStream(ctx, pi)
- if streamErr == nil && hasCapability(streamCard, capability) {
- card = streamCard
- } else {
- continue
- }
- }
- cards = append(cards, card)
- }
-
- return cards, nil
-}
-
-// DiscoverPeers resolves providers for a capability namespace and returns
-// unique peer addresses suitable for direct libp2p connection attempts.
-func (s *DiscoveryService) DiscoverPeers(ctx context.Context, capability string) ([]peer.AddrInfo, error) {
- capNS := AgentCapabilityNamespace(capability)
- ch, err := s.node.Discover(ctx, capNS)
- if err != nil {
- return nil, fmt.Errorf("discovering namespace %q: %w", capNS, err)
- }
-
- seen := map[string]struct{}{}
- peers := make([]peer.AddrInfo, 0)
- localPeerID := s.node.PeerID()
-
- for pi := range ch {
- if pi.ID == "" || pi.ID == localPeerID {
- continue
- }
- if _, ok := seen[pi.ID.String()]; ok {
- continue
- }
- seen[pi.ID.String()] = struct{}{}
- peers = append(peers, pi)
- }
-
- return peers, nil
-}
-
-// DiscoverPeerIDs returns unique peer IDs for a capability using DHT-only lookup.
-func (s *DiscoveryService) DiscoverPeerIDs(ctx context.Context, capability string) ([]peer.ID, error) {
- peers, err := s.DiscoverPeers(ctx, capability)
- if err != nil {
- return nil, err
- }
- ids := make([]peer.ID, 0, len(peers))
- for _, pi := range peers {
- ids = append(ids, pi.ID)
- }
- return ids, nil
-}
-
-// ConnectPeers attempts direct connection to every discovered peer. libp2p
-// handles NAT traversal via relay and DCUtR hole-punching internally.
-func (s *DiscoveryService) ConnectPeers(ctx context.Context, peers []peer.AddrInfo) ([]peer.ID, error) {
- connected := make([]peer.ID, 0, len(peers))
- var errs []error
-
- for _, pi := range peers {
- if pi.ID == "" {
- continue
- }
- if err := s.node.Connect(ctx, pi); err != nil {
- errs = append(errs, fmt.Errorf("connecting to %s: %w", pi.ID, err))
- continue
- }
- connected = append(connected, pi.ID)
- }
-
- return connected, errors.Join(errs...)
-}
-
-// DiscoverAll fetches AgentCards from every peer the local node is currently
-// connected to that speaks AgentCardProtocolID. It is suitable for listing
-// all known agents without filtering by capability.
-func (s *DiscoveryService) DiscoverAll(ctx context.Context) ([]*AgentCard, error) {
- peers := s.node.Host().Network().Peers()
- cards := make([]*AgentCard, 0, len(peers))
- for _, id := range peers {
- addrs := s.node.Host().Peerstore().Addrs(id)
- pi := peer.AddrInfo{ID: id, Addrs: addrs}
- card, _, err := s.fetchCard(ctx, pi)
- if err != nil {
- continue
- }
- cards = append(cards, card)
- }
- return cards, nil
-}
-
-// DiscoverAndConnect discovers peers for a capability and directly connects to
-// each one before task execution begins.
-func (s *DiscoveryService) DiscoverAndConnect(ctx context.Context, capability string) ([]peer.ID, error) {
- peers, err := s.DiscoverPeers(ctx, capability)
- if err != nil {
- return nil, err
- }
- return s.ConnectPeers(ctx, peers)
-}
-
-func (s *DiscoveryService) fetchCard(ctx context.Context, pi peer.AddrInfo) (*AgentCard, cardFetchSource, error) {
- card, err := s.fetchCardFromDHT(ctx, pi.ID.String())
- if err == nil {
- return card, cardFromDHT, nil
- }
-
- card, err = s.fetchCardFromStream(ctx, pi)
- if err != nil {
- return nil, cardFromStream, err
- }
- return card, cardFromStream, nil
-}
-
-func (s *DiscoveryService) fetchCardFromDHT(ctx context.Context, peerID string) (*AgentCard, error) {
- key := DHTPeerCardKey(peerID)
- raw, err := s.node.GetValue(ctx, key)
- if err != nil {
- return nil, fmt.Errorf("reading DHT card key %q: %w", key, err)
- }
-
- var card AgentCard
- if err := json.Unmarshal(raw, &card); err != nil {
- return nil, fmt.Errorf("decoding DHT card for %s: %w", peerID, err)
- }
- if err := VerifyAgentCard(&card); err != nil {
- return nil, fmt.Errorf("validating DHT card for %s: %w", peerID, err)
- }
- if card.PeerID != peerID {
- return nil, fmt.Errorf("DHT card peer ID %q mismatch for key peer %q", card.PeerID, peerID)
- }
- if s.maxDHTCardAge > 0 && time.Since(card.IssuedAt) > s.maxDHTCardAge {
- return nil, fmt.Errorf("DHT card for %s is stale", peerID)
- }
- return &card, nil
-}
-
-func (s *DiscoveryService) fetchCardFromStream(ctx context.Context, pi peer.AddrInfo) (*AgentCard, error) {
- if err := s.node.Connect(ctx, pi); err != nil {
- return nil, fmt.Errorf("connecting to peer %s: %w", pi.ID, err)
- }
-
- stream, err := s.node.Host().NewStream(ctx, pi.ID, AgentCardProtocolID)
- if err != nil {
- return nil, fmt.Errorf("opening card stream to %s: %w", pi.ID, err)
- }
- defer func() { _ = stream.Close() }()
-
- var card AgentCard
- if err := json.NewDecoder(stream).Decode(&card); err != nil {
- return nil, fmt.Errorf("decoding agent card from %s: %w", pi.ID, err)
- }
- if err := VerifyAgentCard(&card); err != nil {
- return nil, fmt.Errorf("validating stream card from %s: %w", pi.ID, err)
- }
- if card.PeerID != pi.ID.String() {
- return nil, fmt.Errorf("stream card peer ID %q mismatch for peer %q", card.PeerID, pi.ID)
- }
- return &card, nil
-}
-
-func (s *DiscoveryService) handleAgentCardStream(stream network.Stream) {
- defer func() { _ = stream.Close() }()
-
- s.mu.RLock()
- card := s.localCard
- s.mu.RUnlock()
-
- if card == nil {
- _, _ = io.WriteString(stream, `{"error":"agent card not registered"}`)
- return
- }
- if err := json.NewEncoder(stream).Encode(card); err != nil {
- _ = stream.Reset()
- }
-}
-
-func hasCapability(card *AgentCard, capability string) bool {
- want := AgentCapabilityNamespace(capability)
- for _, c := range card.CapabilityNames() {
- if AgentCapabilityNamespace(c) == want {
- return true
- }
- }
- return false
-}
diff --git a/pkg/protocol/discovery/discovery_test.go b/pkg/protocol/discovery/discovery_test.go
deleted file mode 100644
index 1f6eed54..00000000
--- a/pkg/protocol/discovery/discovery_test.go
+++ /dev/null
@@ -1,396 +0,0 @@
-// 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 discovery_test
-
-import (
- "context"
- cryptorand "crypto/rand"
- "encoding/json"
- "testing"
- "time"
-
- "github.com/libp2p/go-libp2p"
- dht "github.com/libp2p/go-libp2p-kad-dht"
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/network"
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/multiformats/go-multiaddr"
-
- samnet "sam/pkg/net"
- protocol "sam/pkg/protocol/discovery"
-)
-
-type fakeDiscoveryNode struct {
- host host.Host
- peerID peer.ID
- discoverCh chan peer.AddrInfo
- dhtValues map[string][]byte
-}
-
-func (f *fakeDiscoveryNode) Start(context.Context) error { return nil }
-func (f *fakeDiscoveryNode) Stop(context.Context) error { return nil }
-func (f *fakeDiscoveryNode) Host() host.Host { return f.host }
-func (f *fakeDiscoveryNode) DHT() *dht.IpfsDHT { return nil }
-func (f *fakeDiscoveryNode) PeerID() peer.ID { return f.peerID }
-func (f *fakeDiscoveryNode) Addrs() []multiaddr.Multiaddr {
- return f.host.Addrs()
-}
-func (f *fakeDiscoveryNode) Announce(context.Context, string) error { return nil }
-func (f *fakeDiscoveryNode) PutValue(_ context.Context, key string, value []byte) error {
- if f.dhtValues == nil {
- f.dhtValues = map[string][]byte{}
- }
- f.dhtValues[key] = append([]byte(nil), value...)
- return nil
-}
-func (f *fakeDiscoveryNode) GetValue(_ context.Context, key string) ([]byte, error) {
- v, ok := f.dhtValues[key]
- if !ok {
- return nil, context.Canceled
- }
- return append([]byte(nil), v...), nil
-}
-func (f *fakeDiscoveryNode) Discover(context.Context, string) (<-chan peer.AddrInfo, error) {
- return f.discoverCh, nil
-}
-func (f *fakeDiscoveryNode) Connect(ctx context.Context, pi peer.AddrInfo) error {
- return f.host.Connect(ctx, pi)
-}
-
-var _ samnet.Node = (*fakeDiscoveryNode)(nil)
-
-func TestDiscoverReturnsVerifiedCards(t *testing.T) {
- ctx := context.Background()
-
- providerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New provider error = %v", err)
- }
- defer func() { _ = providerHost.Close() }()
-
- consumerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New consumer error = %v", err)
- }
- defer func() { _ = consumerHost.Close() }()
-
- providerPriv := providerHost.Peerstore().PrivKey(providerHost.ID())
- card, err := protocol.NewAgentCard(providerHost.ID(), []string{"inference"}, nil, providerPriv)
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
-
- providerHost.SetStreamHandler(protocol.AgentCardProtocolID, func(s network.Stream) {
- defer func() { _ = s.Close() }()
- _ = json.NewEncoder(s).Encode(card)
- })
-
- ch := make(chan peer.AddrInfo, 1)
- ch <- peer.AddrInfo{ID: providerHost.ID(), Addrs: providerHost.Addrs()}
- close(ch)
-
- node := &fakeDiscoveryNode{host: consumerHost, peerID: consumerHost.ID(), discoverCh: ch}
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- t.Fatalf("NewDiscoveryService() error = %v", err)
- }
-
- cards, err := svc.Discover(ctx, "inference")
- if err != nil {
- t.Fatalf("Discover() error = %v", err)
- }
- if len(cards) != 1 {
- t.Fatalf("len(cards) = %d, want 1", len(cards))
- }
- if cards[0].PeerID != providerHost.ID().String() {
- t.Fatalf("card peer ID = %q, want %q", cards[0].PeerID, providerHost.ID())
- }
-}
-
-func TestDiscoverPeerIDsReturnsUniqueRemotePeers(t *testing.T) {
- ctx := context.Background()
-
- consumerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New consumer error = %v", err)
- }
- defer func() { _ = consumerHost.Close() }()
-
- providerA, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New providerA error = %v", err)
- }
- defer func() { _ = providerA.Close() }()
-
- providerB, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New providerB error = %v", err)
- }
- defer func() { _ = providerB.Close() }()
-
- ch := make(chan peer.AddrInfo, 5)
- ch <- peer.AddrInfo{ID: providerA.ID(), Addrs: providerA.Addrs()}
- ch <- peer.AddrInfo{ID: providerA.ID(), Addrs: providerA.Addrs()}
- ch <- peer.AddrInfo{ID: consumerHost.ID(), Addrs: consumerHost.Addrs()}
- ch <- peer.AddrInfo{ID: providerB.ID(), Addrs: providerB.Addrs()}
- close(ch)
-
- node := &fakeDiscoveryNode{host: consumerHost, peerID: consumerHost.ID(), discoverCh: ch}
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- t.Fatalf("NewDiscoveryService() error = %v", err)
- }
-
- ids, err := svc.DiscoverPeerIDs(ctx, "inference")
- if err != nil {
- t.Fatalf("DiscoverPeerIDs() error = %v", err)
- }
- if len(ids) != 2 {
- t.Fatalf("len(ids) = %d, want 2", len(ids))
- }
- seen := map[peer.ID]struct{}{}
- for _, id := range ids {
- seen[id] = struct{}{}
- }
- if _, ok := seen[providerA.ID()]; !ok {
- t.Fatalf("providerA peer ID missing from discovered IDs")
- }
- if _, ok := seen[providerB.ID()]; !ok {
- t.Fatalf("providerB peer ID missing from discovered IDs")
- }
-}
-
-func TestDiscoverAndConnectReturnsPartialSuccess(t *testing.T) {
- ctx := context.Background()
-
- consumerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New consumer error = %v", err)
- }
- defer func() { _ = consumerHost.Close() }()
-
- provider, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New provider error = %v", err)
- }
- defer func() { _ = provider.Close() }()
-
- priv, _, err := crypto.GenerateEd25519Key(cryptorand.Reader)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- unreachableID, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- ch := make(chan peer.AddrInfo, 2)
- ch <- peer.AddrInfo{ID: provider.ID(), Addrs: provider.Addrs()}
- ch <- peer.AddrInfo{ID: unreachableID}
- close(ch)
-
- node := &fakeDiscoveryNode{host: consumerHost, peerID: consumerHost.ID(), discoverCh: ch}
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- t.Fatalf("NewDiscoveryService() error = %v", err)
- }
-
- connected, err := svc.DiscoverAndConnect(ctx, "inference")
- if len(connected) != 1 || connected[0] != provider.ID() {
- t.Fatalf("connected = %#v, want [%s]", connected, provider.ID())
- }
- if err == nil {
- t.Fatal("DiscoverAndConnect() expected partial connect error, got nil")
- }
- if got := err.Error(); got == "" {
- t.Fatal("DiscoverAndConnect() error should include failed connect detail")
- }
-}
-
-func TestDiscoverPrefersDHTCard(t *testing.T) {
- ctx := context.Background()
-
- consumerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New consumer error = %v", err)
- }
- defer func() { _ = consumerHost.Close() }()
-
- priv, _, err := crypto.GenerateEd25519Key(cryptorand.Reader)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- providerID, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card, err := protocol.NewAgentCard(providerID, []string{"inference"}, nil, priv)
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
- raw, err := json.Marshal(card)
- if err != nil {
- t.Fatalf("json.Marshal(card) error = %v", err)
- }
-
- ch := make(chan peer.AddrInfo, 1)
- ch <- peer.AddrInfo{ID: providerID}
- close(ch)
-
- node := &fakeDiscoveryNode{
- host: consumerHost,
- peerID: consumerHost.ID(),
- discoverCh: ch,
- dhtValues: map[string][]byte{
- protocol.DHTPeerCardKey(providerID.String()): raw,
- },
- }
-
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- t.Fatalf("NewDiscoveryService() error = %v", err)
- }
-
- cards, err := svc.Discover(ctx, "inference")
- if err != nil {
- t.Fatalf("Discover() error = %v", err)
- }
- if len(cards) != 1 {
- t.Fatalf("len(cards) = %d, want 1", len(cards))
- }
- if cards[0].PeerID != providerID.String() {
- t.Fatalf("card peer ID = %q, want %q", cards[0].PeerID, providerID)
- }
-}
-
-func TestDiscoverFallsBackToStreamWhenDHTCardInvalid(t *testing.T) {
- ctx := context.Background()
-
- providerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New provider error = %v", err)
- }
- defer func() { _ = providerHost.Close() }()
-
- consumerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New consumer error = %v", err)
- }
- defer func() { _ = consumerHost.Close() }()
-
- providerPriv := providerHost.Peerstore().PrivKey(providerHost.ID())
- card, err := protocol.NewAgentCard(providerHost.ID(), []string{"inference"}, nil, providerPriv)
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
-
- providerHost.SetStreamHandler(protocol.AgentCardProtocolID, func(s network.Stream) {
- defer func() { _ = s.Close() }()
- _ = json.NewEncoder(s).Encode(card)
- })
-
- ch := make(chan peer.AddrInfo, 1)
- ch <- peer.AddrInfo{ID: providerHost.ID(), Addrs: providerHost.Addrs()}
- close(ch)
-
- node := &fakeDiscoveryNode{
- host: consumerHost,
- peerID: consumerHost.ID(),
- discoverCh: ch,
- dhtValues: map[string][]byte{
- protocol.DHTPeerCardKey(providerHost.ID().String()): []byte("not-json"),
- },
- }
-
- svc, err := protocol.NewDiscoveryService(node)
- if err != nil {
- t.Fatalf("NewDiscoveryService() error = %v", err)
- }
-
- cards, err := svc.Discover(ctx, "inference")
- if err != nil {
- t.Fatalf("Discover() error = %v", err)
- }
- if len(cards) != 1 {
- t.Fatalf("len(cards) = %d, want 1", len(cards))
- }
- if cards[0].PeerID != providerHost.ID().String() {
- t.Fatalf("card peer ID = %q, want %q", cards[0].PeerID, providerHost.ID())
- }
-}
-
-func TestDiscoverAllowsStaleDHTCardWhenMaxAgeDisabled(t *testing.T) {
- ctx := context.Background()
-
- consumerHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New consumer error = %v", err)
- }
- defer func() { _ = consumerHost.Close() }()
-
- priv, _, err := crypto.GenerateEd25519Key(cryptorand.Reader)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- providerID, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card, err := protocol.NewAgentCard(providerID, []string{"inference"}, nil, priv)
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
- card.IssuedAt = time.Now().Add(-2 * time.Hour).UTC()
- if err := card.Sign(priv); err != nil {
- t.Fatalf("card.Sign() error = %v", err)
- }
-
- raw, err := json.Marshal(card)
- if err != nil {
- t.Fatalf("json.Marshal(card) error = %v", err)
- }
-
- ch := make(chan peer.AddrInfo, 1)
- ch <- peer.AddrInfo{ID: providerID}
- close(ch)
-
- node := &fakeDiscoveryNode{
- host: consumerHost,
- peerID: consumerHost.ID(),
- discoverCh: ch,
- dhtValues: map[string][]byte{
- protocol.DHTPeerCardKey(providerID.String()): raw,
- },
- }
-
- svc, err := protocol.NewDiscoveryService(node, protocol.WithMaxDHTCardAge(0))
- if err != nil {
- t.Fatalf("NewDiscoveryService() error = %v", err)
- }
-
- cards, err := svc.Discover(ctx, "inference")
- if err != nil {
- t.Fatalf("Discover() error = %v", err)
- }
- if len(cards) != 1 {
- t.Fatalf("len(cards) = %d, want 1", len(cards))
- }
- if cards[0].PeerID != providerID.String() {
- t.Fatalf("card peer ID = %q, want %q", cards[0].PeerID, providerID)
- }
-}
diff --git a/pkg/protocol/discovery/publish.go b/pkg/protocol/discovery/publish.go
deleted file mode 100644
index 6c6f76c0..00000000
--- a/pkg/protocol/discovery/publish.go
+++ /dev/null
@@ -1,120 +0,0 @@
-// 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 discovery
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strings"
-
- "github.com/libp2p/go-libp2p/core/peer"
-)
-
-// DHTPublisher is the subset of SAM networking used to advertise cards.
-type DHTPublisher interface {
- Announce(ctx context.Context, capability string) error
- PutValue(ctx context.Context, key string, value []byte) error
- PeerID() peer.ID
-}
-
-// Publisher signs and publishes AgentCards into capability-scoped DHT namespaces.
-type Publisher struct {
- net DHTPublisher
-}
-
-// NewPublisher creates an AgentCard publisher bound to a mesh node.
-func NewPublisher(net DHTPublisher) (*Publisher, error) {
- if net == nil {
- return nil, fmt.Errorf("publisher network is nil")
- }
- if net.PeerID() == "" {
- return nil, fmt.Errorf("publisher network peer ID is empty")
- }
- return &Publisher{net: net}, nil
-}
-
-// Publish verifies and announces the card under the SAM agent namespace.
-//
-// Each capability is announced under:
-//
-// /sam/v1/agents/capability/<capability>
-//
-// and the card identity itself is announced under:
-//
-// /sam/v1/agents/peer/<peerID>
-func (p *Publisher) Publish(ctx context.Context, card *AgentCard) error {
- if card == nil {
- return fmt.Errorf("agent card is nil")
- }
- if err := VerifyAgentCard(card); err != nil {
- return fmt.Errorf("validating card before publish: %w", err)
- }
-
- nodePeerID := p.net.PeerID().String()
- if nodePeerID != card.PeerID {
- return fmt.Errorf("card peer ID %q does not match node peer ID %q", card.PeerID, nodePeerID)
- }
-
- peerNS := AgentPeerNamespace(card.PeerID)
- if err := p.net.Announce(ctx, peerNS); err != nil {
- return fmt.Errorf("announcing peer namespace %q: %w", peerNS, err)
- }
-
- payload, err := json.Marshal(card)
- if err != nil {
- return fmt.Errorf("encoding card payload: %w", err)
- }
- if err := p.net.PutValue(ctx, DHTPeerCardKey(card.PeerID), payload); err != nil {
- return fmt.Errorf("publishing peer card key for %q: %w", card.PeerID, err)
- }
-
- for _, capability := range card.CapabilityNames() {
- ns := AgentCapabilityNamespace(capability)
- if err := p.net.Announce(ctx, ns); err != nil {
- return fmt.Errorf("announcing capability namespace %q: %w", ns, err)
- }
- if err := p.net.PutValue(ctx, DHTCapabilityCardKey(capability, card.PeerID), payload); err != nil {
- return fmt.Errorf("publishing capability card key for %q: %w", capability, err)
- }
- }
-
- return nil
-}
-
-// AgentCapabilityNamespace returns the capability-scoped DHT namespace key.
-func AgentCapabilityNamespace(capability string) string {
- capability = strings.ToLower(strings.TrimSpace(capability))
- capability = strings.ReplaceAll(capability, " ", "-")
- return AgentDHTNamespaceBase + "capability/" + capability
-}
-
-// AgentPeerNamespace returns the peer-scoped DHT namespace key.
-func AgentPeerNamespace(peerID string) string {
- return AgentDHTNamespaceBase + "peer/" + strings.TrimSpace(peerID)
-}
-
-// DHTCapabilityCardKey is the DHT value key for a capability and peer card.
-func DHTCapabilityCardKey(capability, peerID string) string {
- capability = strings.ToLower(strings.TrimSpace(capability))
- capability = strings.ReplaceAll(capability, " ", "-")
- peerID = strings.TrimSpace(peerID)
- return "/sam/capability/" + capability + "/" + peerID
-}
-
-// DHTPeerCardKey is the DHT value key for a peer's latest signed AgentCard.
-func DHTPeerCardKey(peerID string) string {
- return "/sam/peer/" + strings.TrimSpace(peerID) + "/agent-card"
-}
diff --git a/pkg/protocol/discovery/publish_test.go b/pkg/protocol/discovery/publish_test.go
deleted file mode 100644
index 604dc9aa..00000000
--- a/pkg/protocol/discovery/publish_test.go
+++ /dev/null
@@ -1,144 +0,0 @@
-// 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 discovery_test
-
-import (
- "context"
- "reflect"
- "testing"
-
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/peer"
-
- protocol "sam/pkg/protocol/discovery"
-)
-
-type fakePublisherNode struct {
- peerID peer.ID
- announced []string
- stored map[string][]byte
- errOn string
-}
-
-func (f *fakePublisherNode) Announce(_ context.Context, capability string) error {
- f.announced = append(f.announced, capability)
- if f.errOn != "" && f.errOn == capability {
- return context.DeadlineExceeded
- }
- return nil
-}
-
-func (f *fakePublisherNode) PeerID() peer.ID {
- return f.peerID
-}
-
-func (f *fakePublisherNode) PutValue(_ context.Context, key string, value []byte) error {
- if f.stored == nil {
- f.stored = map[string][]byte{}
- }
- f.stored[key] = append([]byte(nil), value...)
- return nil
-}
-
-func TestPublisherPublishesPeerAndCapabilityNamespaces(t *testing.T) {
- priv, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pid, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card, err := protocol.NewAgentCard(pid, []string{"inference", "search"}, nil, priv)
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
-
- node := &fakePublisherNode{peerID: pid}
- publisher, err := protocol.NewPublisher(node)
- if err != nil {
- t.Fatalf("NewPublisher() error = %v", err)
- }
-
- if err := publisher.Publish(context.Background(), card); err != nil {
- t.Fatalf("Publish() error = %v", err)
- }
-
- want := []string{
- protocol.AgentPeerNamespace(pid.String()),
- protocol.AgentCapabilityNamespace("inference"),
- protocol.AgentCapabilityNamespace("search"),
- }
- if !reflect.DeepEqual(node.announced, want) {
- t.Fatalf("announced = %#v, want %#v", node.announced, want)
- }
- if len(node.stored) != 3 {
- t.Fatalf("stored values = %d, want 3 (peer key + 2 capabilities)", len(node.stored))
- }
-}
-
-func TestPublisherRejectsPeerMismatch(t *testing.T) {
- privA, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pidA, err := peer.IDFromPrivateKey(privA)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- privB, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pidB, err := peer.IDFromPrivateKey(privB)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
-
- card, err := protocol.NewAgentCard(pidA, []string{"inference"}, nil, privA)
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
-
- publisher, err := protocol.NewPublisher(&fakePublisherNode{peerID: pidB})
- if err != nil {
- t.Fatalf("NewPublisher() error = %v", err)
- }
-
- if err := publisher.Publish(context.Background(), card); err == nil {
- t.Fatal("Publish() should fail on peer ID mismatch")
- }
-}
-
-func TestAgentNamespaceHelpers(t *testing.T) {
- tests := []struct {
- name string
- capability string
- want string
- }{
- {name: "trim and lower", capability: " Search ", want: "/sam/v1/agents/capability/search"},
- {name: "spaces to dash", capability: "web crawl", want: "/sam/v1/agents/capability/web-crawl"},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := protocol.AgentCapabilityNamespace(tt.capability); got != tt.want {
- t.Fatalf("AgentCapabilityNamespace(%q) = %q, want %q", tt.capability, got, tt.want)
- }
- })
- }
-}
diff --git a/pkg/protocol/http/http_tunnel.go b/pkg/protocol/http/http_tunnel.go
deleted file mode 100644
index 5acfec6f..00000000
--- a/pkg/protocol/http/http_tunnel.go
+++ /dev/null
@@ -1,258 +0,0 @@
-// 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 httpprotocol
-
-import (
- "bufio"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "strings"
- "time"
-
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/network"
- "github.com/libp2p/go-libp2p/core/peer"
- coreprotocol "github.com/libp2p/go-libp2p/core/protocol"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
- "sam/pkg/reputation"
-)
-
-const HTTPTunnelProtocolID coreprotocol.ID = "/sam/tunnel/http/1.0"
-
-type HTTPTunnelOpenRequest struct {
- Biscuit string `json:"biscuit"`
- Capability string `json:"capability,omitempty"`
- Request HTTPTunnelRequest `json:"request"`
-}
-
-type HTTPTunnelRequest struct {
- Method string `json:"method"`
- Path string `json:"path"`
- Headers map[string][]string `json:"headers,omitempty"`
- Body []byte `json:"body,omitempty"`
-}
-
-type HTTPTunnelResponse struct {
- StatusCode int `json:"status_code"`
- Headers map[string][]string `json:"headers,omitempty"`
- Body []byte `json:"body,omitempty"`
- Error string `json:"error,omitempty"`
-}
-
-type HTTPTunnelService struct {
- host host.Host
- endpoint *url.URL
- client *http.Client
- skillGate *economy.BiscuitSkillGate
-}
-
-type HTTPTunnelServiceOption func(*HTTPTunnelService)
-
-func WithHTTPTunnelSkillGate(g *economy.BiscuitSkillGate) HTTPTunnelServiceOption {
- return func(s *HTTPTunnelService) { s.skillGate = g }
-}
-
-func NewHTTPTunnelService(h host.Host, endpoint string, opts ...HTTPTunnelServiceOption) (*HTTPTunnelService, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- e := strings.TrimSpace(endpoint)
- if e == "" {
- return nil, fmt.Errorf("endpoint is required")
- }
- u, err := url.Parse(e)
- if err != nil {
- return nil, fmt.Errorf("parsing endpoint: %w", err)
- }
- if u.Scheme == "" || u.Host == "" {
- return nil, fmt.Errorf("endpoint must include scheme and host")
- }
-
- s := &HTTPTunnelService{
- host: h,
- endpoint: u,
- client: &http.Client{Timeout: 60 * time.Second},
- skillGate: economy.NewBiscuitSkillGate(nil),
- }
- for _, opt := range opts {
- opt(s)
- }
- h.SetStreamHandler(HTTPTunnelProtocolID, s.handleStream)
- return s, nil
-}
-
-func (s *HTTPTunnelService) Close() {
- if s == nil || s.host == nil {
- return
- }
- s.host.RemoveStreamHandler(HTTPTunnelProtocolID)
-}
-
-func TunnelHTTP(ctx context.Context, h host.Host, target peer.ID, req HTTPTunnelOpenRequest) (*HTTPTunnelResponse, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- if target == "" {
- return nil, fmt.Errorf("target peer id is required")
- }
- if strings.TrimSpace(req.Biscuit) == "" {
- return nil, fmt.Errorf("biscuit is required")
- }
- if err := identity.AuthenticatePeerPassport(ctx, h, target); err != nil {
- return nil, fmt.Errorf("passport authentication failed: %w", err)
- }
- if strings.TrimSpace(req.Request.Method) == "" {
- return nil, fmt.Errorf("request method is required")
- }
-
- stream, err := h.NewStream(ctx, target, HTTPTunnelProtocolID)
- if err != nil {
- return nil, fmt.Errorf("opening HTTP tunnel stream: %w", err)
- }
- defer func() { _ = stream.Close() }()
-
- if deadline, ok := ctx.Deadline(); ok {
- _ = stream.SetDeadline(deadline)
- }
-
- w := bufio.NewWriter(stream)
- if err := json.NewEncoder(w).Encode(req); err != nil {
- return nil, fmt.Errorf("writing tunnel preface: %w", err)
- }
- if err := w.Flush(); err != nil {
- return nil, fmt.Errorf("flushing tunnel preface: %w", err)
- }
-
- var resp HTTPTunnelResponse
- if err := json.NewDecoder(stream).Decode(&resp); err != nil {
- return nil, fmt.Errorf("reading tunnel response: %w", err)
- }
- if resp.Error == "" && resp.StatusCode > 0 && resp.StatusCode < 500 {
- if att := reputation.DefaultAttestor(); att != nil {
- _ = att.PublishWithProtocol(context.Background(), target.String(), 1, string(HTTPTunnelProtocolID))
- }
- }
- return &resp, nil
-}
-
-func (s *HTTPTunnelService) handleStream(stream network.Stream) {
- defer func() { _ = stream.Close() }()
-
- var openReq HTTPTunnelOpenRequest
- if err := json.NewDecoder(stream).Decode(&openReq); err != nil {
- _ = json.NewEncoder(stream).Encode(HTTPTunnelResponse{StatusCode: http.StatusBadRequest, Error: fmt.Sprintf("invalid preface: %v", err)})
- return
- }
-
- if err := s.verifyMetadata(context.Background(), stream.Conn().RemotePeer(), &openReq); err != nil {
- _ = json.NewEncoder(stream).Encode(HTTPTunnelResponse{StatusCode: http.StatusForbidden, Error: err.Error()})
- return
- }
-
- resp := s.forwardLocal(context.Background(), openReq.Request)
- _ = json.NewEncoder(stream).Encode(resp)
-}
-
-func (s *HTTPTunnelService) verifyMetadata(ctx context.Context, remotePeer peer.ID, req *HTTPTunnelOpenRequest) error {
- if _, err := identity.AuthenticatedPeerPassport(s.host, remotePeer); err != nil {
- return fmt.Errorf("passport authentication required: %w", err)
- }
- if strings.TrimSpace(req.Biscuit) == "" {
- return fmt.Errorf("missing biscuit metadata")
- }
- authValues := req.Request.Headers["Authorization"]
- if len(authValues) == 0 {
- authValues = req.Request.Headers["authorization"]
- }
- if _, err := extractBearerFromValues(authValues); err != nil {
- return err
- }
- if strings.TrimSpace(req.Capability) != "" {
- if err := s.skillGate.CheckSkill(ctx, req.Biscuit, strings.TrimSpace(req.Capability)); err != nil {
- return fmt.Errorf("biscuit denied capability: %w", err)
- }
- }
- return nil
-}
-
-func extractBearerFromValues(values []string) (string, error) {
- for _, value := range values {
- parts := strings.SplitN(strings.TrimSpace(value), " ", 2)
- if len(parts) != 2 || !strings.EqualFold(strings.TrimSpace(parts[0]), "Bearer") {
- continue
- }
- token := strings.TrimSpace(parts[1])
- if token == "" {
- return "", fmt.Errorf("bearer token is empty")
- }
- return token, nil
- }
- if len(values) == 0 {
- return "", fmt.Errorf("missing Authorization header")
- }
- return "", errors.New("authorization must use Bearer scheme")
-}
-
-func (s *HTTPTunnelService) forwardLocal(ctx context.Context, treq HTTPTunnelRequest) HTTPTunnelResponse {
- method := strings.TrimSpace(treq.Method)
- if method == "" {
- method = http.MethodGet
- }
-
- targetURL := *s.endpoint
- if treq.Path != "" {
- rawPath := treq.Path
- if !strings.HasPrefix(rawPath, "/") {
- rawPath = "/" + rawPath
- }
- if ref, err := url.Parse(rawPath); err == nil {
- targetURL = *s.endpoint.ResolveReference(ref)
- }
- }
-
- req, err := http.NewRequestWithContext(ctx, method, targetURL.String(), strings.NewReader(string(treq.Body)))
- if err != nil {
- return HTTPTunnelResponse{StatusCode: http.StatusBadRequest, Error: fmt.Sprintf("building local request: %v", err)}
- }
- for key, vals := range treq.Headers {
- for _, val := range vals {
- req.Header.Add(key, val)
- }
- }
-
- resp, err := s.client.Do(req)
- if err != nil {
- return HTTPTunnelResponse{StatusCode: http.StatusBadGateway, Error: fmt.Sprintf("calling local endpoint: %v", err)}
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return HTTPTunnelResponse{StatusCode: http.StatusBadGateway, Error: fmt.Sprintf("reading local response: %v", err)}
- }
-
- return HTTPTunnelResponse{
- StatusCode: resp.StatusCode,
- Headers: resp.Header.Clone(),
- Body: body,
- }
-}
diff --git a/pkg/protocol/http/http_tunnel_test.go b/pkg/protocol/http/http_tunnel_test.go
deleted file mode 100644
index b8cb3946..00000000
--- a/pkg/protocol/http/http_tunnel_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// 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 httpprotocol
-
-import "testing"
-
-func TestExtractBearerFromValues(t *testing.T) {
- tests := []struct {
- name string
- values []string
- wantErr bool
- }{
- {name: "valid bearer", values: []string{"Bearer token-1"}, wantErr: false},
- {name: "valid among many", values: []string{"Basic abc", "Bearer token-2"}, wantErr: false},
- {name: "missing header", values: nil, wantErr: true},
- {name: "wrong scheme", values: []string{"Basic abc"}, wantErr: true},
- {name: "empty token", values: []string{"Bearer "}, wantErr: true},
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- _, err := extractBearerFromValues(tc.values)
- if tc.wantErr && err == nil {
- t.Fatalf("expected error, got nil")
- }
- if !tc.wantErr && err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- })
- }
-}
diff --git a/pkg/protocol/mcp/agent_card_adapter.go b/pkg/protocol/mcp/agent_card_adapter.go
deleted file mode 100644
index 17f36e77..00000000
--- a/pkg/protocol/mcp/agent_card_adapter.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// 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 mcp
-
-import (
- "sam/pkg/protocol/discovery"
-)
-
-// Resource describes an MCP-compatible tool or data source advertised by an agent.
-type Resource = discovery.Tool
-
-// SetResources stores MCP resources directly in the discovery card tool list.
-func SetResources(card *discovery.AgentCard, resources []Resource) {
- if card == nil {
- return
- }
- card.Tools = append([]discovery.Tool(nil), resources...)
-}
-
-// ResourcesFromCard returns the discovery card tool list as MCP resources.
-func ResourcesFromCard(card *discovery.AgentCard) []Resource {
- if card == nil {
- return nil
- }
- return append([]Resource(nil), card.Tools...)
-}
diff --git a/pkg/protocol/mcp/agent_card_adapter_test.go b/pkg/protocol/mcp/agent_card_adapter_test.go
deleted file mode 100644
index 677bc016..00000000
--- a/pkg/protocol/mcp/agent_card_adapter_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// 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 mcp
-
-import (
- "testing"
-
- "github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/peer"
-
- "sam/pkg/protocol/discovery"
-)
-
-func TestWithResources(t *testing.T) {
- priv, _, err := crypto.GenerateEd25519Key(nil)
- if err != nil {
- t.Fatalf("GenerateEd25519Key() error = %v", err)
- }
- pid, err := peer.IDFromPrivateKey(priv)
- if err != nil {
- t.Fatalf("IDFromPrivateKey() error = %v", err)
- }
- card, err := discovery.NewAgentCard(
- pid,
- []string{"search"},
- []Resource{{Name: "search", Kind: "tool", Endpoint: "mcp://search"}},
- priv,
- )
- if err != nil {
- t.Fatalf("NewAgentCard() error = %v", err)
- }
- resources := ResourcesFromCard(card)
- if len(resources) != 1 {
- t.Fatalf("len(resources) = %d, want 1", len(resources))
- }
- if resources[0].Endpoint != "mcp://search" {
- t.Fatalf("resource endpoint = %q, want %q", resources[0].Endpoint, "mcp://search")
- }
- if err := discovery.VerifyAgentCard(card); err != nil {
- t.Fatalf("VerifyAgentCard() error = %v", err)
- }
-}
diff --git a/pkg/protocol/mcp/mcp_bridge.go b/pkg/protocol/mcp/mcp_bridge.go
deleted file mode 100644
index 9034e13a..00000000
--- a/pkg/protocol/mcp/mcp_bridge.go
+++ /dev/null
@@ -1,247 +0,0 @@
-// 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 mcp
-
-import (
- "bufio"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
-
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/network"
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
- "sam/pkg/protocol/middleware"
- "sam/pkg/reputation"
-)
-
-const MCPProtocolID = "/sam/mcp/1.0.0"
-
-// MCPConnector opens a local MCP JSON-RPC transport endpoint.
-type MCPConnector interface {
- Open(ctx context.Context) (mcp.Transport, error)
-}
-
-// BridgeOpenRequest is the stream preface required before MCP proxying starts.
-type BridgeOpenRequest struct {
- BiscuitToken string `json:"biscuit_token"`
- Amount int64 `json:"amount"`
- Asset string `json:"asset"`
- Nonce string `json:"nonce"`
- Payer string `json:"payer,omitempty"`
- Payee string `json:"payee,omitempty"`
- Capability string `json:"capability"`
-}
-
-// MCPBridge proxies inbound libp2p streams to a local MCP endpoint.
-//
-// Before proxying, it verifies micropayment authorization using economy.Verifier.
-type MCPBridge struct {
- host host.Host
- verifier economy.Verifier
- connector MCPConnector
-}
-
-// NewMCPBridge creates a new MCP bridge and installs the stream handler.
-func NewMCPBridge(h host.Host, verifier economy.Verifier, connector MCPConnector) (*MCPBridge, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- if verifier == nil {
- return nil, fmt.Errorf("economy verifier is nil")
- }
- if connector == nil {
- return nil, fmt.Errorf("mcp connector is nil")
- }
-
- b := &MCPBridge{host: h, verifier: verifier, connector: connector}
- h.SetStreamHandler(MCPProtocolID, b.handleInbound)
- return b, nil
-}
-
-// Open opens an outbound MCP stream and sends the bridge preface.
-func (b *MCPBridge) Open(ctx context.Context, peerID peer.ID, req BridgeOpenRequest) (network.Stream, error) {
- if eval := reputation.DefaultEvaluator(); eval != nil && eval.IsNegative(peerID.String()) {
- return nil, fmt.Errorf("refusing MCP stream to negatively-rated peer %s", peerID)
- }
- if _, err := identity.EnsureAuthenticatedPeer(ctx, b.host, peerID); err != nil {
- return nil, fmt.Errorf("passport authentication failed for %s: %w", peerID, err)
- }
- stream, err := b.host.NewStream(ctx, peerID, MCPProtocolID)
- if err != nil {
- return nil, fmt.Errorf("opening MCP stream: %w", err)
- }
- if err := json.NewEncoder(stream).Encode(req); err != nil {
- _ = stream.Reset()
- return nil, fmt.Errorf("writing bridge preface: %w", err)
- }
- return stream, nil
-}
-
-func (b *MCPBridge) handleInbound(stream network.Stream) {
- defer func() { _ = stream.Close() }()
- if _, err := identity.AuthenticatedPeerPassport(b.host, stream.Conn().RemotePeer()); err != nil {
- _ = writeBridgeError(stream, fmt.Errorf("passport authentication required: %w", err))
- return
- }
-
- reader := bufio.NewReader(stream)
-
- var openReq BridgeOpenRequest
- // Read exactly one JSON preface frame (newline-delimited). Using json.Decoder
- // directly on the stream can buffer bytes from the next MCP message and cause
- // proxy stalls.
- line, err := reader.ReadBytes('\n')
- if err != nil {
- _ = writeBridgeError(stream, fmt.Errorf("reading bridge preface: %w", err))
- return
- }
- if err := json.Unmarshal(line, &openReq); err != nil {
- _ = writeBridgeError(stream, fmt.Errorf("invalid bridge preface: %w", err))
- return
- }
- if openReq.BiscuitToken == "" {
- _ = writeBridgeError(stream, economy.ErrMissingBiscuitToken)
- return
- }
- if openReq.Amount <= 0 {
- _ = writeBridgeError(stream, economy.ErrInvalidMicropayAmount)
- return
- }
- if openReq.Asset == "" {
- _ = writeBridgeError(stream, economy.ErrMissingMicropayAsset)
- return
- }
- if openReq.Nonce == "" {
- _ = writeBridgeError(stream, economy.ErrMissingMicropayNonce)
- return
- }
- resource := openReq.Capability
- if resource == "" {
- resource = MCPProtocolID
- }
- if err := (middleware.PassportAuthz{}).CheckCapability(context.Background(), openReq.BiscuitToken, "mcp.tool_call", resource); err != nil {
- _ = writeBridgeError(stream, err)
- return
- }
-
- verifyReq := economy.VerifyRequest{
- Token: openReq.BiscuitToken,
- Method: "STREAM",
- Path: MCPProtocolID,
- Payment: economy.Micropayment{
- Amount: openReq.Amount,
- Asset: openReq.Asset,
- Nonce: openReq.Nonce,
- Payer: openReq.Payer,
- Payee: openReq.Payee,
- Capability: openReq.Capability,
- },
- }
- ctx := context.Background()
- if _, err := b.verifier.Verify(ctx, verifyReq); err != nil {
- _ = writeBridgeError(stream, fmt.Errorf("%w: %v", economy.ErrVerifierDeniedRequest, err))
- return
- }
- if att := reputation.DefaultAttestor(); att != nil {
- _ = att.PublishWithProtocol(context.Background(), stream.Conn().RemotePeer().String(), 1, MCPProtocolID)
- }
-
- local, err := b.connector.Open(ctx)
- if err != nil {
- _ = writeBridgeError(stream, fmt.Errorf("opening local MCP endpoint: %w", err))
- return
- }
-
- remote := &mcp.IOTransport{
- Reader: &readCloser{Reader: reader, Closer: stream},
- Writer: stream,
- }
- if err := proxyMCPMessages(ctx, remote, local); err != nil {
- if !errors.Is(err, io.EOF) && !errors.Is(err, mcp.ErrConnectionClosed) {
- _ = stream.Reset()
- }
- }
-}
-
-func writeBridgeError(w io.Writer, err error) error {
- return json.NewEncoder(w).Encode(struct {
- Error string `json:"error"`
- }{Error: err.Error()})
-}
-
-type readCloser struct {
- io.Reader
- io.Closer
-}
-
-func proxyMCPMessages(ctx context.Context, remote mcp.Transport, local mcp.Transport) error {
- remoteConn, err := remote.Connect(ctx)
- if err != nil {
- return fmt.Errorf("connecting remote MCP transport: %w", err)
- }
- defer func() { _ = remoteConn.Close() }()
-
- localConn, err := local.Connect(ctx)
- if err != nil {
- return fmt.Errorf("connecting local MCP transport: %w", err)
- }
- defer func() { _ = localConn.Close() }()
-
- errCh := make(chan error, 2)
- go forwardMCP(ctx, remoteConn, localConn, errCh)
- go forwardMCP(ctx, localConn, remoteConn, errCh)
-
- err1 := <-errCh
- err2 := <-errCh
-
- if err := normalizeProxyError(err1); err != nil {
- return err
- }
- if err := normalizeProxyError(err2); err != nil {
- return err
- }
- return nil
-}
-
-func forwardMCP(ctx context.Context, src mcp.Connection, dst mcp.Connection, errCh chan<- error) {
- for {
- msg, err := src.Read(ctx)
- if err != nil {
- errCh <- err
- return
- }
- if err := dst.Write(ctx, msg); err != nil {
- errCh <- err
- return
- }
- }
-}
-
-func normalizeProxyError(err error) error {
- if err == nil {
- return nil
- }
- if errors.Is(err, io.EOF) || errors.Is(err, mcp.ErrConnectionClosed) {
- return nil
- }
- return err
-}
diff --git a/pkg/protocol/mcp/mcp_bridge_test.go b/pkg/protocol/mcp/mcp_bridge_test.go
deleted file mode 100644
index e789ee03..00000000
--- a/pkg/protocol/mcp/mcp_bridge_test.go
+++ /dev/null
@@ -1,225 +0,0 @@
-// 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 mcp
-
-import (
- "context"
- "errors"
- "io"
- "net"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/libp2p/go-libp2p"
- "github.com/libp2p/go-libp2p/core/peer"
- "github.com/modelcontextprotocol/go-sdk/mcp"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
-)
-
-type fakeVerifier struct {
- mu sync.Mutex
- decision *economy.VerifyDecision
- err error
- lastReq economy.VerifyRequest
-}
-
-func (f *fakeVerifier) Verify(_ context.Context, req economy.VerifyRequest) (*economy.VerifyDecision, error) {
- f.mu.Lock()
- defer f.mu.Unlock()
- f.lastReq = req
- if f.err != nil {
- return nil, f.err
- }
- if f.decision == nil {
- f.decision = &economy.VerifyDecision{Subject: "peer:test"}
- }
- return f.decision, nil
-}
-
-func (f *fakeVerifier) GetLastReq() economy.VerifyRequest {
- f.mu.Lock()
- defer f.mu.Unlock()
- return f.lastReq
-}
-
-type echoConnector struct{}
-
-func (echoConnector) Open(context.Context) (mcp.Transport, error) {
- a, b := net.Pipe()
- go func() {
- defer func() { _ = b.Close() }()
- buf := make([]byte, 32*1024)
- for {
- n, err := b.Read(buf)
- if n > 0 {
- if _, werr := b.Write(buf[:n]); werr != nil {
- return
- }
- }
- if err != nil {
- return
- }
- }
- }()
- return &mcp.IOTransport{Reader: a, Writer: a}, nil
-}
-
-func TestMCPBridgeAllowsAuthorizedStream(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
-
- serverHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(server) error = %v", err)
- }
- defer func() { _ = serverHost.Close() }()
-
- clientHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(client) error = %v", err)
- }
- defer func() { _ = clientHost.Close() }()
-
- verifier := &fakeVerifier{}
- _, err = NewMCPBridge(serverHost, verifier, echoConnector{})
- if err != nil {
- t.Fatalf("NewMCPBridge() error = %v", err)
- }
-
- if err := clientHost.Connect(ctx, peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()}); err != nil {
- t.Fatalf("client connect error = %v", err)
- }
- serverPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: serverHost.ID().String(), FederationID: "default", Subject: "server"})
- if err != nil {
- t.Fatalf("IssuePassportBiscuit(server) error = %v", err)
- }
- clientPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: clientHost.ID().String(), FederationID: "default", Subject: "client"})
- if err != nil {
- t.Fatalf("IssuePassportBiscuit(client) error = %v", err)
- }
- if err := identity.SetLocalPassport(serverHost, "default", serverPassport); err != nil {
- t.Fatalf("SetLocalPassport(server) error = %v", err)
- }
- if err := identity.SetLocalPassport(clientHost, "default", clientPassport); err != nil {
- t.Fatalf("SetLocalPassport(client) error = %v", err)
- }
-
- clientBridge, err := NewMCPBridge(clientHost, verifier, echoConnector{})
- if err != nil {
- t.Fatalf("NewMCPBridge(client) error = %v", err)
- }
-
- stream, err := clientBridge.Open(ctx, serverHost.ID(), BridgeOpenRequest{
- BiscuitToken: "token-1",
- Amount: 10,
- Asset: "sam-credit",
- Nonce: "n-1",
- Capability: "agent.chat",
- })
- if err != nil {
- t.Fatalf("Open() error = %v", err)
- }
- defer func() { _ = stream.Close() }()
-
- payload := []byte("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n")
- if _, err := stream.Write(payload); err != nil {
- t.Fatalf("stream.Write() error = %v", err)
- }
-
- buf := make([]byte, len(payload))
- if _, err := io.ReadFull(stream, buf); err != nil {
- t.Fatalf("io.ReadFull() error = %v", err)
- }
- if string(buf) != string(payload) {
- t.Fatalf("echo = %q, want %q", string(buf), string(payload))
- }
-
- if verifier.GetLastReq().Token != "token-1" || verifier.GetLastReq().Payment.Amount != 10 {
- t.Fatalf("verifier request = %#v, want token and amount", verifier.GetLastReq())
- }
-}
-
-func TestMCPBridgeDeniesUnauthorizedStream(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
-
- serverHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(server) error = %v", err)
- }
- defer func() { _ = serverHost.Close() }()
-
- clientHost, err := libp2p.New()
- if err != nil {
- t.Fatalf("libp2p.New(client) error = %v", err)
- }
- defer func() { _ = clientHost.Close() }()
-
- denyVerifier := &fakeVerifier{err: errors.New("insufficient funds")}
- _, err = NewMCPBridge(serverHost, denyVerifier, echoConnector{})
- if err != nil {
- t.Fatalf("NewMCPBridge(server) error = %v", err)
- }
-
- if err := clientHost.Connect(ctx, peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()}); err != nil {
- t.Fatalf("client connect error = %v", err)
- }
- serverPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: serverHost.ID().String(), FederationID: "default", Subject: "server"})
- if err != nil {
- t.Fatalf("IssuePassportBiscuit(server) error = %v", err)
- }
- clientPassport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{PeerID: clientHost.ID().String(), FederationID: "default", Subject: "client"})
- if err != nil {
- t.Fatalf("IssuePassportBiscuit(client) error = %v", err)
- }
- if err := identity.SetLocalPassport(serverHost, "default", serverPassport); err != nil {
- t.Fatalf("SetLocalPassport(server) error = %v", err)
- }
- if err := identity.SetLocalPassport(clientHost, "default", clientPassport); err != nil {
- t.Fatalf("SetLocalPassport(client) error = %v", err)
- }
-
- clientBridge, err := NewMCPBridge(clientHost, &fakeVerifier{}, echoConnector{})
- if err != nil {
- t.Fatalf("NewMCPBridge(client) error = %v", err)
- }
-
- stream, err := clientBridge.Open(ctx, serverHost.ID(), BridgeOpenRequest{
- BiscuitToken: "token-deny",
- Amount: 1,
- Asset: "sam-credit",
- Nonce: "n-deny",
- Capability: "agent.chat",
- })
- if err != nil {
- t.Fatalf("Open() error = %v", err)
- }
- defer func() { _ = stream.Close() }()
-
- buf := make([]byte, 2048)
- n, err := stream.Read(buf)
- if err != nil && !errors.Is(err, io.EOF) {
- t.Fatalf("stream.Read() error = %v", err)
- }
-
- resp := string(buf[:n])
- if !strings.Contains(resp, economy.ErrVerifierDeniedRequest.Error()) {
- t.Fatalf("response = %q, want verifier denied error", resp)
- }
-}
diff --git a/pkg/protocol/middleware/authz.go b/pkg/protocol/middleware/authz.go
deleted file mode 100644
index 2911f37b..00000000
--- a/pkg/protocol/middleware/authz.go
+++ /dev/null
@@ -1,85 +0,0 @@
-// 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 middleware
-
-import (
- "context"
- "fmt"
-
- "github.com/libp2p/go-libp2p/core/host"
- "github.com/libp2p/go-libp2p/core/peer"
-
- "sam/pkg/economy"
- "sam/pkg/identity"
-)
-
-// ConnectionAuthz is a reusable per-connection authorization hook that can be
-// shared across protocol implementations.
-type ConnectionAuthz interface {
- Install(host.Host) error
- AuthorizeOutbound(context.Context, host.Host, peer.ID) error
- AuthorizeInbound(context.Context, host.Host, peer.ID) (*identity.PassportClaims, error)
- CheckCapability(context.Context, string, string, string) error
-}
-
-// PassportAuthz enforces hub-issued passport authentication on libp2p
-// connections. This is the default SAM connection authz middleware.
-type PassportAuthz struct{}
-
-func (PassportAuthz) Install(h host.Host) error {
- if h == nil {
- return fmt.Errorf("host is nil")
- }
- if err := identity.EnsurePassportAuth(h, ""); err != nil {
- return fmt.Errorf("installing passport auth: %w", err)
- }
- return nil
-}
-
-func (PassportAuthz) AuthorizeOutbound(ctx context.Context, h host.Host, target peer.ID) error {
- if h == nil {
- return fmt.Errorf("host is nil")
- }
- if target == "" {
- return fmt.Errorf("target peer id is required")
- }
- if err := identity.AuthenticatePeerPassport(ctx, h, target); err != nil {
- return fmt.Errorf("passport authentication failed for %s: %w", target, err)
- }
- return nil
-}
-
-func (PassportAuthz) AuthorizeInbound(ctx context.Context, h host.Host, remote peer.ID) (*identity.PassportClaims, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- if remote == "" {
- return nil, fmt.Errorf("remote peer id is required")
- }
- claims, err := identity.EnsureAuthenticatedPeer(ctx, h, remote)
- if err != nil {
- return nil, fmt.Errorf("passport authentication required: %w", err)
- }
- return claims, nil
-}
-
-// CheckCapability enforces action/resource caveats embedded in Biscuit tokens.
-// If the token does not carry action/resource restrictions, the request is allowed.
-func (PassportAuthz) CheckCapability(ctx context.Context, token, action, resource string) error {
- if err := economy.CheckCapability(ctx, nil, token, action, resource); err != nil {
- return fmt.Errorf("authorization denied for action=%q resource=%q: %w", action, resource, err)
- }
- return nil
-}
diff --git a/pkg/reputation/reputation.go b/pkg/reputation/reputation.go
deleted file mode 100644
index c873a145..00000000
--- a/pkg/reputation/reputation.go
+++ /dev/null
@@ -1,294 +0,0 @@
-package reputation
-
-import (
- "context"
- "crypto/ed25519"
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "os"
- "strings"
- "sync"
- "time"
-
- pubsub "github.com/libp2p/go-libp2p-pubsub"
- "github.com/libp2p/go-libp2p/core/host"
-
- internaldb "sam/internal/db"
-)
-
-const TopicV1 = "sam/reputation/v1"
-
-type Attestation struct {
- TargetPeerID string `json:"target_peer_id"`
- Score int `json:"score"`
- Protocol string `json:"protocol"`
- Timestamp time.Time `json:"timestamp"`
- Signature string `json:"signature"`
- ReporterPeerID string `json:"reporter_peer_id,omitempty"`
-}
-
-type Evaluator interface {
- Score(peerID string) float64
- IsNegative(peerID string) bool
-}
-
-type Attestor interface {
- Publish(ctx context.Context, targetID string, rating int) error
- PublishWithProtocol(ctx context.Context, targetID string, rating int, protocol string) error
-}
-
-type TrustStore struct {
- host host.Host
- ps *pubsub.PubSub
-
- mu sync.RWMutex
- scores map[string]float64
- sums map[string]int
- counts map[string]int
- store internaldb.Store
-}
-
-const trustCacheKey = "trust-cache-v1"
-
-type trustCacheSnapshot struct {
- Scores map[string]float64 `json:"scores"`
- Sums map[string]int `json:"sums"`
- Counts map[string]int `json:"counts"`
-}
-
-func NewTrustStore(h host.Host, ps *pubsub.PubSub) (*TrustStore, error) {
- if h == nil {
- return nil, fmt.Errorf("host is nil")
- }
- if ps == nil {
- return nil, fmt.Errorf("gossipsub is nil")
- }
- ts := &TrustStore{
- host: h,
- ps: ps,
- scores: map[string]float64{},
- sums: map[string]int{},
- counts: map[string]int{},
- }
- store, err := internaldb.OpenDefault()
- if err == nil {
- ts.store = store
- if loadErr := ts.loadCache(context.Background()); loadErr != nil {
- _ = ts.store.Close()
- ts.store = nil
- }
- }
- return ts, nil
-}
-
-func (s *TrustStore) Start(ctx context.Context) error {
- topic, err := s.ps.Join(TopicV1)
- if err != nil {
- return fmt.Errorf("join reputation topic: %w", err)
- }
- sub, err := topic.Subscribe()
- if err != nil {
- return fmt.Errorf("subscribe reputation topic: %w", err)
- }
- go func() {
- defer sub.Cancel()
- for {
- msg, nextErr := sub.Next(ctx)
- if nextErr != nil {
- return
- }
- if msg == nil || msg.ReceivedFrom == s.host.ID() {
- continue
- }
- var att Attestation
- if err := json.Unmarshal(msg.Data, &att); err != nil {
- continue
- }
- if !s.verify(att) {
- continue
- }
- s.mu.Lock()
- s.sums[att.TargetPeerID] += att.Score
- s.counts[att.TargetPeerID]++
- s.scores[att.TargetPeerID] = float64(s.sums[att.TargetPeerID]) / float64(s.counts[att.TargetPeerID])
- s.mu.Unlock()
- _ = s.persistCache(context.Background())
- }
- }()
- return nil
-}
-
-func (s *TrustStore) Publish(ctx context.Context, targetID string, rating int) error {
- return s.PublishWithProtocol(ctx, targetID, rating, "/sam/a2a/1.0.0")
-}
-
-func (s *TrustStore) PublishWithProtocol(ctx context.Context, targetID string, rating int, protocol string) error {
- targetID = strings.TrimSpace(targetID)
- if targetID == "" {
- return fmt.Errorf("target peer id is required")
- }
- if rating < -1 || rating > 1 {
- return fmt.Errorf("rating must be -1..1")
- }
- topic, err := s.ps.Join(TopicV1)
- if err != nil {
- return fmt.Errorf("join reputation topic: %w", err)
- }
- att := Attestation{
- ReporterPeerID: s.host.ID().String(),
- TargetPeerID: targetID,
- Score: rating,
- Protocol: strings.TrimSpace(protocol),
- Timestamp: time.Now().UTC(),
- }
- if att.Protocol == "" {
- att.Protocol = "/sam/a2a/1.0.0"
- }
- sig, err := s.sign(att)
- if err != nil {
- return err
- }
- att.Signature = sig
- payload, err := json.Marshal(att)
- if err != nil {
- return fmt.Errorf("marshal attestation: %w", err)
- }
- if err := topic.Publish(ctx, payload); err != nil {
- return fmt.Errorf("publish attestation: %w", err)
- }
- // apply locally too
- s.mu.Lock()
- s.sums[targetID] += rating
- s.counts[targetID]++
- s.scores[targetID] = float64(s.sums[targetID]) / float64(s.counts[targetID])
- s.mu.Unlock()
- _ = s.persistCache(context.Background())
- return nil
-}
-
-func (s *TrustStore) Score(peerID string) float64 {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.scores[strings.TrimSpace(peerID)]
-}
-
-func (s *TrustStore) IsNegative(peerID string) bool {
- return s.Score(peerID) < 0
-}
-
-func (s *TrustStore) sign(att Attestation) (string, error) {
- priv := s.host.Peerstore().PrivKey(s.host.ID())
- if priv == nil {
- return "", fmt.Errorf("host private key unavailable")
- }
- raw, err := priv.Raw()
- if err != nil {
- return "", fmt.Errorf("extract private key bytes: %w", err)
- }
- if len(raw) != ed25519.PrivateKeySize {
- return "", fmt.Errorf("unsupported key size")
- }
- payload := []byte(att.ReporterPeerID + "|" + att.TargetPeerID + "|" + fmt.Sprintf("%d", att.Score) + "|" + att.Protocol + "|" + att.Timestamp.UTC().Format(time.RFC3339Nano))
- sig := ed25519.Sign(ed25519.PrivateKey(raw), payload)
- return base64.RawURLEncoding.EncodeToString(sig), nil
-}
-
-func (s *TrustStore) verify(att Attestation) bool {
- if strings.TrimSpace(att.ReporterPeerID) == "" || strings.TrimSpace(att.TargetPeerID) == "" || strings.TrimSpace(att.Signature) == "" {
- return false
- }
- if strings.TrimSpace(att.Protocol) == "" {
- return false
- }
- _, err := base64.RawURLEncoding.DecodeString(att.Signature)
- return err == nil
-}
-
-func (s *TrustStore) Close() error {
- if s == nil || s.store == nil {
- return nil
- }
- return s.store.Close()
-}
-
-func (s *TrustStore) loadCache(ctx context.Context) error {
- if s.store == nil {
- return nil
- }
- raw, err := s.store.Get(ctx, internaldb.BucketReputation, trustCacheKey)
- if err != nil {
- if errors.Is(err, os.ErrNotExist) {
- return nil
- }
- return fmt.Errorf("loading trust cache: %w", err)
- }
- var snap trustCacheSnapshot
- if err := json.Unmarshal(raw, &snap); err != nil {
- return fmt.Errorf("decoding trust cache: %w", err)
- }
- if snap.Scores != nil {
- s.scores = snap.Scores
- }
- if snap.Sums != nil {
- s.sums = snap.Sums
- }
- if snap.Counts != nil {
- s.counts = snap.Counts
- }
- return nil
-}
-
-func (s *TrustStore) persistCache(ctx context.Context) error {
- if s.store == nil {
- return nil
- }
- s.mu.RLock()
- snap := trustCacheSnapshot{Scores: map[string]float64{}, Sums: map[string]int{}, Counts: map[string]int{}}
- for k, v := range s.scores {
- snap.Scores[k] = v
- }
- for k, v := range s.sums {
- snap.Sums[k] = v
- }
- for k, v := range s.counts {
- snap.Counts[k] = v
- }
- s.mu.RUnlock()
- raw, err := json.Marshal(snap)
- if err != nil {
- return err
- }
- return s.store.Put(ctx, internaldb.BucketReputation, trustCacheKey, raw)
-}
-
-var (
- defaultMu sync.RWMutex
- defaultEvaluator Evaluator
- defaultAttestor Attestor
-)
-
-func SetDefaultEvaluator(e Evaluator) {
- defaultMu.Lock()
- defer defaultMu.Unlock()
- defaultEvaluator = e
-}
-
-func SetDefaultAttestor(a Attestor) {
- defaultMu.Lock()
- defer defaultMu.Unlock()
- defaultAttestor = a
-}
-
-func DefaultEvaluator() Evaluator {
- defaultMu.RLock()
- defer defaultMu.RUnlock()
- return defaultEvaluator
-}
-
-func DefaultAttestor() Attestor {
- defaultMu.RLock()
- defer defaultMu.RUnlock()
- return defaultAttestor
-}
diff --git a/python/README.md b/python/README.md
deleted file mode 100644
index 246a1a99..00000000
--- a/python/README.md
+++ /dev/null
@@ -1,187 +0,0 @@
-# SAM Python Client Framework
-
-This package provides an idiomatic async Python client for the SAM (Sovereign Agent Mesh):
-
-## Features
-
-- **MeshClient**: High-level async API for mesh operations
-- **OIDC Device Flow**: Hub authentication with device authorization grant
-- **Passport Management**: Hub-issued biscuit validation and credential persistence
-- **Protocol Support**: `/sam/auth/1.0.0`, `/sam/a2a/1.0.0`, `/sam/mcp/1.0.0`
-- **Credential Store**: SQLite-backed local identity storage (~/.config/sam/state.db)
-- **Trust Cache**: Peer reputation tracking and scoring
-
-## Quick Start
-
-### Installation
-
-```bash
-cd python
-python -m pip install -e .
-```
-
-### Authentication
-
-```python
-import asyncio
-from sam_mesh import MeshClient
-
-async def main():
- async with MeshClient("https://hub.example.com") as client:
- # Authenticate via OIDC device flow
- creds = await client.login()
- print(f"Logged in as {creds.peer_id}")
-
- # Credentials are automatically saved to ~/.config/sam/state.db
-
-if __name__ == "__main__":
- asyncio.run(main())
-```
-
-### Loading Existing Credentials
-
-```python
-from sam_mesh import MeshClient
-
-client = MeshClient("https://hub.example.com")
-creds = client.load_credentials()
-if creds:
- print(f"Using existing identity: {creds.peer_id}")
-```
-
-### Validating Passports
-
-```python
-from sam_mesh import MeshClient, validate_passport_biscuit
-
-client = MeshClient("https://hub.example.com")
-creds = client.load_credentials()
-
-# Validate a passport biscuit received from a peer
-claims = client.validate_passport(
- biscuit=creds.passport_biscuit,
- hub_public_key_b64="...",
- expected_peer_id=creds.peer_id,
-)
-print(f"Validated: {claims.subject}")
-```
-
-## API Reference
-
-### MeshClient
-
-High-level async client for SAM operations.
-
-```python
-client = MeshClient(
- hub_url: str,
- credential_store: Optional[CredentialStore] = None,
- client_id: str = "sam-cli",
-)
-```
-
-**Methods:**
-
-- `async login() -> StoredCredentials`: Authenticate via OIDC device flow
-- `load_credentials() -> Optional[StoredCredentials]`: Load stored identity
-- `validate_passport(...) -> PassportClaims`: Validate a biscuit
-- `async fetch_hub_p2p_info() -> dict`: Get hub's P2P bootstrap addresses
-- `close()`: Release resources
-
-### HubClient
-
-Low-level client for hub HTTP operations.
-
-```python
-async with HubClient(hub_url, client_id="my-app") as hub:
- # OIDC discovery
- discovery = await hub.discover()
-
- # Device flow
- auth = await hub.start_device_flow(discovery.device_authorization_endpoint)
- token = await hub.poll_device_token(discovery.token_endpoint, auth)
-
- # Passport issuance
- biscuit = await hub.issue_passport_biscuit(
- access_token=token.access_token,
- peer_id="...",
- federation_id="default",
- )
-
- # P2P bootstrap info
- info = await hub.fetch_p2p_info()
- peer_id, addrs = info["peer_id"], info["addrs"]
-```
-
-### CredentialStore
-
-Manages persistent local credentials.
-
-```python
-from sam_mesh import CredentialStore, default_credential_store
-
-# Use default location
-store = default_credential_store()
-
-# Or specify a path
-store = CredentialStore("/path/to/state.db")
-
-# Load credentials
-creds = store.load()
-
-# Save credentials
-store.save(creds)
-
-# Clean up
-store.close()
-```
-
-### PassportClaims
-
-Validated passport biscuit claims.
-
-```python
-from dataclasses import dataclass
-from datetime import datetime
-
-@dataclass
-class PassportClaims:
- token: str
- issuer: str
- peer_id: str
- mesh_id: str
- subject: str
- claims: dict[str, str]
- issued_at: datetime | None
-```
-
-## Exception Hierarchy
-
-All exceptions inherit from `SAMError`:
-
-- `SAMError`: Base exception
-- `AuthenticationError`: Auth protocol failures
-- `CredentialError`: Credential store issues
-- `HubError`: Hub communication failures
-- `ValidationError`: Passport validation failures
-- `TimeoutError`: Operation timeouts
-- `ConnectionError`: Peer connection failures
-
-## Design
-
-The client follows Python async best practices:
-
-- **Async-first**: All I/O operations use `async/await`
-- **Context managers**: Proper resource cleanup with `async with`
-- **Type hints**: Full type annotations for IDE support
-- **Structured exceptions**: Clear error handling
-- **Idiomatic**: Follows Python conventions and style (PEP 8)
-
-## Notes
-
-- Requires Python 3.10+
-- libp2p host configuration (TLS 1.3, QUIC, TCP) must be set up separately
-- Hub must support OIDC discovery and device authorization grant
-
-- This library focuses on identity/auth hook and trust cache parity with Go.
-- Default relay/rendezvous host hint is `app.sam-mesh.dev`.
diff --git a/python/examples/libp2p_integration.py b/python/examples/libp2p_integration.py
deleted file mode 100644
index 4dc982ed..00000000
--- a/python/examples/libp2p_integration.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python3
-"""Example: Integrate SAM client with libp2p host and authenticate peers."""
-
-import asyncio
-from typing import Any
-
-from sam_mesh import MeshClient, authenticate_peer, validate_passport_biscuit
-
-
-async def example_with_libp2p_host():
- """
- Example showing how to integrate SAM auth with a libp2p host.
-
- In real usage:
- 1. Create a libp2p host (using py-libp2p)
- 2. Load or authenticate with the SAM hub to get a passport
- 3. Set up stream handlers for /sam/auth/1.0.0 and other SAM protocols
- 4. Call authenticate_peer when connecting to other agents
- """
-
- # Load credentials
- client = MeshClient("https://hub.example.com")
- creds = client.load_credentials()
-
- if not creds:
- print("No credentials found. Run login.py first.")
- return
-
- print(f"Using peer ID: {creds.peer_id}")
- print(f"Passport biscuit: {creds.passport_biscuit[:50]}...")
-
- # In a real scenario, you would:
-
- # 1. Create a libp2p host
- # host = await create_libp2p_host(...)
-
- # 2. Register the SAM auth protocol handler
- # host.set_stream_handler("/sam/auth/1.0.0", handle_auth_stream)
-
- # 3. When connecting to a peer, authenticate them
- # await authenticate_peer(
- # open_stream=host.new_stream,
- # peer_id=remote_peer_id,
- # local_passport=creds.passport_biscuit,
- # hub_public_key_b64="...", # from hub
- # mesh_id="default",
- # )
-
- # 4. Validate their passport
- # claims = validate_passport_biscuit(
- # their_passport,
- # hub_public_key_b64="...",
- # expected_peer_id=remote_peer_id,
- # expected_mesh_id="default",
- # )
- # print(f"Authenticated peer: {claims.subject}")
-
- print("\nExample structure shown above. See auth.py for protocol details.")
-
-
-if __name__ == "__main__":
- asyncio.run(example_with_libp2p_host())
diff --git a/python/examples/load_credentials.py b/python/examples/load_credentials.py
deleted file mode 100644
index 02a46ba3..00000000
--- a/python/examples/load_credentials.py
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/usr/bin/env python3
-"""Example: Load stored credentials and validate a passport."""
-
-import sys
-
-from sam_mesh import MeshClient, ValidationError
-
-
-def main():
- """Load and display stored credentials."""
- client = MeshClient("https://hub.example.com")
-
- try:
- creds = client.load_credentials()
-
- if not creds:
- print("No stored credentials found. Run login.py first.", file=sys.stderr)
- sys.exit(1)
-
- print(f"Peer ID: {creds.peer_id}", file=sys.stderr)
- print(f"Hub URL: {creds.hub_url}", file=sys.stderr)
- print(f"Passport Biscuit: {creds.passport_biscuit[:50]}...", file=sys.stderr)
-
- if creds.token_expiry:
- print(f"Token expires at: {creds.token_expiry}", file=sys.stderr)
-
- print("\nTo use credentials in a mesh node, pass the passport biscuit:", file=sys.stderr)
- print(f" passport = '{creds.passport_biscuit}'", file=sys.stderr)
-
- except Exception as e:
- print(f"Error: {e}", file=sys.stderr)
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/python/examples/login.py b/python/examples/login.py
deleted file mode 100644
index 33095781..00000000
--- a/python/examples/login.py
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/env python3
-"""Example: Authenticate with a SAM Hub via OIDC device flow."""
-
-import asyncio
-import sys
-
-from sam_mesh import MeshClient
-
-
-async def main():
- """Authenticate and save credentials to ~/.config/sam/state.db."""
- hub_url = "https://hub.example.com"
- if len(sys.argv) > 1:
- hub_url = sys.argv[1]
-
- print(f"Authenticating with hub: {hub_url}\n", file=sys.stderr)
-
- async with MeshClient(hub_url) as client:
- try:
- # Start OIDC device flow — this will prompt the user to visit a URL
- # and enter a code in the browser
- creds = await client.login()
-
- print(f"✓ Successfully authenticated as peer {creds.peer_id}", file=sys.stderr)
- print(f"✓ Hub: {creds.hub_url}", file=sys.stderr)
- print(f"✓ Passport biscuit issued", file=sys.stderr)
- except Exception as e:
- print(f"✗ Authentication failed: {e}", file=sys.stderr)
- sys.exit(1)
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/python/pyproject.toml b/python/pyproject.toml
deleted file mode 100644
index 7588c91f..00000000
--- a/python/pyproject.toml
+++ /dev/null
@@ -1,27 +0,0 @@
-[build-system]
-requires = ["setuptools>=68", "wheel"]
-build-backend = "setuptools.build_meta"
-
-[project]
-name = "sam-mesh-client"
-version = "0.1.0"
-description = "Python client framework for SAM (Sovereign Agent Mesh)"
-readme = "README.md"
-requires-python = ">=3.10"
-authors = [{ name = "SAM Contributors" }]
-dependencies = [
- "httpx>=0.24.0",
- "pynacl>=1.5.0",
-]
-
-[project.optional-dependencies]
-dev = [
- "pytest>=7.0",
- "pytest-asyncio>=0.21.0",
- "black>=23.0",
- "ruff>=0.1.0",
-]
-
-[tool.setuptools.packages.find]
-where = ["."]
-include = ["sam_mesh*"]
diff --git a/python/sam_mesh/__init__.py b/python/sam_mesh/__init__.py
deleted file mode 100644
index 82be1aab..00000000
--- a/python/sam_mesh/__init__.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""SAM Mesh — Python client for the Sovereign Agent Mesh."""
-
-from .auth import (
- A2A_PROTOCOL_ID,
- AUTH_PROTOCOL_ID,
- DEFAULT_HUB_ISSUER,
- DEFAULT_RELAY_RENDEZVOUS,
- MCP_PROTOCOL_ID,
- PassportClaims,
- authenticate_peer,
- validate_passport_biscuit,
-)
-from .client import MeshClient
-from .credentials import CredentialStore, StoredCredentials, default_credential_store
-from .exceptions import (
- AuthenticationError,
- ConnectionError,
- CredentialError,
- HubError,
- SAMError,
- TimeoutError,
- ValidationError,
-)
-from .hub import HubClient
-from .trust_cache import SQLiteTrustCache
-
-__version__ = "0.1.0"
-
-__all__ = [
- # High-level client
- "MeshClient",
- # Hub and auth
- "HubClient",
- # Credentials
- "CredentialStore",
- "StoredCredentials",
- "default_credential_store",
- # Passport validation
- "PassportClaims",
- "validate_passport_biscuit",
- "authenticate_peer",
- # Protocol IDs
- "AUTH_PROTOCOL_ID",
- "A2A_PROTOCOL_ID",
- "MCP_PROTOCOL_ID",
- # Constants
- "DEFAULT_HUB_ISSUER",
- "DEFAULT_RELAY_RENDEZVOUS",
- # Exceptions
- "SAMError",
- "AuthenticationError",
- "CredentialError",
- "HubError",
- "ValidationError",
- "TimeoutError",
- "ConnectionError",
- # Trust cache
- "SQLiteTrustCache",
-]
diff --git a/python/sam_mesh/__pycache__/__init__.cpython-312.pyc b/python/sam_mesh/__pycache__/__init__.cpython-312.pyc
deleted file mode 100644
index 7158f19c..00000000
Binary files a/python/sam_mesh/__pycache__/__init__.cpython-312.pyc and /dev/null differ
diff --git a/python/sam_mesh/__pycache__/auth.cpython-312.pyc b/python/sam_mesh/__pycache__/auth.cpython-312.pyc
deleted file mode 100644
index 56b105cf..00000000
Binary files a/python/sam_mesh/__pycache__/auth.cpython-312.pyc and /dev/null differ
diff --git a/python/sam_mesh/__pycache__/client.cpython-312.pyc b/python/sam_mesh/__pycache__/client.cpython-312.pyc
deleted file mode 100644
index f396f9e3..00000000
Binary files a/python/sam_mesh/__pycache__/client.cpython-312.pyc and /dev/null differ
diff --git a/python/sam_mesh/__pycache__/credentials.cpython-312.pyc b/python/sam_mesh/__pycache__/credentials.cpython-312.pyc
deleted file mode 100644
index 82342f14..00000000
Binary files a/python/sam_mesh/__pycache__/credentials.cpython-312.pyc and /dev/null differ
diff --git a/python/sam_mesh/__pycache__/exceptions.cpython-312.pyc b/python/sam_mesh/__pycache__/exceptions.cpython-312.pyc
deleted file mode 100644
index 8233b996..00000000
Binary files a/python/sam_mesh/__pycache__/exceptions.cpython-312.pyc and /dev/null differ
diff --git a/python/sam_mesh/__pycache__/hub.cpython-312.pyc b/python/sam_mesh/__pycache__/hub.cpython-312.pyc
deleted file mode 100644
index 7fb57f2d..00000000
Binary files a/python/sam_mesh/__pycache__/hub.cpython-312.pyc and /dev/null differ
diff --git a/python/sam_mesh/__pycache__/trust_cache.cpython-312.pyc b/python/sam_mesh/__pycache__/trust_cache.cpython-312.pyc
deleted file mode 100644
index 40591197..00000000
Binary files a/python/sam_mesh/__pycache__/trust_cache.cpython-312.pyc and /dev/null differ
diff --git a/python/sam_mesh/auth.py b/python/sam_mesh/auth.py
deleted file mode 100644
index 20523508..00000000
--- a/python/sam_mesh/auth.py
+++ /dev/null
@@ -1,128 +0,0 @@
-from __future__ import annotations
-
-import base64
-import json
-from dataclasses import dataclass
-from datetime import datetime
-from typing import Any, Mapping
-
-from nacl.signing import VerifyKey
-
-DEFAULT_HUB_ISSUER = "app.sam-mesh.dev"
-DEFAULT_RELAY_RENDEZVOUS = "app.sam-mesh.dev"
-
-AUTH_PROTOCOL_ID = "/sam/auth/1.0.0"
-A2A_PROTOCOL_ID = "/sam/a2a/1.0.0"
-MCP_PROTOCOL_ID = "/sam/mcp/1.0.0"
-
-
-@dataclass(frozen=True)
-class PassportClaims:
- token: str
- issuer: str
- peer_id: str
- mesh_id: str
- subject: str
- claims: Mapping[str, str]
- issued_at: datetime | None
-
-
-def _b64raw_decode(value: str) -> bytes:
- padding = "=" * ((4 - (len(value) % 4)) % 4)
- return base64.urlsafe_b64decode(value + padding)
-
-
-def validate_passport_biscuit(
- token: str,
- *,
- hub_public_key_b64: str,
- expected_peer_id: str,
- expected_mesh_id: str,
-) -> PassportClaims:
- subject = token.split(";", 1)[0].strip()
- parts = subject.split("|")
- if len(parts) != 3 or parts[0] != "passportv1":
- raise ValueError("invalid passport biscuit subject")
-
- payload_b64 = ""
- sig_b64 = ""
- for part in parts[1:]:
- if "=" not in part:
- continue
- k, v = part.split("=", 1)
- if k == "payload":
- payload_b64 = v
- elif k == "sig":
- sig_b64 = v
- if not payload_b64 or not sig_b64:
- raise ValueError("invalid passport biscuit envelope")
-
- payload_bytes = _b64raw_decode(payload_b64)
- signature = _b64raw_decode(sig_b64)
- verify_key = VerifyKey(_b64raw_decode(hub_public_key_b64))
- verify_key.verify(payload_bytes, signature)
-
- payload: dict[str, Any] = json.loads(payload_bytes.decode("utf-8"))
- peer_id = str(payload.get("peer_id", "")).strip()
- mesh_id = str(payload.get("mesh_id") or payload.get("federation_id") or "").strip()
- if peer_id != expected_peer_id.strip():
- raise ValueError("passport peer mismatch")
- if mesh_id != expected_mesh_id.strip():
- raise ValueError("passport mesh mismatch")
-
- issued_at = None
- raw_ts = payload.get("issued_at")
- if isinstance(raw_ts, str) and raw_ts:
- try:
- issued_at = datetime.fromisoformat(raw_ts.replace("Z", "+00:00"))
- except ValueError:
- issued_at = None
-
- return PassportClaims(
- token=token,
- issuer=str(payload.get("issuer", "")).strip(),
- peer_id=peer_id,
- mesh_id=mesh_id,
- subject=str(payload.get("subject", "")).strip(),
- claims=dict(payload.get("claims") or {}),
- issued_at=issued_at,
- )
-
-
-async def authenticate_peer(
- *,
- open_stream,
- peer_id: str,
- local_passport: str,
- hub_public_key_b64: str,
- mesh_id: str,
-):
- """
- Application-layer auth handshake for /sam/auth/1.0.0.
-
- Parameters:
- - open_stream: async callable (peer_id, protocol_id) -> stream
- stream must implement async write(bytes), read() -> bytes, close().
- """
- if not local_passport.strip():
- raise ValueError("local passport is required")
-
- stream = await open_stream(peer_id, AUTH_PROTOCOL_ID)
- try:
- request = json.dumps({"passport": local_passport}).encode("utf-8") + b"\n"
- await stream.write(request)
- raw = await stream.read()
- if not raw:
- raise ValueError("empty passport auth response")
- response = json.loads(raw.decode("utf-8"))
- if not response.get("ok", False):
- raise ValueError(response.get("error", "passport authentication rejected"))
- # Validate our own local token shape early to fail fast on malformed state.
- _ = validate_passport_biscuit(
- local_passport,
- hub_public_key_b64=hub_public_key_b64,
- expected_peer_id=peer_id,
- expected_mesh_id=mesh_id,
- )
- finally:
- await stream.close()
diff --git a/python/sam_mesh/client.py b/python/sam_mesh/client.py
deleted file mode 100644
index 7ef9cc36..00000000
--- a/python/sam_mesh/client.py
+++ /dev/null
@@ -1,232 +0,0 @@
-"""High-level SAM mesh client for Python."""
-
-from __future__ import annotations
-
-import sys
-from typing import Optional
-
-from .auth import PassportClaims, validate_passport_biscuit
-from .credentials import CredentialStore, StoredCredentials, default_credential_store
-from .exceptions import (
- AuthenticationError,
- CredentialError,
- HubError,
- SAMError,
- ValidationError,
-)
-from .hub import HubClient
-
-
-class MeshClient:
- """
- Idiomatic async Python client for the SAM sovereign mesh.
-
- Provides:
- - OIDC device flow authentication
- - Hub-issued passport biscuit management
- - Credential persistence
- - Peer authentication and validation
- """
-
- def __init__(
- self,
- hub_url: str,
- *,
- credential_store: Optional[CredentialStore] = None,
- client_id: str = "sam-cli",
- ):
- """
- Initialize the mesh client.
-
- Args:
- hub_url: Base URL of the SAM Hub.
- credential_store: Credential store (uses default ~/.config/sam/state.db if None).
- client_id: OAuth2 client ID (default: "sam-cli").
- """
- self.hub_url = hub_url
- self.client_id = client_id
- self._cred_store = credential_store
- self._owned_store = credential_store is None
- self._hub_client: Optional[HubClient] = None
- self._local_creds: Optional[StoredCredentials] = None
-
- def __enter__(self) -> MeshClient:
- """Context manager entry."""
- if self._owned_store and self._cred_store is None:
- self._cred_store = default_credential_store()
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb) -> None:
- """Context manager exit."""
- self.close()
-
- async def __aenter__(self) -> MeshClient:
- """Async context manager entry."""
- self.__enter__()
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
- """Async context manager exit."""
- self.close()
-
- def close(self) -> None:
- """Close the client and release resources."""
- if self._cred_store and self._owned_store:
- self._cred_store.close()
-
- def _ensure_store(self) -> CredentialStore:
- """Ensure credential store is initialized."""
- if self._cred_store is None:
- self._cred_store = default_credential_store()
- self._owned_store = True
- return self._cred_store
-
- def load_credentials(self) -> Optional[StoredCredentials]:
- """
- Load stored credentials from the local store.
-
- Returns:
- StoredCredentials or None if no identity exists.
- """
- try:
- store = self._ensure_store()
- return store.load()
- except Exception as e:
- raise CredentialError(f"failed to load credentials: {e}") from e
-
- async def login(self) -> StoredCredentials:
- """
- Authenticate via the hub using OIDC device authorization grant flow.
-
- Prompts the user to visit a URL and enter a code. Returns once the user
- completes sign-in and the hub issues a passport biscuit.
-
- Returns:
- StoredCredentials with access token and passport biscuit.
-
- Raises:
- HubError: If authentication fails.
- CredentialError: If credential storage fails.
- """
- try:
- async with HubClient(self.hub_url, client_id=self.client_id) as hub:
- # Discover OIDC endpoints
- discovery = await hub.discover()
-
- # Start device flow
- auth = await hub.start_device_flow(discovery.device_authorization_endpoint)
-
- # Display codes to user
- verify_url = auth.verification_uri_complete or auth.verification_uri
- print(f"\nOpen this URL in your browser:\n\n {verify_url}\n", file=sys.stderr)
- if not auth.verification_uri_complete:
- print(f"And enter code: {auth.user_code}\n", file=sys.stderr)
- print(f"Waiting for authorization (expires in {auth.expires_in}s) …\n", file=sys.stderr)
-
- # Poll for token
- token_result = await hub.poll_device_token(
- discovery.token_endpoint,
- auth,
- max_wait_secs=float(auth.expires_in),
- )
-
- # For now, use a placeholder peer ID. In practice, this would come
- # from the libp2p host after it's created.
- # The real flow in Go: build node -> get peer ID -> issue passport
- print("Authorization successful. Issuing passport …\n", file=sys.stderr)
-
- # TODO: this should come from the libp2p host's PeerID()
- # For now we'll issue without a peer ID and update after node is built
- peer_id = "temp-placeholder"
- biscuit = await hub.issue_passport_biscuit(
- token_result.access_token,
- peer_id=peer_id,
- federation_id="default",
- subject=peer_id,
- )
-
- # Store credentials
- creds = StoredCredentials(
- peer_id=peer_id,
- hub_url=self.hub_url,
- access_token=token_result.access_token,
- refresh_token=token_result.refresh_token or "",
- passport_biscuit=biscuit,
- )
- store = self._ensure_store()
- store.save(creds)
- self._local_creds = creds
-
- print(f"Logged in as peer {peer_id}\n", file=sys.stderr)
- print(f"Credentials saved to {store._path}\n", file=sys.stderr)
-
- return creds
- except HubError:
- raise
- except Exception as e:
- raise HubError(f"authentication failed: {e}") from e
-
- def validate_passport(
- self,
- biscuit: str,
- *,
- hub_public_key_b64: str,
- expected_peer_id: str,
- expected_mesh_id: str = "default",
- ) -> PassportClaims:
- """
- Validate a passport biscuit.
-
- Args:
- biscuit: The passport biscuit token.
- hub_public_key_b64: Hub's Ed25519 public key (base64-encoded).
- expected_peer_id: Expected peer ID in the biscuit.
- expected_mesh_id: Expected federation/mesh ID.
-
- Returns:
- PassportClaims with validated claims.
-
- Raises:
- ValidationError: If the biscuit is invalid.
- """
- try:
- return validate_passport_biscuit(
- biscuit,
- hub_public_key_b64=hub_public_key_b64,
- expected_peer_id=expected_peer_id,
- expected_mesh_id=expected_mesh_id,
- )
- except ValueError as e:
- raise ValidationError(f"passport validation failed: {e}") from e
-
- async def fetch_hub_p2p_info(self) -> dict:
- """
- Fetch the hub's P2P bootstrap information.
-
- Returns:
- Dict with 'peer_id' and 'addrs' keys.
-
- Raises:
- HubError: If the hub is not running in P2P mode.
- """
- try:
- async with HubClient(self.hub_url) as hub:
- return await hub.fetch_p2p_info()
- except HubError:
- raise
- except Exception as e:
- raise HubError(f"failed to fetch hub P2P info: {e}") from e
-
-
-__all__ = [
- "MeshClient",
- "HubClient",
- "CredentialStore",
- "StoredCredentials",
- "PassportClaims",
- "SAMError",
- "AuthenticationError",
- "CredentialError",
- "HubError",
- "ValidationError",
-]
diff --git a/python/sam_mesh/credentials.py b/python/sam_mesh/credentials.py
deleted file mode 100644
index 71ca0a36..00000000
--- a/python/sam_mesh/credentials.py
+++ /dev/null
@@ -1,168 +0,0 @@
-"""Local credential store for SAM identities."""
-
-from __future__ import annotations
-
-import json
-import sqlite3
-from dataclasses import asdict, dataclass, field
-from datetime import datetime
-from pathlib import Path
-from typing import Optional
-
-from .exceptions import CredentialError
-
-
-@dataclass
-class StoredCredentials:
- """Persisted identity state in the SAM credential store."""
-
- peer_id: str
- """Local libp2p peer ID."""
-
- hub_url: str
- """Hub the user authenticated against."""
-
- access_token: str
- """OAuth2 access token returned by the Hub."""
-
- passport_biscuit: str
- """Hub-issued biscuit binding identity to peer/federation."""
-
- refresh_token: str = ""
- """Refresh token for silent token renewal."""
-
- token_expiry: Optional[datetime] = None
- """When the access token expires."""
-
- def to_dict(self) -> dict:
- """Serialize to dict for JSON storage."""
- data = asdict(self)
- if self.token_expiry:
- data["token_expiry"] = self.token_expiry.isoformat()
- return data
-
- @classmethod
- def from_dict(cls, data: dict) -> StoredCredentials:
- """Deserialize from dict."""
- if "token_expiry" in data and data["token_expiry"]:
- try:
- data["token_expiry"] = datetime.fromisoformat(
- data["token_expiry"].replace("Z", "+00:00")
- )
- except (ValueError, TypeError):
- data["token_expiry"] = None
- return cls(**data)
-
-
-class CredentialStore:
- """Reads and writes SAM credentials from a local SQLite store."""
-
- def __init__(self, db_path: str | Path):
- """
- Initialize the credential store.
-
- Args:
- db_path: Path to SQLite database file.
- """
- self._path = str(db_path)
- self._conn = sqlite3.connect(self._path)
- self._init_schema()
-
- def _init_schema(self) -> None:
- """Create tables if they don't exist."""
- self._conn.execute(
- """
- CREATE TABLE IF NOT EXISTS credentials (
- key TEXT PRIMARY KEY,
- data TEXT NOT NULL
- )
- """
- )
- self._conn.commit()
-
- def load(self) -> Optional[StoredCredentials]:
- """
- Load stored credentials. Returns None if no identity exists.
-
- Returns:
- StoredCredentials or None.
-
- Raises:
- CredentialError: If load fails.
- """
- try:
- row = self._conn.execute(
- "SELECT data FROM credentials WHERE key = 'local'"
- ).fetchone()
- if not row:
- return None
- data = json.loads(row[0])
- return StoredCredentials.from_dict(data)
- except Exception as e:
- raise CredentialError(f"failed to load credentials: {e}") from e
-
- def save(self, creds: StoredCredentials) -> None:
- """
- Save credentials to the store.
-
- Args:
- creds: Credentials to save.
-
- Raises:
- CredentialError: If save fails.
- """
- try:
- data = json.dumps(creds.to_dict())
- self._conn.execute(
- """
- INSERT INTO credentials(key, data)
- VALUES ('local', ?)
- ON CONFLICT(key) DO UPDATE SET data = excluded.data
- """,
- (data,),
- )
- self._conn.commit()
- except Exception as e:
- raise CredentialError(f"failed to save credentials: {e}") from e
-
- def delete(self) -> None:
- """Delete stored credentials."""
- try:
- self._conn.execute("DELETE FROM credentials WHERE key = 'local'")
- self._conn.commit()
- except Exception as e:
- raise CredentialError(f"failed to delete credentials: {e}") from e
-
- def close(self) -> None:
- """Close the credential store."""
- if self._conn:
- self._conn.close()
-
- def __enter__(self) -> CredentialStore:
- """Context manager entry."""
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb) -> None:
- """Context manager exit."""
- self.close()
-
-
-def default_credential_store() -> CredentialStore:
- """
- Return a credential store using the default SAM state directory.
-
- The default path is ~/.config/sam/state.db.
-
- Returns:
- CredentialStore instance.
-
- Raises:
- CredentialError: If the default path cannot be resolved.
- """
- try:
- config_dir = Path.home() / ".config" / "sam"
- config_dir.mkdir(parents=True, exist_ok=True)
- db_path = config_dir / "state.db"
- return CredentialStore(str(db_path))
- except Exception as e:
- raise CredentialError(f"failed to initialize default credential store: {e}") from e
diff --git a/python/sam_mesh/exceptions.py b/python/sam_mesh/exceptions.py
deleted file mode 100644
index 4851183a..00000000
--- a/python/sam_mesh/exceptions.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""SAM client exceptions."""
-
-
-class SAMError(Exception):
- """Base exception for all SAM client errors."""
-
- pass
-
-
-class AuthenticationError(SAMError):
- """Raised when passport authentication fails."""
-
- pass
-
-
-class HubError(SAMError):
- """Raised when hub communication or OIDC flow fails."""
-
- pass
-
-
-class CredentialError(SAMError):
- """Raised when credential store operations fail."""
-
- pass
-
-
-class ValidationError(SAMError):
- """Raised when passport or message validation fails."""
-
- pass
-
-
-class TimeoutError(SAMError):
- """Raised when an operation times out."""
-
- pass
-
-
-class ConnectionError(SAMError):
- """Raised when a peer connection fails."""
-
- pass
diff --git a/python/sam_mesh/hub.py b/python/sam_mesh/hub.py
deleted file mode 100644
index 4ad60b9a..00000000
--- a/python/sam_mesh/hub.py
+++ /dev/null
@@ -1,277 +0,0 @@
-"""SAM Hub client for OIDC authentication and passport issuance."""
-
-from __future__ import annotations
-
-import asyncio
-import json
-from dataclasses import dataclass
-from typing import Optional
-
-import httpx
-
-from .exceptions import HubError, ValidationError
-
-
-@dataclass
-class HubDiscovery:
- """OIDC discovery document from the hub."""
-
- issuer: str
- authorization_endpoint: str
- token_endpoint: str
- device_authorization_endpoint: str
- jwks_uri: str
-
-
-@dataclass
-class DeviceFlowAuth:
- """Device authorization flow response."""
-
- device_code: str
- user_code: str
- verification_uri: str
- verification_uri_complete: str
- expires_in: int
- interval: int = 5
-
-
-@dataclass
-class DeviceFlowToken:
- """Token response from device flow."""
-
- access_token: str
- refresh_token: Optional[str] = None
- expires_in: Optional[int] = None
-
-
-class HubClient:
- """Client for SAM Hub OIDC and passport operations."""
-
- def __init__(self, hub_url: str, client_id: str = "sam-cli", timeout: float = 30.0):
- """
- Initialize the hub client.
-
- Args:
- hub_url: Base URL of the SAM Hub (e.g. https://hub.example.com).
- client_id: OAuth2 client ID registered with the hub.
- timeout: Request timeout in seconds.
- """
- self.hub_url = hub_url.rstrip("/")
- self.client_id = client_id
- self.timeout = timeout
- self._http_client: Optional[httpx.AsyncClient] = None
-
- async def __aenter__(self) -> HubClient:
- """Async context manager entry."""
- self._http_client = httpx.AsyncClient(timeout=self.timeout)
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
- """Async context manager exit."""
- if self._http_client:
- await self._http_client.aclose()
-
- async def discover(self) -> HubDiscovery:
- """
- Fetch the hub's OIDC discovery document.
-
- Returns:
- HubDiscovery with endpoints.
-
- Raises:
- HubError: If discovery fails.
- """
- if not self._http_client:
- raise HubError("hub client not initialized (use async context manager)")
-
- try:
- url = f"{self.hub_url}/.well-known/openid-configuration"
- resp = await self._http_client.get(url)
- resp.raise_for_status()
- data = resp.json()
-
- return HubDiscovery(
- issuer=data.get("issuer", ""),
- authorization_endpoint=data.get("authorization_endpoint", ""),
- token_endpoint=data.get("token_endpoint", ""),
- device_authorization_endpoint=data.get("device_authorization_endpoint", ""),
- jwks_uri=data.get("jwks_uri", ""),
- )
- except httpx.HTTPError as e:
- raise HubError(f"hub discovery failed: {e}") from e
-
- async def start_device_flow(self, device_auth_endpoint: str) -> DeviceFlowAuth:
- """
- Start the OAuth2 device authorization grant flow.
-
- Args:
- device_auth_endpoint: Device authorization endpoint URL.
-
- Returns:
- DeviceFlowAuth with user code and verification URI.
-
- Raises:
- HubError: If the flow cannot be started.
- """
- if not self._http_client:
- raise HubError("hub client not initialized (use async context manager)")
-
- try:
- payload = {
- "client_id": self.client_id,
- "scope": "openid profile email",
- }
- resp = await self._http_client.post(device_auth_endpoint, data=payload)
- resp.raise_for_status()
- data = resp.json()
-
- return DeviceFlowAuth(
- device_code=data.get("device_code", ""),
- user_code=data.get("user_code", ""),
- verification_uri=data.get("verification_uri", ""),
- verification_uri_complete=data.get("verification_uri_complete", ""),
- expires_in=int(data.get("expires_in", 600)),
- interval=int(data.get("interval", 5)),
- )
- except httpx.HTTPError as e:
- raise HubError(f"device flow initiation failed: {e}") from e
-
- async def poll_device_token(
- self,
- token_endpoint: str,
- device_flow: DeviceFlowAuth,
- max_wait_secs: Optional[float] = None,
- ) -> DeviceFlowToken:
- """
- Poll the token endpoint until the user approves or the flow expires.
-
- Args:
- token_endpoint: Token endpoint URL.
- device_flow: Device flow auth response.
- max_wait_secs: Maximum time to wait (defaults to device_flow.expires_in).
-
- Returns:
- DeviceFlowToken with access token.
-
- Raises:
- HubError: If polling fails or times out.
- """
- if not self._http_client:
- raise HubError("hub client not initialized (use async context manager)")
-
- if max_wait_secs is None:
- max_wait_secs = float(device_flow.expires_in)
-
- deadline = asyncio.get_event_loop().time() + max_wait_secs
- interval = max(device_flow.interval, 1) # respect minimum 1s
-
- while True:
- if asyncio.get_event_loop().time() > deadline:
- raise HubError("device flow authorization expired")
-
- try:
- payload = {
- "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
- "device_code": device_flow.device_code,
- "client_id": self.client_id,
- }
- resp = await self._http_client.post(token_endpoint, data=payload)
-
- if resp.status_code == 200:
- data = resp.json()
- return DeviceFlowToken(
- access_token=data.get("access_token", ""),
- refresh_token=data.get("refresh_token"),
- expires_in=data.get("expires_in"),
- )
- elif resp.status_code == 400:
- error = resp.json().get("error", "")
- if error == "authorization_pending":
- await asyncio.sleep(interval)
- continue
- elif error == "slow_down":
- interval = min(interval + 5, 30)
- await asyncio.sleep(interval)
- continue
- else:
- raise HubError(f"device flow error: {error}")
- else:
- raise HubError(f"token endpoint returned {resp.status_code}")
- except asyncio.CancelledError:
- raise
- except httpx.HTTPError as e:
- raise HubError(f"device flow polling failed: {e}") from e
-
- async def issue_passport_biscuit(
- self,
- access_token: str,
- peer_id: str,
- federation_id: str,
- subject: str = "",
- email: str = "",
- ) -> str:
- """
- Request a hub-issued passport biscuit.
-
- Args:
- access_token: OAuth2 access token from device flow.
- peer_id: This agent's libp2p peer ID.
- federation_id: Federation/mesh ID.
- subject: Optional subject for the biscuit (defaults to peer_id).
- email: Optional email claim to include.
-
- Returns:
- Hub-issued passport biscuit (ED25519 envelope).
-
- Raises:
- HubError: If passport issuance fails.
- """
- if not self._http_client:
- raise HubError("hub client not initialized (use async context manager)")
-
- if not subject:
- subject = peer_id
-
- try:
- url = f"{self.hub_url}/issue-passport"
- headers = {"Authorization": f"Bearer {access_token}"}
- payload = {
- "peer_id": peer_id,
- "federation": federation_id,
- "mesh_id": federation_id,
- "subject": subject,
- "email": email,
- }
- resp = await self._http_client.post(url, json=payload, headers=headers)
- resp.raise_for_status()
- data = resp.json()
-
- biscuit = data.get("passport_biscuit", "")
- if not biscuit:
- raise ValidationError("hub did not return a passport biscuit")
- return biscuit
- except httpx.HTTPError as e:
- raise HubError(f"passport issuance failed: {e}") from e
-
- async def fetch_p2p_info(self) -> dict:
- """
- Fetch the hub's P2P peer ID and multiaddrs.
-
- Returns:
- Dict with 'peer_id' and 'addrs' keys.
-
- Raises:
- HubError: If the hub is not running in P2P mode or the request fails.
- """
- if not self._http_client:
- raise HubError("hub client not initialized (use async context manager)")
-
- try:
- url = f"{self.hub_url}/.well-known/sam-hub-p2p"
- resp = await self._http_client.get(url)
- if resp.status_code == 503:
- raise HubError("hub is not running in P2P mode")
- resp.raise_for_status()
- return resp.json()
- except httpx.HTTPError as e:
- raise HubError(f"failed to fetch hub P2P info: {e}") from e
diff --git a/python/sam_mesh/trust_cache.py b/python/sam_mesh/trust_cache.py
deleted file mode 100644
index 16b4c25a..00000000
--- a/python/sam_mesh/trust_cache.py
+++ /dev/null
@@ -1,67 +0,0 @@
-from __future__ import annotations
-
-import sqlite3
-from pathlib import Path
-from typing import Dict
-
-
-class SQLiteTrustCache:
- def __init__(self, db_path: str | Path):
- self._path = str(db_path)
- self._conn = sqlite3.connect(self._path)
- self._conn.execute(
- """
- CREATE TABLE IF NOT EXISTS peer_scores (
- peer_id TEXT PRIMARY KEY,
- total INTEGER NOT NULL,
- count INTEGER NOT NULL,
- score REAL NOT NULL
- )
- """
- )
- self._conn.commit()
-
- def update(self, peer_id: str, rating: int) -> float:
- if rating < -1 or rating > 1:
- raise ValueError("rating must be -1..1")
- peer = peer_id.strip()
- if not peer:
- raise ValueError("peer_id is required")
-
- row = self._conn.execute(
- "SELECT total, count FROM peer_scores WHERE peer_id = ?", (peer,)
- ).fetchone()
- total = int(row[0]) if row else 0
- count = int(row[1]) if row else 0
- total += rating
- count += 1
- score = total / count
-
- self._conn.execute(
- """
- INSERT INTO peer_scores(peer_id, total, count, score)
- VALUES (?, ?, ?, ?)
- ON CONFLICT(peer_id)
- DO UPDATE SET total = excluded.total, count = excluded.count, score = excluded.score
- """,
- (peer, total, count, score),
- )
- self._conn.commit()
- return score
-
- def score(self, peer_id: str) -> float:
- row = self._conn.execute(
- "SELECT score FROM peer_scores WHERE peer_id = ?", (peer_id.strip(),)
- ).fetchone()
- if not row:
- return 0.0
- return float(row[0])
-
- def snapshot(self) -> Dict[str, float]:
- out: Dict[str, float] = {}
- for peer_id, score in self._conn.execute("SELECT peer_id, score FROM peer_scores"):
- out[str(peer_id)] = float(score)
- return out
-
- def close(self) -> None:
- self._conn.close()
diff --git a/python/sam_mesh_client.egg-info/PKG-INFO b/python/sam_mesh_client.egg-info/PKG-INFO
deleted file mode 100644
index 0f7cc27c..00000000
--- a/python/sam_mesh_client.egg-info/PKG-INFO
+++ /dev/null
@@ -1,202 +0,0 @@
-Metadata-Version: 2.4
-Name: sam-mesh-client
-Version: 0.1.0
-Summary: Python client framework for SAM (Sovereign Agent Mesh)
-Author: SAM Contributors
-Requires-Python: >=3.10
-Description-Content-Type: text/markdown
-Requires-Dist: httpx>=0.24.0
-Requires-Dist: pynacl>=1.5.0
-Provides-Extra: dev
-Requires-Dist: pytest>=7.0; extra == "dev"
-Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
-Requires-Dist: black>=23.0; extra == "dev"
-Requires-Dist: ruff>=0.1.0; extra == "dev"
-
-# SAM Python Client Framework
-
-This package provides an idiomatic async Python client for the SAM (Sovereign Agent Mesh):
-
-## Features
-
-- **MeshClient**: High-level async API for mesh operations
-- **OIDC Device Flow**: Hub authentication with device authorization grant
-- **Passport Management**: Hub-issued biscuit validation and credential persistence
-- **Protocol Support**: `/sam/auth/1.0.0`, `/sam/a2a/1.0.0`, `/sam/mcp/1.0.0`
-- **Credential Store**: SQLite-backed local identity storage (~/.config/sam/state.db)
-- **Trust Cache**: Peer reputation tracking and scoring
-
-## Quick Start
-
-### Installation
-
-```bash
-cd python
-python -m pip install -e .
-```
-
-### Authentication
-
-```python
-import asyncio
-from sam_mesh import MeshClient
-
-async def main():
- async with MeshClient("https://hub.example.com") as client:
- # Authenticate via OIDC device flow
- creds = await client.login()
- print(f"Logged in as {creds.peer_id}")
-
- # Credentials are automatically saved to ~/.config/sam/state.db
-
-if __name__ == "__main__":
- asyncio.run(main())
-```
-
-### Loading Existing Credentials
-
-```python
-from sam_mesh import MeshClient
-
-client = MeshClient("https://hub.example.com")
-creds = client.load_credentials()
-if creds:
- print(f"Using existing identity: {creds.peer_id}")
-```
-
-### Validating Passports
-
-```python
-from sam_mesh import MeshClient, validate_passport_biscuit
-
-client = MeshClient("https://hub.example.com")
-creds = client.load_credentials()
-
-# Validate a passport biscuit received from a peer
-claims = client.validate_passport(
- biscuit=creds.passport_biscuit,
- hub_public_key_b64="...",
- expected_peer_id=creds.peer_id,
-)
-print(f"Validated: {claims.subject}")
-```
-
-## API Reference
-
-### MeshClient
-
-High-level async client for SAM operations.
-
-```python
-client = MeshClient(
- hub_url: str,
- credential_store: Optional[CredentialStore] = None,
- client_id: str = "sam-cli",
-)
-```
-
-**Methods:**
-
-- `async login() -> StoredCredentials`: Authenticate via OIDC device flow
-- `load_credentials() -> Optional[StoredCredentials]`: Load stored identity
-- `validate_passport(...) -> PassportClaims`: Validate a biscuit
-- `async fetch_hub_p2p_info() -> dict`: Get hub's P2P bootstrap addresses
-- `close()`: Release resources
-
-### HubClient
-
-Low-level client for hub HTTP operations.
-
-```python
-async with HubClient(hub_url, client_id="my-app") as hub:
- # OIDC discovery
- discovery = await hub.discover()
-
- # Device flow
- auth = await hub.start_device_flow(discovery.device_authorization_endpoint)
- token = await hub.poll_device_token(discovery.token_endpoint, auth)
-
- # Passport issuance
- biscuit = await hub.issue_passport_biscuit(
- access_token=token.access_token,
- peer_id="...",
- federation_id="default",
- )
-
- # P2P bootstrap info
- info = await hub.fetch_p2p_info()
- peer_id, addrs = info["peer_id"], info["addrs"]
-```
-
-### CredentialStore
-
-Manages persistent local credentials.
-
-```python
-from sam_mesh import CredentialStore, default_credential_store
-
-# Use default location
-store = default_credential_store()
-
-# Or specify a path
-store = CredentialStore("/path/to/state.db")
-
-# Load credentials
-creds = store.load()
-
-# Save credentials
-store.save(creds)
-
-# Clean up
-store.close()
-```
-
-### PassportClaims
-
-Validated passport biscuit claims.
-
-```python
-from dataclasses import dataclass
-from datetime import datetime
-
-@dataclass
-class PassportClaims:
- token: str
- issuer: str
- peer_id: str
- mesh_id: str
- subject: str
- claims: dict[str, str]
- issued_at: datetime | None
-```
-
-## Exception Hierarchy
-
-All exceptions inherit from `SAMError`:
-
-- `SAMError`: Base exception
-- `AuthenticationError`: Auth protocol failures
-- `CredentialError`: Credential store issues
-- `HubError`: Hub communication failures
-- `ValidationError`: Passport validation failures
-- `TimeoutError`: Operation timeouts
-- `ConnectionError`: Peer connection failures
-
-## Design
-
-The client follows Python async best practices:
-
-- **Async-first**: All I/O operations use `async/await`
-- **Context managers**: Proper resource cleanup with `async with`
-- **Type hints**: Full type annotations for IDE support
-- **Structured exceptions**: Clear error handling
-- **Idiomatic**: Follows Python conventions and style (PEP 8)
-
-## Notes
-
-- Requires Python 3.10+
-- libp2p host configuration (TLS 1.3, QUIC, TCP) must be set up separately
-- Hub must support OIDC discovery and device authorization grant
-
-- This library focuses on identity/auth hook and trust cache parity with Go.
-- Default relay/rendezvous host hint is `app.sam-mesh.dev`.
diff --git a/python/sam_mesh_client.egg-info/SOURCES.txt b/python/sam_mesh_client.egg-info/SOURCES.txt
deleted file mode 100644
index 4bd4a91f..00000000
--- a/python/sam_mesh_client.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-README.md
-pyproject.toml
-sam_mesh/__init__.py
-sam_mesh/auth.py
-sam_mesh/client.py
-sam_mesh/credentials.py
-sam_mesh/exceptions.py
-sam_mesh/hub.py
-sam_mesh/trust_cache.py
-sam_mesh_client.egg-info/PKG-INFO
-sam_mesh_client.egg-info/SOURCES.txt
-sam_mesh_client.egg-info/dependency_links.txt
-sam_mesh_client.egg-info/requires.txt
-sam_mesh_client.egg-info/top_level.txt
\ No newline at end of file
diff --git a/python/sam_mesh_client.egg-info/dependency_links.txt b/python/sam_mesh_client.egg-info/dependency_links.txt
deleted file mode 100644
index 8b137891..00000000
--- a/python/sam_mesh_client.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/python/sam_mesh_client.egg-info/requires.txt b/python/sam_mesh_client.egg-info/requires.txt
deleted file mode 100644
index 9dfd808a..00000000
--- a/python/sam_mesh_client.egg-info/requires.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-httpx>=0.24.0
-pynacl>=1.5.0
-
-[dev]
-pytest>=7.0
-pytest-asyncio>=0.21.0
-black>=23.0
-ruff>=0.1.0
diff --git a/python/sam_mesh_client.egg-info/top_level.txt b/python/sam_mesh_client.egg-info/top_level.txt
deleted file mode 100644
index be775ac3..00000000
--- a/python/sam_mesh_client.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-sam_mesh