Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat(sam-node): add skill install, --daemonize, and reset --all
Antonio Ojea111f9b091571
diff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.mdnew file mode 100644index 00000000..0f00b062--- /dev/null+++ b/agents/skills/sam-mesh/SKILL.md@@ -0,0 +1,175 @@+---+name: sam-mesh+description: "Use when local tools cannot provide a needed capability and a SAM (Sovereign Agent Mesh) network can: inspect mesh state, discover reachable services/tools, describe and call namespaced remote MCP tools, and reach OpenAI-compatible inference models hosted by mesh peers. Also use to set up, join, or reconnect a sam-node when its MCP tools are not callable yet."+---++# SAM Agent Skill++Use this skill when local tools cannot satisfy the task and the SAM mesh can.+Prefer local tools first. Reach into the SAM mesh only for the capability needed+to complete the task.++Pick the path that matches the need:++- The `sam-node` MCP tools are not callable yet:+ [Bootstrap A Node](#bootstrap-a-node).+- The task needs a remote tool or capability:+ [Inspect The Mesh](#inspect-the-mesh).+- The task needs a model completion:+ [Use Mesh Inference](#use-mesh-inference).++## Bootstrap A Node++The mesh is reached through a local `sam-node`. When its MCP tools are missing,+guide the user through these steps. Propose each shell command and let the user+approve it before running anything.++1. Check the CLI: `sam-node --help`. If it is missing, install it with+ `curl -sL https://sam-mesh.dev/install.sh | bash` or+ `go install github.com/google/sam/cmd/sam-node@latest`.+2. Start the node in the background: `sam-node run --daemonize`. It returns as+ soon as the node answers, and prints the endpoint, the API token file, the+ log file, and how to stop it. It is idempotent, so run it again whenever you+ need to confirm a node is up.+3. If step 2 reports that the node is not enrolled, run the command it prints,+ `sam-node join --headless <control-plane-url>`. That prints a URL and a+ code: show both to the user and wait while they complete the login, then+ repeat step 2. Enrollment is a one-time step per machine.+4. Read the node API token from the file named in step 2, then register the MCP+ endpoint `http://127.0.0.1:8080/mcp` with the header+ `X-Sam-Authentication: Bearer <token>`. Claude Code:+ `claude mcp add --transport http sam-mesh http://127.0.0.1:8080/mcp --header "X-Sam-Authentication: Bearer <token>"`.+ Antigravity: add the same URL as `serverUrl` with the same header to+ `~/.gemini/config/mcp_config.json`.+5. Tell the user to restart the agent session, since MCP tools load at startup.++If setup is stuck in a half-configured state, ask the user before starting over:+stop the node, run `sam-node reset --all --yes` for a clean slate, then go back+to step 2. That deletes the node's identity and its PeerID, and enrolling again+needs another login, so never do it to work around an unexplained error.++Put the node API token only in the agent's MCP configuration. Do not echo it+into the transcript, and do not commit it.++## Inspect The Mesh++Start by understanding the local node and mesh state:++- Use `get_mesh_info` with `{}` to inspect `connected_peers`, `dht_size`, and+ `router_peer_id`.+- Use `list_local_services` with `{}` to see services registered on the local+ node.++## Discover Remote Capabilities++Use service discovery when you need to inventory reachable service providers:++- Use `discover_remote_services` with `{"type":"mcp"}`,+ `{"type":"inference"}`, or `{"type":"a2a"}`. Add `name` only when narrowing+ by service name.+- Treat `discover_remote_services` as service inventory. Non-MCP service types+ are not callable with `call_remote_tool`. For `inference://` services see+ [Use Mesh Inference](#use-mesh-inference).++Use tool discovery when you need remote MCP tools:++- Use `find_remote_tools` to discover reachable aggregated MCP tools advertised+ by remote SAM services.+- Narrow `find_remote_tools` with `service_name` or `peer_id` when you already+ know the target.+- Mesh-wide searches fetch each peer's catalog on a best-effort basis and may+ return an empty array when no reachable aggregated tools are found. Discovery+ failures or explicit `peer_id` lookup failures are returned as errors.++## Describe Before Calling++All tools returned by `find_remote_tools` are namespaced. Always call+`describe_remote_tool` before calling them with `call_remote_tool`.++Remote MCP tools returned by `find_remote_tools` are namespaced as:++```text+<service_name>.<tool_name>+```++Use the input schema from `describe_remote_tool` to build the call arguments.+Do not guess arguments if a tool cannot be described.++After `describe_remote_tool`, inspect the tool name, description, and schema+for side effects and required data. Only call read-only, low-risk tools+autonomously. Ask the user before calls that may mutate state, execute code,+access files, contact external services, spend money, or transmit sensitive or+private data. Pass only task-required data, and never include secrets unless+explicitly authorized.++## Call Remote Tools++Use `call_remote_tool` with:++- `peer_id`: the peer hosting the tool+- `tool_name`: the discovered namespaced tool name, such as `service.tool`+- `arguments`: a JSON object whose keys match the described input schema++`arguments` must be a JSON object, not a string containing JSON.++## Use Mesh Inference++The mesh also carries `inference://` services: OpenAI-compatible model+endpoints. They are plain HTTP and are never invoked with `call_remote_tool`.++The node exposes them through an OpenAI-compatible facade on its own address:++- Base URL `http://localhost:8080/v1`, usable as `base_url` for any OpenAI SDK+ or a direct `curl`.+- `GET /v1/models` lists the models reachable across the mesh.+- `POST /v1/chat/completions` routes to a provider of the requested `model`,+ preferring a local one, and fails over between providers.+- Add `X-Sam-Required-Labels: key=value` (comma-separated, any-of) to accept+ only providers whose labels the control plane attested, for example+ `region=eu`. Enforcement is fail-closed: unattested providers are rejected+ before any request data leaves the node.++To pin one specific provider instead of letting the facade choose, call+`discover_remote_services` with `{"type":"inference"}` and send the request to+the returned `local_proxy_url` (append `/v1/chat/completions`).++Authenticate to the node with `X-Sam-Authentication: Bearer <node token>`; the+`/v1` endpoints also accept it as `Authorization`, so an OpenAI SDK can pass it+as its `api_key`. Send a separate `Authorization` header only when the+destination model service needs its own credential: it passes through to that+service untouched.++Ask the user before sending private or sensitive content to a mesh model, and+say which provider will receive it.++## Minimal Workflow++1. Confirm no local tool can satisfy the task.+2. If the `sam-node` MCP tools are unavailable, follow+ [Bootstrap A Node](#bootstrap-a-node) and stop until the user restarts the+ agent session.+3. Call `get_mesh_info` with `{}`.+4. If a local SAM service may be+ relevant, call `list_local_services` with `{}`.+5. Call `find_remote_tools` with `service_name` or `peer_id` when known. Use+ `{}` only when the user asked to inventory the mesh or no narrower target+ exists.+6. Call `describe_remote_tool` with+ `{"peer_id":"...","tool_name":"service.tool"}`.+7. Call `call_remote_tool` only when the described tool is read-only and+ low-risk, or after the user approves the exact `peer_id`, `tool_name`, side+ effects, and task-required data being sent:+ `{"peer_id":"...","tool_name":"service.tool","arguments":{...}}`.++For a model completion rather than a tool, skip steps 5-7 and follow+[Use Mesh Inference](#use-mesh-inference) instead.++## Safety And Reliability++- Do not call mesh tools when a local tool is sufficient.+- Do not guess remote tool names or arguments.+- Ask before side-effecting or sensitive remote calls.+- Do not send secrets or private data through SAM unless the user explicitly+ approves the data and destination.+- Treat remote capabilities as networked and potentially unavailable.+- Surface peer, service, discovery, schema, and tool-call errors clearly.diff --git a/agents/skills/sam-mesh/embed.go b/agents/skills/sam-mesh/embed.gonew file mode 100644index 00000000..1d4d17ee--- /dev/null+++ b/agents/skills/sam-mesh/embed.go@@ -0,0 +1,24 @@+// 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 samskill embeds the SAM agent skill document so it ships inside the+// binaries that install it. SKILL.md stays the single source of truth.+package samskill++import _ "embed"++// Markdown is the SKILL.md document handed to local AI agents.+//+//go:embed SKILL.md+var Markdown stringdiff --git a/agents/skills/sam/SKILL.md b/agents/skills/sam/SKILL.mddeleted file mode 100644index ac63ed16..00000000--- a/agents/skills/sam/SKILL.md+++ /dev/null@@ -1,96 +0,0 @@-----name: sam-description: "Use when local tools cannot provide a needed capability and connected sam-node MCP tools are available to reach a SAM (Sovereign Agent Mesh) network: inspect mesh state, discover reachable services/tools, describe namespaced remote MCP tools, and call them with JSON-object arguments. Not for AWS SAM / Serverless Application Model tasks."------# SAM Agent Skill--Use this skill when local tools cannot satisfy the task and `sam-node` MCP tools-are already callable. Prefer local tools first. Reach into the SAM mesh only for-the capability needed to complete the task.--## Inspect The Mesh--Start by understanding the local node and mesh state:--- Use `get_mesh_info` with `{}` to inspect `connected_peers`, `dht_size`, and- `router_peer_id`.-- Use `list_local_services` with `{}` to see services registered on the local- node.--## Discover Remote Capabilities--Use service discovery when you need to inventory reachable service providers:--- Use `discover_remote_services` with `{"type":"mcp"}`,- `{"type":"inference"}`, or `{"type":"a2a"}`. Add `name` only when narrowing- by service name.-- Treat `discover_remote_services` as service inventory. Non-MCP service types- are not callable with `call_remote_tool`.--Use tool discovery when you need remote MCP tools:--- Use `find_remote_tools` to discover reachable aggregated MCP tools advertised- by remote SAM services.-- Narrow `find_remote_tools` with `service_name` or `peer_id` when you already- know the target.-- Mesh-wide searches fetch each peer's catalog on a best-effort basis and may- return an empty array when no reachable aggregated tools are found. Discovery- failures or explicit `peer_id` lookup failures are returned as errors.--## Describe Before Calling--All tools returned by `find_remote_tools` are namespaced. Always call-`describe_remote_tool` before calling them with `call_remote_tool`.--Remote MCP tools returned by `find_remote_tools` are namespaced as:--```text-<service_name>.<tool_name>-```--Use the input schema from `describe_remote_tool` to build the call arguments.-Do not guess arguments if a tool cannot be described.--After `describe_remote_tool`, inspect the tool name, description, and schema-for side effects and required data. Only call read-only, low-risk tools-autonomously. Ask the user before calls that may mutate state, execute code,-access files, contact external services, spend money, or transmit sensitive or-private data. Pass only task-required data, and never include secrets unless-explicitly authorized.--## Call Remote Tools--Use `call_remote_tool` with:--- `peer_id`: the peer hosting the tool-- `tool_name`: the discovered namespaced tool name, such as `service.tool`-- `arguments`: a JSON object whose keys match the described input schema--`arguments` must be a JSON object, not a string containing JSON.--## Minimal Workflow--1. Confirm no local tool can satisfy the task.-2. Call `get_mesh_info` with `{}`.-3. If a local SAM service may be- relevant, call `list_local_services` with `{}`.-4. Call `find_remote_tools` with `service_name` or `peer_id` when known. Use- `{}` only when the user asked to inventory the mesh or no narrower target- exists.-5. Call `describe_remote_tool` with- `{"peer_id":"...","tool_name":"service.tool"}`.-6. Call `call_remote_tool` only when the described tool is read-only and- low-risk, or after the user approves the exact `peer_id`, `tool_name`, side- effects, and task-required data being sent:- `{"peer_id":"...","tool_name":"service.tool","arguments":{...}}`.--## Safety And Reliability--- Do not call mesh tools when a local tool is sufficient.-- Do not guess remote tool names or arguments.-- Ask before side-effecting or sensitive remote calls.-- Do not send secrets or private data through SAM unless the user explicitly- approves the data and destination.-- Treat remote capabilities as networked and potentially unavailable.-- Surface peer, service, discovery, schema, and tool-call errors clearly.diff --git a/cmd/sam-node/daemonize.go b/cmd/sam-node/daemonize.gonew file mode 100644index 00000000..db5f762c--- /dev/null+++ b/cmd/sam-node/daemonize.go@@ -0,0 +1,343 @@+// 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"+ "crypto/rand"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "strconv"+ "strings"+ "time"++ "github.com/google/sam/internal/node"+)++const (+ daemonPIDFile = "sam-node.pid"+ daemonLogFile = "sam-node.log"+ daemonTokenFile = "api-token"+ daemonReadyTimeout = 90 * time.Second+ daemonPollInterval = 200 * time.Millisecond+)++// daemonizeRun re-executes this binary as a detached background node and+// returns once its local API answers, so a single non-blocking command is+// enough to bring the mesh up.+func daemonizeRun() error {+ dataDir := resolveDataDir()+ probe := localProbeAddr(bindAddrFlag)++ if probeReady(probe, time.Second) {+ fmt.Printf("sam-node is already running and listening on %s\n", probe)+ return nil+ }++ enrolled, controlPlane, err := storedEnrollment(dataDir)+ if errors.Is(err, node.ErrStoreLocked) {+ fmt.Printf("sam-node is already running%s: %s is in use.\n", runningPIDSuffix(dataDir), dataDir)+ return nil+ }+ if err != nil {+ return err+ }+ if !enrolled && bootstrapTokenFlag == "" && bootstrapTokenPathFlag == "" && jwtFlag == "" && jwtPathFlag == "" {+ return fmt.Errorf("this node is not enrolled yet, and enrolling needs a one-time login you have to approve:\n"++ " sam-node join --headless %s\n"++ "then re-run 'sam-node run --daemonize'", controlPlane)+ }++ tokenArgs, tokenPath, err := ensureDaemonToken(dataDir)+ if err != nil {+ return err+ }++ logPath := filepath.Join(dataDir, daemonLogFile)+ logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)+ if err != nil {+ return fmt.Errorf("opening %s: %w", logPath, err)+ }+ defer func() {+ _ = logFile.Close()+ }()++ exe, err := os.Executable()+ if err != nil {+ return fmt.Errorf("locating the sam-node binary: %w", err)+ }++ child := exec.Command(exe, append(withoutDaemonizeFlag(os.Args[1:]), tokenArgs...)...) // #nosec G204 -- re-executes this same binary with this process's own arguments+ child.Stdout = logFile+ child.Stderr = logFile+ child.SysProcAttr = detachedProcAttr()+ if err := child.Start(); err != nil {+ return fmt.Errorf("starting the background node: %w", err)+ }++ pidPath := filepath.Join(dataDir, daemonPIDFile)+ if err := os.WriteFile(pidPath, []byte(strconv.Itoa(child.Process.Pid)), 0644); err != nil {+ logger.Warnf("Failed to write %s: %v", pidPath, err)+ }++ exited := make(chan error, 1)+ go func() { exited <- child.Wait() }()++ if err := waitForDaemon(probe, exited); err != nil {+ return fmt.Errorf("%w\nLast lines of %s:\n%s", err, logPath, tailFile(logPath, 8192, 10))+ }++ printDaemonSummary(child.Process.Pid, probe, tokenPath, logPath)+ return nil+}++// storedEnrollment reports whether this data directory already holds a mesh+// identity, along with the control plane to enroll with if it does not.+func storedEnrollment(dataDir string) (bool, string, error) {+ store, err := node.NewStore(dataDir)+ if err != nil {+ return false, "", fmt.Errorf("opening the node store: %w", err)+ }+ defer func() {+ if err := store.Close(); err != nil {+ logger.Errorf("closing store: %v", err)+ }+ }()+ identity, _ := store.LoadIdentity()+ return len(identity) > 0, defaultControlPlane(store, controlPlaneAddr), nil+}++// ensureDaemonToken keeps the background node authenticated without the user+// inventing a secret: it reuses an explicitly configured token, or generates+// one under the data directory and passes it to the child by path.+func ensureDaemonToken(dataDir string) ([]string, string, error) {+ if apiTokenPathFlag != "" {+ return nil, apiTokenPathFlag, nil+ }+ if os.Getenv("SAM_API_TOKEN") != "" {+ return nil, "", nil+ }+ tokenPath := filepath.Join(dataDir, daemonTokenFile)+ if _, err := os.Stat(tokenPath); err == nil {+ return []string{"--api-token-path", tokenPath}, tokenPath, nil+ }+ buf := make([]byte, 32)+ if _, err := rand.Read(buf); err != nil {+ return nil, "", fmt.Errorf("generating an API token: %w", err)+ }+ f, err := os.OpenFile(tokenPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)+ if err != nil {+ return nil, "", fmt.Errorf("creating %s: %w", tokenPath, err)+ }+ defer func() {+ _ = f.Close()+ }()+ if _, err := io.WriteString(f, hex.EncodeToString(buf)); err != nil {+ return nil, "", fmt.Errorf("writing %s: %w", tokenPath, err)+ }+ return []string{"--api-token-path", tokenPath}, tokenPath, nil+}++// waitForDaemon blocks until the background node answers, it exits, or the+// startup budget runs out.+func waitForDaemon(probe string, exited <-chan error) error {+ deadline := time.After(daemonReadyTimeout)+ for {+ if probeReady(probe, daemonPollInterval) {+ return nil+ }+ select {+ case err := <-exited:+ return fmt.Errorf("the background node exited during startup (%v)", err)+ case <-deadline:+ return fmt.Errorf("the background node did not answer on %s within %s", probe, daemonReadyTimeout)+ case <-time.After(daemonPollInterval):+ }+ }+}++// probeReady reports whether the node's local API is answering on addr.+func probeReady(addr string, timeout time.Duration) bool {+ if tlsCertFlag != "" {+ conn, err := net.DialTimeout("tcp", addr, timeout)+ if err != nil {+ return false+ }+ _ = conn.Close()+ return true+ }+ client := &http.Client{Timeout: timeout}+ resp, err := client.Get("http://" + addr + "/healthz")+ if err != nil {+ return false+ }+ _ = resp.Body.Close()+ return resp.StatusCode == http.StatusOK+}++// localProbeAddr turns a listen address into one that can be dialed from this+// machine, since a wildcard bind is not itself a destination.+func localProbeAddr(bindAddr string) string {+ host, port, err := net.SplitHostPort(bindAddr)+ if err != nil {+ return bindAddr+ }+ switch host {+ case "", "0.0.0.0", "::", "[::]":+ host = "127.0.0.1"+ }+ return net.JoinHostPort(host, port)+}++// runningPIDSuffix renders the pid of a previously daemonized node, when the+// data directory still records one, for use inside a status message.+func runningPIDSuffix(dataDir string) string {+ data, err := os.ReadFile(filepath.Join(dataDir, daemonPIDFile))+ if err != nil {+ return ""+ }+ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))+ if err != nil {+ return ""+ }+ return fmt.Sprintf(" (pid %d)", pid)+}++// confirmPurge gates the destructive reset: the identity it deletes can only+// be recreated by enrolling again, so it is never implicit.+func confirmPurge(dataDir string) error {+ if assumeYesFlag {+ return nil+ }+ if !isInteractiveTerminal() {+ return fmt.Errorf("refusing to delete the node state in %s without confirmation: re-run with --yes", dataDir)+ }+ fmt.Printf("Delete all node state in %s, including the key behind this node's PeerID? [y/N]: ", dataDir)+ answer, err := bufio.NewReader(os.Stdin).ReadString('\n')+ if err != nil {+ return fmt.Errorf("reading the confirmation: %w", err)+ }+ switch strings.ToLower(strings.TrimSpace(answer)) {+ case "y", "yes":+ return nil+ default:+ return fmt.Errorf("aborted: nothing was deleted")+ }+}++// nodeStateFiles are the files a node creates in its data directory. Reset+// removes exactly these and never the directory itself, since --data-dir can+// point at a directory that holds unrelated files.+func nodeStateFiles() []string {+ return []string{node.StoreFile, daemonTokenFile, daemonPIDFile, daemonLogFile}+}++// purgeDataDir deletes all local node state, so the next start behaves like a+// first start instead of inheriting a half-configured one.+func purgeDataDir(dataDir string) ([]string, error) {+ if err := ensureNodeStopped(dataDir); err != nil {+ return nil, err+ }+ var removed []string+ for _, name := range nodeStateFiles() {+ path := filepath.Join(dataDir, name)+ switch err := os.Remove(path); {+ case err == nil:+ removed = append(removed, path)+ case os.IsNotExist(err):+ default:+ return removed, fmt.Errorf("removing %s: %w", path, err)+ }+ }+ return removed, nil+}++// ensureNodeStopped refuses to touch state that a running node still owns.+func ensureNodeStopped(dataDir string) error {+ // No database, no lock to take, and nothing to recreate by looking.+ if _, err := os.Stat(filepath.Join(dataDir, node.StoreFile)); os.IsNotExist(err) {+ return nil+ }+ store, err := node.NewStore(dataDir)+ if errors.Is(err, node.ErrStoreLocked) {+ return fmt.Errorf("a sam-node is still running%s: stop it before resetting %s", runningPIDSuffix(dataDir), dataDir)+ }+ if err != nil {+ // Any other failure, such as a corrupt database, is itself a reason to reset.+ return nil+ }+ return store.Close()+}++// withoutDaemonizeFlag drops --daemonize so the child runs in the foreground.+func withoutDaemonizeFlag(args []string) []string {+ out := make([]string, 0, len(args))+ for _, arg := range args {+ if arg == "--daemonize" || strings.HasPrefix(arg, "--daemonize=") {+ continue+ }+ out = append(out, arg)+ }+ return out+}++// tailFile returns at most the last maxLines lines of path, read from its last+// maxBytes, for reporting a failed startup.+func tailFile(path string, maxBytes int64, maxLines int) string {+ f, err := os.Open(path)+ if err != nil {+ return ""+ }+ defer func() {+ _ = f.Close()+ }()+ info, err := f.Stat()+ if err != nil {+ return ""+ }+ if info.Size() > maxBytes {+ if _, err := f.Seek(-maxBytes, io.SeekEnd); err != nil {+ return ""+ }+ }+ data, err := io.ReadAll(f)+ if err != nil {+ return ""+ }+ lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")+ if len(lines) > maxLines {+ lines = lines[len(lines)-maxLines:]+ }+ return strings.Join(lines, "\n")+}++func printDaemonSummary(pid int, probe, tokenPath, logPath string) {+ fmt.Printf("sam-node is running in the background.\n")+ fmt.Printf(" PID %d\n", pid)+ fmt.Printf(" Endpoint http://%s/mcp\n", probe)+ if tokenPath != "" {+ fmt.Printf(" Token %s\n", tokenPath)+ }+ fmt.Printf(" Logs %s\n", logPath)+ fmt.Printf(" Stop kill %d\n", pid)+ fmt.Printf("\nAuthenticate to it with the header \"X-Sam-Authentication: Bearer <token>\".\n")+}diff --git a/cmd/sam-node/daemonize_test.go b/cmd/sam-node/daemonize_test.gonew file mode 100644index 00000000..fac7dc1f--- /dev/null+++ b/cmd/sam-node/daemonize_test.go@@ -0,0 +1,180 @@+// 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 (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestWithoutDaemonizeFlag(t *testing.T) {+ got := withoutDaemonizeFlag([]string{"run", "--daemonize", "--join", "--bind-addr", "127.0.0.1:8080"})+ want := []string{"run", "--join", "--bind-addr", "127.0.0.1:8080"}+ if strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("got %v, want %v", got, want)+ }++ got = withoutDaemonizeFlag([]string{"run", "--daemonize=true", "--log-level", "debug"})+ want = []string{"run", "--log-level", "debug"}+ if strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("got %v, want %v", got, want)+ }++ // A value that merely looks like the flag must survive.+ got = withoutDaemonizeFlag([]string{"run", "--labels", "mode=--daemonize"})+ if len(got) != 3 {+ t.Errorf("flag values must not be stripped: got %v", got)+ }+}++func TestLocalProbeAddr(t *testing.T) {+ for bind, want := range map[string]string{+ "127.0.0.1:8080": "127.0.0.1:8080",+ "0.0.0.0:8080": "127.0.0.1:8080",+ ":8080": "127.0.0.1:8080",+ "[::]:8080": "127.0.0.1:8080",+ "nonsense": "nonsense",+ } {+ if got := localProbeAddr(bind); got != want {+ t.Errorf("localProbeAddr(%q) = %q, want %q", bind, got, want)+ }+ }+}++func TestProbeReady(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/healthz" {+ t.Errorf("unexpected probe path %q", r.URL.Path)+ }+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()++ addr := strings.TrimPrefix(srv.URL, "http://")+ if !probeReady(addr, time.Second) {+ t.Error("a listening node must probe ready")+ }+ srv.Close()+ if probeReady(addr, 200*time.Millisecond) {+ t.Error("a stopped node must not probe ready")+ }+}++func TestEnsureDaemonToken(t *testing.T) {+ t.Setenv("SAM_API_TOKEN", "")+ apiTokenPathFlag = ""+ dir := t.TempDir()++ args, path, err := ensureDaemonToken(dir)+ if err != nil {+ t.Fatalf("generating a token: %v", err)+ }+ if path != filepath.Join(dir, daemonTokenFile) {+ t.Errorf("token path: got %q", path)+ }+ if len(args) != 2 || args[0] != "--api-token-path" || args[1] != path {+ t.Errorf("child must receive the token by path, got %v", args)+ }+ first, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("reading the token: %v", err)+ }+ if len(first) != 64 {+ t.Errorf("token should be 32 random bytes hex-encoded, got %d chars", len(first))+ }+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat token: %v", err)+ }+ if info.Mode().Perm() != 0600 {+ t.Errorf("token file must not be readable by others: got %v", info.Mode().Perm())+ }++ if _, _, err := ensureDaemonToken(dir); err != nil {+ t.Fatalf("reusing a token: %v", err)+ }+ second, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("re-reading the token: %v", err)+ }+ if string(second) != string(first) {+ t.Error("an existing token must be reused, not rotated")+ }++ t.Setenv("SAM_API_TOKEN", "from-env")+ args, path, err = ensureDaemonToken(t.TempDir())+ if err != nil || args != nil || path != "" {+ t.Errorf("a configured SAM_API_TOKEN must be left alone: got %v, %q, %v", args, path, err)+ }+}++func TestPurgeDataDir(t *testing.T) {+ dir := t.TempDir()+ unrelated := filepath.Join(dir, "notes.txt")+ if err := os.WriteFile(unrelated, []byte("keep me"), 0600); err != nil {+ t.Fatalf("seeding unrelated file: %v", err)+ }+ for _, name := range nodeStateFiles() {+ if err := os.WriteFile(filepath.Join(dir, name), []byte("state"), 0600); err != nil {+ t.Fatalf("seeding %s: %v", name, err)+ }+ }++ removed, err := purgeDataDir(dir)+ if err != nil {+ t.Fatalf("purge: %v", err)+ }+ if len(removed) != len(nodeStateFiles()) {+ t.Errorf("every state file should be reported as removed, got %v", removed)+ }+ for _, name := range nodeStateFiles() {+ if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {+ t.Errorf("%s should be gone, stat returned %v", name, err)+ }+ }+ if _, err := os.Stat(unrelated); err != nil {+ t.Errorf("purge must not touch unrelated files: %v", err)+ }++ // A second purge is a no-op rather than an error.+ removed, err = purgeDataDir(dir)+ if err != nil {+ t.Fatalf("purging a clean directory: %v", err)+ }+ if len(removed) != 0 {+ t.Errorf("a clean directory has nothing to remove, got %v", removed)+ }+}++func TestTailFile(t *testing.T) {+ path := filepath.Join(t.TempDir(), "sam-node.log")+ if err := os.WriteFile(path, []byte("one\ntwo\nthree\nfour\n"), 0600); err != nil {+ t.Fatalf("seeding log: %v", err)+ }+ if got := tailFile(path, 8192, 2); got != "three\nfour" {+ t.Errorf("tailFile should return the last lines, got %q", got)+ }+ if got := tailFile(path, 8192, 10); got != "one\ntwo\nthree\nfour" {+ t.Errorf("a short log should be returned whole, got %q", got)+ }+ if got := tailFile(filepath.Join(t.TempDir(), "missing.log"), 8192, 10); got != "" {+ t.Errorf("a missing log must not fail the report, got %q", got)+ }+}diff --git a/cmd/sam-node/daemonize_unix.go b/cmd/sam-node/daemonize_unix.gonew file mode 100644index 00000000..1457ecb7--- /dev/null+++ b/cmd/sam-node/daemonize_unix.go@@ -0,0 +1,25 @@+// 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.++//go:build !windows++package main++import "syscall"++// detachedProcAttr puts the background node in its own session, so closing the+// launching terminal or interrupting it does not take the node down.+func detachedProcAttr() *syscall.SysProcAttr {+ return &syscall.SysProcAttr{Setsid: true}+}diff --git a/cmd/sam-node/daemonize_windows.go b/cmd/sam-node/daemonize_windows.gonew file mode 100644index 00000000..ae5eb0e7--- /dev/null+++ b/cmd/sam-node/daemonize_windows.go@@ -0,0 +1,25 @@+// 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.++//go:build windows++package main++import "syscall"++// detachedProcAttr puts the background node in its own process group, so a+// Ctrl-C in the launching console does not take the node down.+func detachedProcAttr() *syscall.SysProcAttr {+ return &syscall.SysProcAttr{CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP}+}diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex da5cf902..7e9f6e71 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -71,6 +71,9 @@ var (audienceFlag stringdataDirFlag stringheadlessFlag bool+ daemonizeFlag bool+ resetAllFlag bool+ assumeYesFlag boolofflineAccessFlag boollogLevelFlag stringkeyGracePeriodFlag time.Duration@@ -217,6 +220,13 @@ func main() {Short: "Start the sovereign mesh node",Run: func(cmd *cobra.Command, args []string) {ctx := cmd.Context()+ if daemonizeFlag {+ if err := daemonizeRun(); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ return+ }// Configure logging to duplicate to ring buffercfg := golog.GetConfig()cfg.URL = "ringbuffer://"@@ -726,8 +736,35 @@ func main() {resetCmd := &cobra.Command{Use: "reset",Short: "Clear this node's stored mesh identity so it can join a different mesh",+ Long: "Clear this node's stored mesh identity so it can join a different mesh.\n" ++ "The node keeps its PeerID and any generated API token.\n\n" ++ "Use --all for a clean slate instead: it deletes every file the node keeps\n" ++ "in its data directory, including the key behind its PeerID, so the next\n" ++ "start behaves like a first start.",Run: func(cmd *cobra.Command, args []string) {- store, err := node.NewStore(resolveDataDir())+ dataDir := resolveDataDir()+ if resetAllFlag {+ if err := confirmPurge(dataDir); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ removed, err := purgeDataDir(dataDir)+ if err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ if len(removed) == 0 {+ fmt.Printf("No local node state found in %s.\n", dataDir)+ return+ }+ fmt.Println("Deleted all local node state:")+ for _, path := range removed {+ fmt.Printf(" %s\n", path)+ }+ fmt.Println("The next start generates a new PeerID and needs to enroll again.")+ return+ }+ store, err := node.NewStore(dataDir)if err != nil {logger.Fatalf("Failed to open store: %v", err)}@@ -742,6 +779,8 @@ func main() {fmt.Println("Cleared stored mesh identity (PeerID unchanged). Run 'sam-node join <control-plane-url>' or 'sam-node run --join' to enroll again.")},}+ resetCmd.Flags().BoolVar(&resetAllFlag, "all", false, "Delete every file the node keeps in its data directory, not just the mesh identity")+ resetCmd.Flags().BoolVar(&assumeYesFlag, "yes", false, "Skip the confirmation prompt for --all")// Configure FlagsrunCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}, "libp2p Listen Addrs")@@ -763,6 +802,7 @@ func main() {runCmd.Flags().DurationVar(&autoRelayBackoffFlag, "autorelay-backoff", 3*time.Second, "AutoRelay Backoff")runCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")runCmd.Flags().BoolVar(&enableRelayFlag, "enable-relay", false, "Allow this node to serve as a relay for others")+ runCmd.Flags().BoolVar(&daemonizeFlag, "daemonize", false, "Run the node in the background and return once its local API answers (writes sam-node.log and sam-node.pid to the data directory, and generates an API token there if none is configured)")runCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "Log level (debug, info, warn, error)")runCmd.Flags().DurationVar(&keyGracePeriodFlag, "key-grace-period", 24*time.Hour, "Key grace period for old keys (e.g. 24h)")runCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")@@ -793,6 +833,7 @@ func main() {rootCmd.AddCommand(runCmd)rootCmd.AddCommand(joinCmd)rootCmd.AddCommand(resetCmd)+ rootCmd.AddCommand(newSkillCmd())ctx, cancel := context.WithCancel(context.Background())defer cancel()diff --git a/cmd/sam-node/skill.go b/cmd/sam-node/skill.gonew file mode 100644index 00000000..695782b3--- /dev/null+++ b/cmd/sam-node/skill.go@@ -0,0 +1,198 @@+// 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 (+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"+ "text/tabwriter"++ "github.com/google/sam/internal/skill"+ "github.com/spf13/cobra"+)++// newSkillCmd builds `sam-node skill`, which teaches local AI agents how to+// bootstrap a node and use the mesh.+func newSkillCmd() *cobra.Command {+ var (+ dirFlag string+ projectFlag bool+ )++ skillCmd := &cobra.Command{+ Use: "skill",+ Short: "Manage the SAM skill that teaches local AI agents to use the mesh",+ Long: "Install the SAM agent skill into the directories AI coding agents scan.\n" ++ "Agents load the skill on their own and use it to bootstrap a node,\n" ++ "discover mesh services, and call remote tools.",+ }++ installCmd := &cobra.Command{+ Use: "install",+ Short: "Install the SAM skill for local AI agents",+ Args: cobra.NoArgs,+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ targets, home, err := resolveSkillTargets(dirFlag, projectFlag)+ if err != nil {+ return err+ }+ return installSkill(cmd.OutOrStdout(), targets, home)+ },+ }++ listCmd := &cobra.Command{+ Use: "list",+ Short: "Show where the SAM skill is installed and whether it is current",+ Args: cobra.NoArgs,+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ targets, home, err := resolveSkillTargets(dirFlag, projectFlag)+ if err != nil {+ return err+ }+ return listSkill(cmd.OutOrStdout(), targets, home)+ },+ }++ showCmd := &cobra.Command{+ Use: "show",+ Short: "Print the skill document, for agents with a different layout",+ Args: cobra.NoArgs,+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ _, err := io.WriteString(cmd.OutOrStdout(), skill.Content)+ return err+ },+ }++ for _, c := range []*cobra.Command{installCmd, listCmd} {+ c.Flags().StringVar(&dirFlag, "dir", "", "Skills directory to use instead of the per-user ones")+ c.Flags().BoolVar(&projectFlag, "project", false, "Use the skill directories of the current project instead of the per-user ones")+ c.MarkFlagsMutuallyExclusive("dir", "project")+ }++ skillCmd.AddCommand(installCmd, listCmd, showCmd)+ return skillCmd+}++// resolveSkillTargets picks the directories to act on, and the home directory+// used to shorten paths when printing them.+func resolveSkillTargets(dir string, project bool) ([]skill.Target, string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ home = ""+ }+ switch {+ case dir != "":+ return []skill.Target{skill.CustomTarget(dir)}, home, nil+ case project:+ wd, err := os.Getwd()+ if err != nil {+ return nil, home, fmt.Errorf("resolving the current directory: %w", err)+ }+ return skill.ProjectTargets(wd), home, nil+ case home == "":+ return nil, home, errors.New("cannot locate the home directory; pass --dir or --project")+ default:+ return skill.UserTargets(home), home, nil+ }+}++func installSkill(w io.Writer, targets []skill.Target, home string) error {+ var errs []error+ installed := 0+ _, _ = fmt.Fprintf(w, "Installing the SAM skill (%s):\n", skill.Name)+ tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)+ for _, target := range targets {+ before, err := skill.Install(target)+ if err != nil {+ _, _ = fmt.Fprintf(tw, " failed\t%s\t%v\n", displayPath(home, target.Path()), err)+ errs = append(errs, err)+ continue+ }+ verb := "installed"+ switch before {+ case skill.StateOutdated:+ verb = "updated"+ case skill.StateCurrent:+ verb = "up to date"+ }+ _, _ = fmt.Fprintf(tw, " %s\t%s\t%s\n", verb, displayPath(home, target.Path()), target.Agent)+ installed+++ }+ if err := tw.Flush(); err != nil {+ errs = append(errs, err)+ }+ if installed > 0 {+ printSkillNextSteps(w)+ }+ return errors.Join(errs...)+}++func listSkill(w io.Writer, targets []skill.Target, home string) error {+ var errs []error+ _, _ = fmt.Fprintf(w, "SAM skill (%s):\n", skill.Name)+ tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)+ for _, target := range targets {+ state, err := skill.Inspect(target)+ if err != nil {+ _, _ = fmt.Fprintf(tw, " unreadable\t%s\t%v\n", displayPath(home, target.Path()), err)+ errs = append(errs, err)+ continue+ }+ _, _ = fmt.Fprintf(tw, " %s\t%s\t%s\n", state, displayPath(home, target.Path()), target.Agent)+ }+ if err := tw.Flush(); err != nil {+ errs = append(errs, err)+ }+ return errors.Join(errs...)+}++func printSkillNextSteps(w io.Writer) {+ _, _ = fmt.Fprint(w, `+Next steps:+ 1. Start a node in the background (prints its endpoint and API token file):+ sam-node run --daemonize+ If it reports the node is not enrolled, run the join command it prints+ first, then re-run it.+ 2. Point your agent at http://127.0.0.1:8080/mcp, authenticated with the+ header "X-Sam-Authentication: Bearer <token>". For example:+ Claude Code claude mcp add --transport http sam-mesh \+ http://127.0.0.1:8080/mcp \+ --header "X-Sam-Authentication: Bearer <token>"+ Antigravity add that URL as "serverUrl", with the same header, to+ ~/.gemini/config/mcp_config.json+ Other agents: https://sam-mesh.dev/docs/integrations/+ 3. Restart your agent so it picks up the skill and the mesh tools.+`)+}++// displayPath shortens a path under the home directory to ~/... so the output+// stays readable.+func displayPath(home, path string) string {+ if home == "" {+ return path+ }+ prefix := home + string(filepath.Separator)+ if !strings.HasPrefix(path, prefix) {+ return path+ }+ return filepath.Join("~", strings.TrimPrefix(path, prefix))+}diff --git a/cmd/sam-node/skill_test.go b/cmd/sam-node/skill_test.gonew file mode 100644index 00000000..d9235106--- /dev/null+++ b/cmd/sam-node/skill_test.go@@ -0,0 +1,85 @@+// 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 (+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/google/sam/internal/skill"+)++func TestSkillCmdInstallAndList(t *testing.T) {+ root := filepath.Join(t.TempDir(), "skills")++ var out bytes.Buffer+ cmd := newSkillCmd()+ cmd.SetOut(&out)+ cmd.SetErr(&out)+ cmd.SetArgs([]string{"install", "--dir", root})+ if err := cmd.Execute(); err != nil {+ t.Fatalf("skill install: %v", err)+ }++ installed := filepath.Join(root, skill.Name, "SKILL.md")+ data, err := os.ReadFile(installed)+ if err != nil {+ t.Fatalf("reading installed skill: %v", err)+ }+ if string(data) != skill.Content {+ t.Error("installed skill does not match the embedded content")+ }+ if !strings.Contains(out.String(), "Next steps:") {+ t.Errorf("install must guide the user to the next step, got:\n%s", out.String())+ }++ out.Reset()+ cmd = newSkillCmd()+ cmd.SetOut(&out)+ cmd.SetErr(&out)+ cmd.SetArgs([]string{"list", "--dir", root})+ if err := cmd.Execute(); err != nil {+ t.Fatalf("skill list: %v", err)+ }+ if !strings.Contains(out.String(), string(skill.StateCurrent)) {+ t.Errorf("list must report the installed skill as current, got:\n%s", out.String())+ }+}++func TestSkillCmdRejectsConflictingScopes(t *testing.T) {+ cmd := newSkillCmd()+ cmd.SetOut(&bytes.Buffer{})+ cmd.SetErr(&bytes.Buffer{})+ cmd.SetArgs([]string{"install", "--dir", t.TempDir(), "--project"})+ if err := cmd.Execute(); err == nil {+ t.Error("--dir and --project must be mutually exclusive")+ }+}++func TestDisplayPath(t *testing.T) {+ home := filepath.Join("/home", "u")+ if got := displayPath(home, filepath.Join(home, ".claude", "skills")); got != filepath.Join("~", ".claude", "skills") {+ t.Errorf("paths under home should be shortened: got %q", got)+ }+ if got := displayPath(home, "/opt/skills"); got != "/opt/skills" {+ t.Errorf("paths outside home should be left alone: got %q", got)+ }+ if got := displayPath("", "/opt/skills"); got != "/opt/skills" {+ t.Errorf("unknown home should be left alone: got %q", got)+ }+}diff --git a/internal/node/store.go b/internal/node/store.goindex ec2d00c4..0108422a 100644--- a/internal/node/store.go+++ b/internal/node/store.go@@ -28,6 +28,9 @@ import ()const (+ // StoreFile is the node database inside the data directory.+ StoreFile = "agent.db"+bucketIdentity = "identity"keyBiscuit = "identity_biscuit"keyPrivKey = "node_private_key"@@ -42,6 +45,10 @@ type Store struct {db *bbolt.DB}+// ErrStoreLocked reports that another process already holds the data+// directory, which for a node data directory means a node is running.+var ErrStoreLocked = errors.New("another sam-node instance is using this data directory")+func GetDefaultDataDir() (string, error) {base, err := os.UserConfigDir()if err != nil {@@ -58,11 +65,11 @@ func NewStore(dir string) (*Store, error) {if err := os.MkdirAll(dir, 0700); err != nil {return nil, fmt.Errorf("failed to create data directory: %w", err)}- dbPath := filepath.Join(dir, "agent.db")+ dbPath := filepath.Join(dir, StoreFile)db, err := bbolt.Open(dbPath, 0600, &bbolt.Options{Timeout: 5 * time.Second})if err != nil {if errors.Is(err, bbolterrors.ErrTimeout) {- return nil, fmt.Errorf("timeout waiting for file lock, is another instance of sam-node running?")+ return nil, fmt.Errorf("%w: timed out waiting for the file lock on %s", ErrStoreLocked, dbPath)}return nil, err}diff --git a/internal/node/store_test.go b/internal/node/store_test.goindex 5e9eb7af..1989136e 100644--- a/internal/node/store_test.go+++ b/internal/node/store_test.go@@ -16,6 +16,7 @@ package nodeimport ("bytes"+ "errors""fmt""os""path/filepath"@@ -288,6 +289,25 @@ func TestStore_ControlPlaneURL(t *testing.T) {}}+func TestStore_ErrStoreLocked(t *testing.T) {+ dir := t.TempDir()+ store, err := NewStore(dir)+ if err != nil {+ t.Fatalf("Failed to create store: %v", err)+ }+ defer func() {+ if err := store.Close(); err != nil {+ t.Errorf("failed to close store: %v", err)+ }+ }()++ // The CLI relies on this sentinel to tell "a node is already running" from+ // a genuine store failure, so it must survive the wrapping in NewStore.+ if _, err := NewStore(dir); !errors.Is(err, ErrStoreLocked) {+ t.Errorf("opening a locked data directory: got %v, want ErrStoreLocked", err)+ }+}+func TestStore_ResetMeshIdentity(t *testing.T) {store, err := NewStore(t.TempDir())if err != nil {diff --git a/internal/skill/skill.go b/internal/skill/skill.gonew file mode 100644index 00000000..1f46f1bf--- /dev/null+++ b/internal/skill/skill.go@@ -0,0 +1,118 @@+// 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 skill installs the SAM agent skill into the directories local AI+// agents scan, so an agent can bootstrap a node and drive the mesh without the+// user pasting instructions by hand.+package skill++import (+ "fmt"+ "os"+ "path/filepath"++ samskill "github.com/google/sam/agents/skills/sam-mesh"+)++const (+ // Name is the directory an installed skill lives in.+ Name = "sam-mesh"+ // fileName is the document every agent skill runtime looks for.+ fileName = "SKILL.md"+)++// Content is the skill document installed for local agents.+var Content = samskill.Markdown++// Target is a directory tree that an agent scans for skills.+type Target struct {+ // Agent names the tool that reads this directory.+ Agent string+ // Root is the skills directory, e.g. ~/.claude/skills.+ Root string+}++// Path is the file this target installs to.+func (t Target) Path() string {+ return filepath.Join(t.Root, Name, fileName)+}++// UserTargets are the per-user skill directories, shared by every project.+func UserTargets(home string) []Target {+ return []Target{+ {Agent: "Claude", Root: filepath.Join(home, ".claude", "skills")},+ {Agent: "Antigravity", Root: filepath.Join(home, ".gemini", "config", "skills")},+ }+}++// ProjectTargets are the skill directories scoped to the project rooted at dir.+func ProjectTargets(dir string) []Target {+ return []Target{+ {Agent: "Claude", Root: filepath.Join(dir, ".claude", "skills")},+ {Agent: "Antigravity", Root: filepath.Join(dir, ".agents", "skills")},+ }+}++// CustomTarget installs into an explicit skills directory.+func CustomTarget(root string) Target {+ return Target{Root: root}+}++// State is what a target holds relative to the embedded skill.+type State string++const (+ // StateMissing means no skill is installed for this target.+ StateMissing State = "not installed"+ // StateOutdated means an older or edited skill is installed.+ StateOutdated State = "outdated"+ // StateCurrent means the installed skill matches this binary's.+ StateCurrent State = "up to date"+)++// Inspect reports the state of t without modifying anything.+func Inspect(t Target) (State, error) {+ existing, err := os.ReadFile(t.Path())+ switch {+ case os.IsNotExist(err):+ return StateMissing, nil+ case err != nil:+ return "", fmt.Errorf("reading %s: %w", t.Path(), err)+ case string(existing) == Content:+ return StateCurrent, nil+ default:+ return StateOutdated, nil+ }+}++// Install writes the skill to t, creating parent directories as needed. It+// reports the state found before writing, so callers can tell an install from+// an upgrade from a no-op.+func Install(t Target) (State, error) {+ before, err := Inspect(t)+ if err != nil {+ return "", err+ }+ if before == StateCurrent {+ return before, nil+ }+ dir := filepath.Dir(t.Path())+ if err := os.MkdirAll(dir, 0755); err != nil {+ return "", fmt.Errorf("creating %s: %w", dir, err)+ }+ if err := os.WriteFile(t.Path(), []byte(Content), 0644); err != nil {+ return "", fmt.Errorf("writing %s: %w", t.Path(), err)+ }+ return before, nil+}diff --git a/internal/skill/skill_test.go b/internal/skill/skill_test.gonew file mode 100644index 00000000..a57972b6--- /dev/null+++ b/internal/skill/skill_test.go@@ -0,0 +1,121 @@+// 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 skill++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestContentIsAValidSkill(t *testing.T) {+ // Agent runtimes require the skill directory to match the declared name.+ if !strings.HasPrefix(Content, "---\nname: "+Name+"\n") {+ t.Errorf("skill must start with frontmatter declaring name %q, got %.40q", Name, Content)+ }+ if !strings.Contains(Content, "description:") {+ t.Error("skill frontmatter must carry a description, agents use it to decide when to load the skill")+ }+}++func TestTargetPaths(t *testing.T) {+ user := UserTargets("/home/u")+ want := map[string]bool{+ filepath.Join("/home/u", ".claude", "skills", Name, "SKILL.md"): true,+ filepath.Join("/home/u", ".gemini", "config", "skills", Name, "SKILL.md"): true,+ }+ for _, target := range user {+ if !want[target.Path()] {+ t.Errorf("unexpected user target path %q", target.Path())+ }+ delete(want, target.Path())+ }+ if len(want) != 0 {+ t.Errorf("missing user target paths: %v", want)+ }++ project := ProjectTargets("/work/repo")+ wantProject := map[string]bool{+ filepath.Join("/work/repo", ".claude", "skills", Name, "SKILL.md"): true,+ filepath.Join("/work/repo", ".agents", "skills", Name, "SKILL.md"): true,+ }+ for _, target := range project {+ if !wantProject[target.Path()] {+ t.Errorf("unexpected project target path %q", target.Path())+ }+ delete(wantProject, target.Path())+ }+ if len(wantProject) != 0 {+ t.Errorf("missing project target paths: %v", wantProject)+ }++ if got := CustomTarget("/opt/skills").Path(); got != filepath.Join("/opt/skills", Name, "SKILL.md") {+ t.Errorf("custom target path: got %q", got)+ }+}++func TestInstallLifecycle(t *testing.T) {+ target := CustomTarget(filepath.Join(t.TempDir(), "skills"))++ if state, err := Inspect(target); err != nil || state != StateMissing {+ t.Fatalf("fresh directory: got %q, %v; want %q, nil", state, err, StateMissing)+ }++ if state, err := Install(target); err != nil || state != StateMissing {+ t.Fatalf("first install: got %q, %v; want %q, nil", state, err, StateMissing)+ }+ data, err := os.ReadFile(target.Path())+ if err != nil {+ t.Fatalf("reading installed skill: %v", err)+ }+ if string(data) != Content {+ t.Error("installed skill does not match the embedded content")+ }++ if state, err := Install(target); err != nil || state != StateCurrent {+ t.Fatalf("reinstall must be a no-op: got %q, %v; want %q, nil", state, err, StateCurrent)+ }++ if err := os.WriteFile(target.Path(), []byte("stale skill"), 0644); err != nil {+ t.Fatalf("seeding stale skill: %v", err)+ }+ if state, err := Inspect(target); err != nil || state != StateOutdated {+ t.Fatalf("stale skill: got %q, %v; want %q, nil", state, err, StateOutdated)+ }+ if state, err := Install(target); err != nil || state != StateOutdated {+ t.Fatalf("upgrade: got %q, %v; want %q, nil", state, err, StateOutdated)+ }+ data, err = os.ReadFile(target.Path())+ if err != nil {+ t.Fatalf("reading upgraded skill: %v", err)+ }+ if string(data) != Content {+ t.Error("upgrade must overwrite a stale skill")+ }+}++func TestInstallReportsUnwritableTarget(t *testing.T) {+ if os.Geteuid() == 0 {+ t.Skip("root bypasses directory permissions")+ }+ root := filepath.Join(t.TempDir(), "readonly")+ if err := os.Mkdir(root, 0500); err != nil {+ t.Fatalf("creating read-only root: %v", err)+ }+ if _, err := Install(CustomTarget(filepath.Join(root, "skills"))); err == nil {+ t.Error("install into an unwritable directory must return an error")+ }+}diff --git a/site/content/docs/integrations/antigravity.md b/site/content/docs/integrations/antigravity.mdindex 3599e16d..25c43b30 100644--- a/site/content/docs/integrations/antigravity.md+++ b/site/content/docs/integrations/antigravity.md@@ -15,7 +15,28 @@ Antigravity natively supports Streamable HTTP MCP servers via the `serverUrl` co## Running the Node Alongside Antigravity-Antigravity talks to `sam-node` as a plain HTTP server rather than launching it itself (unlike a `stdio` MCP server, which the harness spawns and manages). That means `sam-node run` has to already be listening on the configured port *before* Antigravity starts, and keep running for the whole session — in practice, two separate long-running processes.+Antigravity talks to `sam-node` as a plain HTTP server rather than launching it itself (unlike a `stdio` MCP server, which the harness spawns and manages). That means `sam-node run` has to already be listening on the configured port *before* Antigravity starts, and keep running for the whole session.++### Recommended: `--daemonize`++`--daemonize` starts the node in the background and returns once its local API answers, so there is no second terminal to keep open. It also generates an API token under the data directory if you have not configured one:++```bash+sam-node run --daemonize+```++```text+sam-node is running in the background.+ PID 48213+ Endpoint http://127.0.0.1:8080/mcp+ Token /home/you/.config/sam-mesh/api-token+ Logs /home/you/.config/sam-mesh/sam-node.log+ Stop kill 48213+```++The command is idempotent: re-run it any time to make sure a node is up. Enrollment still needs a one-time login, so if the node has no identity yet the command tells you to run `sam-node join --headless <control-plane-url>` first, which prints a URL and a code to complete in your browser.++### Alternative: a dedicated terminalOn the very first run, `--join` needs an interactive terminal to complete the browser/device-code login; after that, the identity is stored and `--join` is a no-op, so the node can be started detached/hidden freely.@@ -29,16 +50,9 @@ SAM_API_TOKEN=my-secret-token sam-node run --join --bind-addr 127.0.0.1:8080# Terminal 2agy```-Or background it in the same shell once you've completed the first interactive login:-```bash-SAM_API_TOKEN=my-secret-token nohup sam-node run --join --bind-addr 127.0.0.1:8080 > sam-node.log 2>&1 &-```### Windows-PowerShell and cmd.exe don't have a direct equivalent of Unix job control (`&`), so the straightforward option is the same as macOS/Linux: run `sam-node.exe run --join` in one Windows Terminal/PowerShell tab and leave it running, then open a second tab for Antigravity. To start it detached instead (after the first interactive login):-```powershell-Start-Process sam-node.exe -ArgumentList "run","--join","--bind-addr","127.0.0.1:8080" -WindowStyle Hidden-```+PowerShell and cmd.exe don't have a direct equivalent of Unix job control (`&`), so either use `sam-node.exe run --daemonize` or run `sam-node.exe run --join` in one Windows Terminal/PowerShell tab and leave it running, then open a second tab for Antigravity.### Any OS: DockerThe Docker image already runs detached, so it doesn't need a second terminal at all — pass `-it` instead of `-d` only for the first run, to complete the interactive login:@@ -75,6 +89,16 @@ Add the node directly using its HTTP endpoint (replace `<YOUR_TOKEN>` with yourAntigravity will automatically discover the change. The `sam-node` tools — `discover_remote_services`, `find_remote_tools`, `describe_remote_tool`, and `call_remote_tool` — will then be available.+## Install the SAM Skill++The MCP tools give Antigravity the ability to reach the mesh; the [SAM skill](https://antigravity.google/docs/skills) tells it when and how to use them, including how to reach mesh inference models. Install it once:++```bash+sam-node skill install+```++This writes `~/.gemini/config/skills/sam-mesh/SKILL.md`, Antigravity's global skills location, so it applies to every workspace. Use `sam-node skill install --project` instead to check it into the current workspace at `.agents/skills/sam-mesh/SKILL.md`, and `sam-node skill list` to see whether an installed copy is current. The agent picks the skill up on its own when a task needs the mesh.+## Discovering and Invoking Remote ToolsThe tool flow for Antigravity is as follows:diff --git a/site/content/docs/integrations/claude-code.md b/site/content/docs/integrations/claude-code.mdindex 48613911..6c27ba6a 100644--- a/site/content/docs/integrations/claude-code.md+++ b/site/content/docs/integrations/claude-code.md@@ -54,6 +54,16 @@ claude mcp get p2p-mesh-nodeA healthy server reports `✔ Connected`. MCP tools are loaded at session start, so start (or restart) Claude Code and run `/mcp` to see `p2p-mesh-node` and its tools.+## Install the SAM Skill++The MCP tools give Claude Code the ability to reach the mesh; the SAM skill tells it when and how to use them. Install it once:++```bash+sam-node skill install+```++This writes the skill to `~/.claude/skills/sam-mesh/SKILL.md`, available in every project. Use `sam-node skill install --project` instead to commit it to the current repository (`./.claude/skills/sam-mesh/SKILL.md`), and `sam-node skill list` to check whether an installed copy is current. Restart Claude Code afterwards, then run `/skills` to confirm `sam-mesh` is loaded.+## Discovering and Invoking Remote ToolsClaude Code calls the tools `sam-node` exposes like any other tool. The flow mirrors the local MCP API:diff --git a/site/content/docs/integrations/claude-desktop.md b/site/content/docs/integrations/claude-desktop.mdindex 98174c87..0fc0add6 100644--- a/site/content/docs/integrations/claude-desktop.md+++ b/site/content/docs/integrations/claude-desktop.md@@ -47,6 +47,10 @@ Add the node through the `mcp-remote` bridge (replace `<YOUR_TOKEN>` with your tRestart Claude Desktop for the change to take effect. The `sam-node` tools — `discover_remote_services`, `find_remote_tools`, `describe_remote_tool`, and `call_remote_tool` — then appear in the MCP tools menu (the connectors / plug icon).+## Install the SAM Skill++The MCP tools let Claude reach the mesh; the SAM skill tells it when and how to use them. Install it once with `sam-node skill install`, which writes `~/.claude/skills/sam-mesh/SKILL.md`, then restart Claude Desktop.+## Discovering and Invoking Remote ToolsThe tool flow is identical to the [Claude Code guide](./claude-code/#discovering-and-invoking-remote-tools):diff --git a/site/content/docs/quickstart.md b/site/content/docs/quickstart.mdindex 5d90c5de..32de6395 100644--- a/site/content/docs/quickstart.md+++ b/site/content/docs/quickstart.md@@ -75,6 +75,35 @@ Use `-it` for this first run so you can complete the browser/device-code login;By default `--join` enrolls with the public testnet (`bananas.sam-mesh.dev`); pass `--control-plane <url>` to join a different mesh.+#### Running It in the Background++`sam-node run` stays in the foreground. Add `--daemonize` to start it detached and return as soon as its local API answers — useful when an AI agent is driving the setup, or when you don't want a terminal dedicated to the node:++```bash+sam-node run --daemonize+```+```text+sam-node is running in the background.+ PID 48213+ Endpoint http://127.0.0.1:8080/mcp+ Token /home/you/.config/sam-mesh/api-token+ Logs /home/you/.config/sam-mesh/sam-node.log+ Stop kill 48213+```++If no API token is configured (`SAM_API_TOKEN` or `--api-token-path`), `--daemonize` generates one under the data directory and reuses it on later starts. The command is idempotent: re-run it to confirm a node is up. Enrollment still needs a one-time login, so on a node with no identity it tells you to run `sam-node join --headless <control-plane-url>` first.++#### Starting Over++A node reuses whatever is already in its data directory, which is what you want day to day but not when you are testing setup flows. Two levels of reset:++```bash+sam-node reset # forget the mesh identity only, keep the PeerID+sam-node reset --all # delete every file the node keeps, including its key+```++`--all` asks for confirmation, and needs `--yes` when there is no terminal to ask on. Both refuse while a node is still running, so stop it first (`kill <pid>` from the `--daemonize` output). After `--all` the node generates a new PeerID and has to enroll again.+### Alternative: Join and Run SeparatelyIf you're deploying headlessly with a pre-issued bootstrap token, or just prefer explicit steps, you can join and run as two commands instead.@@ -194,3 +223,29 @@ mcp-client -url http://localhost:8080/mcp \-tool call_remote_tool \-args '{"peer_id":"<target-peer-id>","tool_name":"everything.get-sum","arguments":{"a":12.5,"b":7.5}}'```++## 4. Teach Your AI Agent to Use the Mesh++Knowing the tools exist is not the same as knowing when and how to use them. `sam-node` ships an [agent skill](https://agentskills.io) that tells your agent how to bring a node online, discover mesh services, call remote tools, and reach mesh inference models. Install it once:++```bash+sam-node skill install+```++This writes `SKILL.md` into the per-user skill directories your agents scan:++| Agent | Path |+| :--- | :--- |+| Claude Code, Claude Desktop | `~/.claude/skills/sam-mesh/SKILL.md` |+| Google Antigravity | `~/.gemini/config/skills/sam-mesh/SKILL.md` |++Useful variants:++```bash+sam-node skill install --project # install into this project (./.claude and ./.agents)+sam-node skill install --dir DIR # install into a specific skills directory+sam-node skill list # show where it is installed and whether it is current+sam-node skill show # print the document, for agents with a different layout+```++Re-run `sam-node skill install` after upgrading `sam-node` to refresh the document. Then connect your agent to the node's MCP endpoint — see the [integration guides](../integrations/) — and restart it so both the skill and the tools load.diff --git a/tests/e2e/sam.bats b/tests/e2e/sam.batsindex 50d263aa..bcf45c9a 100644--- a/tests/e2e/sam.bats+++ b/tests/e2e/sam.bats@@ -6,6 +6,10 @@ setup() {export SAM_ROUTER_BINARY="${SAM_ROUTER_BINARY:-./bin/sam-router}"export MCP_CLIENT_BINARY="${MCP_CLIENT_BINARY:-./bin/mcp-client}"+ # Kept so helpers built with "go run" reuse the real module cache instead of+ # filling the sandboxed HOME with read-only files.+ export REAL_HOME="$HOME"+export TEST_TMPDIRTEST_TMPDIR="$(mktemp -d)"export HOME="$TEST_TMPDIR/home"@@ -16,7 +20,7 @@ setup() {}teardown() {-+ chmod -R +w "$TEST_TMPDIR" || truerm -rf "$TEST_TMPDIR"}@@ -56,6 +60,67 @@ teardown() {+@test "sam-node skill install writes the agent skill and reports it as current" {+ local skills_dir="$TEST_TMPDIR/skills"++ run "$SAM_NODE_BINARY" skill install --dir "$skills_dir"+ [[ "$status" -eq 0 ]]+ [[ "$output" == *"installed"* ]]+ [[ -f "$skills_dir/sam-mesh/SKILL.md" ]]+ grep -q "^name: sam-mesh$" "$skills_dir/sam-mesh/SKILL.md"++ run "$SAM_NODE_BINARY" skill list --dir "$skills_dir"+ [[ "$status" -eq 0 ]]+ [[ "$output" == *"up to date"* ]]+}++@test "sam-node run --daemonize without an identity points at join instead of backgrounding" {+ run "$SAM_NODE_BINARY" run --daemonize --bind-addr "127.0.0.1:8086"+ [[ "$status" -eq 1 ]]+ [[ "$output" == *"not enrolled yet"* ]]+ [[ "$output" == *"sam-node join --headless"* ]]+ [[ ! -f "$XDG_CONFIG_HOME/sam-mesh/sam-node.pid" ]]+}++@test "sam-node run --daemonize starts a background node and reports why it stopped" {+ HOME="$REAL_HOME" go run tests/e2e/gen_db.go "$XDG_CONFIG_HOME/sam-mesh/agent.db"++ # No control plane is reachable here, so the backgrounded node exits during+ # startup: the parent must notice, surface the child's log, and fail.+ run "$SAM_NODE_BINARY" run --daemonize \+ --bind-addr "127.0.0.1:8086" \+ --router-connect-timeout 2s \+ --listen /ip4/127.0.0.1/udp/0/quic-v1 --listen /ip4/127.0.0.1/tcp/0+ [[ "$status" -eq 1 ]]+ [[ "$output" == *"the background node exited during startup"* ]]+ [[ "$output" == *"Last lines of"* ]]++ # The child ran detached with a generated token and its own log.+ [[ -f "$XDG_CONFIG_HOME/sam-mesh/api-token" ]]+ [[ -s "$XDG_CONFIG_HOME/sam-mesh/sam-node.log" ]]+ [[ "$(stat -c %a "$XDG_CONFIG_HOME/sam-mesh/api-token")" == "600" ]]+}++@test "sam-node reset --all needs confirmation and then clears the data directory" {+ HOME="$REAL_HOME" go run tests/e2e/gen_db.go "$XDG_CONFIG_HOME/sam-mesh/agent.db"++ # </dev/null keeps this deterministic: with no terminal to prompt on, the+ # command must refuse rather than block.+ run "$SAM_NODE_BINARY" reset --all </dev/null+ [[ "$status" -eq 1 ]]+ [[ "$output" == *"--yes"* ]]+ [[ -f "$XDG_CONFIG_HOME/sam-mesh/agent.db" ]]++ run "$SAM_NODE_BINARY" reset --all --yes </dev/null+ [[ "$status" -eq 0 ]]+ [[ "$output" == *"Deleted all local node state"* ]]+ [[ ! -f "$XDG_CONFIG_HOME/sam-mesh/agent.db" ]]++ run "$SAM_NODE_BINARY" reset --all --yes </dev/null+ [[ "$status" -eq 0 ]]+ [[ "$output" == *"No local node state found"* ]]+}+@test "sam-control-plane --help returns success" {run "$SAM_CONTROL_PLANE_BINARY" --help[[ "$status" -eq 0 ]]