Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
docs: restructure and rewrite the documentation site
Antonio Ojea1f2c13e6e186
diff --git a/.github/workflows/deploy-sam-one.yaml b/.github/workflows/deploy-sam-one.yamlindex 05876871..f8d3c8a9 100644--- a/.github/workflows/deploy-sam-one.yaml+++ b/.github/workflows/deploy-sam-one.yaml@@ -1,7 +1,7 @@name: Sam-One Cloud Run Sandbox# On-demand sam-one deployments on Cloud Run (see-# site/content/docs/user/cloud-run-deployment.md for the manual version).+# site/content/docs/guides/cloud-run.md for the manual version).# Deploys are gated by the 'sam-one-sandbox' GitHub Environment: required# reviewers approve each run before GCP credentials are minted.#diff --git a/AGENTS.md b/AGENTS.mdindex 685397c6..9fc0b954 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -7,7 +7,7 @@ You are an expert software engineering assistant helping to develop, maintain, a* **API Communication:** All data communication between `sam-control-plane`, `sam-router` and `sam-node` must happen exclusively via the common API defined in `api/sam.proto`.* **Two API surfaces, two encodings:** the *mesh protocol* — anything a mesh component speaks (node, router, `sam-box`, the agent connector): enrollment, refresh, keys, leases, auth streams, policy sync — is protobuf from `api/sam.proto` (`application/x-protobuf`). The *operator plane* — what humans, the web console and admin CLIs call (`/admin/*`, `/users/*`) — is JSON, with its request and response types declared as Go structs in `api/` (e.g. `api.BootstrapTokenRequest`). Never define a wire shape as an anonymous struct or `map[string]any` inside a handler, and never serialize an `internal/storage` (or any other internal) type onto either surface; clients in `cmd/` and `internal/console` import `api/` only. A message that a mesh component consumes goes in the proto even if a console also reads it.* **Secrets never travel as flag values:** binaries read credentials from a file (`--*-path`) or the environment, never from a command-line argument that would sit in `ps` output and shell history. Banners and logs name the source of an operator-supplied secret instead of echoing it.-* **Sandbox Dataplane:** `sam-box` (one per sandbox) is the single egress policy enforcement point. It holds no libp2p host, no enrollment and no mesh identity, and reaches the mesh exclusively as a client of the local `sam-node` sidecar socket. `nano-init` (PID 1 inside the guest, its own Go module) owns the guest side; its datapath is the `tun2connect` library. The sandbox boundary is a Unix socket speaking named HTTP tunnels: CONNECT (TCP) and connect-udp (UDP) out, `CONNECT <port>` back in. The authoritative design is `site/content/docs/agent-architecture.md`; do not contradict it.+* **Sandbox Dataplane:** `sam-box` (one per sandbox) is the single egress policy enforcement point. It holds no libp2p host, no enrollment and no mesh identity, and reaches the mesh exclusively as a client of the local `sam-node` sidecar socket. `nano-init` (PID 1 inside the guest, its own Go module) owns the guest side; its datapath is the `tun2connect` library. The sandbox boundary is a Unix socket speaking named HTTP tunnels: CONNECT (TCP) and connect-udp (UDP) out, `CONNECT <port>` back in. The authoritative design is `site/content/docs/preview/agent-architecture.md`; do not contradict it.* **Enforcement over Convention:** never gate sandbox traffic on the agent's cooperation — no proxy environment variables, no `LD_PRELOAD` shims, no DNS spoofing. The agent harness stays unmodified and mesh-unaware; confinement is a route and a socket, built by the userspace launcher (`nano-init`) and judged in `sam-box`. An agent that must cooperate with its own confinement is not confined.* **Policy on Names:** egress policy, secret injection and routing decisions are made on the destination *name*, never on an IP. Deny by default.* **Agent Identity:** the agent is the principal; the node is only the channel. Agent identity comes from the platform's workload credential, verified at admission — never asserted in-band from inside the sandbox. Platforms integrate solely through the connector interface (`Attach`/`Detach`/`Refresh`/`Status` and the agent bundle), not by reaching into SAM internals.diff --git a/README.md b/README.mdindex 7a581bf2..24be25df 100644--- a/README.md+++ b/README.md@@ -1,83 +1,71 @@-# SAM: Sovereign Agent Mesh--<img alt="SAM" src="site/content/docs/sam_logo.png" />--SAM is a smart network built for autonomous AI agents:--* **Zero Config:** Nodes discover each other and build the P2P network automatically.-* **Zero Trust:** Every connection, node, and packet is strictly authenticated.-* **Agentic Network:** Formed by lightweight nodes (`sam-node`) that provide self-healing, P2P connectivity, allowing autonomous agents to plug in, communicate, and invoke tools dynamically.-* **Portability:** Cryptographic identities are environment-agnostic, allowing seamless node mobility across cloud, local, and edge environments.--Getting started is a one-liner (see the [Quick Start Guide](site/content/docs/quickstart.md)): install, add the skill, and your agent is on the mesh.--<img src="site/static/demo.gif" alt="Demo: installing SAM, adding the sam-mesh skill, and an agent discovering and calling tools across the mesh" width="100%" />--<details>-<summary><b>Advanced demo</b>: an agent fans a batch of work across a warm pool of reviewer agents on the mesh</summary>--<video src="https://github.com/user-attachments/assets/f1a61b6f-efcd-46d8-a6e6-659fb29dd1ce" width="100%" autoplay loop muted playsinline controls></video>--Full walkthrough: [Warm Agent Pool use case](site/content/docs/use-cases/warm-agent-pool.md).--</details>-------## What "Sovereign" Means in SAM--SAM is an **open-source software project (Apache-2.0)** providing decentralized networking and cryptographic building blocks for autonomous AI agents. It carries no vendor telemetry and has no hardcoded dependencies on proprietary cloud services or model providers.--SAM provides the open protocols, cryptographic building blocks, and software to build **sovereign, zero-trust agent meshes**. In SAM, digital sovereignty is built on architectural and cryptographic control—custody of root keys, independent identity federation, and policy-enforced data boundaries. In a sovereign deployment, operators:--1. **Deploy Dedicated Mesh Infrastructure:** Run a dedicated control plane (`sam-control-plane`) and routing relays (`sam-router`) on your chosen infrastructure (managed cloud environments like Google Cloud, private Kubernetes clusters, or air-gapped datacenters) using our [Helm chart](charts/sam-mesh/README.md) or Kubernetes manifests.-2. **Maintain Root Cryptographic Key Custody:** Generate, manage, and hold your own Ed25519 root signing keys (via local HSMs, KMS, or Cloud EKM). You maintain 100% of the cryptographic authority—no external party can mint credentials, revoke nodes, or alter policies.-3. **Bring Your Own Identity Provider:** Bridge agent and user identities through your own OIDC identity provider (such as Dex, Keycloak, or corporate IdP).-4. **Enforce Territorial & Jurisdictional Boundaries:** Use cryptographically attested label gates (`labels: {jurisdiction: eu}` in the node config, `X-Sam-Required-Labels`) to mathematically guarantee prompts and tool invocations never leave authorized geographic scopes.-5. **Retain Autonomous Local Vetoes:** Configure local node attenuation policies (`sam-node.yaml`) to evaluate access rules *before* control plane grants, ensuring local nodes retain absolute veto authority.--> [!NOTE]-> **About the Public Developer Testnets:**-> The public endpoints (`bananas.sam-mesh.dev` and `hub.sam-mesh.dev`) are free testbeds created using community resources solely for developer testing, continuous integration, and rapid experimentation. They provide **no guarantees, no uptime commitments, zero SLA, and no sovereign guarantees**. Running on a shared community testnet delegates identity management to the testbed maintainers; true sovereignty requires deploying a dedicated control plane with customer-held keys.->-> [](https://github.com/google/sam/actions/workflows/testnet-health.yaml) Every half hour a fresh node's view of each testnet is checked (enrollment surface, routers, canaries, and a cold-path probe that joins and calls a tool); a red badge means one of them is unhealthy and an issue labelled `testnet-health` says which check failed.->-> 📖 **Deep Dive:** Read our full **[Digital & Data Sovereignty Architecture](site/content/docs/sovereignty.md)** covering the 5 pillars, fail-closed label gates, uncooperative sandbox confinement, and regulatory alignment (GDPR Chapter V, EU Cloud Sovereignty Framework SEAL-3, EU Data Act).-------## Architecture Components--* `sam-control-plane`: The registry control plane for node identity registration, authorization policies, and router coordinating.-* `sam-router`: The libp2p bootstrap nodes and relays providing data-plane connectivity and forwarding.-* `sam-node`: The local node clients providing mesh transport integration and MCP sidecar routing.-----+# SAM++<img alt="SAM" src="site/content/docs/sam_logo.png" width="160" />++SAM is a private network for AI agents. A node runs next to an agent and+gives it three things: a way to publish tools and models to the network, a+way to find and call what other nodes publish, and an identity every other+node can verify. Nodes connect directly when they can and through relays when+they cannot, so the network works across laptops, containers, clusters and+phones behind NAT.++Two properties hold everywhere:++- **Nothing is reachable by default.** A node exposes no services until its+ configuration says so, and no node may call a service the mesh policy has+ not granted. Grants are evaluated on service names, never on addresses.+- **Identity comes from your identity provider.** A node enrolls with an+ OpenID Connect token or a one-time bootstrap token, and the control plane+ turns that into a short-lived, offline-verifiable credential bound to the+ node's own key.++<img src="site/static/demo.gif" alt="Installing sam-node, adding the skill, and an agent discovering and calling tools across the mesh" width="100%" />++## Try it++```bash+curl -sL https://sam-mesh.dev/install.sh | bash # sam-node, mcp-client and friends+sam-node join https://bananas.sam-mesh.dev # one-time login+sam-node run --daemonize # local MCP server on 127.0.0.1:8080+sam-node skill install # teach your agent to use it+```++Your agent now has tools that discover and call services across the mesh,+and an OpenAI-compatible endpoint that routes model requests to whoever+serves the model. `bananas.sam-mesh.dev` is a shared developer testnet with+no uptime promise; the [quick start](https://sam-mesh.dev/docs/getting-started/quickstart/)+walks through it, and [your own mesh](https://sam-mesh.dev/docs/getting-started/your-own-mesh/)+runs a control plane on your laptop in one command.++## What is in a mesh++| Program | Role |+|---|---|+| `sam-control-plane` | Verifies who is joining, issues each node a signed credential, and holds the policy that says who may call what. |+| `sam-router` | A well-known peer that nodes connect to first. Relays traffic between nodes that cannot reach each other and hosts the discovery table. |+| `sam-node` | Runs next to your agent or service. Enrolls, connects, serves your local backends to the mesh, and exposes the mesh to your agent as a local MCP server and OpenAI-compatible API. |+| `sam-one` | The control plane, a router and a web console in one binary, for laptops and small deployments. |## Documentation-Start exploring the Sovereign Agent Mesh:--### Digital & Data Sovereignty-- 🏛️ **[Digital & Data Sovereignty Architecture](site/content/docs/sovereignty.md)**: How SAM enforces data residency, territorial label gates, autonomous local vetoes, and regulatory compliance (GDPR, EU Cloud Sovereignty Framework SEAL-3, EU Data Act).--### For Users & Operators-- 🚀 **[User Quick Start Guide](site/content/docs/quickstart.md)**: Connect and run a SAM node on the community-hosted developer testnet (`bananas.sam-mesh.dev`, strictly for testing with no guarantees) using binaries or Docker.-- 🎛️ **[Dedicated Sovereign Deployment](site/content/docs/user/kubernetes-deployment.md)**: Run your own private sovereign hub (control plane, router, console) via the [sam-mesh Helm chart](charts/sam-mesh/README.md) or Kubernetes manifests.-- 🤖 **[Agent Integration Guides](site/content/docs/integrations/_index.md)**: Connect Google Gemini, Claude, and other AI agents to your SAM node to dynamically discover and call tools across the mesh.-- 📡 **[Testnet Validation Tutorial](site/content/docs/development/testnet-validation.md)**: Real-time verification, remote tool invocation, and HTTP stream proxies on public developer testnets.--### For Developers & Contributors-Compile from source, run local clusters, or execute tests:-- 🛠️ **[Developer Guide](site/content/docs/development/_index.md)**: Prereqs, compilation, local control plane setup, and Kubernetes Kind deployment.-- 🧪 **[Testing Guide](site/content/docs/development/testing.md)**: Go tests, E2E BATS, and containerized mesh execution.+[sam-mesh.dev/docs](https://sam-mesh.dev/docs/) is built from `site/`.----+- [Getting started](https://sam-mesh.dev/docs/getting-started/): one node on the testnet, then a mesh of your own.+- [Concepts](https://sam-mesh.dev/docs/concepts/): architecture, identity and enrollment, authorization, networking.+- [Guides](https://sam-mesh.dev/docs/guides/): exposing services, connecting agent clients, headless enrollment, Kubernetes, Cloud Run.+- [Reference](https://sam-mesh.dev/docs/reference/): every flag, configuration key, HTTP route and policy field.+- [Preview](https://sam-mesh.dev/docs/preview/): sandboxed agents and the mobile app, which work but are still settling.+- [Contributing](https://sam-mesh.dev/docs/contributing/): building, testing and the local kind environment.-## License+## Status-See [LICENSE](LICENSE).+SAM is pre-1.0. The node, routers, control plane, identity and policy model+are stable in shape and exercised by the test suite and two public testnets;+see [ROADMAP.md](ROADMAP.md) for the release plan. Sandboxed agents+(`sam-box`, `nano-init`) and the mobile app are in preview.-## Disclaimer+## License and disclaimer-This is not an officially supported Google product. This project is not eligible for the [Google Open Source Software Vulnerability Rewards Program](https://bughunters.google.com/open-source-security).+Apache-2.0; see [LICENSE](LICENSE). This is not an officially supported+Google product, and it is not eligible for the+[Google Open Source Software Vulnerability Rewards Program](https://bughunters.google.com/open-source-security).diff --git a/ROADMAP.md b/ROADMAP.mdindex f7125fd2..43b03320 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,4 +1,4 @@-# Sovereign Agent Mesh (SAM) Roadmap+# SAM Roadmap## Phase 1: Alpha@@ -11,7 +11,7 @@ The Alpha phase is focused on laying the foundational architecture, finalizing A* Establish P2P routing and base node lifecycle.* Deploy community developer testnets.- * Draft initial sovereignty architectural documentation.+ * Draft the initial architecture documentation.* Integrate baseline network services: MCP, A2A, Inference.* **Exit Criteria:**@@ -35,7 +35,7 @@ The Beta phase iterates on functional completeness based on real-world deploymen* **Exit Criteria:**- * All planned sovereignty features are implemented and passing integration tests.+ * All planned data-residency and control features are implemented and passing integration tests.* API and Datalog schemas are frozen.## Phase 3: The Audit Freeze (Release Candidates)@@ -44,24 +44,24 @@ The Beta phase iterates on functional completeness based on real-world deploymen**Status:** Feature Frozen / Undergoing AuditDuring this phase, **no new features are merged**.-The codebase is strictly locked down to undergo rigorous external validation to ensure it meets our security and sovereignty guarantees.+The codebase is strictly locked down to undergo rigorous external validation to ensure it meets our security and data-residency guarantees.* **Core Objectives:*** **Security Audit:** Comprehensive third-party penetration testing, code review, and cryptography validation (focusing on Biscuit tokens and Ed25519 key handling).- * **Sovereignty & Compliance Audit:** Validation against strict digital sovereignty frameworks (e.g., GDPR data residency, EU AI Act traceability, CSF SEAL-3).+ * **Compliance Audit:** Validation against data-residency and traceability frameworks (e.g., GDPR data residency, EU AI Act traceability, CSF SEAL-3).* **Exit Criteria:*** All critical and high-severity security vulnerabilities are remediated.- * External auditors officially sign off on the cryptographic and architectural sovereignty claims.+ * External auditors officially sign off on the cryptographic and architectural claims.## Phase 4: Production Stable**Versions:** `v1.0.0` and beyond**Status:** Mission-Critical Ready-The framework is certified for enterprise, sovereign, and cross-border deployments.+The framework is certified for enterprise, regulated, and cross-border deployments.* **Core Objectives:**diff --git a/agents/skills/sam-a2a-bridge/SKILL.md b/agents/skills/sam-a2a-bridge/SKILL.mdindex 233c69a7..0d9b2bff 100644--- a/agents/skills/sam-a2a-bridge/SKILL.md+++ b/agents/skills/sam-a2a-bridge/SKILL.md@@ -1,6 +1,6 @@---name: sam-a2a-bridge-description: "Use when the task should be delegated to a remote A2A agent on the SAM (Sovereign Agent Mesh) network: send it work with send_agent_task (with text, structured data, or file attachments), check agent capabilities with get_agent_card, poll results with get_agent_task, hold multi-turn conversations, and enforce data-sovereignty labels on every call. Also use to set up the sam-a2a-bridge MCP server when those tools are not callable yet."+description: "Use when the task should be delegated to a remote A2A agent on the SAM agent mesh: send it work with send_agent_task (with text, structured data, or file attachments), check agent capabilities with get_agent_card, poll results with get_agent_task, hold multi-turn conversations, and enforce data-residency labels on every call. Also use to set up the sam-a2a-bridge MCP server when those tools are not callable yet."---# SAM A2A Bridge Skill@@ -71,7 +71,7 @@ input schema) and `file_path` attachments appropriately.- `data` (optional) contains structured JSON returned inline.- `files` (optional) is a list of paths where agent-returned files are savedunder the download directory.-- **Sovereignty**: when the task involves data that must stay in a region or+- **Data residency**: when the task involves data that must stay in a region orjurisdiction, set `required_labels` (comma-separated `key=value`, e.g.`region=eu-west-1`). The local node then refuses fail-closed before any dataleaves it unless the peer's control-plane-attested labels match. Never drop@@ -96,7 +96,7 @@ message while running and its answer or artifacts when completed. `data` and## Interpret Errors-- `403: Required labels not attested by provider` — the sovereignty gate+- `403: Required labels not attested by provider` — the label gaterefused before egress. Expected for non-matching regions; report it to theuser, do not retry with weaker labels on your own.- `400: Invalid X-Sam-Required-Labels header ...` — malformed labels; fix thediff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.mdindex 0725a892..ef4d87bb 100644--- a/agents/skills/sam-mesh/SKILL.md+++ b/agents/skills/sam-mesh/SKILL.md@@ -1,6 +1,6 @@---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."+description: "Use when local tools cannot provide a needed capability and a SAM agent mesh 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 Skilldiff --git a/charts/sam-mesh/Chart.yaml b/charts/sam-mesh/Chart.yamlindex e89a669e..59fbb336 100644--- a/charts/sam-mesh/Chart.yaml+++ b/charts/sam-mesh/Chart.yaml@@ -1,6 +1,6 @@apiVersion: v2name: sam-mesh-description: A Helm chart for deploying the Sovereign Agent Mesh (SAM) Control Plane, Router, and Console+description: A Helm chart for deploying the SAM control plane, router and consoletype: applicationversion: 0.1.0appVersion: "1.0.0"diff --git a/charts/sam-mesh/README.md b/charts/sam-mesh/README.mdindex 807a2c79..ba3a017d 100644--- a/charts/sam-mesh/README.md+++ b/charts/sam-mesh/README.md@@ -4,10 +4,9 @@ Deploys a self-contained SAM mesh (control plane, router, console, and anin-cluster Postgres) for local development, testing, or self-hosting yourown mesh.-> For large-scale production deployments (GKE/EKS/AKS) using externally-> managed Postgres/DNS/OIDC, see the-> [Production Kubernetes Deployment guide](https://sam-mesh.dev/docs/user/kubernetes-deployment/),-> which uses plain manifests instead of this chart.+> For deployments on GKE/EKS/AKS with externally managed Postgres, DNS and+> OIDC, see the+> [Kubernetes guide](https://sam-mesh.dev/docs/guides/kubernetes/).## Install@@ -65,7 +64,7 @@ Defaults to `true` (any node/router presenting a valid identity token isenrolled immediately, no manual step). Set to `false` if you want anadministrator to approve each enrollment via `/admin/enrollments` before anode can join — see the-[Control Plane Configuration guide](https://sam-mesh.dev/docs/user/control-plane-configuration/#6-headless-node-enrollment-bootstrap-token-flow).+[Headless enrollment guide](https://sam-mesh.dev/docs/guides/headless-enrollment/).## Gateway API (`gateway.enabled`)diff --git a/cmd/nano-init/README.md b/cmd/nano-init/README.mdindex 4c63d94b..226d1710 100644--- a/cmd/nano-init/README.md+++ b/cmd/nano-init/README.md@@ -82,7 +82,7 @@ image that has nothing else in it.## See also-- [Running agents on SAM](https://sam-mesh.dev/docs/user/running-agents/) — the+- [Sandboxed agents](https://sam-mesh.dev/docs/preview/sandboxed-agents/) — thefull picture, including the microVM arrangement-- [Agent architecture](https://sam-mesh.dev/docs/agent-architecture/) — why the+- [Agent architecture](https://sam-mesh.dev/docs/preview/agent-architecture/) — why theboundary speaks named HTTP tunnelsdiff --git a/cmd/sam-node/skill.go b/cmd/sam-node/skill.goindex 695782b3..bbb6a8f9 100644--- a/cmd/sam-node/skill.go+++ b/cmd/sam-node/skill.go@@ -179,7 +179,7 @@ Next steps:--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/+ Other agents: https://sam-mesh.dev/docs/guides/connecting-agents/3. Restart your agent so it picks up the skill and the mesh tools.`)}diff --git a/development/examples/agent-harness/README.md b/development/examples/agent-harness/README.mdindex f078034f..c1de9ed4 100644--- a/development/examples/agent-harness/README.md+++ b/development/examples/agent-harness/README.md@@ -5,7 +5,7 @@ conversation and the tool loop, and nothing else. No model endpoint toconfigure, no API key, no tool servers deployed alongside it, and no networkbeyond what its policy names.-Full walkthrough: [Running agents on SAM](https://sam-mesh.dev/docs/user/running-agents/).+Full walkthrough: [Sandboxed agents](https://sam-mesh.dev/docs/preview/sandboxed-agents/).## What it demonstratesdiff --git a/mobile/sam-node-app/README.md b/mobile/sam-node-app/README.mdindex 99d1354f..e2610c59 100644--- a/mobile/sam-node-app/README.md+++ b/mobile/sam-node-app/README.md@@ -97,7 +97,7 @@ Publishing is keyless: [`hack/publish-play.sh`](../../hack/publish-play.sh) drivOnce launched, the app (installed as **SAM Connect**, application id `dev.sammesh.connect`) asks you to enroll, then shows the dashboard:-1. **Scan enrollment code**: The primary path. `sam-one` prints a single-use `sam://enroll?server=...&token=...` QR code at startup (and on demand with `sam-one token qr`); scan it, confirm the control plane hostname, and the app enrolls through `POST /enroll` with no identity provider involved. The phone's stock camera app can scan it too: the `sam://` link opens SAM Connect. Only `https://` control planes are accepted (plaintext `http://` for loopback only), because the control plane is the device's trust root. See [A Mesh in 30 Seconds](../../site/content/docs/user/device-enrollment.md).+1. **Scan enrollment code**: The primary path. `sam-one` prints a single-use `sam://enroll?server=...&token=...` QR code at startup (and on demand with `sam-one token qr`); scan it, confirm the control plane hostname, and the app enrolls through `POST /enroll` with no identity provider involved. The phone's stock camera app can scan it too: the `sam://` link opens SAM Connect. Only `https://` control planes are accepted (plaintext `http://` for loopback only), because the control plane is the device's trust root. See [Your own mesh](../../site/content/docs/getting-started/your-own-mesh.md).2. **Enter details manually**: Paste a whole `sam://enroll` link or a bare bootstrap token together with the **Control plane URL**, then **Join with token**. On a full control plane, mint the token with `POST /admin/bootstrap-tokens` (see `development/kind/run-local-node.sh`); on `sam-one`, `sam-one token create`. Below it, **Login & Enroll (Browser)** and **Device Login** are the OIDC alternatives: the app reads the issuer from the control plane's `/info` endpoint and opens a login.3. **Local API Token**: The bearer token that secures the local sidecar REST API. It is generated on first launch and kept in the app's private storage; view, copy or regenerate it on the **Config** tab. There is no default: Android loopback is shared by every installed app, so a fixed value would let any of them act as this node.4. **Labels**: Set on the **Config** tab *before* enrolling; they are attested into the node's Biscuit at that point.@@ -133,7 +133,7 @@ Exposes capabilities directly to the OS registry, allowing native assistants (li1. **Dashboard Tab**: Displays current status, Node ID, connected peers, and DHT size.2. **Services Tab**: Allows enabling/disabling embedded sensors (Battery/Location) and bridging external local MCP servers.-3. **Config Tab**: The node's labels and attenuation, the app's stand-in for `sam-node.yaml`. Labels (comma-separated `key=value`) are set here; the control plane attests them into the node's Biscuit at enrollment, so changing them later means pressing Re-enroll, which re-attests them with the login session saved at enrollment (the browser opens only if that session has expired) and keeps the node's identity. A node that joined with a token or QR code has no login session and the control plane re-mints from the labels already on record, so Re-enroll is disabled for it: unenroll and join again with the new labels. Attenuation is Datalog rules, policies and checks that limit who may call this node, one statement per line (e.g. `check if label("region", "eu-west-1");`). They are read when the node starts, and a syntax error fails the start. Same syntax and same errors as the `attenuation` block of `sam-node.yaml`; see [Node configuration §3](../../site/content/docs/user/node-configuration.md#3-defining-local-security-target-attenuation).+3. **Config Tab**: The node's labels and attenuation, the app's stand-in for `sam-node.yaml`. Labels (comma-separated `key=value`) are set here; the control plane attests them into the node's Biscuit at enrollment, so changing them later means pressing Re-enroll, which re-attests them with the login session saved at enrollment (the browser opens only if that session has expired) and keeps the node's identity. A node that joined with a token or QR code has no login session and the control plane re-mints from the labels already on record, so Re-enroll is disabled for it: unenroll and join again with the new labels. Attenuation is Datalog rules, policies and checks that limit who may call this node, one statement per line (e.g. `check if label("region", "eu-west-1");`). They are read when the node starts, and a syntax error fails the start. Same syntax and same errors as the `attenuation` block of `sam-node.yaml`; see [Node configuration](../../site/content/docs/reference/node-config.md#attenuation).---diff --git a/sam-mcp-python/README.md b/sam-mcp-python/README.mdindex 916f2e89..2a1c8131 100644--- a/sam-mcp-python/README.md+++ b/sam-mcp-python/README.md@@ -1,6 +1,6 @@# SAM Python SDK (sam-mcp-python)-The official Python SDK for the Sovereign Agent Mesh (SAM).+The official Python SDK for SAM.This SDK acts as a "Thin Client" that connects to the local Go node via a Unix Domain Socket and communicates using the Model Context Protocol (MCP) over JSON-RPC 2.0.diff --git a/sam-mcp-python/pyproject.toml b/sam-mcp-python/pyproject.tomlindex f5bd8e41..73bb959c 100644--- a/sam-mcp-python/pyproject.toml+++ b/sam-mcp-python/pyproject.toml@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"[project]name = "sam-mcp"version = "0.1.0"-description = "Python SDK for Sovereign Agent Mesh (SAM) using MCP"+description = "Python SDK for SAM agent mesh nodes, using MCP"readme = "README.md"requires-python = ">=3.10"dependencies = [diff --git a/site/content/_index.md b/site/content/_index.mdindex 97f6275d..677769f9 100644--- a/site/content/_index.md+++ b/site/content/_index.md@@ -1,9 +1,13 @@---title: SAM-description: Sovereign Agent Mesh - A zero-config, zero-trust decentralized mesh network built for autonomous AI agents.+description: A private, zero-trust network for AI agents to publish, discover and call tools and models across machines.----SAM (Sovereign Agent Mesh) provides a secure, zero-trust P2P network specifically designed for AI agents to discover, share, and invoke tools across machines.+SAM is a private network for AI agents. A node runs beside an agent, publishes+the tools and models it offers, finds what other nodes offer, and calls them+over authenticated peer-to-peer connections, through relays when the machines+cannot reach each other directly.-Think of it as a private, zero-trust overlay network tailored for agent-to-agent communication.--**Secure by Default**: You do not join a mesh automatically, and your tools are never exposed by default. SAM relies on a Zero-Trust architecture, meaning you are 100% isolated until you explicitly join a mesh and allow access. You can use our public testnet for "Easy Mode" testing, or run completely in "DIY Mode" by hosting your own control plane.+Nothing is reachable by default: a node exposes no services until told to, and+no node may call a service the mesh policy has not granted. Identity comes from+your identity provider, and the control plane that turns it into mesh+credentials is one you can run yourself.diff --git a/site/content/docs/_index.md b/site/content/docs/_index.mdindex 840c3b9c..d30b0768 100644--- a/site/content/docs/_index.md+++ b/site/content/docs/_index.md@@ -2,43 +2,59 @@title: "SAM Documentation"linkTitle: "Documentation"----SAM (Sovereign Agent Mesh) is a smart, zero-config, zero-trust P2P network built for autonomous AI agents. Think of it as a modern, zero-trust overlay network (similar to a private VPN), but specifically designed and scoped for agent-to-agent tool sharing and communication.-## Why SAM?--Instead of exposing your agent's tools (like local scripts, LLM endpoints, or internal APIs) to the public internet, SAM allows you to create secure, private mesh networks. This is especially critical because modern AI agents operate across highly heterogeneous environments—spanning cloud servers, on-premises datacenters, personal laptops, Raspberry Pis, and Android devices. SAM seamlessly connects them all, regardless of complex network topologies or NATs.--**Security & Sovereignty Fundamentals**-* **Open Source Project:** SAM is an open-source project (Apache-2.0). It carries no vendor telemetry, has no proprietary lock-in, and can be deployed on any cloud, on-premises datacenter, or air-gapped environment.-* **Isolated by Default:** You do NOT join any mesh by default. You must explicitly configure the control plane you want to join.-* **Closed by Default:** Joining a mesh does not expose your tools. By default, your node does not allow any services to be reached by others. You must explicitly configure policies to share tools.-* **Public Testnets vs. Sovereign Deployments:** Public testnets (`bananas.sam-mesh.dev`, `hub.sam-mesh.dev`) are created using donated community resources solely as developer playgrounds for CI and experimentation. They hold zero production value, offer no guarantees or SLA, and carry no sovereignty. True sovereignty is achieved by deploying a dedicated control plane and routers with customer-managed cryptographic keys on your chosen infrastructure.-* 🏛️ **[Digital & Data Sovereignty Architecture](sovereignty/)**: Read our detailed breakdown on territorial attestation, jurisdictional label gates, local vetoes, and regulatory alignment.-------## Where to Start--### "Developer Testnet Mode" (Ephemeral Testing Sandbox)-For the fastest way to get started and experiment with the open-source code, you can connect a node to our public developer testnet (`bananas.sam-mesh.dev`). *Note: This is a shared developer testbed created with community resources. There are no guarantees; it is strictly for testing. Do not expose sensitive or production tools in a public testing environment.*--{{< demo >}}--- 🚀 **[User Quick Start Guide](quickstart/)**: Connect and run a SAM node using binaries or Docker, and query the local MCP server.-- 🤖 **[Agent Integration Guide](user/agent-usage/)**: Connect Google Gemini, Claude, and other AI agents to your SAM node to call tools across the mesh.-- 📡 **[Testnet Validation Tutorial](development/testnet-validation/)**: Real-time verification, remote tool invocation, and HTTP stream proxies.--### "Dedicated Sovereign Deployment Mode" (For Production & Private Meshes)-Deploy your own control plane, manage your own keys, and retain 100% cryptographic authority:-- 🏛️ **[Digital & Data Sovereignty Guide](sovereignty/)**: Deep-dive into jurisdictional label gates, local veto attenuation, uncooperative sandbox boundaries, and compliance.-- 🎛️ **[Production Kubernetes Deployment](user/kubernetes-deployment/)**: Deploy your own control plane and routers via Helm or Kubernetes manifests.-- 🛠️ **[Developer Guide](development/)**: Prereqs, compilation, local control plane setup, and Kind deployment.-- 🧪 **[Testing Guide](development/testing/)**: Go tests, E2E BATS, and containerized mesh execution.-------## Architecture--* **`sam-control-plane`**: The control plane for identity mapping, token issuing, and policy distribution.-* **`sam-router`**: The GossipSub routing overlays and bootstrap points for the P2P mesh.-* **`sam-node`**: The P2P nodes providing the mesh transport layer, self-healing connectivity, and local Model Context Protocol (MCP) HTTP interfaces.+SAM is a private network for AI agents. A node runs+next to an agent and gives it three things: a way to publish tools and+models to the network, a way to find and call what other nodes publish, and+an identity that every other node can verify. Nodes reach each other+directly when they can and through relays when they cannot, so the network+works across laptops, containers, clusters and phones behind NAT.++Three programs make up a mesh:++| Program | Role |+|---|---|+| `sam-control-plane` | Verifies who is joining, issues each node a signed credential, and holds the policy that says who may call what. |+| `sam-router` | A well-known peer that new nodes connect to first. It relays traffic between nodes that cannot reach each other and hosts the discovery table. |+| `sam-node` | Runs next to your agent. It enrolls with the control plane, connects to the mesh, serves your local tools to others, and exposes the mesh to your agent as a local MCP server and an OpenAI-compatible API. |++`sam-one` bundles the first two, plus a web console, into a single binary for+laptops and small deployments.++Two rules apply to every mesh:++- **Closed by default.** A node does not expose any service until you+ configure one, and a node cannot call a service unless the mesh policy+ grants it. Policy is written in terms of service names, not IP addresses.+- **Identity comes from your identity provider.** A node enrolls with an+ OpenID Connect token or with a one-time bootstrap token. The control plane+ turns that into a short-lived credential+ ([Biscuit](https://www.biscuitsec.org/)) that is bound to the node's own+ key and that any node can verify offline.++## How these pages are organised++- [Getting started](getting-started/) puts one node on the public+ testnet, then shows you how to run a mesh of your own with `sam-one`.+- [Concepts](concepts/) explains how the pieces fit together: the+ components, enrollment and identity, authorization, and how traffic moves.+- [Guides](guides/) show how to do specific tasks: expose a service, connect+ an agent client, enroll headless nodes, deploy on Kubernetes or Cloud Run.+- [Reference](reference/) lists every flag, configuration key, HTTP route+ and policy field.+- [Use cases](use-cases/) are worked examples of things built on top of+ the mesh.+- [Preview](preview/) covers features that work today but whose interfaces+ may still change: sandboxed agents and the mobile app.+- [Contributing](contributing/) covers building, testing and changing SAM+ itself.++## About the public testnets++`bananas.sam-mesh.dev` (built from `main`) and `hub.sam-mesh.dev` (built from+the latest release tag) are shared developer testnets that run on donated+resources. They exist for trying things out and for the project's own CI.+They have no uptime commitment, and anyone who can log in with the+configured identity provider can join them. Do not publish anything+sensitive there. If you need a mesh that you control, run your own control+plane. The guides explain how.diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.mddeleted file mode 100644index be383924..00000000--- a/site/content/docs/agent-architecture.md+++ /dev/null@@ -1,1023 +0,0 @@-----title: "Agent Architecture"-weight: 15------# Agent Sandbox Architecture--This document defines how an **agent** — an unmodified harness such as-`cmd/chaos-agent`, a LangChain script, or Claude Code — is connected to the-Sovereign Agent Mesh when it runs inside a sandbox (a Firecracker microVM or a-`--network none` container).--It is a design document: it states the layering, the contracts each layer-exposes, and the tests that hold those contracts in place.--What the result costs is measured in-[Scale: what an agent costs]({{< relref "/docs/scale-report" >}}).--## 1. Goals--1. **The harness is unmodified and mesh-unaware.** It opens ordinary sockets, it- resolves ordinary names, it speaks ordinary HTTP. No SDK, no `LD_PRELOAD`, no- proxy environment variables it has to honour.-2. **One enforcement point.** Every packet the sandbox emits is authorized in- exactly one place, by name, against one policy.-3. **The sandbox has no network.** Not a filtered network — *no* network device- other than the one we hand it. Isolation is a property of the runtime- (`network=none`, a microVM without a tap device), not of a firewall rule.-4. **The mesh looks like the internet.** Reaching a remote model or a remote MCP- server is the same act as reaching `api.github.com`: connect to a name. Which- names are mesh-internal and which are public is a policy decision made on the- host, not a code path in the agent.-5. **Deps stay put.** The design below adds no `go.mod` entry (see §7).--## 2. Why one enforcement point--There are three common ways to intercept a sandbox's traffic at the application-layer. Each of them leaks, and that is why none of them is used here.--* **Proxy environment variables** are honoured only by HTTP-aware clients. A- harness that opens a raw socket, a Python library using `httpx` with- `trust_env=False`, or anything speaking gRPC or Postgres simply escapes.-* **DNS spoofing** forces every flow through a MITM even when no secret needs- injecting, and it answers with loopback addresses, which destroys the- destination name the policy engine exists to reason about.-* **An `LD_PRELOAD` socket shim** must be built and served for every arch/libc- pair, and a statically linked binary defeats it outright.--The shared failure is that each one asks the agent to cooperate with its own-confinement. An agent that has to *agree* to be confined is not confined: the-next library that ignores the convention, the next subprocess that clears its-environment, and the next protocol that is not HTTP are each outside the-boundary.--Routing does not have that failure mode, because nothing has to agree to it. So-the boundary is a route and a socket rather than a convention, and there is-exactly one of them — one place where a flow is named, decided and opened.--## 3. The layering--One socket, one protocol, one policy point. Named HTTP tunnels are the waist.--```text-┌─ sandbox (microVM, or container with network=none) ───────────────┐-│ │-│ harness (unmodified: sockets + DNS + HTTP) │-│ │ IP │-│ tun0 ── default route, the only device besides lo │-│ │ │-│ tun2connect ── IP flows → CONNECT (TCP) / connect-udp (UDP), │-│ │ destination kept as a NAME │-│ │ (virtual DNS, see Decision 2) │-└────────┼──────────────────────────────────────────────────────────┘- │ one byte stream per flow- │ microVM : AF_VSOCK → firecracker → host UDS <uds>_<port>- │ container: bind-mounted UDS-┌────────┼──────────────────────────────────────────────────────────┐-│ host ▼ │-│ sam-box (one per sandbox, NO libp2p host, NO enrollment) │-│ = CONNECT server = THE policy enforcement point │-│ │ │-│ ├── mesh.sam.alt ── /v1 + /mcp only ─────┐ │-│ ├── <svc>.<type>.sam.alt ── HTTP: discover, then ┤ │-│ │ /sam/<peer>/<type>/… │ │-│ └── anything else ── deny-by-default domain │ │-│ policy, opt-in MITM + │ │-│ secret injection │ │-│ │ ▼ │-│ │ sam-node sidecar │-│ ▼ UDS: /mcp /v1/* │-│ the internet /sam/* │-└─────────────────────────────────────────────────────┼─────────────┘- │ libp2p- mesh-```--### Decision 1 — named HTTP tunnels are the sandbox boundary protocol--The boundary speaks authority-form `CONNECT` (RFC 9110) for TCP and-connect-udp (RFC 9298, capsules per RFC 9297) for UDP. An earlier revision of-this document chose SOCKS5 over HTTP proxying, for three properties; the-reversal is worth being explicit about, because all three properties are kept-and the reasons the comparison once favoured SOCKS5 stopped being true:--* **It carries the destination name.** `CONNECT api.github.com:443` is- authority-form: the gateway authorizes `api.github.com`, not- `140.82.121.5`. Domain filtering still needs no DNS interception, no MITM- and no IP allowlists that rot. connect-udp carries the name the same way,- in the URI template `/.well-known/masque/udp/{host}/{port}/`.-* **It is protocol-agnostic.** After the `200 OK` the tunnel is a byte pipe.- `git`, Postgres, gRPC and a raw socket are all first-class; HTTP is the- *handshake*, not a requirement on the payload.-* **It has a refusal vocabulary.** A policy denial is `403` with a- `Boundary-Reason` header, which tun2connect turns into a clean- `ECONNREFUSED` in the guest — exactly what an agent should observe when it- reaches for something it may not have — while an operator reading a log- sees the reason in words.--What SOCKS5 could not offer, and what decided the reversal:--* **One protocol in both directions.** The reverse channel into a sandbox- (§9.2) always spoke `CONNECT <port>`; now egress and ingress are the same- shape, and there is one grammar to reason about on the whole boundary.-* **Headers are the extension point.** Sandbox identity for multiplexing- rides in `Proxy-Authorization` (§8.5), and anything else — tracing, a- sandbox id — is a header away. SOCKS5 had a fixed binary vocabulary and- nowhere to put any of that.-* **UDP fits.** `UDP ASSOCIATE` presumes a datagram socket beside the TCP- one, which never fit a boundary that is a single Unix socket. connect-udp- frames datagrams as capsules *on the same stream*, so UDP arrives named,- policy-checked and audit-delimited like every TCP flow (§11).-* **It is curl-testable.** `curl --proxy` speaks the TCP half natively, which- makes the boundary probeable with a tool every operator already has.--HTTP MITM does not disappear; it moves *above* the waist. When a domain is-configured for secret injection, the gateway terminates TLS for that flow with-the existing `internal/sambox` ephemeral CA and injects the header. Every other-flow is a byte pipe with no interception at all — a meaningful improvement over-the status quo, where every flow is MITM'd.--### Decision 2 — names are resolved on the host, never in the guest--tun2connect answers guest DNS from synthetic pools it invents — IPv4 out of-`100.64.0.0/10` (CGNAT space: link-local would be leak-proof, but SSRF guards-in HTTP clients commonly block `169.254/16` and would break legitimate-egress), IPv6 out of `100::/64` (the RFC 6666 discard prefix, so an escaped-packet blackholes). The guest resolver gets a synthetic address, the engine-maps it back to the FQDN when the flow opens, and the gateway receives the-FQDN in the tunnel request. A flow whose destination was never resolved has-no name and is refused in the guest. Nothing in the guest ever performs a-real DNS lookup, so:--* `nano-init`'s DNS spoofer, `/etc/resolv.conf` rewrite, `HTTP_PROXY` injection- and `libinterceptor.so` bootstrap are **deleted**, not reimplemented;-* the guest cannot exfiltrate over DNS, because there is no resolver path out;-* the policy engine gets the name for free, on every flow, for every protocol.--### Decision 3 — the host never speaks AF_VSOCK--Firecracker's vsock device already terminates AF_VSOCK and hands the host a Unix-socket per guest port (`<uds_path>_<port>`). The gateway therefore accepts on a-`net.Listener` that is *always* a UDS. A microVM and a `network=none` container-become the same code path, and the difference is one line of sandbox setup:--| sandbox | guest side | host side |-|---|---|---|-| Firecracker microVM | `tun2connect` → vsock CID 2, port *P* | listener on `<uds>_P` |-| container, `network=none` | `tun2connect` → `/run/sam/agent.sock` | listener on the bind-mounted path |--This keeps AF_VSOCK out of the Go code entirely (no new dependency) and — more-importantly for the test pyramid — makes the whole datapath exercisable in a Go-integration test against a UDS in `t.TempDir()`, with no VM and no KVM.--### Decision 4 — a mesh name is the service namespace written in DNS shape--The mesh already has a canonical namespace: `mcp://<service>`,-`inference://<service>`, `system://sam.catalog`, and internally-`libp2p://<peer>/<type>/<service>/…`. That namespace is what the control plane-authorizes in `allowed_services` and what lands in the Biscuit `service()` fact.-Sandbox names are a **projection of it**, not a second namespace:--```text-inference://openrouter <-> openrouter.inference.sam.alt-mcp://code-reviewer <-> code-reviewer.mcp.sam.alt-(the mesh, curated) <-> mesh.sam.alt-```--The mapping is declared once, in [`api/names.go`](https://github.com/google/sam/blob/main/api/names.go)-(`MeshZone`, `MeshEntrypointHost`, `MeshHost`, `ParseMeshHost`), so the gateway-and the node cannot drift. The rule that keeps it honest: **never introduce a-routing decision expressible in one form but not the other.**--`.alt` is the pseudo-TLD reserved by RFC 9476 for namespaces that are-deliberately *not* resolved through the DNS — which is exactly what these are.-It cannot collide with a delegated gTLD, and a name that escapes a sandbox fails-closed instead of resolving to somebody else's host. `.local` was rejected: it-is mDNS's (RFC 6762) and resolvers treat it specially.--Provider selection is *not* in the name. `openrouter.inference.sam.alt` says-which service, never which peer; that stays a discovery decision, scored by the-existing provider scorer. Pinning a peer would mirror `libp2p://<peer>/…` as a-longer name, but needs a DNS-safe peer encoding first — base58 peer IDs are-case-sensitive and DNS labels are not. IPFS hit the same wall and solved it with-lowercase base36 CIDs in subdomain gateways; that is the path if we ever need-it, and it is noted in `api/names.go` rather than half-built.--### Decision 5 — the agent is the principal; the node is only the channel--Traceability and granular policy are the product. "Agent `foo` may use-`inference://X`, agent `bar` may not" has to be a statement the *whole mesh* can-evaluate, and it has to survive an agent being paused on one node and resumed on-another. So agent identity travels with the agent, never with the host.--A Biscuit is bound to a peer ID: `SamNode.Authorize` requires a `node(<peer>)`-fact matching the connecting peer and enforces `BaselineReplayCheck`-(`client_peer_id == connection_peer_id`). That binding is right — for the-*channel*. It is the wrong place to express *who is asking*.--The mesh already knows how to take in a foreign identity, and agents reuse that-pattern one level down. A node presents an OIDC JWT **once**, at enrollment; the-control plane verifies it against a configured issuer and mints a Biscuit;-`translateClaimsToFacts` turns claims into facts, and the JWT never appears on-the datapath again. The two domains are joined at exactly one point and never-mixed:--| | asserted by | verified against | when | on the datapath as |-|---|---|---|---|---|-| node identity | control plane | the OIDC issuer | enrollment | a Biscuit |-| agent identity | the enrolled SAM component that admitted the agent | the platform's workload issuer (K8s SA token, pod certificate, SVID) | admission | an appended Biscuit block |--The agent's facts ride as an **attenuation block appended to the node token**,-not as a second credential. `biscuit-go` cannot verify a block signed by a third-party (§8.2), so splitting them buys no extra cryptographic attribution while-costing a second verification on every request. The identifier is still the-agent's and still portable: teleport the actor to another worker and the SAM-component there verifies the same workload credential and asserts the same-`agent:` name. Nothing downstream notices the move.--The residual trust, stated plainly: an enrolled node asserts its own agents.-Mesh policy limits this with a role's `allowed_agents`, which lists the-namespaces a node is allowed to use. Only a node whose role grants `*.c1.acme`-can claim an agent in that namespace, and a node with no grant cannot name any-agent at all. Non-repudiation *by the agent itself* needs proof of possession,-which stays an upgrade path (§8.6).--## 4. Where the gateway lives: `sam-box`, without a libp2p host--There are two binaries with disjoint jobs.--**`sam-node` — the mesh member.** It owns the libp2p host, enrollment, identity,-discovery and the sidecar API (`/mcp`, `/v1/*`, `/sam/service/*`,-`/sam/<peer>/…`) over TCP and its Unix socket.--**`sam-box` — the sandbox dataplane.** One per sandbox. It holds **no libp2p-host, no enrollment, no mesh identity**. It serves the named-tunnel boundary-(CONNECT, connect-udp) on the sandbox-facing socket, enforces the egress-policy, does MITM/secret injection where configured, and reaches the mesh-solely by dialling the local `sam-node` sidecar Unix socket as a client.--What this buys:--* *N* sandboxes per host still share **one** libp2p host, so no *N*× DHT- clients, identify/ping loops or router connections — the thing that would- otherwise cap density in the scale experiment.-* `sam-box` becomes small and boring: an HTTP CONNECT server plus an HTTP- client. No `join`, no OIDC, no Biscuit handling, no bbolt store. Most of- [cmd/sam-box/main.go](cmd/sam-box/main.go) is deleted.-* The blast radius of a compromised sandbox stops at its `sam-box`, which holds- one agent credential and can be killed and reissued in isolation.-* Failure isolation and lifecycle match the sandbox's, not the host's.--`sam-box` is a **multiplexer of agents**: it may serve one agent per socket, or-many agents over one socket, and each flow it forwards carries that agent's own-identity (Decision 5, §8). Losing the libp2p host costs it nothing here — the-agent's authority never came from the host in the first place.--`internal/sambox` keeps the ephemeral CA and secret injection and gains the-CONNECT server; `internal/node` keeps everything mesh.--## 5. Contracts--### 5.1 What the harness sees--```bash-OPENAI_BASE_URL=http://mesh.sam.alt/v1 # inference, provider chosen by policy-MCP_URL=http://mesh.sam.alt/mcp # tools: local catalog + remote services-```--No `HTTP_PROXY`. No CA bundle, unless a domain is explicitly configured for-secret injection. No mesh concepts, and no token of any kind.-`cmd/chaos-agent` already takes `--mcp-url` and `--inference-url`, so it needs-no change beyond the values it is given.--A harness that wants one specific service instead of policy-chosen routing uses-its mesh name directly: `http://code-reviewer.mcp.sam.alt/`.--### 5.2 Gateway dispatch--Applied to the tunnel request's `(host, port)` — `host` is the name-`tun2connect` preserved, never an IP — in order:--1. **`mesh.sam.alt`** (`api.IsMeshEntrypointHost`) → the gateway's own- agent-facing surface, served in process: `/v1/models`,- `/v1/chat/completions`, `/v1/completions`, and `/mcp`. Nothing else. Any- other path is refused with 403 and never reaches the node.-- **The agent never touches the node.** A `sam-node` sidecar is a local,- operator-facing API: it can register services under the node's identity, and- its `/sam/<peer>/<type>/<name>` proxy will carry a request to any peer and- service the caller names. Worse, arriving on its Unix socket *is* the- credential — `withAuth` treats reaching the socket as proof of authorization,- on the grounds that it is the same bar as reading the token file. So piping- an agent's bytes to that socket would hand every sandbox the node's full- local authority. `sam-box` is the node's consumer; the agent is the mesh's- consumer, through `sam-box`, and the two are different surfaces.-- Discovery is deliberately absent from the list even though agents need it:- MCP already exposes `find_remote_tools` and `discover_remote_services` as- tools, so opening `/sam/service/discover` as well would widen the surface- without adding a capability.-2. **`<service>.<type>.sam.alt`** (`api.ParseMeshHost`) → `sam-box` terminates- HTTP and rewrites onto the sidecar's existing surface:- `GET /sam/service/discover?type=<type>&name=<service>` picks a provider, then- the request is reverse-proxied to `/sam/<peer>/<type>/<service>/<path>`. No- new sidecar endpoint, no libp2p in `sam-box`.-3. **anything else** → egress policy (§5.3). Allowed flows are dialled directly;- flows on a secret-injection domain are terminated with the ephemeral CA.-4. **no match, or a name in the zone that resolves to nothing** → `403` with- `Boundary-Reason: not allowed by policy`.--Case 2 is the only one that inspects payload, and only because provider-selection is an HTTP-level decision. `https://` to a mesh name therefore needs-the ephemeral CA trusted in the guest; v1 documents mesh names as `http://`-(the transport underneath is libp2p, already authenticated and encrypted) and-leaves guest CA installation to sandbox image build rather than a bootstrap-endpoint.--### 5.3 Egress policy--Deny-by-default, evaluated on the name, expressed in the node config next to the-existing `attenuation` block:--```yaml-version: v1-sandbox:- egress:- allow:- - "api.github.com"- - "*.pypi.org"- secrets:- "api.github.com":- kind: bearer- value_from: /etc/sam/secrets/github-```--Filtering by name without MITM is honest here: the gateway dials the name it-authorized and, for TLS, requires the client's SNI to match it.--### 5.4 What a sandbox must provide--`nano-init` builds the route out of a sandbox. It does not build the sandbox,-so a profile is the answer to "who provides the isolation", and there are three-supported answers. Each must satisfy the same five preconditions:--1. **A network namespace with no way out.** No interface but loopback. This is- the one that cannot be compromised: an agent with a second route does not- have a boundary, it has a suggestion.-2. **A private `/etc/resolv.conf`.** `nano-init` points it at the resolver on- `tun0`, so anything sharing that file would have its DNS repointed too.-3. **A Unix socket to the boundary.** Sockets are filesystem objects and are- unaffected by the network namespace, which is what lets the sandbox have no- network and still be reachable.-4. **A way to create a TUN device.** A kernel with `CONFIG_TUN` in a microVM;- `/dev/net/tun` plus `CAP_NET_ADMIN` elsewhere.-5. **PID 1**, so children are reaped and signals and exit codes travel.--| | `docker run --network none` | Firecracker microVM | Kubernetes pod |-| --- | --- | --- | --- |-| netns with no way out | the container runtime | the guest kernel, given no network device | **nothing does** |-| private `resolv.conf` | the container's mount namespace | the guest rootfs | **nothing does** |-| boundary socket | bind-mounted UDS | vsock, surfacing on the host as `<uds>_<port>` | shared `emptyDir` |-| TUN | `--device /dev/net/tun --cap-add NET_ADMIN` | `CONFIG_TUN` in the guest kernel | `hostPath` of type `CharDevice` |-| PID 1 | the container's entrypoint | `/sbin/init` | the container's entrypoint |-| isolation strength | namespaces, shared kernel | own kernel | namespaces, shared kernel |--The first two columns are satisfied by the runtime. The third is not, and the-reason is structural rather than an oversight: **every container in a pod shares-one network namespace**, so there is no per-container equivalent of-`--network none`, and the `resolv.conf` the kubelet generates is shared by all-of them. A pod profile therefore has to create those two namespaces for itself,-inside the container, before `nano-init` starts.--The pod column needs no capabilities, which is worth stating because the obvious-guesses are both wrong. The device cgroup does not deny `/dev/net/tun`, so no-device plugin is involved and a bind mount is enough; and granting-`CAP_SYS_ADMIN` alone is actively worse than granting nothing, because the-namespace then gets created without the `CAP_NET_ADMIN` the tun needs. Creating-a user namespace first supplies both over the namespaces it owns, so that is the-path taken whenever user namespaces are available. What a pod does need is a-seccomp and AppArmor policy that permits `unshare(CLONE_NEWUSER|CLONE_NEWNS)`-and `mount` — Kubernetes applies neither profile by default, and Docker's-defaults block both.--Because the failure is silent -- `tun0` alongside `eth0` is a working network,-not an error -- `nano-init` refuses to start in a namespace that has any-interface other than loopback and its own tun, whichever profile is in use.-That check is what makes a third profile safe to add rather than a way to-quietly lose the boundary.--## 6. Test plan--Coverage is pushed as far down the pyramid as it will go. Firecracker appears-exactly once, at the top.--**Unit (`internal/…`, `api/`).** CONNECT and connect-udp request parsing, the-refusal-status mapping and the RFC 9297 capsule codec; the name↔URI-projection (`api/names_test.go`, already landed); dispatch classification-(`mesh.sam.alt` / mesh name / public / denied); the agent-facing path allowlist;-wildcard matching in the egress allowlist; SNI-vs-authorized-name mismatch.-Pure functions, microseconds.--**Integration (`tests/integration/`, budget 10s each).** The whole datapath, no-containers:--* node A registers a fake OpenAI-compatible backend — reuse the- `registerInferenceService` + `httptest` pattern already in- `openai_facade_test.go`;-* node B registers a fake MCP service — reuse `newFakeMCPHandler`;-* node C runs with a sidecar Unix socket, and a `sam-box` beside it serves- the boundary on a second socket in `t.TempDir()`;-* the test opens real CONNECT tunnels over that socket (stdlib `net/http`, the- same wire shape tun2connect produces) and asserts:- 1. `mesh.sam.alt:80` → `/v1/chat/completions` reaches A's fake LLM across the mesh,- 2. `mesh.sam.alt:80` → `/mcp` `call_remote_tool` reaches B's fake MCP,- 3. `<svc>.mcp.sam.alt:80` resolves through discovery to B and reaches it,- 4. an allowlisted public name reaches a local `httptest` server,- 5. a non-allowlisted name is refused with `403`,- 6. no path outside `/v1/*` and `/mcp` reaches node C at all.--**E2E (`tests/e2e/*.bats`).** Two CUJs, no more:--* *Container sandbox*: `docker run --network none` with the real harness plus- `nano-init`, a bind-mounted UDS to a host `sam-node`, against the existing bats- mesh (`lib/container_mesh.bash`). Asserts a real inference call, a real tool- call, and one blocked domain.-* *microVM sandbox*: the same rootfs under Firecracker, `skip` unless `/dev/kvm`- is present. It exists to prove the vsock↔UDS mapping and nothing else; every- behavioural assertion is already covered above.--## 7. Dependencies--Nothing on the host requires a `go.mod` change:--* CONNECT / connect-udp **server** — a few hundred lines against the stdlib,- including the RFC 9297 capsule codec, on a Unix socket.-* CONNECT **client** (tests, `sam-bench`) — stdlib `net/http` request writing.-* AF_VSOCK — never touched by Go code (Decision 3).-* MITM CA and secret injection — `internal/sambox`, already ours.-* Mesh name projection — `api/names.go`, stdlib only.--### 7.1 The guest-side datapath: tun2connect--The guest side is Go, in `cmd/nano-init`, which is **its own module**-(`github.com/google/sam/cmd/nano-init`). Its datapath is the-[`tun2connect`](https://github.com/aojea/agents.net) library — gVisor's-netstack terminating the sandbox's TCP/IP in userspace, a `BoundaryClient`-speaking CONNECT and connect-udp, and a `VirtualDNS` preserving names — plus-`github.com/vishvananda/netlink` to build `tun0`. All of it lives in the-nano-init module, so the root `go.mod` is untouched and the host binaries-carry none of it.--Consuming the datapath as a library, rather than shipping a universal guest-binary, is a deliberate split: the engine, the tunnel client and the name-preservation are universal and live upstream with their own tests; what stays-in `nano-init` is exactly what is SAM- and platform-specific — the vsock-boundary for microVMs, `--create-namespaces` for pods, the `copy` mode for-image builds, and PID 1 duty.--Owning the guest datapath is what makes the rest of this design possible:--* the destination stays a **name** all the way to the tunnel request. A stack- that proxies by address has already thrown away the thing policy reasons- about, so the virtual DNS hands out synthetic addresses from- `100.64.0.0/10` and `100::/64` and the engine restores the name when it- opens the flow — and refuses a flow that never had one;-* policy and telemetry decisions can be made *inside* the guest — per-process- attribution, for instance — which an external binary cannot be extended to do;-* it builds for whatever architectures the project builds for, with no- third-party release URL pinned into the image;-* it is covered by `go test`, not only by the bats CUJ.--The module boundary is the point. A userspace network stack is a large-dependency, and keeping it in a separate module means it is a guest-image-concern rather than something every `sam-node` and `sam-box` build has to carry.--The host is unaffected either way: the sandbox boundary is CONNECT over a byte-stream, so the guest implementation could be replaced without changing anything-on the host or rewriting any test above.--## 8. Agent identity--### 8.1 Requirements--1. **Portable.** An agent paused on node A and resumed on node B is the same- principal. Identity moves with the agent's state, never with the host.-2. **Verifiable mesh-wide.** Any peer can decide "agent `foo` may use- `inference://X`, agent `bar` may not" without asking anyone.-3. **Scales to 10⁹ agents and services.** No central per-agent record, no- per-agent mint on the hot path, no enumeration in any policy document, no- revocation list proportional to the agent population.--### 8.2 The library constraint that decides the shape--`biscuit-go/v2 v2.2.0` has **no third-party blocks**: the library's own sample-suite explicitly skips `test024_third_party.bc`, and the API exposes no-public-key (`trusting`) checks. So an agent-signed block cannot be embedded-inside the node's token.--What the library *does* give us is exactly enough:--* `New` — mint under a root key;-* `CreateBlock` + `Append` — **offline attenuation**, no root key, no network;-* multi-root verification (`VerifyBiscuit(..., trustedPublicKeys, ...)`);-* `RevocationIds()` — per-block revocation identifiers;-* `Seal` — stop further attenuation.--Hence the agent's facts travel as an ordinary appended block on the node token-(Decision 5). This is not a workaround — it is why **`Authorize` needs no change-at all**: appended blocks are already part of the token and already evaluated,-so only the component that admits the agent has to learn to append. If-`biscuit-go` later gains third-party blocks, the agent can sign its own block-and non-repudiation arrives without a wire break.--> **Correction (falsified by test).** The paragraph above was wrong, and-> `TestAttenuationBlockFactsAreInvisibleToTheAuthorizer` in `internal/identity`-> now pins why. `Authorize()` merges **only the authority block's** facts and-> rules into the authorizer's world; every appended block is evaluated in a-> world of its own, so its facts can satisfy that block's own checks and-> nothing else. A fact appended by a holder is invisible to the far end's-> policy.->-> That is deliberate and correct: if appending could add facts the authorizer-> sees, attenuation would be able to *grant* authority instead of only-> narrowing it, and any bearer could promote itself.->-> The consequence is that "append a block naming the agent" cannot work, so the-> claim has to travel beside the token instead — and it is worth being precise-> that this costs nothing cryptographically. Whoever can append a block can-> append *any* block, so a node's claim about which agent it is speaking for is-> worth exactly what the node is worth either way (Decision 5's residual-> trust, bounded by binding namespaces to node attestation). Only a block-> signed by the agent itself would change that, and that needs third-party-> blocks.->-> Options, to be settled before the node side is built:->-> 1. **Propagate `X-Sam-Agent` peer to peer** and have the receiving node inject-> `agent(...)` into its authorizer, exactly as `injectIdentityFacts` already-> injects facts the node derived itself. Simple, and honest about the trust-> involved.-> 2. **Append the block anyway and read it back out** of the token at the far-> end, then inject the same fact. Identical trust, plus datalog text parsing,-> since `biscuit-go` exposes no structured per-block fact accessor.-> 3. **Wait for third-party blocks**, which would make the agent's own signature-> the thing being verified, and is the only option that adds real-> non-repudiation.->-> **Decided: option 1**, implemented in `internal/node/agent.go`.--### 8.2.1 What the agent claim covers, and what it does not--**Covers.** Attribution and policy on **both** datapaths. A peer can authorize-and audit "agent `reviewer-7` called me" rather than only "some node did", using-the existing vocabulary, because the claim is injected as an ordinary `agent()`-fact. `TestAgentPolicyCUJ` shows two agents behind two gateways on one node-being told apart by the provider's policy — over HTTP for inference and over the-libp2p stream for tool calls — including a lookalike authority being refused and-an unidentified sandbox being refused.--The two paths carry it differently because they authenticate differently: HTTP-requests carry `X-Sam-Agent`, and streams carry `AuthFrame.agent`. On the stream-path the claim is bound to the MCP *session* rather than the request, since the-SDK hands a tool handler the session's context and not the request's. That fits-how sandboxes work anyway: one gateway serves one agent, so a session belongs to-one agent for its whole life.--**Does not cover.**--* **Proof.** The claim is the calling node's word. A node that lies can name any- agent, so a mesh that cares must also constrain which peers may speak for- which agent namespaces. Carrying it in a header rather than a block costs- nothing here: an appended block is exactly as forgeable by the same party.-* **Anything that never leaves the node**, which the boundary already gates- locally.--**A consequence to design around.** A node's own housekeeping carries no agent,-because no agent asked for it. A provider whose policy demands an agent-unconditionally therefore also refuses that node's model-catalog probe, and its-models stop appearing in peers' `/v1/models` listings even though agents can-still call them. This was found by the test, not by reasoning. Policy that means-to gate agent traffic should say so rather than demanding an agent everywhere.--### 8.3 Why it scales: delegation, not enumeration--Three rules, each of which removes a per-agent bottleneck:--**Minting is offline and local.** The control plane never mints per agent. It-grants a *namespace holder* — in practice the enrolled `sam-node`/`sam-box` in a-cluster, scoped by its attestation (§8.6) — authority over an agent namespace,-once. That holder asserts a per-agent identity by appending a block to its own-token with `Append`: no root key, no round trip, no central state. Admitting an-agent is O(1) local work, which is the only way 10⁹ of them exist.--**Policy is written over namespaces, not identities.** This needs almost no new-machinery, because the existing vocabulary is already shaped for it:-`BuildTargetDatalogFacts` compiles targets into `granted_target_prefix`,-`granted_target_suffix`, `granted_target_set` and `granted_target_exact`. Making-`agent` a first-class principal is:--* `FactAgent = "agent"` in `api/datalog.go`;-* the agent block's `agent(...)` fact injected as a `target_fact` at- authorization time.--After that, `allowed_targets: ["agent:acme/prod/*"]` works with **zero new-evaluation logic**, and "foo yes, bar no" is expressed as a namespace, a set or-a prefix — never as a list of a billion names.--**Revocation is tiered.** A revocation list sized like the agent population is-not a design, so nothing depends on one:--| what happened | mechanism | cost |-|---|---|---|-| agent is done or misbehaving | kill the sandbox | instant, local, free |-| credential must stop being usable elsewhere | short-lived workload credential; the platform stops renewing it | bounded window, no list |-| a namespace holder is compromised | `RevocationIds()` on its delegation block | one entry kills every agent under it |--### 8.4 How the identity travels--The agent's credential bundle lives **in the agent's own state**, next to-whatever else the platform migrates — not in `sam-box`'s configuration and not in-the node's store. Pause, snapshot, move, resume: `sam-box` on node B reads the-bundle from the migrated state and starts asserting it. **No control-plane call-on resume.** That is what makes migration cheap, and it is the same property-that makes 10⁹ agents possible.--### 8.5 Where the agent's identity comes from--Not from the agent. The harness stays unmodified (Goal 1), so it never asserts-anything about itself — it could only lie. It comes from the credential the-platform **already** issues to the workload:--* a **Kubernetes projected service-account token**, audience-scoped and- short-lived;-* a **pod certificate** (KEP-4317) — which Substrate already provides today via- its `podcertcontroller` polyfill;-* a **SPIFFE SVID**, where SPIRE is in play.--`sam-box` verifies that credential against the platform's issuer at admission —-in-cluster, cheap, no mesh round trip — and translates it into `agent:` facts by-the rules in §8.8. **The scheduler needs no mesh enrollment and no mesh-credential of its own.** It keeps doing exactly what it already does for every-workload: project an identity document. This is the OIDC relationship, not a-merger of the two domains.-The check that carries the weight is not the signature but the subject: the-credential must attest the `external_id` the bundle declares. Every sandbox on a-platform holds a valid credential, so verifying the signature alone would let-any of them claim to be any other. And the issuer is operator configuration-(`--credential-issuer`), never a bundle field — the bundle travels with the-agent, so an issuer named there could be one an attacker controls, and their-self-signed credential would verify perfectly.--Verification is the default: a bundle without an issuer to check it against is-refused. Deployments with no platform issuer can still run, but by saying so-(`--insecure-unverified-bundle`), because a name the whole mesh authorizes-against should not become trustworthy through a field being left unset.-`sam-box` then binds that identity to the channel, so nothing has to be asserted-in-band afterwards:--1. **One socket per agent (default).** Identity is a property of the socket,- fixed when the sandbox is created: one vsock UDS per microVM, one bind-mounted- socket per container. Nothing in-band, nothing to spoof.-2. **Proxy-Authorization (multiplexing).** When one `sam-box` fronts many agents- over one socket, Basic credentials on the tunnel request carry the agent id- and its admission token. It is standard, in-band, supported by every HTTP- proxy client, and it makes identity **per-connection** — which is exactly- what a multiplexer needs.--### 8.6 The honest limit--An enrolled node asserts its own agents, so a compromised node can claim any-agent identity inside the namespaces its role allows (`allowed_agents`, §3).-That limit is the mitigation, and the same policy machinery enforces it. Without-it, one compromised node could impersonate any agent anywhere. A node that holds-no grant cannot name any agent.--The grant is keyed on the node's **role**, not on its labels. Nodes declare-their own labels at OIDC enrollment and the control plane only checks the-syntax, so a namespace derived from a label would be one the node picked for-itself. Roles are resolved from verified OIDC claims against bindings the admin-wrote, so that chain holds all the way back.--Two things follow:--* How tight the limit is depends on the connector's naming (§8.8, property 5).- If a name has no label for the boundary it runs in, the only grant you can- write is a tenant-wide one.-* `allowed_agents: ["*"]` goes back to the old, unlimited behaviour. It is- allowed because some meshes have a single tenant, and nodes log a warning so- it is never silent.--Removing the residue entirely requires proof of possession: the agent holds a-key and signs a per-request binding. That needs either a mesh-aware harness-(violates Goal 1) or a signer inside the sandbox, and it needs third-party-blocks in `biscuit-go` to be attributable. It is a clean upgrade, not a rewrite.--### 8.7 Consequences for the plan--* `api/` — `FactAgent`, the §8.8 translation helpers, and- the §10 bundle schema.-* `internal/node` — **nothing** for authorization: appended blocks are already- verified and evaluated. Only the namespace-binding policy is new.-* `internal/sambox` — holds the bundle, attaches it per flow, per socket or per- tunnel connection; serves the §10 control socket and routes the §9 serving- channel.-* `cmd/nano-init` — owns the guest side of the ingress channel (§9.2).-* Sidecar — propagates the agent header on egress alongside `X-Sam-Biscuit`.-* Tests — the CUJ that demonstrates the selling point belongs at integration- level: two agents behind one `sam-box`, same node, same mesh; `foo` reaches- `inference://X` and `bar` is refused, purely on their own credentials.--### 8.8 The agent identifier--**Decided: dot-separated, DNS-shaped, most-specific-first.**-`agent:reviewer-7.prod.acme.example`, matched by `agent:*.prod.acme.example`.--The policy engine chooses this for us. `BuildTargetDatalogFact` compiles-`*.acme.example` into a suffix fact that **keeps the leading dot**-(`.acme.example`) and `acme.*` into a prefix fact that **keeps the trailing dot**-(`acme.`). Wildcards are therefore already anchored on dot boundaries:-`evil-acme.example` cannot match `*.acme.example`. A slash-separated-`agent:acme/prod/name` would need new fact types and new matching code, and-would reintroduce the boundary bug the dot anchoring already avoids. It also-matches every other name in the system: service names are validated by-`dnsNameRegex`, and mesh hosts are DNS-shaped (§Decision 4).--**Is it a mesh-only convention? Yes — and that is fine, for exactly the reason-you gave.** It is the same relationship the mesh already has with OIDC:-`translateClaimsToFacts` turns `sub`, `email` and `groups` into `user`, `email`-and `group` facts, and policy is written against *those*, never against the raw-JWT. Third parties do not adopt `agent:`; connectors translate into it.--A connector's translation must satisfy four properties, and this is the part-worth writing down because "without losing capabilities" lives here:--1. **Total** — every foreign identity maps to exactly one mesh identifier.-2. **Injective** — two foreign identities never collide, or policy leaks across- tenants. The rightmost labels must be an authority the platform actually- controls.-3. **Hierarchy-preserving** — foreign hierarchy boundaries must land on dot- boundaries. This is the capability-preserving requirement: if the connector- flattens the hierarchy, wildcard policies stop being expressible and the- operator is forced back to enumeration.-4. **Auditable** — the original identifier travels verbatim alongside the- translated one. Where translation cannot round-trip, the verbatim value is- what an auditor reads.-5. **Bounded** — the name must include a label for the boundary where the- agent's workload credential stops being valid, usually the cluster or trust- domain. Node grants (`allowed_agents`, §8.6) are written against that label.- A mapping can satisfy properties 1–4 and still fail this one: a flat- `spiffe://acme.example/prod/reviewer-7` → `reviewer-7.prod.acme.example` has- no cluster label, so every node hosting these agents needs a tenant-wide- grant and the limit gets much weaker. The Kubernetes and Substrate rows- below keep the cluster in the name, so their grants stay tight.--| foreign identity | mesh identifier |-|---|---|-| `spiffe://acme.example/prod/reviewer-7` | `agent:reviewer-7.prod.acme.example` |-| K8s SA `prod/reviewer` in cluster `c1.acme.example` | `agent:reviewer.prod.c1.acme.example` |-| OIDC `iss=https://acme.example`, `sub=reviewer-7` | `agent:reviewer-7.acme.example` |--Each segment must be a valid DNS label; a connector encodes anything else.-Non-hierarchical attributes do **not** belong in the name — that is what the-attested label machinery (`api/labels.go`) is for.--## 9. Ingress: agents that serve--An agent serves exactly one thing: itself, over A2A. `code-reviewer.a2a.sam.alt`-is already the name (Decision 4); serving it just means being its provider.-MCP and inference services are operator services, declared in a node's-configuration — an agent is not a generic backend and never advertises one.--### 9.1 Declaring: a static contract, no runtime registration--The agent does **not** declare anything, to anyone, ever. There is no-registration API on the node — services only exist by declaration in the-node's configuration at startup — and there is no announce endpoint on the-gateway. Both facts follow from the same rule: anything an agent can request-at runtime is an interface it can abuse. A runtime declaration carries a-*name*, so an agent could advertise itself as `code-reviewer` under the-node's identity and take over somebody else's traffic; give it a-`target_url` and it can point the mesh at anything and turn its node into an-open relay.--So the whole route is contracted before the agent runs:--* **The bundle names what the agent serves** (§10.1 `serves`): one name, one- port. `sam-box` routes that name to that port inside the sandbox from- startup, over the reverse channel (§9.2). A name outside the contract is- not expressible rather than merely rejected.-* **The node's configuration declares the service** — `type: a2a`, the- contracted name, `target_url` pointing at the gateway's serving listener.-* **Advertisement is gated on the probe.** The node fetches the agent's card- (`/.well-known/agent-card.json`) through the gateway before advertising,- and keeps re-probing. An agent that is not up yet, or has died, is simply- not discoverable; when it answers, it is. Readiness is observed, never- asserted.--The agent runs a stock A2A server on its contracted port and knows nothing-else. Its card can claim any address it likes — the mesh regenerates the-card at the consumer edge (interfaces rewritten to the mesh path, stale-signatures dropped), so nothing the agent writes in its own card escapes the-sandbox unverified.--**Implemented, including delivery into an isolated sandbox.** Reaching back in-cannot be done by dialling the agent: every sandbox has a network namespace of-its own, so the gateway's `127.0.0.1` is its own loopback and not the agent's.-That is true of all three profiles, because it follows from the isolation-rather than from any one runtime.--The way in is the way out. Egress crosses the boundary over a pathname Unix-socket, which network namespaces do not apply to because it is a filesystem-object. Ingress uses a second one: `nano-init --ingress-socket` serves it from-inside the sandbox, where it can reach the agent at the contracted port, and-`sam-box --agent-ingress-socket` dials it. The handshake is Firecracker's —-`CONNECT <port>`, then `OK` — so a microVM can offer the same protocol over-vsock without the gateway learning the difference.--`TestSandboxServesThroughTheReverseChannel` drives a real sandbox and asserts-both halves: that dialling the agent directly from outside fails, and that the-same agent answers through the channel. `TestAgentIngressCUJ` covers the-mesh-facing half with a stock A2A SDK on both ends: the card is regenerated at-the consumer, the message round-trips, and the agent has no serving surface to-ask anything of.--### 9.1.1 Why this is also the better UX--The runtime-announcement design this replaces argued that only the agent-knows *when* it is ready and *which port* it chose. Both turned out to be-better served without an API:--* **Readiness is the probe's job.** A declared-but-dead service is registered- yet withheld from discovery until its card answers. That closes the- advertise-before-listening window without a health-check protocol — and- without trusting the agent's claim, which the old design listed as an open- problem.-* **The port is part of the contract.** An agent that must be told nothing- can still be told one thing by its environment (every serverless platform- does exactly this); in exchange, port flapping and re-registration rate- limits stop being problems because re-registration does not exist.-* **Lifetime is tied to the sandbox, structurally.** The gateway's serving- listener closes when the sandbox goes; the probe fails; discovery- converges. Nothing unregisters because nothing registered.-* **Resume is still automatic.** The bundle travels with the agent (§8.4), so- `Attach` on another host renders the same contract: the new gateway routes- the same name, the new node declares the same service, and the probe- re-points discovery to the new peer. The property §8 exists to provide- survives — it never needed a runtime API, only a declaration that moves- with the agent.--### 9.2 The reverse channel--Inbound is the one place the datapath is not egress-shaped:--```text-remote peer → libp2p → sam-node → sam-box ingress endpoint- │- ▼ one stream per inbound request- sandbox boundary- │- nano-init accept loop- │- 127.0.0.1:<port> (the agent's listener)-```--So a sandbox has exactly two channels, one per direction:--| channel | direction | protocol | who listens |-|---|---|---|---|-| egress | guest → host | named HTTP tunnels (CONNECT, connect-udp) | host (`sam-box`) |-| ingress | host → guest | one stream per request (`CONNECT <port>`) | guest (`nano-init`) |--Firecracker's vsock is bidirectional, so host→guest needs no new transport: the-host connects to the firecracker UDS and writes `CONNECT <port>`, with the guest-listening on that vsock port. A container gets the symmetric arrangement with a-second bind-mounted socket. This is also what finally justifies `nano-init`-beyond PID 1 hygiene: it owns the guest side of the ingress channel.--### 9.3 Authorization closes the loop--Nothing new is needed. `sam-node` authorizes the **caller** — their node token-carrying their agent block (Decision 5) — before the stream ever reaches-`sam-box`. "Agent `foo` may call agent `bar`" is therefore one policy statement,-evaluated at `bar`'s node, with the existing machinery, and both ends are named-by portable identities rather than by hosts.--### 9.4 Migration--The serving contract is part of what travels (§8.4). On resume, `sam-box` on-node B routes the same contracted name, node B's configuration declares the-same service, and the probe re-points discovery to node B. The name is-stable because it belongs to the agent, not to the node — which is the whole-point of §8.--## 10. The platform integration interface--This is the seam a scheduler or harness connector builds against. It must be-small, versioned, and the only place identity enters the system.--### 10.1 The agent bundle--What the platform provides per agent. It lives in the agent's state directory, so-it migrates with the agent by construction:--```yaml-version: v1-agent:- id: reviewer-7.prod.acme.example # canonical mesh identifier (§8.8)- external_id: spiffe://acme.example/prod/reviewer-7 # verbatim, for audit- credential: /var/run/secrets/substrate/token # the platform's own workload- # credential, verified at- # admission (§8.5)-egress:- allow: ["api.github.com", "*.pypi.org"]- secrets:- "api.github.com": {kind: bearer, value_from: /etc/sam/secrets/github}-serves:- name: code-reviewer # the agent's A2A name; routed to its contracted port- port: 8080-```--### 10.2 Operations--Exposed by `sam-box` on a control socket that is **not** reachable from inside-the sandbox:--| operation | meaning |-|---|---|-| `Attach(bundle)` | admit an agent; returns the egress and ingress endpoints to wire into the sandbox |-| `Detach(agent_id)` | stop it: close the serving listener and channels, drop credentials |-| `Refresh(agent_id, credential)` | hand in a rotated workload credential (§8.3) |-| `Status(agent_id)` | what is routed and connected, for the scheduler's reconcile loop |--### 10.3 Guarantees the interface owes a connector--1. **`Attach` is idempotent, keyed by agent id.** Resume after a crash or a- migration is just another `Attach` — no special-case path.-2. **Identity never arrives in-band from the sandbox.** The platform is the sole- identity source (§8.5).-3. **The agent id is stable across `Attach` on different hosts.** This is what- makes migration invisible to the rest of the mesh.-4. **`Detach` is complete.** No residual advertisement; discovery converges.-5. **Versioned.** `version: v1`, and the schema lives in `api/`, so it is a real- contract and not a convention.--### 10.4 The first connector: Agent Substrate--[Agent Substrate](https://github.com/agent-substrate/substrate) is the-integration target, and it lines up unusually well:--| Substrate | SAM |-|---|---|-| **Actor** (the agent) | the principal: `agent:<actor>.<atespace>.<cluster domain>` |-| **Atespace** (namespace) | the hierarchy label policy wildcards on |-| routing by Host `my-counter-1.demo.actors.resources.substrate.ate.dev` | already dot-separated and most-specific-first — the same shape as §8.8 |-| `podcertcontroller` (KEP-4317 pod certificates), projected SA tokens | the workload credential `sam-box` verifies at admission (§8.5) |-| `atelet` per-node DaemonSet; `ateom-gvisor` / `ateom-microvm` | where `sam-box` attaches: one sandbox, two channels |-| suspend/resume with full-state snapshot (RAM + filesystem) | carries the agent bundle with no extra work (§8.4) |-| `atenet` (DNS, Envoy routing, proxy sidecars, CONNECT) | the seam to negotiate: who owns egress |--The name mapping is a pure string translation with no capability loss, which is-the §8.8 test: the Host `my-counter-1.demo.actors.resources.substrate.ate.dev`-becomes `agent:my-counter-1.demo.actors.resources.substrate.ate.dev`, and-`agent:*.demo.actors.resources.substrate.ate.dev` means "every actor in atespace-`demo`" — injective, hierarchy-preserving, reversible.--Two things to settle **with** the Substrate side rather than assume:--* **Egress ownership.** `atenet` already supplies DNS, routing, proxy sidecars- and CONNECT. The named-tunnel boundary has to slot in as the sandbox's egress- rather than compete with it — speaking CONNECT is what makes that a fit- rather than a translation. `sam-box` behind atenet's sidecar seam is the- likely arrangement, but that is a conversation, not a decision to take- unilaterally.-* **Ingress.** Substrate already routes inbound to actors by Host header. §9- must reuse that path rather than build a parallel one: a SAM ingress- declaration should end up as a Substrate route.--### 10.5 Still to settle--* **Wire format — decided.** Proto in `api/sam.proto` for the operations- (`AgentAttach`/`AgentDetach`/`AgentRefresh`/`AgentStatus` request and response- messages), YAML for the bundle. Substrate is Go, so proto costs its connector- nothing; the bundle stays YAML because its canonical copy is a file in the- agent's state directory, where it has to be readable and diffable by whoever- operates the platform. `AgentBundle` in the proto is the transport mirror of- that file, not a second source of truth.-* **Bulk pre-creation is deliberately not in v1** — premature until the semantics- are proven. What v1 owes it is *room*: `Attach` takes a bundle and is- idempotent per agent id, so `AttachBatch` is a purely additive operation- later, and the offline attenuation in §8.3 already makes it possible with no- protocol change.--## 11. Remaining smaller open items--1. **UDP — shipped.** Carried as connect-udp (RFC 9298) with capsules on the- same one-socket boundary, under the same name-based deny-by-default policy.- DNS never leaves the guest either way: port 53 is answered by the virtual- DNS, and everything else is a named, policy-checked session.-2. **Guest trust of the ephemeral CA.** Baked into the sandbox image at build- time, or re-introduce a bootstrap endpoint? v1 avoids the question by keeping- mesh names on `http://` (§5.2).-3. **Peer-pinned mesh names.** Deferred until a DNS-safe peer encoding is chosen- (Decision 4).diff --git a/site/content/docs/concepts/_index.md b/site/content/docs/concepts/_index.mdnew file mode 100644index 00000000..84739f83--- /dev/null+++ b/site/content/docs/concepts/_index.md@@ -0,0 +1,9 @@+---+title: "Concepts"+linkTitle: "Concepts"+weight: 2+---++How SAM works, in enough depth to reason about a deployment. Read+[Architecture](architecture/) first. The other pages each take one part of+it further.diff --git a/site/content/docs/concepts/architecture.md b/site/content/docs/concepts/architecture.mdnew file mode 100644index 00000000..d7415846--- /dev/null+++ b/site/content/docs/concepts/architecture.md@@ -0,0 +1,157 @@+---+title: "Architecture"+linkTitle: "Architecture"+weight: 1+---++An agent mesh has a small control plane, one or more routers, and any number+of nodes. The control plane decides who is in the mesh and what they may do.+Routers make the nodes reachable. Nodes do the work: they publish services+and call each other's services on behalf of the agents next to them.++```mermaid+flowchart LR+ subgraph cp["control plane"]+ CP["sam-control-plane<br/>identity · policy · signing key"]+ DB[("database")]+ CP --- DB+ end+ IDP["identity provider<br/>(OIDC)"]+ R["sam-router<br/>bootstrap · relay · DHT"]+ A["sam-node A"]+ B["sam-node B"]+ AG["agent"]+ SVC["your tool or model"]++ CP -. verifies tokens .-> IDP+ R -- lease --> CP+ A -- enroll / refresh --> CP+ B -- enroll / refresh --> CP+ A <--> R+ B <--> R+ A <-. direct when possible .-> B+ AG -- "MCP · OpenAI API<br/>(local)" --> A+ B --- SVC+```++## The control plane++`sam-control-plane` is an HTTP service backed by SQLite or PostgreSQL. It is+the only component that has to be trusted. It is not on the data path: tool+calls and model requests never pass through it.++It has four jobs:++- **Admitting nodes.** A node presents an OpenID Connect token from the+ configured identity provider, or a bootstrap token minted by an operator,+ together with proof that it holds the private key it is registering.+- **Issuing credentials.** For each admitted node, the control plane mints a+ [Biscuit](https://www.biscuitsec.org/): a signed token that carries the+ node's peer ID, its roles, the identity facts from the login (user, email,+ groups), the labels it was allowed to declare, and the grants its roles+ give it. Nodes verify these tokens offline with the control plane's public+ key.+- **Holding the mesh policy.** Roles and bindings are edited through the+ admin API or the console, and nodes read them on a schedule.+- **Tracking routers.** Routers hold short leases. A new node fetches the+ list of live routers from `/info` before it connects to anything.++The control plane also rotates its signing key, keeps a ban list, and serves+the public keys that nodes need to verify their peers. [Identity](../identity/)+covers all of that.++## Routers++`sam-router` is a libp2p peer with a stable address. It runs the mesh's+Kademlia DHT (a distributed hash table), where nodes advertise their services+and look up who provides what. It also relays traffic for nodes that cannot+accept inbound+connections. A router has no policy of its own. It verifies every peer's+credential and refuses peers it cannot verify and peers that have been+banned.++Routers keep no state apart from their key file, which fixes their peer ID.+You can run any number of them. Nodes learn about them from the control plane+and connect to the ones that answer.++## Nodes++`sam-node` runs as one process per host or per pod, next to the service it+serves or the agent that uses it. On the mesh side it is a libp2p peer with+its own Ed25519 key. Its peer ID is derived from that key, and every other+component refers to the node by that ID.++Towards the mesh, a node:++- publishes the services declared in its configuration file (MCP servers,+ OpenAI-compatible inference backends, A2A agents) to the DHT and, on+ request, to the control plane's catalog+- accepts connections from other nodes, verifies their credential, evaluates+ policy for the requested service, and proxies the request to the local+ backend if the check passes+- verifies the credential of every node it calls, so that a caller can+ require properties of a provider (its labels, for example) before sending+ any data++Towards the agent, a node exposes a local API on `127.0.0.1:8080` by default+and on a Unix socket. The API includes an MCP server whose tools discover and+call services across the mesh, an OpenAI-compatible `/v1` endpoint that+routes model requests to inference providers on the mesh, and a proxy path+`/sam/<peer-id>/<type>/<name>/` that reaches a specific service directly.+[Networking](../networking/) describes the API and how traffic moves.++## Names instead of addresses++A service is identified by type and name: `mcp://code-reviewer`,+`inference://vllm-eu`, `a2a://triage`. Policy grants are written against+these names, discovery returns them, and the node that hosts a service+decides whether a caller may use it. IP addresses do not appear in policy.+Because of this, a node can move between networks or sit behind NAT without+any rule changing.++## Where decisions are made++| Decision | Made by | Based on |+|---|---|---|+| May this identity join, with this role and these labels? | control plane, at enrollment | OIDC token or bootstrap token, mesh policy bindings, `allowed_labels` |+| Is this peer's credential genuine and current? | every node and router, on every connection | control plane public keys, expiration, ban list |+| May this caller use this service? | the node hosting the service | grants in the caller's credential, the synced mesh policy, the host's own local rules |+| Is this provider acceptable to me? | the calling node, before sending data | the provider's credential and attested labels |++Every one of these decisions is deny by default. A new control plane with+no policy admits nodes but grants them nothing, and a node with no services+configured publishes nothing. [Authorization](../authorization/) explains+the policy model.++## Trust boundaries++The control plane is the trust root. Whoever controls it controls who is in+the mesh and what the policy says. A node refuses to fetch its trust root+over plaintext from a remote address, so a control plane URL must use+`https://` unless the control plane runs on the same host.++Routers see connection metadata and relay encrypted streams. They cannot+read relayed traffic and cannot mint credentials. A compromised router can+deny service but cannot grant access.++Nodes trust each other only as far as a verified credential says. The node+that hosts a service has the final say over who calls it, even beyond what+the control plane granted: its local configuration can add conditions that+the caller's credential must also satisfy.++## Packaging++The same three programs ship in several forms:++- **Binaries** for Linux, macOS and Windows, from the releases page or the+ install script.+- **Container images**: `ghcr.io/google/sam-control-plane`,+ `sam-router`, `sam-node`, `sam-console` and `sam-one`.+- **`sam-one`**, a single binary that runs the control plane, a router and+ the console in one process on one port, for laptops, Cloud Run and small+ meshes.+- **Helm charts**: `sam-mesh` deploys the control plane, router, console and+ PostgreSQL. `sam-node` deploys a node beside a service container.++The web console (`sam-console`) is a separate program that talks to the+control plane's admin API. It is not required to run a mesh.diff --git a/site/content/docs/concepts/authorization.md b/site/content/docs/concepts/authorization.mdnew file mode 100644index 00000000..3094f740--- /dev/null+++ b/site/content/docs/concepts/authorization.md@@ -0,0 +1,212 @@+---+title: "Authorization"+linkTitle: "Authorization"+weight: 3+---++Authorization in SAM answers one question: may this caller use this service+on this node? Three sources contribute to the answer, and the node that hosts+the service combines them: the caller's credential, the mesh policy, and the+node's own configuration. Each source can only narrow what the others allow.+If none of them grants access, the answer is no.++## Services are the unit of authorization++A node publishes services, each with a type and a name: `mcp://calculator`,+`inference://vllm-eu`, `a2a://triage`, and the built-in+`system://sam.catalog` that answers discovery queries. Policy grants access+to services by these names. It does not look inside a service: a grant on+`mcp://db` offers every tool that the MCP server exposes. To offer different+privilege levels, publish different services (`mcp://db-reader`,+`mcp://db-writer`) and grant them separately. Choosing which tools a backend+exposes is the job of the backend, or of a small MCP server placed in front+of it.++## Mesh policy: roles and bindings++The mesh policy is a document held by the control plane. You edit it through+`POST /policies` or the console. `sam-one` can also seed it on first boot+from a file (`--policy-file`). The document has two lists.++**Roles** name a set of permissions:++```json+{+ "name": "developer",+ "allowed_services": ["mcp://code-reviewer", "mcp://build-runner.*", "inference://*"],+ "allowed_targets": ["group:dev-nodes"],+ "allowed_labels": ["region=*"],+ "allowed_agents": [],+ "custom_datalog": []+}+```++- `allowed_services`: the services holders may call, as `type://name`. `*`+ can stand for the whole name, for a leading component (`mcp://*.internal`)+ or for a trailing one (`mcp://build-runner.*`). A bare `*` means every+ service.+- `allowed_targets`: the nodes holders may call, as facts about the+ destination node's identity: `node:<peer-id>`, `user:<sub>`,+ `email:<addr>`, `group:<name>`, `idp_role:<name>`, or `*`. If absent, any+ node may be called.+- `allowed_labels`: the labels a node with this role may declare at+ enrollment: `key=value`, `key=*` or `*`. If absent, the node may declare+ no labels.+- `allowed_agents`: the agent identifiers a node with this role may claim to+ act for. Only used by the sandboxed-agent+ [preview](../../preview/sandboxed-agents/).+- `custom_datalog`: extra Datalog facts or rules for holders of the role.++**Bindings** attach roles to identities:++```json+{ "role": "developer", "members": ["group:eng", "email:[email protected]"] }+```++A member is one of: `user:`, `email:`, `group:` or `idp_role:` followed by a+value from the identity's OIDC claims; `node:` followed by a peer ID; or the+special value `sam:system:authenticated`, which matches every identity that+the identity provider authenticates. Be careful with the last one. On a+public identity provider it means everyone, so bind it only to roles with+few grants.++Roles are never members and never claims. `role:x` is not a valid member,+and an identity provider cannot give out a mesh role by putting it in a+`roles` claim. Such a claim becomes an `idp_role` fact, and a binding can+choose to honour it. The three built-in roles, `sam:role:node`,+`sam:role:router` and `sam:role:sambox`, follow the same rule: a binary can+only enroll if a binding gives its identity the role it needs.++The control plane validates a policy when it is posted. It rejects a policy+that references an undefined role, uses an unknown member prefix, or would+give a single identity more grants than the Biscuit authorizer can+evaluate.++## From policy to facts++At enrollment and at every refresh, the control plane resolves the identity's+roles from the bindings and writes the result into the credential as Datalog+facts: one `role(...)` fact per role, plus the grants compiled from the+lists of every role. For example, `allowed_services: ["mcp://calculator"]`+becomes `granted_service_exact("mcp", "calculator")`, `mcp://*` becomes+`granted_service_all("mcp")`, and `mcp://*.internal` becomes+`granted_service_suffix("mcp", ".internal")`. Wildcards keep their dot, so+`*.acme.example` matches `svc.acme.example` but not `evil-acme.example`.++Nodes also fetch the policy themselves, every `--policy-sync-interval` (one+hour by default), and compile it into rules such as+`role("developer") <- group("eng")` and+`granted_service_exact("mcp", "calculator") <- role("developer")`. When a+node verifies a credential, these rules run against the identity facts in it.+A grant added to the policy therefore reaches every node within the sync+interval, with no need to reissue credentials. Removing a grant takes effect+through the credential instead: the facts already in a token stay valid until+the token is refreshed, which happens within its TTL (24 hours by default).++## What the hosting node checks++When a request for service `S` arrives from peer `P`, the node builds a+Biscuit authorizer and adds the following, in this order:++1. **The request**: `service("mcp", "calculator")` for the requested+ service, and `connection_peer_id(P)` from the authenticated connection.+ If the caller named an agent, the agent claim is added together with the+ check that the caller's own token grants that agent namespace.+2. **The baseline checks**: `client_peer_id($id), connection_peer_id($id)`+ (the token belongs to the peer that presents it), and the expiration+ check against the current time.+3. **The node's own identity facts**, taken from its own credential, as+ `target_fact("group", "dev-nodes")` and similar. The caller's+ `allowed_targets` are matched against these facts. The destination node+ proves that it is an intended target; the origin node does not check its+ own traffic.+4. **The node's local rules**, from the `attenuation` block of its+ configuration file: extra facts, extra checks, and `allow` and `deny`+ policies.+5. **The baseline policies**: `allow if service($t,$n), granted_service_exact($t,$n)`+ and the equivalent policies for sets, prefixes, suffixes, per-type and+ global wildcards, plus the target check+ `allow_network_target(...) or target_unrestricted()`.+6. **The synced mesh policy rules** described above.++Biscuit evaluates every `check` and requires all of them to pass. It then+walks the policies in order and applies the first `allow` or `deny` that+matches. As a result, a failing check denies the request regardless of any+policy. A local `deny` placed before the baseline `allow` overrides a grant.+A local `allow` can admit a caller that the policy did not grant, but it can+never admit a caller that fails a check.++Before any of this, the connection itself is gated. A peer on the ban list is+dropped at the transport layer, and a peer whose credential does not verify+under a trusted signing key cannot name a service at all.++## Local rules++The `attenuation` block in `sam-node.yaml` gives the hosting node the final+say. Use it for constraints that the operator of that node wants regardless+of what the mesh policy grants:++```yaml+attenuation:+ rules:+ - 'maintenance() <- time($t), $t > 2026-12-31T00:00:00Z;'+ checks:+ - 'check if label("jurisdiction", "eu");' # every caller must carry this label+ policies:+ - 'deny if service("mcp", "db-writer"), group("contractors");'+ - 'deny if maintenance();'+```++`rules` derive new facts, `checks` must all hold, and `policies` are+evaluated before the baseline policies. A syntax error in any of them stops+the node at start, so a broken rule cannot weaken the node without notice.+The mobile app has the same block, with the same syntax, in its settings.++## Labels++Labels are `key=value` pairs. A node declares them in its configuration, and+the control plane writes them into the node's credential as `label(k, v)`+facts, one per label, if a role the node holds allows them. Labels let+policy describe where a node is or what it is for. SAM does not define a+fixed set of keys: `region`, `jurisdiction`, `team`, `compliance`, or+whatever the operator needs.++Labels are used in three places:++- **A provider restricting callers** adds `check if label("region", "eu")`+ to its `attenuation.checks`. Every caller's credential must then carry+ that label.+- **A caller choosing providers** sends `X-Sam-Required-Labels: region=eu`+ on the node's `/v1` inference endpoints or on a proxied A2A request, or+ passes `required_labels` to `call_remote_tool`. Before it sends any request+ data, the calling node fetches the provider's credential through the+ mutual handshake, verifies it, and confirms that the label facts are+ present. A provider that cannot show them is skipped.+- **An operator drawing a boundary** sets `egress.require_labels` in the+ node configuration. Every provider this node talks to must attest all of+ those labels, whether or not the caller asked for any. The caller can add+ further requirements but cannot remove the operator's.++The header and the operator floor have different matching rules, and the+difference follows from their purpose. The header is any-of: the caller is+choosing among acceptable providers. The floor is all-of: the operator is+drawing a line. Labels seen in discovery results are only used to rank+candidates. The only labels that authorize anything are the signed ones in a+credential.++## Agents acting through a node++A node may forward requests on behalf of a sandboxed agent and name that+agent to the destination. The name travels next to the token, not inside it.+The destination accepts the name only if the calling node's credential+grants that agent namespace through `allowed_agents`. A node with no such+grant cannot name any agent. This is attribution, not proof, and that is why+the namespace belongs to the node's role and not to the agent. The+[sandboxed agents preview](../../preview/sandboxed-agents/) has the details.++## See also++- [Policy reference](../../reference/policy/): every field, pattern and fact+ name.+- [Node configuration reference](../../reference/node-config/): the+ `attenuation`, `labels` and `egress` blocks.diff --git a/site/content/docs/concepts/boundaries.md b/site/content/docs/concepts/boundaries.mdnew file mode 100644index 00000000..75a66cf3--- /dev/null+++ b/site/content/docs/concepts/boundaries.md@@ -0,0 +1,111 @@+---+title: "Control and data boundaries"+linkTitle: "Boundaries"+weight: 5+aliases:+ - /docs/sovereignty/+---++When you run your own control plane, you decide everything about the mesh.+On the public testnets, someone else decides who joins and what the policy+says. This page lists the decisions that become yours in a dedicated+deployment and the mechanism that enforces each of them.++## What you control in a dedicated deployment++- **Membership.** Enrollment goes through your identity provider or through+ bootstrap tokens that you mint. The bindings in the control plane decide+ which identities receive which roles. An identity without a binding cannot+ enroll a node.+- **The signing key.** The control plane generates its Ed25519 signing keys+ and stores them in its database. Every credential in the mesh is signed by+ one of these keys, and nobody outside the deployment can mint or extend a+ credential. The keys rotate on the schedule you set.+- **The policy.** What each role may call, on which nodes and with which+ labels, is stored in your database. It can only be changed with your admin+ token or through your console.+- **Revocation.** A ban takes effect on the next credential refresh (within+ the credential TTL, 24 hours by default) and, through the mesh event+ channel, immediately on every connected node.+- **Where the software runs.** SAM is Apache-2.0, sends no telemetry, and+ does not depend on any hosted service. The control plane, routers and+ nodes run wherever you put them: a laptop, a private cluster, an+ air-gapped network.++The public testnets give you none of this. They are useful for trying the+software. Do not put anything there that you would not publish.++## Where data goes++The control plane is not on the data path. A request from an agent goes from+its node to the provider's node over an encrypted libp2p stream. The stream+is relayed through a router only when the two nodes cannot connect directly,+and the relay sees only ciphertext. No part of a request, its arguments or+its result is recorded centrally.++Routers are on the path, so place them with care. If the nodes in a region+use a router in that region, relayed traffic between them stays in the+region.++## Keeping data inside a boundary++Labels are how a deployment expresses facts such as "this node is in the EU"+or "this node handles HIPAA data". A node declares its labels, the control+plane attests only the labels that the node's role permits, and the labels+become signed facts in the node's credential. Three mechanisms can then hold+a boundary:++- **A provider refuses callers from outside the boundary.**+ `check if label("jurisdiction", "eu")` in the provider node's+ `attenuation.checks` rejects any caller whose credential lacks that fact,+ regardless of what the mesh policy granted.+- **A caller refuses providers outside the boundary.** With+ `X-Sam-Required-Labels` on a request, the calling node verifies the+ provider's credential before it sends anything. A provider that cannot+ show the label is skipped.+- **An operator sets a floor for a whole node.** `egress.require_labels` in+ the node configuration applies to every outbound request from that node.+ Callers cannot lower it.++All three mechanisms act on signed facts, not on discovery data, and all+three fail closed. A provider whose credential cannot be fetched or verified+is treated as if it did not have the label.++## The host has the final say++The node that publishes a service decides who calls it. The mesh policy+grants access. The node's `attenuation` block can add checks that the caller+must also satisfy, and `deny` rules that override a grant. This is+intentional. The central policy states what the operator of the mesh+intends. The operator of the machine that holds the data can always refuse.++## Evidence++Two endpoints on the node's local API expose what the node knows, for audit+or automation. They are reachable only over the node's Unix socket or over+mTLS.++- `GET /sam/identity` returns the node's own credential, the control plane+ public key it was verified against, and its roles, labels and expiry.+- `GET /sam/peer/{peer-id}/evidence` returns the same information for a peer+ that the node has authenticated.++Both results can be verified offline with the control plane's public key.++## Why credentials expire++A credential lasts 24 hours by default and is renewed in the background.+Short lifetimes make revocation work without a central check on every+request. A stolen credential is useful for at most its remaining lifetime. A+banned node cannot renew. A node that has been offline for longer than the+signing key's grace period has to come back through enrollment instead of+reappearing without notice. The lifetime, the session length, the rotation+interval and the grace period are all control plane flags that the operator+sets.++## See also++- [Identity](../identity/) for enrollment, refresh, rotation and revocation.+- [Authorization](../authorization/) for labels and local rules in detail.+- [Kubernetes](../../guides/kubernetes/) and [your own mesh](../../getting-started/your-own-mesh/)+ for deploying a control plane.diff --git a/site/content/docs/concepts/identity.md b/site/content/docs/concepts/identity.mdnew file mode 100644index 00000000..1b9a6c6d--- /dev/null+++ b/site/content/docs/concepts/identity.md@@ -0,0 +1,185 @@+---+title: "Identity and enrollment"+linkTitle: "Identity"+weight: 2+---++Every participant in a mesh, node or router, has a key that it generated+itself and a credential that the control plane issued for that key. This page+follows the credential from enrollment to expiry: how a node gets it, what it+contains, how it is renewed, and how it is revoked.++## Keys and peer IDs++The first thing a node does is generate an Ed25519 key pair and store it in+its data directory (`~/.config/sam-mesh/agent.db` by default). Its **peer+ID**, the `12D3KooW...` string that appears in logs, discovery results and+proxy URLs, is derived from the public key. The key never leaves the machine.+The credential is bound to the key, so a copied credential is useless without+it, and every peer-to-peer connection proves possession of the key as part+of the libp2p handshake.++`sam-node reset --all` deletes the key and gives the node a new peer ID.+`sam-node reset` without `--all` keeps the key and deletes only the+credential.++## Enrollment++Enrollment is a request to the control plane: "here is my public key, here is+who I am, please issue me a credential for role *X* with labels *Y*". There+are three ways to say who you are.++**Interactive OIDC login.** `sam-node join <control-plane-url>` fetches the+control plane's `/info`, learns which identity provider it trusts, and runs an+OpenID Connect login. If a browser is available, it uses the loopback flow.+On a headless machine it uses the device flow (a URL and a code that you enter+on another device), or falls back to pasting a code. `--auth-mode` selects+one of these explicitly. The ID token from the login is sent to+`POST /register` together with the public key and a signature over a fresh+challenge. This is how a person enrolls a laptop.++**Non-interactive OIDC.** A workload that already has an OIDC token does not+need a login. `sam-node run --jwt-path <file>` enrolls with the token in that+file. On Kubernetes this is a projected service account token with the+audience the control plane expects. `--client-id` and `--client-secret-path`+do the same with an OAuth client-credentials grant. Routers enroll in the+same way with `sam-router --jwt-path`.++**Bootstrap token.** An operator mints a token with the admin API, the+console, or `sam-one token create`, and copies it to the machine. The node+sends it to `POST /enroll`. Unless the control plane runs with+`--auto-approve-enrollment`, the request waits in a queue until an+administrator approves it, and the node polls `GET /enroll/status` while it+waits. A token has a role, an expiry and a usage count. A single-use token is+spent as soon as one node is approved with it. This is how machines without+an identity of their own enroll, and how `sam-one` enrolls devices by QR+code.++For all three paths, the control plane checks the same things before it+mints a credential:++1. The peer ID matches the submitted public key, and the challenge signature+ verifies under that key. This proves that the requester holds the key it+ is registering.+2. Neither the peer ID nor the identity behind it is banned.+3. The identity resolves, through the bindings in the mesh policy, to the+ role being requested. `sam-node` requests `sam:role:node`, `sam-router`+ requests `sam:role:router`, and `sam-box` requests `sam:role:sambox`. If+ the policy binds nobody to `sam:role:node`, no node can enroll.+4. Every label the node declared is permitted by the `allowed_labels` of a+ role it holds. A role without `allowed_labels` permits no labels.++The node stores the credential, the control plane's public key, the control+plane URL and the router addresses it received. From then on it is a member+of that mesh only. If you point it at a different control plane later, it+refuses until you reset it, because a credential is only valid for the mesh+that issued it.++## The credential++The credential is a [Biscuit](https://www.biscuitsec.org/), a signed+authorization token. Its authority block holds facts written in Datalog, a+small logic language in which a fact looks like `role("sam:role:node")`. The+block is signed by the control plane's Ed25519 key. Any node with the public+key can verify it without contacting anyone. The block contains:++| Fact | Meaning |+|---|---|+| `node("12D3KooW...")`, `client_peer_id("12D3KooW...")` | The peer ID the token belongs to. Every verifier checks that the connection it arrived on was authenticated as this peer. |+| `expiration(<time>)` | When the token stops being valid. |+| `role("sam:role:node")`, `role("developer")` | The roles the identity resolved to, one fact each. |+| `user("...")`, `email("...")`, `group("...")`, `idp_role("...")` | Claims copied from the OIDC token: subject, verified email, each group, each entry of the issuer's `roles` claim. Absent for bootstrap enrollments. |+| `label("region", "eu")` | One fact per declared and permitted label. |+| `granted_service_*`, `granted_target_*`, `granted_agent_*` | What the roles allow, compiled from `allowed_services`, `allowed_targets` and `allowed_agents`. [Authorization](../authorization/) describes them. |++The node does not set any of these facts. Roles come from the bindings in+the mesh policy, not from the identity provider: an issuer's `roles` claim+is stored as `idp_role()`, which grants nothing by itself. Labels are the+ones the node asked for and the policy allowed. Grants come from the policy.++Tokens carry no appended blocks. Biscuit lets a holder attenuate a token by+appending blocks, but SAM verifiers reject any token that has one. A request+that needs to carry an extra claim (for example, which agent a node is acting+for) sends it next to the token instead.++## Lifetime and refresh++A credential is valid for `--biscuit-ttl`, 24 hours by default. If the OIDC+token expires sooner, the credential expires with it. Nodes and routers check+every ten minutes, and when less than a fifth of the lifetime remains they+call `POST /refresh` with the current token and a signature over a fresh+challenge. The control plane verifies both, resolves the identity's roles+against the current policy again, and mints a new token with the same+identity facts and labels.++Refresh is limited by the **session**, which is a record on the control+plane, not a field in the token. The session of an OIDC enrollment lasts+`--oidc-session-ttl`, 90 days by default. After that, the node has to log in+again. A bootstrap enrollment has no session expiry. A ban also acts on the+session record.++A node that enrolled interactively with `--offline-access` also keeps an OIDC+refresh token. If its credential expires completely, it uses the refresh+token to obtain a new ID token and re-enrolls under the same peer ID without+any user action.++## Signing keys and rotation++The control plane rotates its signing key every `--key-rotation-interval`+(24 hours by default). The previous key stays valid for `--key-grace-period`+(1 hour by default) and is then retired. `GET /keys` returns the current set+of keys, signed by each key in the set. Routers poll it every+`--keys-sync-interval`. Nodes fetch it at start and when they receive a+rotation event. Both accept a new set only if one of its signatures verifies+under a key they already trust. The first key comes from enrollment, and+each later key is vouched for by the key it replaces.++Nobody can verify a credential signed by a retired key, including the+control plane. A node that was offline for a whole grace period therefore+cannot refresh. This is intentional. The grace period is the deadline after+which a machine that went quiet cannot come back unnoticed. How it comes back+depends on how it enrolled:++- An OIDC node with a refresh token re-enrolls on its own.+- A bootstrap node needs an operator to mint a new token and run+ `sam-node join` again (or to restart the router with the new token). The+ node keeps its peer ID. The control plane recognises the approved peer and+ mints a new credential without going through the approval queue.+- A bootstrap node whose record has `autonomous_recovery` set may refresh on+ proof of possession of its key alone. This is off by default, and an+ administrator sets it per token or per node. A node that can always+ recover holds a credential that never expires, and only a ban stops it.++## Revocation++`POST /admin/revoke` with a peer ID (or `sam-one admin ban`, or the console)+marks the node as banned. Its next refresh is refused and the node daemon+exits. The control plane publishes the peer ID in `/info`, which routers and+nodes read, so peers stop accepting connections from it before its current+token expires. If the node was enrolled through OIDC, the identity behind it+(`issuer|subject`) is banned too. It can no longer register a new key, and+bootstrap tokens it minted stop working. `POST /admin/nodes/{peer_id}/unban`+reverses both bans.++A bootstrap token can be revoked before it expires with+`DELETE /admin/bootstrap-tokens/{id}`. The token stays in the list, marked+as revoked, so the record of what it enrolled is kept.++## What a node proves on every connection++The control plane's HTTP API is protected by challenge signatures, because a+peer ID in a request body is otherwise only a claim. On the mesh, the libp2p+secure channel already proves which key is on the other end, so the handshake+between two nodes is simpler. Each side sends its credential. Each side+verifies the other's signature and expiry, checks that the credential's+`node()` fact matches the authenticated peer, and checks the ban list. Only+then is the requested service name evaluated against policy. Routers perform+the same handshake on every connection they accept, so a banned or unenrolled+peer cannot reach the DHT.++## See also++- [Headless enrollment](../../guides/headless-enrollment/) for the bootstrap+ token workflow step by step.+- [Control plane reference](../../reference/control-plane/) for the flags+ and HTTP routes named here.diff --git a/site/content/docs/concepts/networking.md b/site/content/docs/concepts/networking.mdnew file mode 100644index 00000000..9a8097b5--- /dev/null+++ b/site/content/docs/concepts/networking.md@@ -0,0 +1,138 @@+---+title: "Networking and the node API"+linkTitle: "Networking"+weight: 4+---++This page follows a request from an agent to a service on another node:+how the calling node finds the provider, how the two connect, and what the+agent sees at each end.++## The node's local API++An agent does not speak to the mesh directly. It speaks to the `sam-node` on+its own machine, through one of two listeners:++- **TCP**, `127.0.0.1:8080` by default (`--bind-addr`). Every request must+ carry the node's API token as `X-Sam-Authentication: Bearer <token>`.+- **A Unix socket**, `<data-dir>/sam.sock` by default (`--socket-path`),+ created with mode `0600`. No token is needed, because only the user who+ owns the socket can open it. `docker.sock` works the same way.++You can turn either listener off by passing an empty value. With+`--bind-addr=`, the node has no listening port and no secret to manage. This+is a good setup when everything that uses the node runs as the same user.++The token travels in `X-Sam-Authentication` and not in `Authorization`, so+that `Authorization` always means the same thing: the credential for the+service that is being called through the node. On the proxy path that header+is forwarded unchanged. The endpoints that never forward anything (`/mcp`,+`/v1/*`, `/sam/service/*`) also accept the token in `Authorization`, for+clients that cannot set a custom header.++The API has four parts:++| Path | What it is |+|---|---|+| `/mcp` | An MCP server (Streamable HTTP). Its tools are the mesh operations: list and discover services, find and describe tools, call a tool on a peer. |+| `/v1/models`, `/v1/chat/completions`, `/v1/completions` | An OpenAI-compatible endpoint. `/v1/models` lists every model that a reachable `inference://` provider serves. A completion request is routed to a provider that serves the requested model. |+| `/sam/<peer-id>/<type>/<name>/<path>` | A reverse proxy to one specific service on one specific node, for every service type. `<type>` is `mcp`, `inference` or `a2a`, and `<path>` is passed through to the backend. This is how a caller reaches an A2A agent: `/sam/<peer-id>/a2a/<name>/` serves the agent's card, rewritten for the mesh, and its JSON-RPC endpoint. |+| `/sam/service/discover` | Service discovery over plain HTTP, with the same results as the `discover_remote_services` tool. |++The [node API reference](../../reference/node-api/) lists every route.++## Discovery++A node that publishes a service does two things. It records itself in the+Kademlia DHT, hosted by the routers, as a provider of that service name. It+also announces the service over GossipSub to nodes that have asked about that+name. A node that looks for a service asks the DHT for providers, and for+names it asked about before it already has the gossip announcements.++Before a node advertises a backend, it probes the backend+(`--backend-probe-timeout`, 2 seconds by default). A backend that does not+answer is not advertised, so `discover_remote_services` does not list+services that would fail on the first call.++Discovery results are hints. They tell the caller who claims to provide a+service and, if the provider declared labels, what those labels are. Nothing+is authorized on that basis. The provider's credential is verified when the+connection is made.++Every node also runs the built-in `system://sam.catalog` service, which+answers the question "what do you host?" for callers whose credential grants+it. `find_remote_tools` uses it to list a peer's tools.++## Connecting++Nodes are libp2p peers. By default a node listens on QUIC (`udp/5001`) and+TCP (`tcp/5002`) and advertises the addresses it has, including private+ones unless you pass `--announce-private=false`. Two nodes that can reach+each other connect directly. When neither can accept an inbound connection,+which is the common case, they use a **relay circuit** through a router.+Hole punching is enabled, so a relayed connection is upgraded to a direct+one when the NATs allow it.++Routers are the fixed points. A node learns their addresses from the control+plane's `/info` at enrollment and fetches them again when its connections+drop. A router accepts a connection only from a peer that presents a valid+credential, so the DHT and the relay are closed to anyone who is not+enrolled.++When a node opens a stream to another node for a service request, the first+message is an authentication frame with the caller's credential and the+service it wants. The receiver verifies the credential, evaluates policy for+that service (see [Authorization](../authorization/)), and answers with its+own credential. Both sides now know who the other is. The caller can check+what it needs to know about the provider, for example its labels, before it+sends any request data.++## What travels where++Every hop between two nodes is encrypted by libp2p's TLS 1.3 secure channel.+TLS is the only security transport enabled, so that FIPS-validated+cryptography can be used end to end. A relay forwards ciphertext and learns+only that the two peers are talking. The control plane sees enrollments,+refreshes, router leases, policy fetches and catalog reports. It never sees a+request.++Traffic to the control plane is protobuf over HTTPS. Traffic between nodes is+HTTP over libp2p streams for service requests, and protobuf frames for the+authentication handshake, the DHT and gossip.++## Inference routing++`inference://` services are OpenAI-compatible HTTP backends: vLLM, Ollama,+LiteLLM, or a hosted API behind a local proxy. The node's `/v1` endpoint+hides which node serves a model. It keeps a short-lived view of the model+list of every reachable provider. It prefers a local provider when one+serves the model, and otherwise picks among remote providers, ranked by the+labels it knows about and by load. Backends are registered by their root URL+and the node adds the `/v1` prefix. The same backend is therefore reachable+through the `/v1` endpoint and, with `/v1/...` appended, through the proxy+path.++A caller can restrict which providers are acceptable with+`X-Sam-Required-Labels: key=value[,key=value]`. The node then verifies the+provider's credential and confirms that the labels are attested in it before+forwarding. The header is removed before the request leaves the node. An+operator can set a floor that every provider must meet with+`egress.require_labels` in the node configuration.++## Mesh events++The control plane publishes bans and signing-key rotations as signed events.+Routers inject them into a GossipSub topic that every node subscribes to. A+node that receives a ban event drops the banned peer immediately. A node+that receives a rotation event fetches the new key set. Each event is+verified against the control plane's key before a node acts on it or+forwards it.++## Resource limits++Nodes rate-limit authentication attempts per peer and cap the size of every+frame and body they read. Routers cap inbound connections per source IP+(`--conns-per-source-ip`) and total connections (`--low-watermark`,+`--high-watermark`). A router behind a TLS-terminating proxy, or behind a NAT+that puts many peers on one address, needs a higher per-source limit.+`sam-one` raises it automatically for its embedded router.diff --git a/site/content/docs/contributing/_index.md b/site/content/docs/contributing/_index.mdnew file mode 100644index 00000000..35752a42--- /dev/null+++ b/site/content/docs/contributing/_index.md@@ -0,0 +1,124 @@+---+title: "Contributing"+linkTitle: "Contributing"+weight: 7+aliases:+ - /docs/development/+ - /docs/development/testing/+ - /docs/development/kubernetes-deployment/+---++How to build SAM from source, run its tests, and bring up a local mesh to+develop against. Contributions go through GitHub pull requests and need a+signed [Contributor License Agreement](https://cla.developers.google.com/).+[CONTRIBUTING.md](https://github.com/google/sam/blob/main/CONTRIBUTING.md)+in the repository has the details.++## Layout++| Path | Contents |+|---|---|+| `cmd/` | One directory per binary: `sam-node`, `sam-control-plane`, `sam-router`, `sam-one`, `sam-console`, `sam-box`, `nano-init`, `mcp-client`, and smaller tools. |+| `api/` | The wire contract: `sam.proto` and its generated code, plus the Go types for the JSON admin API and the validation and Datalog helpers both sides share. |+| `internal/` | Implementation, one package per component (`node`, `controlplane`, `router`, `standalone`, `console`, `sambox`, `identity`, `storage`, ...). |+| `charts/` | The `sam-mesh` and `sam-node` Helm charts. |+| `tests/integration/` | Go tests that start several components in one process. |+| `tests/e2e/` | Bats tests that drive the built binaries and containers. |+| `development/` | The kind environment and example services. |+| `site/` | This documentation, a Hugo site. |++Two rules from `AGENTS.md` shape most changes. Components talk to each other+only through `api/sam.proto` (protobuf for anything a mesh component speaks,+JSON types in `api/` for the operator API). And no new module may be added+to `go.mod` without discussion. Guest-only code such as `nano-init` lives in+its own module for that reason.++## Build++You need Go 1.25 or later. Docker is needed for the container tests and the+linter, and `bats-core` for the end-to-end tests.++```bash+git clone https://github.com/google/sam.git && cd sam+make build # binaries in ./bin+make docker-build # container images tagged :local+make proto # regenerate api/sam.pb.go after editing sam.proto+```++## Test++The suite is layered so that most coverage lives where it runs fastest.++| Command | What runs | Time |+|---|---|---|+| `make test` | Every Go test with the race detector: the unit tests next to the code, and the integration tests under `tests/integration/`, which start a control plane, a router and nodes in one process. Each integration test is expected to finish within ten seconds. `WHAT=TestName` runs a subset. | minutes |+| `make e2e-test` | The Bats suite under `tests/e2e/`, in parallel. It covers the CLI (`sam.bats`), a containerised mesh with a mock identity provider (`container_mesh.bats` and the tests built on it), policy, services, A2A, the console, `sam-one`, and the sandbox. It builds the binaries and images first. `WHAT=pattern` filters the tests. | 10 to 30 minutes |+| `make test-e2e-container` | Only the containerised-mesh test. | |+| `make ui-test` | Playwright against the console, on a stack of local processes with SQLite. `make ui-dev` starts the same stack and leaves it running for manual use. | |+| `make lint` | `go fmt`, Helm lint, then `golangci-lint` in Docker and a dead-code check. Any exported identifier that no binary and no test reaches fails the check, so new exported API must land together with its tests. | about a minute |+| `make verify` | Checks that generated code is current and that no secrets are committed. | |++Put coverage as low in this pyramid as possible. An edge case that a unit or+integration test can cover should not become an end-to-end test. The e2e+suite exists for a small number of critical user journeys and is slow by+nature.++The container tests build images only when they are absent. After you change+a binary, run `make docker-build` before you run them again, or the tests+run the old code.++## A local mesh in kind++`development/kind/` brings up a control plane, a router, a console and Dex+in a local kind cluster with one command. It exposes them through Gateway+API addresses served by `cloud-provider-kind`, which must be installed.++```bash+make kind-up # create the cluster, build and load images, deploy; opens a tmux log view+make kind-up ARGS=-s # the same without the log view+make kind-logs # reattach the log view+make kind-down # delete everything+```++The mesh comes up with no nodes. Put a service on it with the `sam-node`+chart and one of the examples:++```bash+./development/deploy-kind-service.sh development/examples/calc-mcp+```++The script builds the example's image, loads it into the cluster, and+installs a `sam-node` release with the example's `values.yaml` on top of+`development/kind/sam-node.values.yaml`. Any directory with a `Dockerfile`+and a `values.yaml` works, and extra arguments are passed to Helm.++To use the mesh from a node built from your working tree:++```bash+make kind-local-node # mints a bootstrap token, runs ./bin/sam-node, API on 127.0.0.1:9099 with token "devtoken"+make kind-local-node ARGS="--config my-node.yaml"++./bin/mcp-client -url http://127.0.0.1:9099/mcp -token devtoken -tool find_remote_tools -args '{}'+```++`make kind-e2e-mesh` runs the whole loop without interaction. It deploys+`calc-mcp`, enrolls a local node, discovers `mcp://calculator/add`, calls+it, and checks the answer.++## The documentation++The site is Hugo with the Docsy theme, under `site/`. The deploy workflow+pins Hugo 0.136.5, and newer Hugo releases do not build the current Docsy+version, so use that release locally too. Run `npm ci` once in `site/` for+the CSS pipeline, then `hugo server`. The site deploys from `main` to+`sam-mesh.dev`. When a page moves, keep its old URL with `aliases` in the+front matter. `tests/e2e/docs_snippets.bats` runs the Python snippet under+`site/content/docs/snippets/` against a live node, so a change to that+snippet is a change to a test.++## Releases and testnets++A `v*` tag produces a GitHub release with binaries and images through+`goreleaser`, and deploys to the `hub.sam-mesh.dev` testnet. Every push to+`main` deploys to `bananas.sam-mesh.dev`. [Testnets](testnets/) describes+both.diff --git a/site/content/docs/contributing/testnets.md b/site/content/docs/contributing/testnets.mdnew file mode 100644index 00000000..b550a9bd--- /dev/null+++ b/site/content/docs/contributing/testnets.md@@ -0,0 +1,48 @@+---+title: "Testnets"+linkTitle: "Testnets"+weight: 1+aliases:+ - /docs/development/release-tracks/+---++The project runs two public meshes for its own testing and for anyone who+wants to try the software without deploying anything.++| | `bananas.sam-mesh.dev` | `hub.sam-mesh.dev` |+|---|---|---|+| Built from | every push to `main` | every `v*` tag |+| Image tag | the commit SHA | the release version |+| Purpose | continuous integration of unreleased code | the latest release, for interoperability testing |++Both are deployed by `.github/workflows/deploy.yaml` to a GKE cluster from+the templates in `.github/k8s/`. Each testnet has a control plane Deployment+on PostgreSQL, a router StatefulSet that announces+`/dnsaddr/bootstrap.<env>.sam-mesh.dev` (a DNS-sync CronJob keeps the record+current), the console, and a few canary nodes that publish demo services:+the MCP `everything` server, an OpenRouter proxy, and a vLLM instance when+one is running. Identity comes from a Dex instance at `auth.sam-mesh.dev`+that accepts Google and GitHub logins, and from the cluster's own issuer for+in-cluster workloads.++Deploys run one at a time per environment, replace pods one at a time, and+fail the workflow if the rollout does not complete. A probe CronJob enrolls+a new node every half hour and calls a tool through it. The+[testnet-health](https://github.com/google/sam/actions/workflows/testnet-health.yaml)+badge on the repository turns red when the probe fails, and an issue+labelled `testnet-health` names the failed check.++## What they are not++The testnets run on donated resources with no uptime commitment. Their+policy binds `sam:system:authenticated` to `sam:role:node`, so anyone who+can log in with Google or GitHub can enroll a node, and the demo services+are granted to every node. Nothing that you publish from a node enrolled+there is private. The testnets are a place to see the software work and the+project's own canary. If you need a mesh you can rely on, run its control+plane yourself.++Only the enrollment paths are routed to the public. `/healthz`, `/readyz`,+`/metrics` and `/admin` answer `404` from outside the cluster. `/info` is+public, because enrollment needs it, and it lists the current router+addresses.diff --git a/site/content/docs/development/_index.md b/site/content/docs/development/_index.mddeleted file mode 100644index 8a5c35f0..00000000--- a/site/content/docs/development/_index.md+++ /dev/null@@ -1,97 +0,0 @@-----title: "Developer Guide"-linkTitle: "Developer Guide"-weight: 4-----This document is for developers who want to compile SAM from source, run a local development mesh, run the test suites, or contribute to the repository.-------## Prerequisites--To build and test the Go binaries natively:--- **Go Toolchain**: Go 1.25+-- **Docker**: For running containerized integration tests and building local images.-- **BATS**: `bats-core` framework for running E2E shell tests.-------## Build from Source--Clone the repository and compile the binaries:--```bash-git clone https://github.com/google/sam.git-cd sam-make build-```--This compiles and generates the following binaries under `./bin/`:--- `./bin/sam-control-plane`: The OIDC identity bridge and cryptographic Biscuit token issuer.-- `./bin/sam-router`: The GossipSub routing overlays and bootstrap points for the P2P mesh.-- `./bin/sam-node`: The mesh agent node CLI supporting `join` and `run` commands.-- `./bin/mcp-client`: A CLI-based utility to interact with MCP servers.-------## Running a Local Dev Control Plane and Router--To run the control plane and router locally for testing:--1. **Start the Control Plane**:-```bash-export SAM_OIDC_ISSUER=https://issuer.example.com-export SAM_OIDC_ID=sam-client-export SAM_OIDC_SECRET=sam-secret--./bin/sam-control-plane --issuer=$SAM_OIDC_ISSUER --allowed-audiences=sam-mesh-audience-```--2. **Start the Router**:-```bash-./bin/sam-router \- --control-plane=http://localhost:8080 \- --listen=/ip4/127.0.0.1/tcp/4501 \- # api token via SAM_API_TOKEN env or --api-token-path-```-------## Testing--The repository implements a testing pyramid. Ensure the test suites are green before pushing code:--### 1. Go Unit & Integration Tests-Runs the packages' unit tests and multi-node integration tests:-```bash-make test-```--### 2. Local E2E Tests (BATS)-Validates local command-line behaviors for `sam-node`, `sam-control-plane`, and `sam-router`:-```bash-make test-e2e-```--### 3. Containerized Mesh E2E (BATS)-Builds local Docker images, spins up a mock OIDC server, runs control-plane, router, and multiple `sam-node` containers in a local bridge network, and performs end-to-end device flows and tool discovery:-```bash-make test-e2e-container-```-------## Local Kubernetes Test Setup--For end-to-end integration testing in a local Kubernetes environment, the repository provides `make` targets that stand up a complete mesh in `kind` with a single command:--```bash-make kind-up # create the sam-kind cluster, build+load images, deploy the sam infrastructure-make kind-local-node # enroll a locally-built ./bin/sam-node into the mesh-make kind-e2e-mesh # run the end-to-end discover-and-call check-make kind-down # tear the cluster down-```--`make kind-up` builds the `sam-control-plane:local`, `sam-router:local`, `sam-node:local` and `sam-console:local` images, creates a `sam-kind` cluster, and deploys the control plane, router, console and Dex — no sam-nodes. Deploy services with `charts/sam-node`; see the [Kubernetes Deployment and Local Testing Guide](kubernetes-deployment/#1-local-testing-with-kind) for details.diff --git a/site/content/docs/development/kubernetes-deployment.md b/site/content/docs/development/kubernetes-deployment.mddeleted file mode 100644index ca2ba853..00000000--- a/site/content/docs/development/kubernetes-deployment.md+++ /dev/null@@ -1,446 +0,0 @@-----title: "Kubernetes Deployment and Local Testing Guide"-linkTitle: "Kubernetes Deployment and Local Testing Guide"-----This guide explains how to deploy the SAM control plane and router in a Kubernetes cluster and how to test it locally with `kind` — using the bundled `make kind-*` targets for a one-command mesh, or a manual setup. Both paths need `cloud-provider-kind`.--> [!TIP]-> This guide focuses on local development sandboxing. For production-grade Kubernetes deployments (GKE, EKS, AKS), see the [Production Kubernetes Deployment](../../user/kubernetes-deployment/) guide.-------## 1. Local Testing with Kind--The repository ships a one-command local mesh under `development/kind/`, driven by `make` targets. This is the fastest way to get a running control plane, router and console on your machine — ready for you to deploy services onto.--### Automated Mesh (Recommended)--```bash-make kind-up-```--This creates a `sam-kind` cluster (one control-plane plus two workers — one-labeled `sam-role: control-plane` for the router), builds the-`sam-control-plane:local`, `sam-router:local`, `sam-node:local` and-`sam-console:local` images, loads them into the cluster, and deploys:--- The **control plane**, configured to trust the cluster's own OIDC issuer.-- The **console**.-- **Dex**.-- The **router**.-- **No sam-nodes.** The mesh comes up empty; put services on it with the- `charts/sam-node` chart (next section) or enroll a local node.--In-cluster nodes authenticate to the control plane via **Workload Identity Federation** (projected ServiceAccount tokens), so no static secrets or mock OIDC provider are needed.--The mesh is exposed through Gateway API LoadBalancer addresses, so there are no port-forwards and no `extraPortMappings`. `run.sh` runs **`cloud-provider-kind`** as a container (a hard prerequisite — it needs the docker socket) to serve those addresses, and prints them when the mesh is up:--- The **control plane** on its own address, routing the 8 exact enrollment paths, plus a dev-only `/admin` route.-- The **console** at `/console/` on that same address, shaped like the production deployment: `/console` 302s to `/console/`, and a `URLRewrite` filter strips the prefix before the console sees the request.-- **Dex** on its own address, deployed from `development/kind/dex.yaml` rather than the chart — Dex is an independent component the chart no longer bundles.-- The **router** at its own node's IP on port 4501, TCP **and** QUIC, announced from `status.hostIP`.--Once everything is up, `make kind-up` opens a tmux session with live per-pod logs (control plane and router, each in its own pane). Manage the mesh with:--```bash-make kind-up ARGS=-s # bring the mesh up without attaching the log view-make kind-logs # (re)attach the live-logs tmux session-make kind-down # delete the sam-kind cluster and stop cloud-provider-kind-```--### Deploying a Service--A service is any backend a node advertises to the mesh (`type: mcp` or-`type: inference`). In Kubernetes a service ships as a **`charts/sam-node`-release**: one pod holding your service container and a `sam-node` sidecar-that advertises it. The repository ships ready-made examples under-`development/examples/`; each is a `Dockerfile` plus a `values.yaml`-describing only the service — kind-wide wiring (control plane URL, fast-discovery) lives once in `development/kind/sam-node.values.yaml` and is-stacked underneath with a second `-f`.--Deploy one (calc-mcp) into the running kind mesh:--```bash-docker build -t calc-mcp:local development/examples/calc-mcp-kind load docker-image --name sam-kind calc-mcp:local-helm --kube-context kind-sam-kind -n sam-kind install calc-mcp charts/sam-node \- -f development/kind/sam-node.values.yaml \- -f development/examples/calc-mcp/values.yaml-```--`development/deploy-kind-service.sh` wraps those commands (as-`helm upgrade --install`, plus a rollout wait) and echoes each one as it-runs, so deploying — or redeploying after a code change — is one line. It-takes a path to any directory holding a `Dockerfile` and a `values.yaml`,-and extra args pass through to helm:--```bash-./development/deploy-kind-service.sh development/examples/calc-mcp-./development/deploy-kind-service.sh development/examples/code-reviewer-pool/reviewer --set replicaCount=3-./development/deploy-kind-service.sh ~/src/my-service-# same service as a second, differently-labeled node:-./development/deploy-kind-service.sh development/examples/calc-mcp --release-name calc-b \- --set-json 'extraArgs=["--discovery-interval=200ms"]' --set config.labels.region=us-east-1-```--To write your own service, copy an example folder: a backend listening on a-local port, a `Dockerfile`, and a `values.yaml` declaring the service —--```yaml-config:- version: v1alpha1- attenuation:- policies: []- services:- - type: mcp- name: my-service- description: What it does- target_url: http://127.0.0.1:7779/mcp-service:- name: my-mcp- image: my-mcp:local-```--The service container and `sam-node` share the pod's network, so `target_url`-is always `127.0.0.1:<port>`. Iterate with `docker build … && kind load … &&-helm upgrade calc-mcp charts/sam-node -f … -f …` — the chart rolls the pods-on config changes. Remove a service with `helm uninstall`.--Discover and call it from another node — enroll a local node and use the MCP-client:--```bash-make kind-local-node-# in another shell:-./bin/mcp-client -url http://127.0.0.1:9099/mcp -token devtoken -tool find_remote_tools -args '{}'-```--`find_remote_tools` lists the discovered tools (e.g. `mcp://my-service/...`)-and the peer hosting them; pass that `peer_id` and `tool_name` to-`call_remote_tool` to invoke it.--### Enrolling a Local Node--To iterate on `sam-node` without rebuilding the image, enroll a locally-built binary into the running mesh:--```bash-make build # produce ./bin/sam-node-make kind-local-node-```--This mints a bootstrap token through the control plane's `/admin` API and runs `./bin/sam-node` against the control plane's gateway address — the same credential and path a real external node uses — exposing its MCP API on `127.0.0.1:9099` with the API token `devtoken`. Extra flags pass through via `ARGS`, e.g. `make kind-local-node-ARGS="--config my-node.yaml"` to host a service from a local config file-(same schema as the `config:` block in a `charts/sam-node` values file).--You can then drive it with the bundled MCP client:--```bash-./bin/mcp-client -url http://127.0.0.1:9099/mcp -token devtoken -tool find_remote_tools -args '{}'-```--### End-to-End Mesh Check--To verify the full discovery-and-call path against a freshly built mesh:--```bash-make kind-up ARGS="-s"-make kind-e2e-mesh-```--`kind-e2e-mesh` deploys `calc-mcp` as a `charts/sam-node` release, enrolls a local node, waits for it to discover `mcp://calculator/add`, calls `add(2, 3)`, and asserts the result is `5`.-------## 2. Manual Deployment--If you'd rather deploy the pieces by hand — for example to exercise the Mock OIDC provider or wire up Google OIDC — you can apply the manifests below to a cluster yourself. SAM supports either a **Mock OIDC Provider** (recommended for quick local testing, since it needs no external credentials) or **Google OIDC** for authentication. The local `kind` path below uses `cloud-provider-kind` to allocate LoadBalancer IPs.--### Mock OIDC Provider Manifests (Optional)--The manifests for the mock OIDC provider are available in [mock-oidc.yaml](manifests/mock-oidc.yaml).--> **Warning:** the mock issuer signs a token for whatever identity it is asked-> for. It generates its signing key at start-up so nothing secret ships in the-> manifest, but any control plane that trusts this issuer admits anyone who can-> reach it. Use it only on a cluster nobody else can reach, and never as the-> `--issuer` of a control plane exposed beyond that cluster.--[mock-oidc.yaml](manifests/mock-oidc.yaml ':include')--### SAM Control Plane and Router Manifests--The manifests for the SAM Control Plane and Router are available in [sam-control-plane.yaml](manifests/sam-control-plane.yaml) and [sam-router.yaml](manifests/sam-router.yaml).--[sam-control-plane.yaml](manifests/sam-control-plane.yaml ':include')--[sam-router.yaml](manifests/sam-router.yaml ':include')--### Configuring Google OIDC (Optional)--To use Google as the OIDC provider instead of the mock provider:--2. **No Redirect URI required:** Because `sam-node` implements RFC 8252 (dynamic loopback port selection for native apps), you don't need to configure a specific Redirect URI when setting up a Desktop app. The authorization server will automatically allow loopback redirects.-3. **Update Secret:** Update the `sam-control-plane-secret` in `sam-control-plane.yaml` with your Google credentials:- ```yaml- SAM_OIDC_ISSUER: "https://accounts.google.com"- SAM_OIDC_ID: "<your-client-id>.apps.googleusercontent.com"- SAM_OIDC_SECRET: "<your-client-secret>"- ```--### Deploying to Kind--#### Step 1: Create a Kind Cluster-```bash-kind create cluster --name sam-test-```--#### Step 2: Run cloud-provider-kind-Run it in a separate terminal:-```bash-cloud-provider-kind-```--#### Step 3: Load Images into Kind-```bash-kind load docker-image sam-control-plane:local --name sam-test-kind load docker-image sam-router:local --name sam-test-kind load docker-image sam-node:local --name sam-test-```--#### Step 4: Apply Manifests--If using the **Mock OIDC Provider**:-```bash-kubectl apply -f mock-oidc.yaml-kubectl apply -f sam-control-plane.yaml-kubectl apply -f sam-router.yaml-```--If using **Google OIDC**:-```bash-kubectl apply -f sam-control-plane.yaml-kubectl apply -f sam-router.yaml-```--#### Step 5: Get the External IP-You can use the following command to extract the allocated IP into an environment variable:--```bash-CONTROL_PLANE_IP=$(kubectl get svc sam-control-plane -o jsonpath='{.status.loadBalancer.ingress[0].ip}')-```-------## 3. Connecting an Agent--To connect a `sam-node` to the control plane, you just need its external IP and port.--### Enrolling the Agent--To connect a `sam-node` to the control plane for the first time, you need to enroll it. The node needs to authenticate with the control plane using a JWT token.--If you are using the **Mock OIDC Provider**, the node can fetch the token using OIDC Client Credentials flow:--1. **Get the Mock OIDC Service IP:**- ```bash- MOCK_IP=$(kubectl get svc mock-oidc -o jsonpath='{.status.loadBalancer.ingress[0].ip}')- ```--2. **Run the Node to enroll:**- ```bash- sam-node run \- --control-plane "http://$CONTROL_PLANE_IP:9090" \- --insecure-control-plane \- --oidc-issuer "http://$MOCK_IP:18080" \- --client-id "sam-mesh-audience" \- # client secret via SAM_CLIENT_SECRET env or --client-secret-path- ```--If you are using **Google OIDC**, you must obtain a valid Google ID token for your user and pass it via the `--jwt` flag:-```bash-sam-node run \- --control-plane "http://$CONTROL_PLANE_IP:9090" \- --insecure-control-plane \- --jwt "<your-google-id-token>"-```--Once enrolled, the identity is stored in the local database (`agent.db`), and you can run subsequent times without OIDC credentials:-```bash-sam-node run-```-------## 4. Automating Node Deployment--To automate the deployment of `sam-nodes` in Kubernetes and have them fetch the JWT token automatically, you can use a standard Kubernetes `Deployment` or `StatefulSet`.--### Example Deployment--Here is a sample manifest that uses the in-cluster DNS to fetch the token from the mock provider:--```yaml-apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-node-spec:- replicas: 3- selector:- matchLabels:- app: sam-node- template:- metadata:- labels:- app: sam-node- spec:- containers:- - name: sam-node- image: sam-node:local- command: ["sam-node", "run"]- args:- - "--control-plane"- - "http://sam-control-plane:8080"- - "--oidc-issuer"- - "http://mock-oidc:18080"- - "--client-id"- - "sam-mesh-audience"- - "--client-secret"- - "sam-e2e-secret"- env:- - name: HOME- value: /data- volumeMounts:- - name: data-volume- mountPath: /data- volumes:- - name: data-volume- emptyDir: {}-```--### Supported Authentication Flows--The SAM project supports three primary flows for acquiring a JWT token to enroll nodes, depending on the environment and security requirements:--#### 1. Client Credentials Flow (Machine-to-Machine)-* **Description:** Defined in OAuth 2.0 RFC 6749, section 4.4. An application exchanges its application credentials (such as Client ID and Client Secret) for an access token.-* **Use Case:** For unattended services or deployments connecting to a production OIDC provider.-* **How to use:** Pass the `--oidc-issuer`, `--client-id`, and `--client-secret` flags to `sam-node run`.-* **Example:**-```bash-sam-node run \- --control-plane "https://control-plane.example.com:9090" \- --oidc-issuer "https://accounts.google.com" \- --client-id "$SAM_OIDC_ID" \- --client-secret "$SAM_OIDC_SECRET"-```--#### 2. Native App Authorization Code Flow (Human Intervention)-* **Description:** For devices operated by humans, this uses the standard Authorization Code Flow with PKCE for native apps (RFC 8252). The human operator runs `sam-node join` to open a web browser (or get a verification code via `--headless`), completes the login, and obtains a Biscuit token which is stored in the local database (`agent.db`).-* **Use Case:** When a human operator is enrolling a node manually via their local terminal.-* **How to use:** Run `sam-node join <control-plane-url>` before running the node daemon. Alternatively, you can obtain a token yourself and pass it via the `--jwt` flag to `sam-node run`.-* **Example:**-```bash-# First, join interactively:-sam-node join https://control-plane.example.com--# Then start the node daemon:-sam-node run-```--#### 3. Workload Identity Federation (Secretless Kubernetes)-* **Description:** The current best practice in Kubernetes. It removes the need for static secrets entirely. The machine proves its identity based on where it is running by presenting a ServiceAccount token (a signed JWT issued by the K8s API).-* **Use Case:** Production Kubernetes deployments.-* **How it works:** The Pod has a ServiceAccount token mounted. The Pod presents this token to the `sam-control-plane`. The control plane verifies it by calling back to the Kubernetes OIDC discovery endpoint.-* **How to use:** Pass the path to the mounted ServiceAccount token to the `--jwt-path` flag.-* **Example:**-```bash-sam-node run \- --control-plane "https://control-plane.example.com:9090" \- --jwt-path "/var/run/secrets/kubernetes.io/serviceaccount/token"-```-> [!NOTE]-> The `sam-control-plane` must be configured to trust the Kubernetes API server as an OIDC issuer for this flow to work.-------## 5. Configuring Workload Identity in Kubernetes--Workload Identity allows `sam-node` pods to authenticate with the `sam-control-plane` using their Kubernetes ServiceAccount token, removing the need for static credentials.--Here are the exact steps to configure this:--### Step 1: Ensure OIDC Discovery is enabled on your Cluster-Most managed Kubernetes services (GKE, EKS, AKS) and local tools like `kind` support ServiceAccount Issuer Discovery.-In `kind`, this is enabled by default. You can find the issuer URL by running:-```bash-kubectl get --raw /.well-known/openid-configuration | jq -r .issuer-```-(Or check your cloud provider's documentation for the public issuer URL).--### Step 2: Configure the Control Plane to trust the Kubernetes Issuer-Update the `sam-control-plane` deployment to include the Kubernetes issuer URL in the `--issuer` flag.--If you are using `kind`, the issuer URL is usually `https://kubernetes.default.svc.cluster.local` (internal) or the external URL mapped by kind.--Update `sam-control-plane.yaml`:-```yaml- spec:- containers:- - name: sam-control-plane- args:- - "--issuer"- - "https://accounts.google.com,https://kubernetes.default.svc.cluster.local"-```--### Step 3: Create a ServiceAccount for the Node-Create a ServiceAccount that the `sam-node` pods will use.-```yaml-apiVersion: v1-kind: ServiceAccount-metadata:- name: sam-node-sa-```--### Step 4: Deploy the Node with a Projected Volume-Deploy the `sam-node` and configure it to use the ServiceAccount. We use a **Projected Volume** to request a token with the specific audience expected by the control plane (e.g., the mesh name or a specific client ID).--```yaml-apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-node-spec:- replicas: 3- selector:- matchLabels:- app: sam-node- template:- metadata:- labels:- app: sam-node- spec:- serviceAccountName: sam-node-sa- containers:- - name: sam-node- image: sam-node:local- command: ["sam-node", "run"]- args:- - "--control-plane"- - "http://sam-control-plane:8080"- - "--jwt-path"- - "/var/run/secrets/tokens/sam-token"- volumeMounts:- - name: sam-token- mountPath: /var/run/secrets/tokens- readOnly: true- volumes:- - name: sam-token- projected:- sources:- - serviceAccountToken:- path: sam-token- expirationSeconds: 3600- audience: "sam-control-plane-audience" # Match this with what the control plane expects-```diff --git a/site/content/docs/development/mobile.md b/site/content/docs/development/mobile.mddeleted file mode 100644index 8d8c94f2..00000000--- a/site/content/docs/development/mobile.md+++ /dev/null@@ -1,130 +0,0 @@-----title: "Mobile Support (Android & iOS)"-linkTitle: "Mobile Support"-weight: 6------This guide describes the architecture, compilation toolchain, development workflow, and testing procedures for running `sam-node` on mobile platforms (Android and iOS).-------## Architecture Overview--To run `sam-node` on mobile with near-zero codebase maintenance, we avoid rewriting the p2p network stack and routing logic in Kotlin/Swift. Instead, we use Go's CGO compiler to generate native C-compatible libraries that are loaded and controlled inside a Flutter app using **Dart FFI (Foreign Function Interface)**.--```- ┌────────────────────────────────────────────────────────┐- │ Flutter Mobile App │- │ │- │ ┌─────────────────┐ ┌──────────────────┐ │- │ │ Dart GUI │ │ Dart FFI Client │ │- │ └────────┬────────┘ └────────┬─────────┘ │- │ │ │ │- └───────────┼───────────────────────────────┼────────────┘- │ │ (C Function Calls)- │ (HTTP / JSON RPC) ▼- ┌───────────┼───────────────────────────────┼────────────┐- │ ▼ │ │- │ ┌─────────────────┐ ┌────────▼─────────┐ │- │ │ Sidecar API │ │ Go FFI Entry │ │- │ │ (127.0.0.1) │ │ (sam-node-ffi) │ │- │ └────────┬────────┘ └────────┬─────────┘ │- │ │ │ (Go APIs) │- │ ▼ ▼ │- │ ┌──────────────────────────────────────────────────┐ │- │ │ sam-node │ │- │ └──────────────────────────────────────────────────┘ │- │ Go Runtime │- └────────────────────────────────────────────────────────┘-```--1. **Go FFI Binding Package (`mobile/sam-node-ffi/`)**: Contains CGO-exported functions (`StartNode`, `StopNode`, `EnrollNode`, `GetNodeID`, `FreeString`) which compile into a C-shared library (`.so`) or static archive (`.a`).-2. **Flutter App (`mobile/sam-node-app/`)**: A cross-platform app containing:- - `lib/sam_ffi.dart`: The Dart FFI wrapper loading the Go library and exposing Dart methods.- - `lib/main.dart`: Simple control UI to enroll and start/stop the background node. The Config tab holds the node's labels and attenuation, the app's stand-in for `sam-node.yaml`. Labels (comma-separated `key=value`, the wire format of the `labels` map) are set there; the control plane mints them into the node's Biscuit at enrollment, and the app keeps a copy in its data directory and sends it again on every start. Biscuit refresh re-mints the labels stored at enrollment, so changing them means enrolling again, which the tab's Re-enroll button does while keeping the node's identity: the app asks the OIDC provider for `offline_access`, the FFI stores the refresh token like the CLI does, and `ReEnrollNode` trades it for a JWT; the browser login runs only when that fails. Unlike the CLI, which re-reads them from its config file on every run, the app remembers them. The same tab accepts local Datalog rules, policies and checks (one statement per line) in place of the CLI's `attenuation` block; the app stores them as `attenuation.json` in the same data directory and sends them on every start, and the FFI parses them with the same code path the config file uses.-3. **Local Loopback Communication**:- - The Flutter Dart environment controls the node lifecycle (construction, starting, stopping) via FFI.- - Any actual tool registration, discovery, or mesh API queries are performed using standard HTTP JSON-RPC calls over local loopback (`127.0.0.1`) to the `sam-node` sidecar API.-------## Make Build Targets--We provide dedicated `Makefile` targets to automate Go FFI compilation and copy binaries into the mobile app:--### 1. Build Host FFI (For local desktop testing)-Compiles `bin/libsam.so` for the host platform:-```bash-make mobile-ffi-host-```--### 2. Build Android FFI Library-Compiles `bin/android/libsam.so` targeting Android ARM64 devices:-```bash-make mobile-ffi-android-```--### 3. Build Android Emulator FFI Library-Compiles `bin/android-x86_64/libsam.so` for x86_64 emulator images (Intel and Linux hosts). Emulators on Apple Silicon run arm64-v8a images; use target 2 for those:-```bash-make mobile-ffi-android-x86_64-```--### 4. Build iOS FFI Library-Compiles `bin/ios/libsam.a` targeting iOS ARM64 devices:-```bash-make mobile-ffi-ios-```--### 5. Build Complete Android Release APK-Compiles the FFI library, bundles it inside the Flutter project, and builds the final release APK:-```bash-make mobile-app-apk-```-------## Local Development Workflow--To make changes to `sam-node` and run them on a mobile device:--### Android Setup-The `mobile-ffi-*` targets only build into `bin/`; copy the library into `jniLibs/` yourself (or use `make mobile-app-apk`, which does both and builds the APK). For an x86_64 emulator, swap in `mobile-ffi-android-x86_64`, `bin/android-x86_64/libsam.so` and `jniLibs/x86_64`.--1. Compile the Android ARM64 FFI shared library:- ```bash- make mobile-ffi-android- ```-2. Copy the library into the Android project's `jniLibs` directory:- ```bash- mkdir -p mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a- cp bin/android/libsam.so mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a/libsam.so- ```-3. Connect your Android device via USB (verify connection with `adb devices`).-4. Run the app:- ```bash- cd mobile/sam-node-app- flutter run- ```-------## Integration Testing (E2E)--We automate end-to-end integration verification in the CI by running a headless Android Emulator and executing bidirectional MCP discovery:--### Local Execution of E2E Script-If you have an active emulator running locally, you can run the full E2E orchestration test:-```bash-./mobile/mobile_e2e.sh-```--#### What the E2E test validates:-1. Starts a local **Mock OIDC Server** and **sam-control-plane** process on the host.-2. Registers a dummy tool (`host-tool`) on a host-level **sam-node**.-3. Boots the **Android Emulator**, installs the FFI-embedded app, and starts the node inside the emulator.-4. Registers an `emulator-tool` inside the emulator app.-5. Asserts **bidirectional discovery**:- - The emulator app successfully discovers the host's `host-tool` via the mesh.- - The host node successfully discovers the emulator's `emulator-tool` via the mesh.-6. Terminates all background processes and cleans up directories on completion.diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.mddeleted file mode 100644index 3d6851aa..00000000--- a/site/content/docs/development/policy.md+++ /dev/null@@ -1,312 +0,0 @@-----title: "SAM Policy & Authorization Reference"-linkTitle: "SAM Policy & Authorization Reference"-----SAM uses a decentralized authorization model powered by [Biscuit](https://www.biscuitsec.org/).-The `sam-control-plane` authenticates users via OIDC and injects **Facts** into their token based on the mesh policy held in its database. The `sam-node` operates offline, evaluating the token against baseline rules and optional local attenuation policies.--> [!IMPORTANT]-> **Default-Deny Security Posture**-> SAM enforces a strict **default-deny** model. By default, when a node joins the mesh, **all of its services (MCP tools, LLM inference endpoints) are completely locked down and inaccessible to other peers**.-> Access is only permitted if the caller presents a Biscuit token containing capability facts (e.g., `granted_service_exact(...)`) explicitly issued by the control plane based on matched user roles.-> There are no built-in exceptions; even the catalog service (system://sam.catalog) must be explicitly permitted (e.g., via a role mapping) to facilitate peer-to-peer discovery.---## 1. OIDC to Biscuit Translation-The control plane automatically translates OIDC claims into undeniable cryptographic facts:--| OIDC Claim / Data | Biscuit Fact | Description |-| :--- | :--- | :--- |-| `sub` | `user("<sub-id>")` | The unique subject ID from the identity provider. |-| `email` | `email("<email>")` | The user's email address (if present). |-| `groups` | `group("<group-name>")` | One fact is injected for *each* group the user possesses. |-| `roles` / Resolved Roles | `role("<role-name>")` | One fact is injected for *each* role mapped or direct role. |-| Peer ID | `node("<peer-id>")`, `client_peer_id("<peer-id>")` | Binds the token to the specific agent's libp2p cryptographic identity. |-| Expiration | `expiration(<date>)` | The token expiration date based on the OIDC session. |--### 1.1 Translating Identity to Capability: OIDC to Biscuit-The core innovation of the SAM Network's security model is translating standard web identity (OIDC JSON Web Tokens defined in [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#Claims)) into decentralized capability tokens (Biscuits). This translation happens securely at the `sam-control-plane` during the authentication phase.--The Datalog authority facts generated by the control plane are constructed using the Biscuit [Symbol Table specification](https://doc.biscuitsec.org/reference/specifications.html#symbol-table), ensuring compact serialization and cryptographically undeniable credentials.--Here is exactly how an OIDC JWT is transformed into a policy-ready Biscuit:--#### 1. Claim Extraction-When an agent or user submits a valid OIDC JWT, the sam-control-plane verifies the token's signature against the Identity Provider. Once validated, the control plane extracts the payload claims—typically attributes like sub (subject), email, and custom arrays like groups or roles.--#### 2. Datalog Fact Generation-Biscuit policies are written in Datalog, a declarative logic language. The sam-control-plane acts as a translator, mapping the JSON claims from the OIDC token into immutable Datalog facts.--For example, an incoming OIDC payload like this:--```json-{- "sub": "user-12345",- "email": "[email protected]",- "groups": ["beta-testers", "engineering"]-}-```--Is translated by the control plane into the following Datalog facts:--```datalog-user("user-12345");-email("[email protected]");-group("beta-testers");-group("engineering");-```--#### 3. Minting the Authority Block-The sam-control-plane takes these generated Datalog facts and embeds them into the Authority Block of a brand new Biscuit token. The control plane signs this block with its private cryptographic key.--Because the facts are sealed in the Authority Block by the control plane, any sam-node in the mesh can implicitly trust that the user holding the Biscuit possesses those specific emails and groups.--#### 4. Policy Evaluation at the Node-When the agent presents the Biscuit to a sam-node to execute a tool, the node evaluates its local policies against the facts embedded in the token.--Because the OIDC claims were translated into Datalog, a node administrator can write elegant, logic-based rules in policy.go or their YAML configs:--```datalog-// The node will only execute the tool if the control plane certified the agent is in the engineering group-allow if group("engineering");-```--## 2. Control plane policy configuration (REST API)-Admins manage central permissions dynamically via the Control Plane REST API. The policy database defines a set of **Roles** and **Bindings**.--* **Roles**: Define specific capabilities (allowed destinations and services).- * `allowed_targets`: Defines which logical groups or specific peers a user can route messages to, analogous to Active Directory security groups. Target definitions must be formatted as resolved facts (e.g., `group:<name>`, `user:<sub-id>`, `email:<email>`, `idp_role:<role-name>` for the issuer's `roles` claim, or `node:<peer-id>`). *Note: These are evaluated dynamically at the destination node using its own identity (see Section 3.1).*- * `allowed_agents`: The agent namespaces a node with this role can act for, such as `*.prod.acme.example`. When a node forwards a request for a sandboxed agent, it sends the agent's name alongside the token (see `internal/node/agent.go`). The receiving node accepts that name only if it matches one of these namespaces, and a node with no grant cannot name any agent. You can also use `agent:<id>` as a binding member to give a role to a named agent, but that is only as reliable as the namespace grant held by the node making the claim.- * `allowed_services`: Defines the application-level tools or endpoints a user can access. Services use a strict `type://name` convention (e.g., `mcp://db-agent` or `inference://openrouter`).- * **Strict Namespaces**: There are no implicit fallbacks. `system://...` is used for internal services, `mcp://...` for node services, `inference://...` for AI models, etc. Service names must be valid domain labels (e.g. `value1.value2.value3`).- * **Wildcards**: SAM natively supports domain-level wildcards to build complex policies. The control plane generates specific facts like `granted_service_exact($type, $name)`, `granted_service_prefix($type, $prefix)`, `granted_service_suffix($type, $suffix)`, `granted_service_all_in_type($type)`, or `granted_service_all_types()`. You can grant access to an entire type via `mcp://*`, allow prefix-based wildcard matching like `mcp://*.service.local` (which matches services ending in `.service.local`), suffix-based wildcard matching like `mcp://service.*` (which matches services starting with `service.`), or global access to everything via `*`.- * **MCP Namespace Convention**: The `mcp://` prefix (`api.MCPServicePrefix`) is the explicit convention for all Model Context Protocol targets.- * **The service is the unit of authorization — deliberately.** Mesh policy does not filter individual MCP tools inside a service. The mesh authorizes *names* (see the architecture's "a mesh name is the service namespace" decision), and a registered service is the operator's exposure decision: registering it offers its whole tool surface, exactly as the backend defines it. To offer different privilege tiers, split them into services — register a read-only backend as `mcp://db-reader` and a mutating one as `mcp://db-writer` (see the node configuration example in §6.2) and grant them to different roles. If a third-party MCP server bundles tools you do not want to offer, front it with a backend that exposes only the tools you mean to publish; curating the tool surface is the server registration's job, not the token's.-* **Bindings**: Map OIDC identities (sub/user, email, group) to specific Roles.--### 2.1 Updating Mesh Policy-Admins POST policy JSON updates to the Control Plane `/policies` endpoint using the admin authorization token:--```bash-curl -X POST \- -H "Authorization: Bearer <your-admin-token>" \- -H "Content-Type: application/json" \- -d '{- "roles": [- {- "name": "data-scientist-role",- "allowed_targets": ["group:backend-nodes", "node:12D3KooW..."],- "allowed_services": ["mcp://db-agent", "inference://openrouter", "mcp://*"]- }- ],- "bindings": [- {- "role": "data-scientist-role",- "members": ["group:data-science-team"]- }- ]- }' \- http://<control-plane-ip>:8080/policies-```--## 3. Node Local Policy Schema (`sam-node-config.yaml`)-Local developers can configure custom validation rules for their specific node under `attenuation:`. These rules are loaded directly into the main authorizer and evaluated entirely at the destination node.--```yaml-version: "v1alpha1"-attenuation:- checks:- - 'check if time($time), $time < 2026-12-31T00:00:00Z;'- policies:- - 'deny if user("untrusted_sub_id");'- - 'deny if service("mcp", "restricted-tool"), group("externals");'-```--### 3.1 Understanding Authorization Limits (Local vs. control plane)-The SAM network operates on a Zero Trust architecture where authorization is typically managed centrally by the control plane. However, local nodes have full sovereignty over their resources and can define their own authorization policies using the local `sam-node` configuration.--Local policies (defined under `attenuation.policies`) configure the **Verifier** on the local node.--* **Restrictive Policies (Deny)**: Local nodes can narrow down or restrict permissions granted by the control plane. For example, blocking users during off-hours, restricting specific contractors, or adding custom time-bound checks using `deny if` policies.-* **Permissive Policies (Allow)**: Local nodes can explicitly grant access to peers, overriding an **implicit deny** (e.g., when the control plane omits a `granted_service` fact). However, local allow policies **cannot bypass explicit constraints** (such as target restrictions or expirations) enforced via control-plane-injected `check if` statements. In Biscuit, all `check if` conditions must evaluate to true; if the control plane seals a token with a target restriction that the destination node does not satisfy, the request is unconditionally rejected regardless of any local `allow if` policies.---### 3.2 Evaluating `allowed_targets` at the Destination-The SAM network operates on a Zero Trust architecture. The origin node does not police its own traffic. When the control plane injects `allowed_targets` permissions (like `- "group:backend-nodes"`) into the token, it creates `granted_target_group("backend-nodes")` capability facts and seals the token with a `target_restricted()` fact. If no targets are specified, the control plane mints a `target_unrestricted()` fact.--It is up to the **destination node** to mathematically prove that it is the intended target. To do this, the destination node automatically injects its own identity into the local authorization context as target facts (e.g., `target_fact("group", "backend-nodes")`).--The destination node enforces this via a baseline check:-```datalog-check if allow_network_target($fact, $val) or target_unrestricted();-```--Because the target logic is baked directly into the node's middleware, you don't need to write manual Datalog rules for it. The node dynamically deduces `allow_network_target($fact, $val)` if any of its injected `target_fact`s match the `granted_target_*` facts presented in the incoming token.--If the token is `target_restricted()` and the destination node does not possess an identity matching the granted targets, the connection is instantly rejected.--> [!NOTE]-> **Policy Evaluation Precedence**-> Local policies defined in `sam-node-config.yaml` are evaluated **before** baseline rules. This means local administrators can write rules that explicitly `deny` access based on custom logic, overriding access granted by the control plane. While they can also use local `allow` policies to bypass control plane service capability constraints, all hardcoded baseline checks (OIDC signatures, replay defense, and target group restrictions) remain strictly enforced.--## 4. Node Baseline Security Rules--Every `sam-node` enforces a set of baseline security rules (defined in Go code) to secure the transport layer. These rules run automatically before evaluating custom OIDC or local policies:--### 4.1 Replay & Impersonation Prevention-Every request must prove that the libp2p cryptographic peer ID of the connection matches the client peer ID embedded in the authorization token:-```datalog-check if client_peer_id($id), connection_peer_id($id);-```--### 4.2 The Catalog Service (`sam.catalog`)-To allow remote peers to discover tools and query connectivity, each node hosts a built-in catalog service at the special target `sam.catalog`. This service exposes local metadata tools (e.g. `list_local_services`, `get_mesh_info`).--Access to the catalog service is not granted by default and must be explicitly permitted (e.g. via a control plane role mapping allowing `system://sam.catalog` to verified nodes) to facilitate peer-to-peer discovery.--Example policy allowing catalog discovery:-```datalog-allow if service("system", "sam.catalog");-```--## 5. Ingress Authorization Pipeline (Execution Flow)--When a node receives an incoming connection request (via P2P HTTP Ingress or wrapped protocol streams like MCP/Inference), it performs a multi-stage verification pipeline.--### 5.1 Pipeline Stages--```mermaid-graph TD- A[Incoming Connection] --> B(Stage 1: Connection Gating)- B -->|Banned/Revoked| C[Drop Connection]- B -->|Allowed| D(Stage 2: Biscuit Token Verification)- D --> E[Run 1: Authorize Node's Own Identity Token]- E --> F[Query & Inject Destination Target Facts]- F --> G[Run 2: Authorize Caller's Request Token]- G -->|Success| H[Proxy to Downstream Service]- G -->|Denied| I[Return 403 Forbidden / Reject Auth Frame]-```--1. **Stage 1: Connection Gating (Layer 2)**- - Performed immediately at the connection manager level (`gate.go`).- - Checks the remote peer ID against local blacklist (`Store.IsBanned`) and revocation caches (`revokedPeers`).- - Does not parse Biscuit tokens. Connection is dropped early if matched.--2. **Stage 2: Biscuit Token Verification (Layer 3/4)**- - Handled inside node middleware (`middleware.go`).- - Performs exactly **two Biscuit authorizer execution runs** to process authorization:--#### Run 1: Destination Identity Fact Evaluation-- **Target**: The node's **own identity token** (issued by the control plane during enrollment).-- **Purpose**: We must mathematically evaluate the node's own OIDC group/user claims and node ID to produce `target_fact(...)` datalog assertions (e.g. `target_fact("group", "backend-nodes")`). These facts represent *who we are*.-- **Mechanism**:- 1. We create an authorizer for our own token signed by the control plane's public key.- 2. We add a baseline `allow if true` policy. This policy is required by Biscuit so that the authorizer can execute (since the token itself holds only identity facts and has no operation-level authorization policies).- 3. We execute `Authorize()` to verify our token signature and validate internal checks (such as expiration).- 4. We query `api.TargetFactRules` against this authorizer to extract target facts.- 5. We inject these extracted `target_fact` assertions into the main request authorizer.--#### Run 2: Caller Request Authorization-- **Target**: The caller's **request token** (the Biscuit token presented in the request's `X-Sam-Biscuit` header or `AuthFrame`).-- **Purpose**: Verifies that the caller has been granted access by the control plane to the requested target service, checks for replay protection, and evaluates local attenuation constraints.-- **Mechanism**:- 1. We create an authorizer for the caller's token using the control plane's public key.- 2. We inject the target matching facts derived from Run 1.- 3. We add baseline rules (e.g. peer ID matching connection ID check, system catalog access policies) and local attenuation configurations (`sam-node-config.yaml`).- 4. We execute `Authorize()` to check all signatures, checks, and policies. If successful, the request is forwarded to the underlying service.--## 6. Comprehensive Mesh Policy Example--Here is a representative configuration for an engineering mesh deployment. It shows how to use roles, target groups, service namespaces, wildcards, and local attenuation checks to build a zero-trust development network.--### 6.1 Central control plane policy API update--Send this JSON payload via `POST /policies` to define global roles and user/service-account mappings.--```json-{- "roles": [- {- "name": "admin",- "allowed_targets": ["*"],- "allowed_services": ["*"]- },- {- "name": "developer",- "allowed_targets": ["group:dev-nodes"],- "allowed_services": ["mcp://code-reviewer", "mcp://git-helper", "mcp://build-runner.*"]- },- {- "name": "data-scientist",- "allowed_targets": ["group:data-nodes", "node:12D3KooWSpecialNode"],- "allowed_services": ["mcp://db-reader", "inference://*"]- },- {- "name": "auditor",- "allowed_targets": ["*"],- "allowed_services": ["system://sam.catalog"]- }- ],- "bindings": [- {- "role": "admin",- "members": ["user:system:serviceaccount:sam-mesh:admin-sa", "group:infrastructure-leads"]- },- {- "role": "developer",- "members": ["group:software-engineering-team"]- },- {- "role": "data-scientist",- "members": ["group:data-science-team"]- },- {- "role": "auditor",- "members": ["email:[email protected]"]- }- ]-}-```--### 6.2 Node-Level Configuration (`sam-node-config.yaml`)--Deploy this file on a specific database node in the `data-nodes` group to register services and enforce local restrictions.--```yaml-version: "v1alpha1"--# Static services hosted by this local node-services:- - type: "mcp"- name: "db-reader"- description: "Read-only SQL execution tool"- target_url: "http://127.0.0.1:5001/mcp"-- - type: "mcp"- name: "db-writer"- description: "Database modification tool"- target_url: "http://127.0.0.1:5002/mcp"--# Local policies further restrict or override permissions on this specific node-attenuation:- # local rules generate new facts based on existing ones- rules:- # e.g., 'is_off_hours() <- current_hour($h), $h >= 21;'-- # local checks must be satisfied for any connection to succeed- checks:- # 1. Enforce strict TLS certificate expiry limit- - 'check if time($time), $time < 2026-12-31T23:59:59Z;'-- # local policies can contain deny rules (to restrict control plane grants) or allow rules (to override implicit denies)- policies:- # 2. Block db-writer calls during off-hours (9 PM to 6 AM)- - 'deny if service("mcp", "db-writer"), current_hour($hour), $hour >= 21;'- - 'deny if service("mcp", "db-writer"), current_hour($hour), $hour < 6;'-- # 3. Restrict contractors from accessing db-writer even if the control plane granted it- - 'deny if service("mcp", "db-writer"), role("contractor");'-- # 4. Explicitly allow local admin bypass- - 'allow if user("local-admin");'-```diff --git a/site/content/docs/development/release-tracks.md b/site/content/docs/development/release-tracks.mddeleted file mode 100644index 4c1048a9..00000000--- a/site/content/docs/development/release-tracks.md+++ /dev/null@@ -1,44 +0,0 @@-----title: "Release Tracks, Autoupdate, and Autoscaling"-linkTitle: "Release Tracks, Autoupdate, and Autoscaling"-----Sovereign Agent Mesh (SAM) is deployed to public endpoints using automated environments, release tracks, and self-healing/scaling infrastructure.-------## 1. Public Developer Testnets--> [!NOTE]-> **Developer Testnets Disclaimer:**-> Both public endpoints (`bananas.sam-mesh.dev` and `hub.sam-mesh.dev`) are **developer testnets created using community resources**. They are provided solely for testing, continuous integration, and rapid experimentation with the open-source codebase. They carry **no guarantees, no uptime commitments, and zero SLA**, and are not sovereign. For production workloads or strict data sovereignty, operators should deploy a dedicated mesh with customer-held keys using the [Helm chart](https://github.com/google/sam/tree/main/charts/sam-mesh) or [Kubernetes deployment guide](../user/kubernetes-deployment/). See [Digital & Data Sovereignty](../sovereignty/) for full architectural details.--The public developer deployment maintains two isolated testnet tracks:--### A. Bleeding-Edge Testnet Track (Bananas)-* **Domain Name:** `bananas.sam-mesh.dev`-* **Source Branch:** Tracks the `main` branch.-* **Deployment Trigger:** Automatically deployed on every new push/commit to the `main` branch.-* **Target Tag:** The deployment is tagged with the Git commit SHA (`github.sha`).-* **Purpose:** Serves as the continuous integration and staging testbed for the latest unreleased features.--### B. Release-Tagged Testnet Track (Hub)-* **Domain Name:** `hub.sam-mesh.dev`-* **Source Branch:** Tracks semantic version tags matching `v*.*.*`.-* **Deployment Trigger:** Automatically deployed whenever a new version tag is pushed to GitHub.-* **Target Tag:** The deployment is tagged with the exact Git release tag (e.g. `v1.0.0`).-* **Purpose:** Public testbed running tagged releases for developer interoperability testing.------## 2. Autoupdate Mechanism--Updates to both release tracks are fully automated via a robust **Continuous Deployment** pipeline:--1. **GitHub Actions Trigger:** The workflow defined in [.github/workflows/deploy.yaml](../.github/workflows/deploy.yaml) is automatically triggered by repository events (pushing to main or pushing a version tag).-2. **Determining the Track & Tag:**- * If the event is a release tag, the pipeline dynamically targets the `hub` GitHub environment and sets the container image tag to the release version.- * Otherwise, it targets the `bananas` environment and sets the container image tag to the Git commit SHA.-3. **Rolling Updates:**- * Images are built and pushed to GitHub Container Registry (`ghcr.io`).- * The workflow executes `kubectl apply` on the Kubernetes templates.- * Kubernetes uses a `RollingUpdate` strategy, updating the pods one-by-one. This guarantees **zero-downtime** updates while replacing running processes with the new version.- * The workflow executes `kubectl rollout status` to verify that the new pods become healthy and ready. If an update fails, GKE automatically rolls back to the previous stable version.diff --git a/site/content/docs/development/testing.md b/site/content/docs/development/testing.mddeleted file mode 100644index ad59f968..00000000--- a/site/content/docs/development/testing.md+++ /dev/null@@ -1,111 +0,0 @@-----title: "Testing"-linkTitle: "Testing"-----Current testing is intentionally minimal and aligned with the current binaries.--## Test Layers--1. Go tests: `make test`-2. BATS CLI tests: `make test-e2e`-3. Containerized BATS mesh tests: `make test-e2e-container`-4. Console UI tests: `make ui-test`--## Commands--```bash-make build-make test-make test-e2e-make test-e2e-container-make ui-test-```--## Go Tests--Run all Go tests with race detection:--```bash-make test-```--Run only integration package:--```bash-go test ./tests/integration/...-```--## BATS CLI Tests--These tests validate current command behavior for:--- `sam-node`-- `sam-control-plane`-- `sam-router`--Run:--```bash-make test-e2e-```--## Containerized Mesh BATS--The container framework is implemented in:--- `tests/e2e/lib/container_mesh.bash`--It starts:--1. mock OIDC container-2. `sam-control-plane` container-3. `sam-router` container-4. multiple `sam-node` containers--Run:--```bash-make test-e2e-container-```--Optional image override:--```bash-MESH_RUNTIME_IMAGE=sam-e2e-runtime:dev make test-e2e-container-```--## Console UI--Playwright drives the console in `tests/ui/console.spec.js`. The stack is built-in `tests/ui/lib/stack.sh` and runs entirely as local processes against a-throwaway sqlite database, so no docker, kind or postgres is involved.--```bash-make ui-test-make ui-test WHAT="policy editor" # --grep a subset-```--To click around that same stack instead of asserting against it:--```bash-make ui-dev-```--That seeds a mesh policy, enrolls a router and a node with bootstrap tokens, then-leaves the console running with its URL and admin token printed. Only the OIDC-issuer is a stand-in: it serves a discovery document but cannot sign tokens,-which is why enrollment uses bootstrap tokens rather than a JWT.--The console serves its static assets from `internal/console/public`, so edits to-the HTML, CSS or JS need only a browser refresh; only Go changes need a rebuild.--## Troubleshooting--- Ensure Docker daemon is running before container tests.-- Ensure `bats` is installed and available in `PATH`.-- If a test fails, inspect containers:--```bash-docker ps -a-docker logs <container-name>-```diff --git a/site/content/docs/development/testnet-validation.md b/site/content/docs/development/testnet-validation.mddeleted file mode 100644index e3c35143..00000000--- a/site/content/docs/development/testnet-validation.md+++ /dev/null@@ -1,146 +0,0 @@-----title: "Testnet & Mesh Validation Tutorial"-linkTitle: "Testnet & Mesh Validation Tutorial"-----This tutorial guides you through validating your local environment integration with the public Sovereign Agent Mesh (SAM) testnets (`bananas.sam-mesh.dev` or `hub.sam-mesh.dev`). You will learn how to verify your node's connection, discover remote MCP services, and invoke remote tools.--> [!NOTE]-> **Community Testnet Notice:**-> The public testnets are hosted using community resources and are provided strictly for developer testing, debugging, and experimentation. There are **no guarantees, uptime warranties, or SLA**. Do not deploy production agents or transmit sensitive data on public testnets.-------## Prerequisites--Before starting, ensure you have:-1. Compiled the local binaries (`sam-node` and `mcp-client`) by running:- ```bash- make build- ```-2. An active local `sam-node` container or process running and successfully joined to the target public testnet.- For example, join via:- ```bash- bin/sam-node join https://bananas.sam-mesh.dev- ```- And run via:- ```bash- docker run --name sam-node \- --user "$(id -u):$(id -g)" \- -v ~/.config/sam-mesh:/data \- -p 5001:5001/udp -p 5002:5002 -p 8080:8080 \- sam-node:local \- run --data-dir /data \- --control-plane https://bananas.sam-mesh.dev \- --bind-addr 0.0.0.0:8080 \- # api token via SAM_API_TOKEN env or --api-token-path \- --log-level debug- ```-------## Step 1: Verifying Local Connection to the Testnet--Check the logs of your local `sam-node` to ensure it has successfully joined and is online:-```text-INFO sam-node [AuthN] Successfully authenticated with router via libp2p-SAM Node Online.-PeerID: 12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR-```-------## Step 2: Discovering Remote Services on the Testnet--Use the local `mcp-client` binary against your local node to discover active services of type `mcp` on the public testnet:--```bash-bin/mcp-client -url http://localhost:8080 -stream -token secret-token -args '{"type":"mcp"}'-```--You will see discovered remote peer details in real-time, including proxy endpoint URLs for any running canary/test replicas on GKE:-```json-{"peer_id":"12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR","local_proxy_url":"http://[::]:8080/sam/12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR/mcp/everything","srv_name":"everything","srv_description":"MCP everything test server"}-```-Note down the remote `peer_id` of the service you want to target (e.g. `everything` or `openclaw`).-------## Step 3: Invoking Tools via the Control Plane--You can invoke control plane tools on your local `sam-node` to locate, query, and invoke remote tools.--### List Local Control Plane Tools-```bash-bin/mcp-client -url http://localhost:8080/mcp -token secret-token -list-```--### Find Remote Tools on a Specific Peer-```bash-bin/mcp-client -url http://localhost:8080/mcp -token secret-token -tool find_remote_tools -args '{"peer_id":"12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR"}'-```-This returns the list of available tools (e.g., `everything.get-sum`, `everything.echo`).--### Inspect Tool Schemas-```bash-bin/mcp-client -url http://localhost:8080/mcp -token secret-token -tool describe_remote_tool -args '{"peer_id":"12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR", "tool_name":"everything.get-sum"}'-```--### Call the Remote Tool-```bash-bin/mcp-client -url http://localhost:8080/mcp -token secret-token -tool call_remote_tool -args '{"peer_id":"12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR", "tool_name":"everything.get-sum", "arguments":{"a":37.5, "b":5.2}}'-```-Response:-```text-The sum of 37.5 and 5.2 is 42.7.-```-------## Step 4: Bypassing the Control Plane (HTTP Proxy & Streamable HTTP)--The `sam-node` includes an HTTP reverse proxy endpoint at `/sam/` which maps raw HTTP calls over P2P streams to the target service. For services using the **Streamable HTTP** transport, you can manage sessions and retrieve resources directly:--### 1. Initialize a Streamable Session-Initiate a handshake by sending a POST `initialize` JSON-RPC request. You must supply both `Accept` and `Mcp-Session-Id` headers to satisfy the transport:--```bash-curl -i -X POST \- -H "X-Sam-Authentication: Bearer secret-token" \- -H "Content-Type: application/json" \- -H "Accept: application/json, text/event-stream" \- -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}' \- http://localhost:8080/sam/12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR/mcp/everything/-```--Observe the response headers. The server returns a session ID:-```http-HTTP/1.1 200 OK-Mcp-Session-Id: 4616e90e-a1a9-4953-b7d3-6884ff502472-Content-Type: text/event-stream-```--### 2. List Remote Resources-Use the returned session ID to query the remote service's resource list:--```bash-curl -s -X POST \- -H "X-Sam-Authentication: Bearer secret-token" \- -H "Mcp-Session-Id: 4616e90e-a1a9-4953-b7d3-6884ff502472" \- -H "Content-Type: application/json" \- -H "Accept: application/json, text/event-stream" \- -d '{"jsonrpc":"2.0","id":2,"method":"resources/list"}' \- http://localhost:8080/sam/12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR/mcp/everything/-```--### 3. Read Resource Content-Request the contents of a specific resource URI (e.g. `demo://resource/static/document/features.md`):--```bash-curl -s -X POST \- -H "X-Sam-Authentication: Bearer secret-token" \- -H "Mcp-Session-Id: 4616e90e-a1a9-4953-b7d3-6884ff502472" \- -H "Content-Type: application/json" \- -H "Accept: application/json, text/event-stream" \- -d '{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"demo://resource/static/document/features.md"}}' \- http://localhost:8080/sam/12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR/mcp/everything/-```diff --git a/site/content/docs/getting-started/_index.md b/site/content/docs/getting-started/_index.mdnew file mode 100644index 00000000..a7033be7--- /dev/null+++ b/site/content/docs/getting-started/_index.md@@ -0,0 +1,10 @@+---+title: "Getting started"+linkTitle: "Getting started"+weight: 1+---++Two short walkthroughs. The first puts one node on the public testnet and+calls a tool through it, which is enough to see what a node does. The+second runs a complete mesh of your own on a laptop with `sam-one`, which is+the shape every real deployment takes.diff --git a/site/content/docs/getting-started/quickstart.md b/site/content/docs/getting-started/quickstart.mdnew file mode 100644index 00000000..ccc02b94--- /dev/null+++ b/site/content/docs/getting-started/quickstart.md@@ -0,0 +1,167 @@+---+title: "Quick start"+linkTitle: "Quick start"+weight: 1+aliases:+ - /docs/quickstart/+---++This page installs `sam-node`, enrolls it in the public `bananas.sam-mesh.dev`+testnet, and calls a tool hosted by another node. It takes a few minutes.++The testnet is a shared developer playground with no uptime commitment. See+[About the public testnets](../../#about-the-public-testnets). The steps are+the same for any mesh: replace the URL with your own control plane.++## 1. Install++On Linux and macOS, the install script downloads the latest release and+places the binaries in `/usr/local/bin`:++```bash+curl -sL https://sam-mesh.dev/install.sh | bash+```++With a Go toolchain, you can build from source instead:++```bash+go install github.com/google/sam/cmd/sam-node@latest+go install github.com/google/sam/cmd/mcp-client@latest+```++On Windows, download `sam_Windows_x86_64.zip` from the+[releases page](https://github.com/google/sam/releases) and put `sam-node.exe`+on your `PATH`.++## 2. Enroll++A node needs an identity before it can join a mesh. `sam-node join` obtains one+by logging you in with the mesh's identity provider and registering the node's+key with the control plane:++```bash+sam-node join https://bananas.sam-mesh.dev+```++The command opens a browser for the login. If no browser is available, it+prints a URL and a code to enter on another device. When the login completes,+the credential is stored under `~/.config/sam-mesh/`. You do this once per+machine. Later starts reuse the stored identity and renew it automatically.++## 3. Run the node++```bash+sam-node run --daemonize+```++The node starts in the background, connects to the mesh, and prints where its+local API is:++```text+sam-node is running in the background.+ PID 48213+ Endpoint http://127.0.0.1:8080/mcp+ Socket /home/you/.config/sam-mesh/sam.sock+ Token /home/you/.config/sam-mesh/api-token+ Logs /home/you/.config/sam-mesh/sam-node.log+ Stop kill 48213+```++The local API is served on two listeners. The TCP port requires the token+from the file shown. The Unix socket requires no token, because only your+user can open it. `--daemonize` generates the token on first use. To choose+the token yourself, set `SAM_API_TOKEN` or pass `--api-token-path`. Run the+command without `--daemonize` to keep the node in the foreground.++You can run `sam-node run --daemonize` again at any time. If a node is+already running, the command does not start a second one. It prints the+address of the running node and exits.++## 4. Call a tool on the mesh++The node's local API is an MCP server. `mcp-client` is installed together+with `sam-node` and is the quickest way to talk to it. Export the token once:++```bash+export TOKEN=$(cat ~/.config/sam-mesh/api-token)+```++List the tools the node itself offers:++```bash+mcp-client -url http://127.0.0.1:8080/mcp -token "$TOKEN" -list+```++Find MCP services other nodes are publishing:++```bash+mcp-client -url http://127.0.0.1:8080/mcp -token "$TOKEN" \+ -tool discover_remote_services -args '{"type":"mcp"}'+```++Each result carries a `peer_id`. Ask one of them which tools it hosts:++```bash+mcp-client -url http://127.0.0.1:8080/mcp -token "$TOKEN" \+ -tool find_remote_tools -args '{"peer_id":"<peer-id>"}'+```++Then call one. The testnet runs the MCP reference `everything` server as a+demo. Its `add` tool adds two numbers:++```bash+mcp-client -url http://127.0.0.1:8080/mcp -token "$TOKEN" \+ -tool call_remote_tool \+ -args '{"peer_id":"<peer-id>","tool_name":"mcp://everything/add","arguments":{"a":2,"b":3}}'+```++The call left your machine over an authenticated peer-to-peer connection.+The node that hosts the service checked the mesh policy, ran the tool, and+returned the result the same way. Any MCP client can make the same calls.++## 5. Give your agent the skill++The MCP tools tell an agent what it can do. The SAM skill tells it when and+how to use them: start a node, discover services, describe a tool before+calling it, reach a mesh inference model. Install it once:++```bash+sam-node skill install+```++This writes `SKILL.md` into the directories that the common agent harnesses+read: `~/.claude/skills/sam-mesh/` for Claude Code and Claude Desktop, and+`~/.gemini/config/skills/sam-mesh/` for Antigravity. Then register the node's+MCP endpoint with your agent. [Connecting agents](../../guides/connecting-agents/)+has the configuration for each client.++With the skill installed, you can ask an agent to "connect to the mesh" and+it brings a node online by itself. The one step it cannot do for you is the+`sam-node join` login, which requires a person.++## Starting over++The node reuses whatever is in its data directory. To forget the mesh+identity but keep the node's key:++```bash+sam-node reset+```++To delete everything the node stores, including its key (the node gets a new+peer ID and must enroll again):++```bash+sam-node reset --all+```++Both commands refuse to run while a node is up. Stop the node first with the+`kill` command from the `--daemonize` output.++## Next++- [Your own mesh](../your-own-mesh/) runs a control plane and router on your+ laptop in one command.+- [Exposing services](../../guides/exposing-services/) publishes a tool or a+ model from your node.+- [Architecture](../../concepts/architecture/) explains what just happened.diff --git a/site/content/docs/getting-started/your-own-mesh.md b/site/content/docs/getting-started/your-own-mesh.mdnew file mode 100644index 00000000..8a68629e--- /dev/null+++ b/site/content/docs/getting-started/your-own-mesh.md@@ -0,0 +1,197 @@+---+title: "Your own mesh"+linkTitle: "Your own mesh"+weight: 2+aliases:+ - /docs/user/device-enrollment/+---++The quick start joined a mesh that someone else runs. This page runs one for+you: a control plane, a router and a web console on your laptop, in one+process, with two nodes talking through it. `sam-one` runs the same code as a+Kubernetes deployment, so what you learn here applies there too.++You need the `sam-one`, `sam-node` and `mcp-client` binaries. The+[install script](../quickstart/#1-install) provides all three.++## 1. Start the control plane++```bash+sam-one --data-dir ~/sam-one+```++`--data-dir` holds the database, the router's key and the generated tokens.+If you delete it, you get a new mesh. After a moment `sam-one` prints a+banner:++```text+══════════════════════════════════════════════════════════════════+SAM standalone mesh is ready!++API URL: http://0.0.0.0:33775+Web Console: http://0.0.0.0:33775/console+Router Peer: 12D3KooWBzUDQCkZhz2rWrYBhpjcCH8VnrRNcwCW6DoF36iADYrY+Admin Token: sam_adm_…+Join Token: sam_tok_…++To enroll a node:+ sam-node join http://0.0.0.0:33775 --bootstrap-token-path /home/you/sam-one/join-token+══════════════════════════════════════════════════════════════════+```++`sam-one` picked a free port. Pass `--port 8080` for a fixed one. The **join+token** is a standing bootstrap token that lets nodes enroll without an+identity provider. The **admin token** authenticates the console and the+admin API. Both are also written to files in the data directory, and the rest+of this page reads them from there.++On first boot, `sam-one` seeds an open development policy and logs a warning+about it: any enrolled node may register any service and call any service.+This is a reasonable default for a laptop and a bad one for anything shared.+The last section explains how to replace it.++## 2. Publish a service from one node++Any HTTP backend can be a mesh service. Start a simple one and declare it in+a node configuration file:++```bash+mkdir -p /tmp/www && echo "hello from node a" > /tmp/www/hello.txt+python3 -m http.server 9000 --bind 127.0.0.1 --directory /tmp/www &++cat > ~/node-a.yaml <<'EOF'+version: "v1alpha1"+services:+ - type: mcp+ name: hello+ description: "a static file, served over the mesh"+ target_url: "http://127.0.0.1:9000"+EOF+```++Then run a node with it. Substitute the port from your banner:++```bash+URL=http://127.0.0.1:33775++sam-node run --control-plane $URL \+ --bootstrap-token-path ~/sam-one/join-token \+ --config ~/node-a.yaml \+ --data-dir ~/node-a --bind-addr= --allow-loopback --listen /ip4/127.0.0.1/tcp/0+```++Three of these flags are only needed because both nodes run on one machine.+`--bind-addr=` (an empty value) keeps the node's local API on its Unix socket,+so the two nodes do not compete for port 8080. `--allow-loopback` lets the+nodes advertise and dial `127.0.0.1`. `--listen .../tcp/0` picks a free+peer-to-peer port. On separate machines you would not pass any of them.++The node enrolls with the join token, connects to the router and prints its+peer ID:++```text+SAM Node Online.+PeerID: 12D3KooWSCnbUoZ8Jv3EKGv17LqEWtnTMfZ3XYJUg2WTm5Gz2hUK+```++Keep that value.++## 3. Call it from another node++In a second terminal, start a node with no services:++```bash+URL=http://127.0.0.1:33775++sam-node run --control-plane $URL \+ --bootstrap-token-path ~/sam-one/join-token \+ --data-dir ~/node-b --bind-addr= --allow-loopback --listen /ip4/127.0.0.1/tcp/0+```++Every node's local API includes a proxy at `/sam/<peer-id>/<type>/<name>/`+that forwards to a service on another node. Ask node B for node A's file:++```bash+PEER_A=12D3KooWSCnbUoZ8Jv3EKGv17LqEWtnTMfZ3XYJUg2WTm5Gz2hUK++curl --unix-socket ~/node-b/sam.sock "http://localhost/sam/$PEER_A/mcp/hello/hello.txt"+# hello from node a+```++The request went from B's socket to B, then over an authenticated connection+to A, through A's policy check, to the Python server, and back. If A and B+cannot reach each other directly, the connection is relayed through the+router inside `sam-one`. Allow a few seconds after A starts for B to learn+about it. Nodes announce their services in a discovery table that the router+hosts, and the announcement takes a moment to arrive.++An MCP backend works the same way. The difference is that the node+understands the protocol: the service appears in `discover_remote_services`+and its tools in `find_remote_tools`, as on the testnet.++## 4. Look at it in the console++Open `http://127.0.0.1:33775/console` and paste the admin token. The console+shows the enrolled nodes, the router, the services each node reports, the+bootstrap tokens with their remaining uses, and the mesh policy. You can edit+the policy in place.++The same operations are available from the command line. `sam-one` is also+an admin client for a running server. It reads the admin token from the data+directory, from `SAM_ADMIN_TOKEN`, or from `--admin-token-path`, never from a+flag value:++```bash+sam-one token list --server $URL --data-dir ~/sam-one+sam-one token create --server $URL --data-dir ~/sam-one --description "node c" --max-usages 1+sam-one token revoke <token-id> --server $URL --data-dir ~/sam-one+sam-one admin ban <peer-id> --server $URL --data-dir ~/sam-one+```++## Reaching it from other machines++Everything above used `http://127.0.0.1`. `sam-node` accepts a plain `http`+URL only when the control plane is on the same host. A node on another+machine needs an `https` URL, because the control plane is the node's trust+root and SAM refuses to fetch it over plaintext from a remote address.++On a laptop behind NAT, the quickest way to get an `https` URL is a temporary+tunnel:++```bash+sam-one --data-dir ~/sam-one --tunnel cloudflare+```++This publishes the port on a random `trycloudflare.com` hostname, with no+account needed, and prints that URL in the banner. If `cloudflared` is not+installed, `sam-one` offers to download a pinned, checksum-verified release+into the data directory. `--tunnel-install` accepts the download without+asking. Nodes on any network then enroll with the same+`sam-node run --control-plane <url> --bootstrap-token-path <file>` command,+without the loopback flags.++If you have a real hostname and a reverse proxy in front, pass+`--external-url https://mesh.example.com` instead. The+[Cloud Run guide](../../guides/cloud-run/) shows a hosted variant.++With `--tunnel` or any other `https` URL, `sam-one` also prints a QR code+that enrolls a phone running the SAM Connect app. That app is in+[preview](../../preview/mobile/).++## Before you rely on it++- **Policy**: replace the open development policy. Write a+ [mesh policy](../../reference/policy/) file and start `sam-one` with+ `--policy-file` on a fresh data directory, or edit the policy in the+ console. Once the database has a policy, the database is the source of+ truth.+- **Enrollment**: run with `--no-join-token` so nodes can only enroll with+ tokens you mint (`sam-one token create`, single-use by default), or give+ the mesh an identity provider with `--issuer` and let people log in.+- **State**: keep the data directory on durable storage, or point+ `--db-driver postgres --db-dsn ...` at a database.+- **Tokens in logs**: read the admin token from `SAM_ADMIN_TOKEN` or+ `--admin-token-path` instead of the banner, and pass `--enroll-qr=false`+ in non-interactive environments.++The [sam-one reference](../../reference/sam-one/) lists every flag.diff --git a/site/content/docs/guides/_index.md b/site/content/docs/guides/_index.mdnew file mode 100644index 00000000..1f75dd37--- /dev/null+++ b/site/content/docs/guides/_index.md@@ -0,0 +1,13 @@+---+title: "Guides"+linkTitle: "Guides"+weight: 3+aliases:+ - /docs/user/+ - /docs/integrations/+---++Step-by-step pages for common tasks: publish a service, connect an agent+client, enroll machines that cannot log in, and deploy a control plane on+Kubernetes or Cloud Run. Each page assumes that you have read the+[quick start](../getting-started/quickstart/).diff --git a/site/content/docs/guides/cloud-run.md b/site/content/docs/guides/cloud-run.mdnew file mode 100644index 00000000..f131c1ab--- /dev/null+++ b/site/content/docs/guides/cloud-run.md@@ -0,0 +1,132 @@+---+title: "Cloud Run"+linkTitle: "Cloud Run"+weight: 5+aliases:+ - /docs/user/cloud-run-deployment/+---++`sam-one` serves its HTTP API, the console and the router's WebSocket+transport on one port. That is the shape Cloud Run expects. This guide+deploys it there, joins nodes from anywhere, and lists what changes when+`sam-one` runs on Cloud Run. The same steps apply to any platform that+forwards HTTP and WebSockets to a container.++## 1. Build and push++```bash+PROJECT=my-project+REGION=us-central1+IMG=${REGION}-docker.pkg.dev/${PROJECT}/sam-mesh/sam-one:latest++docker build -f Dockerfile.sam-one -t "$IMG" .+gcloud auth configure-docker ${REGION}-docker.pkg.dev+docker push "$IMG"+```++## 2. Deploy++Cloud Run has no persistent disk, so the join and admin tokens are set+through environment variables. Without this, a new instance would generate+new tokens and nodes that enrolled earlier could not renew.++```bash+JOIN_TOKEN="sam_tok_$(openssl rand -hex 16)"+ADMIN_TOKEN="sam_adm_$(openssl rand -hex 16)"++gcloud run deploy sam-one \+ --project "$PROJECT" --region "$REGION" \+ --image "$IMG" \+ --allow-unauthenticated \+ --min-instances 1 --max-instances 1 \+ --port 8080 \+ --no-cpu-throttling \+ --timeout 3600 \+ --set-env-vars "SAM_TOKEN=${JOIN_TOKEN},SAM_ADMIN_TOKEN=${ADMIN_TOKEN}"+```++Each flag is needed:++- `--min-instances 1 --max-instances 1`: the router's DHT and relay state+ live in the one process. Two instances would be two separate meshes behind+ one URL.+- `--no-cpu-throttling`: the router runs background loops (lease renewal,+ key sync, DHT maintenance) between requests.+- `--timeout 3600`: Cloud Run limits the lifetime of a streaming request,+ and each node's WebSocket connection is one. Nodes reconnect when the limit+ closes a connection, but a low value causes unnecessary reconnects.+- `--allow-unauthenticated`: the mesh authenticates its own callers. Cloud+ Run's IAM check would block nodes before they could present a credential.++The router needs to know its public URL so that it can advertise an address+that nodes can dial. The URL only exists after the first deploy:++```bash+URL=$(gcloud run services describe sam-one --project "$PROJECT" --region "$REGION" \+ --format='value(status.url)')++gcloud run services update sam-one --project "$PROJECT" --region "$REGION" \+ --update-env-vars "SAM_EXTERNAL_URL=${URL}"+```++## 3. Verify++```bash+curl -s "$URL/readyz" # 200+curl -s "$URL/info" | head -c 200 # contains /dns4/<host>/tcp/443/wss/p2p/<peer-id>+```++The console is at `$URL/console`. Use `/readyz` for probes. `/healthz` is+reserved by Cloud Run's frontend on `run.app` domains and never reaches the+container.++## 4. Join nodes++```bash+echo -n "$JOIN_TOKEN" > join-token+sam-node run --control-plane "$URL" --bootstrap-token-path join-token+```++The node enrolls over HTTPS, reads the router's `wss` address from `/info`,+and connects through the same port. Nodes behind NAT reach each other+through relay circuits on the Cloud Run instance, so neither node needs an+inbound port. Pass `--announce-private=false` to the nodes so that they do+not advertise LAN addresses that no remote peer can use.++Publishing and calling a service works as in+[your own mesh](../../getting-started/your-own-mesh/): declare the service in+`sam-node.yaml` on one node, and call it through+`/sam/<peer-id>/<type>/<name>/` on another.++## 5. Administer++`sam-one` is also the admin client. With `SAM_ADMIN_TOKEN` exported:++```bash+sam-one token create --server "$URL" --role sam:role:node --max-usages 1+sam-one token qr --server "$URL"+sam-one token list --server "$URL"+sam-one token revoke <token-id> --server "$URL"+sam-one admin ban <peer-id> --server "$URL"+```++## What Cloud Run changes++- **State is ephemeral.** The SQLite database is in the container's memory.+ When an instance restarts, it forgets enrolled nodes and minted tokens,+ and the router gets a new peer ID. Nodes read `/info` again and re-enroll+ with the pinned join token. For state that survives restarts, point+ `--db-driver postgres --db-dsn <dsn>` at a managed database, or run+ `sam-one` on a VM with a disk.+- **Rollouts overlap.** During a deploy, `/info` may advertise the new+ instance while some WebSocket upgrades still reach the old one. Nodes+ detect the peer ID mismatch and retry. Joins succeed once the old revision+ has drained.+- **One source IP for everyone.** All traffic arrives from a small number of+ frontend proxies. `sam-one` raises libp2p's per-source-IP connection limit+ for this automatically. A separate `sam-router` behind a proxy needs+ `--conns-per-source-ip` raised by hand.+- **Policy.** First boot seeds the open development policy. Build a+ `--policy-file` into the image or post a policy after the deploy, and run+ with `--no-join-token` once you mint per-device tokens. The+ [sam-one reference](../../reference/sam-one/) lists the flags.diff --git a/site/content/docs/guides/connecting-agents.md b/site/content/docs/guides/connecting-agents.mdnew file mode 100644index 00000000..ea7c8b04--- /dev/null+++ b/site/content/docs/guides/connecting-agents.md@@ -0,0 +1,239 @@+---+title: "Connecting agents"+linkTitle: "Connecting agents"+weight: 2+aliases:+ - /docs/user/agent-usage/+ - /docs/integrations/claude-code/+ - /docs/integrations/claude-desktop/+ - /docs/integrations/antigravity/+ - /docs/integrations/gemini/+ - /docs/integrations/openclaw/+ - /docs/integrations/vscode-copilot/+---++An agent uses the mesh through the `sam-node` that runs on its own machine.+The node is an MCP server, so you can point any MCP client at it. This guide+gives the configuration for the common clients and explains what the agent+gets.++## What every client needs++Three values, all printed by `sam-node run --daemonize`:++- **The endpoint**: `http://127.0.0.1:8080/mcp` (Streamable HTTP).+- **The token**: the contents of `~/.config/sam-mesh/api-token`, or the+ `SAM_API_TOKEN` you started the node with. It goes in the header+ `X-Sam-Authentication: Bearer <token>`.+- **The socket**: `~/.config/sam-mesh/sam.sock`. Anything the agent runs in a+ shell can use the socket without a token. This is the easier way to reach+ the node's `/v1` inference endpoint from scripts.++The node must be running before the client starts. MCP clients start and+manage stdio servers themselves, but `sam-node` is an HTTP server that they+connect to. You can run `sam-node run --daemonize` as often as you like, so it+is safe to put it in a shell profile or to let the agent run it.++## What the agent gets++Six tools:++| Tool | Purpose |+|---|---|+| `get_mesh_info` | Router, connected peers, DHT size, the local socket path. A quick health check. |+| `list_local_services` | The services this node publishes. |+| `discover_remote_services` | The services other nodes publish, by type (`mcp`, `inference`, `a2a`) and optionally by name. Returns the hosting peer ID for each. |+| `find_remote_tools` | The tools behind MCP services, across the mesh or limited to a peer, a service, or a tool name. |+| `describe_remote_tool` | The input schema of one tool on one peer. Call this before `call_remote_tool`, because the provider chooses the argument names. |+| `call_remote_tool` | Run a tool on a peer. Takes `peer_id`, the namespaced `tool_name` (`mcp://service/tool`) and `arguments`. |++Inference is not an MCP tool. `discover_remote_services` with+`{"type":"inference"}` lists providers, but to use a model you send an+ordinary OpenAI request to the node's `/v1` endpoint, with `base_url`+`http://127.0.0.1:8080/v1` and the token as the API key. `/v1/models` lists+the available models.++Two things an agent should know (the skill below tells it): service names+are not unique across the mesh, so the peer ID identifies a provider, and+discovery is best-effort per peer, so on a partly reachable mesh some entries+come back with an `error` field next to the good ones.++## The skill++Tools tell an agent what it can do. A skill tells it when and how to use+them. `sam-node` ships one:++```bash+sam-node skill install # ~/.claude/skills/sam-mesh/ and ~/.gemini/config/skills/sam-mesh/+sam-node skill install --project # ./.claude/skills/ and ./.agents/skills/ in the current repository+sam-node skill install --dir DIR # anywhere else+sam-node skill list # where it is installed and whether it is current+sam-node skill show # print it, for a harness with its own layout+```++Reinstall the skill after you upgrade `sam-node`. `list` says `outdated` when+the installed copy differs from the one in the binary. Restart the client+afterwards so that it loads both the skill and the tools.++## Claude Code++```bash+claude mcp add --transport http sam-mesh http://127.0.0.1:8080/mcp \+ --header "X-Sam-Authentication: Bearer <token>"+```++The default scope is the current project. `--scope user` makes the server+available everywhere, and `--scope project` writes a shareable `.mcp.json`.+The equivalent file entry, where `type` is required:++```json+{+ "mcpServers": {+ "sam-mesh": {+ "type": "http",+ "url": "http://127.0.0.1:8080/mcp",+ "headers": { "X-Sam-Authentication": "Bearer <token>" }+ }+ }+}+```++`claude mcp list` should report the server as connected. Tools load at+session start. `/mcp` inside a session shows them, and `/skills` shows+`sam-mesh` once the skill is installed.++## Google Antigravity++Add to `~/.gemini/config/mcp_config.json`:++```json+{+ "mcpServers": {+ "sam-mesh": {+ "serverUrl": "http://127.0.0.1:8080/mcp",+ "headers": { "X-Sam-Authentication": "Bearer <token>" }+ }+ }+}+```++Antigravity picks up the change without a restart. `sam-node skill install`+writes the skill to Antigravity's global skills directory. `--project` writes+it to `.agents/skills/` in the workspace instead.++## VS Code and GitHub Copilot++Create `.vscode/mcp.json` in the workspace. VS Code asks for the token once+and keeps it in its secret store, so the file is safe to commit:++```json+{+ "inputs": [+ { "type": "promptString", "id": "sam-api-token",+ "description": "SAM node API token", "password": true }+ ],+ "servers": {+ "sam-mesh": {+ "type": "http",+ "url": "http://127.0.0.1:8080/mcp",+ "headers": { "X-Sam-Authentication": "Bearer ${input:sam-api-token}" }+ }+ }+}+```++VS Code does not start a newly declared server on its own. Open the file and+use the **Start** action shown above the entry, or run **MCP: List Servers**+from the command palette. A server listed as stopped was read correctly and+is waiting to be started. If you entered a wrong token, clear it with+**MCP: Reset Cached Tokens**. New tools may not appear in a chat that is+already in progress. Start a new chat and check that `sam-mesh` is ticked in+the tools picker. To use the server in all workspaces, put the same JSON in+the user-level configuration (**MCP: Open User Configuration**). Copilot+reads `~/.claude/skills/`, so the default skill install applies.++## Claude Desktop++Claude Desktop launches stdio servers only, so it needs a bridge.+[`mcp-remote`](https://www.npmjs.com/package/mcp-remote) is a small+stdio-to-HTTP proxy that Claude Desktop can launch. Add it to+`claude_desktop_config.json` (`~/Library/Application Support/Claude/` on+macOS, `%APPDATA%\Claude\` on Windows):++```json+{+ "mcpServers": {+ "sam-mesh": {+ "command": "npx",+ "args": [+ "mcp-remote", "http://127.0.0.1:8080/mcp", "--allow-http",+ "--header", "X-Sam-Authentication: Bearer <token>"+ ]+ }+ }+}+```++`--allow-http` is needed because the node serves plain HTTP on loopback. Quit+and reopen Claude Desktop. The tools appear under the connectors icon. On+Windows the command may need to be `npx.cmd`. Claude's cloud-hosted "custom+connectors" cannot reach a node on your machine, so use the bridge.++## OpenClaw++```bash+openclaw mcp set sam-mesh '{+ "url": "http://127.0.0.1:8080/mcp",+ "headers": { "X-Sam-Authentication": "Bearer <token>" }+}'+openclaw mcp list+```++Restart the OpenClaw gateway after adding it.++## Your own code++Any MCP SDK works. In Python, with the official `mcp` package (2.x):++```python+import httpx+from mcp import ClientSession+from mcp.client.streamable_http import streamable_http_client++http = httpx.AsyncClient(headers={"X-Sam-Authentication": "Bearer <token>"})+async with streamable_http_client("http://127.0.0.1:8080/mcp", http_client=http) as (read, write):+ async with ClientSession(read, write) as session:+ await session.initialize()+ tools = await session.list_tools()+```++The repository's `sam-mcp-python` package wraps this in a `SamClient`.+`sam-mcp-python/examples/gemini_agent.py` is a complete agent that maps the+node's tools to Gemini function calls with the `google-genai` SDK. For+inference, point any OpenAI SDK at `http://127.0.0.1:8080/v1` with the token+as `api_key`, or at the socket with no key.++## A note on trust++A client configured this way is a client of your node. It holds the node's+token and gets everything that the node's credential grants. That is the+right arrangement for an assistant on your own machine. Code that you do not+trust should not be able to reach the node's API at all. The+[sandboxed agents preview](../../preview/sandboxed-agents/) covers that case.++## When it does not work++- **401**: the header value does not match the node's token. Over the+ socket no token is needed. Over TCP it is required.+- **Connection refused**: the node is not running, or it is bound to another+ address. If+ `curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/mcp`+ answers `401`, the endpoint is up.+- **Node in WSL or in a container**: the client runs on the host, so bind+ the node to an address the host can reach (`--bind-addr 0.0.0.0:8080`) or+ forward the port.+- **No remote tools**: check `get_mesh_info` first. An empty+ `connected_peers` means the node has not reached a router. A `dht_size` of+ zero means it has not found the mesh yet.+- **A tool is listed with an `error`**: the provider's backend is not+ answering. Another peer that offers the same service name may work.diff --git a/site/content/docs/guides/exposing-services.md b/site/content/docs/guides/exposing-services.mdnew file mode 100644index 00000000..4b2f1708--- /dev/null+++ b/site/content/docs/guides/exposing-services.md@@ -0,0 +1,249 @@+---+title: "Exposing services"+linkTitle: "Exposing services"+weight: 1+aliases:+ - /docs/integrations/openrouter/+---++A node does not publish any service by default. You declare the services it+offers in `sam-node.yaml`. This guide covers the three kinds of service a+node can serve and what the mesh policy must contain before anyone can reach+them.++## The configuration file++`sam-node` reads `sam-node.yaml` from the working directory, or the file+named by `--config`. Both `join` and `run` read it, because labels are+declared at enrollment. A minimal file with one service:++```yaml+version: "v1alpha1"+services:+ - type: mcp+ name: calculator+ description: "Arithmetic tools"+ target_url: "http://127.0.0.1:7779/mcp"+```++Services exist only through this file. There is no runtime API for adding+one, so an agent with access to the node cannot make it publish a new+backend. To change the services, edit the file and restart the node. The+[node configuration reference](../../reference/node-config/) lists every key.++A `name` must be a valid DNS-style label sequence (`db-reader`,+`build.runner`), because the mesh uses it in URLs and in policy. A policy+grant refers to the pair `type://name`, so `mcp://calculator` in the policy+means this service and no other.++## MCP servers++[MCP](https://modelcontextprotocol.io/) (Model Context Protocol) is the+standard that agents use to call tools. An MCP server is a program that+offers tools over that protocol. There are two ways to serve an MCP backend.++**A subprocess that speaks stdio.** The node starts it, keeps it running, and+translates between the mesh and its stdin and stdout:++```yaml+ - type: mcp+ name: filesystem+ description: "Read-only access to the docs tree"+ command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/srv/docs"]+ env:+ NODE_OPTIONS: "--max-old-space-size=256"+```++**A Streamable HTTP server that is already running.** The node proxies to it+and does not manage it:++```yaml+ - type: mcp+ name: code-reviewer+ description: "Reviews diffs"+ target_url: "http://127.0.0.1:7777/mcp"+```++`command` and `target_url` are mutually exclusive. Before the node advertises+a service of either kind, it probes the backend. A subprocess that needs more+than two seconds to answer its first request is not advertised unless you+raise `--backend-probe-timeout`.++Callers see the whole tool list of the server. If a third-party server+bundles tools that you do not want to offer, put a small MCP server in front+of it that exposes only the tools you want to publish, or split the tools+into several services with different names and grant them to different+roles.++## Inference backends++Any OpenAI-compatible HTTP server can be an `inference` service: vLLM,+Ollama, LiteLLM, or a proxy in front of a hosted API. Register the root URL+without `/v1`. The node adds the prefix.++```yaml+ - type: inference+ name: local-llama+ description: "Llama 3 on this workstation"+ target_url: "http://127.0.0.1:11434"+```++Every model that the backend lists on `/v1/models` becomes available on+`/v1/models` of every authorized node, and a `chat/completions` request for+that model may be routed here. Give backends distinct names when they serve+different models or run in different places, because policy and label rules+work on the name.++### A hosted API behind a proxy++To share a commercial API without sharing its key, run a proxy that holds the+key next to the node and register the proxy. For example, with LiteLLM in the+same pod or on the same host:++```yaml+ - type: inference+ name: openrouter+ description: "OpenRouter via LiteLLM"+ target_url: "http://127.0.0.1:4000"+```++```bash+OPENROUTER_API_KEY=... litellm --model openrouter/auto --port 4000+```++The key never leaves the proxy. Callers on the mesh authenticate with their+credential, the node checks the policy, and the proxy adds the key on the way+out. If the backend itself requires a credential, put it in a file and name+the file in `target_auth_path`. A bare token is sent as+`Authorization: Bearer`, and a `user:pass` pair as HTTP Basic. This is a+file and not an inline value because `sam-node.yaml` is copied into+ConfigMaps and repositories. For the same reason, a URL with embedded+credentials is refused.++## A2A agents++An agent that speaks the [A2A protocol](https://a2a-protocol.org) is served+by URL only:++```yaml+ - type: a2a+ name: triage+ description: "Ticket triage agent"+ target_url: "http://127.0.0.1:9999"+```++Remote callers reach it at `/sam/<peer-id>/a2a/triage/` on their own node.+The agent card gets special treatment. The caller's node fetches+`/.well-known/agent-card.json` from the agent and serves a regenerated card+whose interface URLs point at the mesh path. Bindings that the mesh cannot+carry (gRPC) are removed, and the original signatures are dropped because the+content changed. Standard A2A client SDKs then work without changes. Cards+must use the A2A 1.0 format. Older formats are refused. The+[A2A chat use case](../../use-cases/chat-a2a/) runs one end to end.++## Making it reachable++Declaring a service publishes it, but nobody can call it until the mesh+policy grants access. Two conditions must hold:++1. The caller's identity resolves to a role whose `allowed_services`+ includes `mcp://calculator`, or a pattern that covers it.+2. If that role has `allowed_targets`, one of them matches this node's+ identity: its peer ID as `node:<id>`, or a claim from the identity it+ enrolled with.++A policy that grants the service to a role bound to your users:++```json+{+ "roles": [+ { "name": "sam:role:node", "allowed_labels": ["region=*"] },+ { "name": "calc-users", "allowed_services": ["mcp://calculator"] }+ ],+ "bindings": [+ { "role": "sam:role:node", "members": ["group:engineering"] },+ { "role": "calc-users", "members": ["group:engineering"] }+ ]+}+```++Post it to the control plane, or paste it into the console's policy editor:++```bash+curl -fsS -X POST https://mesh.example.com/policies \+ -H "Authorization: Bearer $SAM_ADMIN_TOKEN" \+ -H "Content-Type: application/json" \+ --data @policy.json+```++Discovery (`system://sam.catalog`) follows the same rule. A role that should+be able to browse what a node offers needs `system://sam.catalog` in its+grants. On a mesh where everyone may browse, grant it to `sam:role:node`.++## Labels++If the node should be identifiable by where it is or what it is for, declare+labels:++```yaml+labels:+ region: eu-west-1+ team: platform+```++Labels are attested at enrollment, so the role the node enrolls with must+permit them (`allowed_labels: ["region=*", "team=platform"]`, or `["*"]`).+Enrollment is refused if a label is not allowed by the role. Once attested,+callers can require the labels (`X-Sam-Required-Labels: region=eu-west-1`),+and the node can require labels from its callers:++```yaml+attenuation:+ checks:+ - 'check if label("team", "platform");'+```++## Restricting callers locally++The `attenuation` block adds your own conditions on top of the policy. All+checks must hold, and `deny` policies override grants:++```yaml+attenuation:+ policies:+ - 'deny if service("mcp", "calculator"), group("contractors");'+ checks:+ - 'check if time($t), $t < 2027-01-01T00:00:00Z;'+```++The syntax is Biscuit Datalog. Your rules can use the facts from the+caller's credential (`user`, `email`, `group`, `idp_role`, `role`, `label`+and the `granted_*` facts), plus `service($type, $name)` for the request and+`time($now)`. A syntax error stops the node at start.++## Checking that it worked++From another enrolled node:++```bash+mcp-client -url http://127.0.0.1:8080/mcp -token "$TOKEN" \+ -tool discover_remote_services -args '{"type":"mcp","name":"calculator"}'+```++If the service is missing, check these causes in order:++1. The backend did not answer the probe. Look for "Withholding" in the+ node log.+2. The caller's role lacks `system://sam.catalog`.+3. The two nodes have not exchanged discovery state yet. Wait a few seconds+ and try again.++If the service is listed but a call returns a policy error, the grant or the+target is wrong. The node's log names the check that failed.++## Kubernetes++On Kubernetes a service is a pod with your backend container and a+`sam-node` sidecar, deployed with the `charts/sam-node` Helm chart; the+`config:` value is this file. The [Kubernetes guide](../kubernetes/) covers+it.diff --git a/site/content/docs/guides/headless-enrollment.md b/site/content/docs/guides/headless-enrollment.mdnew file mode 100644index 00000000..bee424f0--- /dev/null+++ b/site/content/docs/guides/headless-enrollment.md@@ -0,0 +1,180 @@+---+title: "Headless enrollment"+linkTitle: "Headless enrollment"+weight: 3+---++Servers, containers and routers cannot complete an interactive login: there+is no browser, and no person to log in. Such a machine enrolls in one of two+ways: with an OIDC token that it already holds, or with a bootstrap token+that an operator mints for it. This guide covers both, and then explains+what happens when the credential of such a node expires.++## With an OIDC token that the workload already has++If the platform gives the workload a token from an issuer that the control+plane trusts, no operator step is needed. On Kubernetes this is a projected+service account token with the right audience:++```yaml+volumes:+ - name: sam-token+ projected:+ sources:+ - serviceAccountToken:+ path: sam-token+ expirationSeconds: 3600+ audience: sam-mesh-audience+```++```bash+sam-node run --control-plane https://mesh.example.com --jwt-path /var/run/secrets/tokens/sam-token+```++The control plane must list the cluster's issuer in `--issuer` and the+audience in `--allowed-audiences`. The policy must bind the service account+(`user:system:serviceaccount:<namespace>:<name>`) to `sam:role:node`.+Routers enroll the same way with `sam-router --jwt-path`. The+[Kubernetes guide](../kubernetes/) shows the complete setup.++A workload with an OAuth client ID and secret can use the client-credentials+grant instead, with `--oidc-issuer`, `--client-id` and+`--client-secret-path` (or `SAM_CLIENT_SECRET`).++## With a bootstrap token++For a machine that has no identity of its own, an operator mints a token.++### 1. Mint++Call the control plane API with the admin token. `sam-one` prints the admin+token at start and writes it to its data directory. A separate+`sam-control-plane` reads it from the file given by `--admin-token-path` or+from the `SAM_ADMIN_TOKEN` environment variable.++```bash+curl -fsS -X POST https://mesh.example.com/admin/bootstrap-tokens \+ -H "Authorization: Bearer $SAM_ADMIN_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"role":"sam:role:node","ttl_hours":24,"max_usages":1,"description":"build-runner-3"}'+```++```json+{"id":"62e92ffca…","token":"sam-bt-72fb0175788dee0…","role":"sam:role:node","expires_at":"2026-09-20T15:00:00Z"}+```++The plaintext `token` is shown once. The control plane keeps only its hash.+`role` is the role that the token enrolls into (`sam:role:router` for a+router). `ttl_hours` defaults to 24 and `max_usages` to 1. The Bootstrap+Tokens view in the console and `sam-one token create` do the same thing. An+OIDC user who is already enrolled can mint tokens for their own machines+through `POST /user/bootstrap-tokens` with their ID token. Such tokens+record the user as owner, and banning the user disables them.++Write the token to a file on the target machine. The node reads it from a+file and not from a flag, so it does not appear in process listings or in+the shell history.++### 2. Enroll++```bash+sam-node join https://mesh.example.com --bootstrap-token-path /etc/sam/bootstrap-token+```++or, to enroll and start in one step:++```bash+sam-node run --control-plane https://mesh.example.com --bootstrap-token-path /etc/sam/bootstrap-token+```++The node submits its public key, the token, and a signature over a fresh+challenge to `POST /enroll`. If the control plane runs with+`--auto-approve-enrollment` (the default in the Helm chart and in `sam-one`),+the credential comes back immediately. Otherwise the request is queued and+the node polls until an administrator decides.++### 3. Approve++```bash+curl -fsS https://mesh.example.com/admin/enrollments -H "Authorization: Bearer $SAM_ADMIN_TOKEN"+curl -fsS -X POST https://mesh.example.com/admin/enrollments/<request-id>/approve \+ -H "Authorization: Bearer $SAM_ADMIN_TOKEN"+```++`.../reject` refuses the request. The console lists pending requests with+the same two actions. Approval spends one usage of the token and checks again+that the token is still valid. If the token was revoked, expired or used up+between the request and the approval, the approval fails. It also fails if+the node declared a label that the token's role does not permit.++### Labels++A node enrolled with a bootstrap token declares labels in its configuration+file, like any other node, and the token's role must allow them through+`allowed_labels`. Approval by an administrator does not bypass this check.+The grant decides which labels a node may carry.++### Revoking a token++```bash+curl -fsS -X DELETE https://mesh.example.com/admin/bootstrap-tokens/<id> \+ -H "Authorization: Bearer $SAM_ADMIN_TOKEN"+```++The token stays in the list, marked as revoked, so the record of what it+enrolled is kept. Nodes that already enrolled with it are not affected. To+remove one of those, ban the node.++## When the credential expires++A node enrolled with a bootstrap token has no login to fall back on. Its+credential is refreshed automatically while it runs. But if the node is off+for longer than the control plane's key grace period (`--key-grace-period`,+one hour by default), it comes back with a credential signed by a retired+key, and `/refresh` refuses it. There are three ways out, in order of+preference.++**Enroll again.** Mint a new token and run `sam-node join` with it. The+control plane already knows the peer ID, so it mints a new credential+directly instead of queueing a new approval, as long as the token's role+matches and the node is not banned. Each re-enrollment spends one token+usage, so `max_usages` limits how often a machine can be brought back this+way.++**Widen the grace period.** A longer `--key-grace-period` on the control+plane gives a quiet node more time to refresh. The trade-off is that a+machine that has been lost or stolen can keep renewing for the same time.++**Allow autonomous recovery.** A node whose record has+`autonomous_recovery` set may refresh on proof of its own key alone, even+after the signing key that issued its credential is gone. Set it on the token+so that every node enrolled with it inherits the flag, or set it on one node+afterwards:++```bash+# on the token, at mint time+-d '{"role":"sam:role:node","max_usages":10,"autonomous_recovery":true}'++# on an enrolled node+curl -fsS -X POST https://mesh.example.com/admin/nodes/<peer-id>/autonomous-recovery \+ -H "Authorization: Bearer $SAM_ADMIN_TOKEN" -H "Content-Type: application/json" \+ -d '{"enabled":true}'+```++This is off by default, because a node that can always recover holds a+credential that never expires in practice. Only a ban stops it. It suits+fleets where an operator round trip per stale node is impractical and the+machines are controlled in other ways.++## Banning++```bash+curl -fsS -X POST https://mesh.example.com/admin/revoke \+ -H "Authorization: Bearer $SAM_ADMIN_TOKEN" -H "Content-Type: application/json" \+ -d '{"peer_id":"12D3KooW…"}'+```++The node's next refresh fails and its daemon exits. Connected peers drop it+as soon as the ban event reaches them. `POST /admin/nodes/<peer-id>/unban`+reverses the ban. `sam-control-plane admin ban --peer <id>` and `unban` do+the same directly in the database, for cases where the API is not reachable.diff --git a/site/content/docs/guides/kubernetes.md b/site/content/docs/guides/kubernetes.mdnew file mode 100644index 00000000..44874fb5--- /dev/null+++ b/site/content/docs/guides/kubernetes.md@@ -0,0 +1,214 @@+---+title: "Kubernetes"+linkTitle: "Kubernetes"+weight: 4+aliases:+ - /docs/user/kubernetes-deployment/+---++This guide deploys a control plane, a router and a console into a cluster+with the `sam-mesh` Helm chart, then puts services on the mesh with the+`sam-node` chart. The last section lists the settings to change when you+move from a test cluster to one that you keep. The public testnets run this+setup on GKE. Their manifests are in `.github/k8s/` in the repository.++## What gets deployed++| Component | Kind | Notes |+|---|---|---|+| `sam-control-plane` | Deployment (2 replicas) | Stateless. All state is in PostgreSQL. |+| PostgreSQL | StatefulSet | In-cluster by default (`database.postgres.deployInternal`). You can point the chart at your own database instead. |+| `sam-router` | StatefulSet | A PVC holds `router.key`, so the peer ID survives rescheduling. |+| `sam-console` | Deployment | Optional (`console.enabled`). |+| bootstrap Job | Job (post-install hook) | Seeds the mesh policy and mints the router's bootstrap token. |+| Gateway + HTTPRoute | Gateway API | Optional (`gateway.enabled`). Routes the enrollment paths and the console. |++The chart does not include an identity provider, and the control plane needs+one to start. The cluster's own OIDC issuer is a good choice, because every+pod can then enroll with a projected service account token and no secret has+to be distributed.++## 1. Install the mesh++```bash+ISSUER=$(kubectl get --raw /.well-known/openid-configuration | jq -r .issuer)++helm upgrade --install sam-mesh ./charts/sam-mesh \+ --namespace sam --create-namespace \+ --set controlPlane.oidcIssuer="$ISSUER" \+ --set controlPlane.insecureSkipTlsVerify=true \+ --set bootstrap.nodeMembers='{user:system:serviceaccount:sam-nodes:calc-mcp-sam-node}' \+ --set bootstrap.nodeServices='{mcp://calculator,system://sam.catalog}'+```++`insecureSkipTlsVerify` is needed when the cluster issuer is served with the+cluster CA, which the control plane does not trust by default. Leave it off+for a public provider. On a managed cluster the issuer is often public (on+GKE: `https://container.googleapis.com/v1/projects/.../clusters/...`) and+does not need the flag.++The three `bootstrap.*` values write the initial policy:++- `nodeMembers`: the identities that may enroll as `sam:role:node`. If+ empty, no node can join until you post a policy.+- `nodeServices`: the services that nodes may call. If empty, nodes can call+ nothing.+- `nodeLabels`: the label patterns that nodes may attest. If empty, nodes+ cannot declare labels.++If you want to bind more roles than the node role, `bootstrap.bindings`+replaces the whole bindings list. Everything the bootstrap job seeds can be+changed later through the console or `POST /policies`. The job runs on+install and on upgrade, but once the database has a policy, the database is+the source of truth.++The chart generates an admin token and a database password and stores them+in the `sam-mesh-secrets` Secret. The release notes print the command to+read them:++```bash+kubectl -n sam get secret sam-mesh-secrets -o jsonpath='{.data.admin-token}' | base64 -d+```++The router enrolls with a bootstrap token that the job writes into+`sam-mesh-router-token`, with `max_usages` equal to `router.replicaCount`.+Set `router.useOidcToken=true` to make it use a projected service account+token instead.++## 2. Expose it++Inside the cluster, the control plane answers at+`http://sam-mesh-control-plane.sam.svc:8080` and the router at+`sam-mesh-router.sam.svc:4501`. That is enough for nodes in the same cluster.++Nodes outside the cluster need two things: the control plane over HTTPS+(nodes refuse to fetch their trust root over plaintext from a remote+address), and the router's libp2p ports. The chart's Gateway handles the+control plane:++```yaml+gateway:+ enabled: true+ className: gke-l7-global-external-managed+ listeners:+ - name: https+ protocol: HTTPS+ port: 443+ tls:+ certificateRefs: [{ name: sam-mesh-tls }]+ allowedRoutes: { namespaces: { from: Same } }+ hostnames: [mesh.example.com]+```++The route exposes only the paths that nodes need (`/info`, `/register`,+`/keys`, `/routers/lease`, `/policies`, `/enroll`, `/enroll/status`,+`/refresh`, `/nodes/catalog`) and the console under `gateway.consolePath`.+`/admin` and `/user` are not routed unless you set `gateway.adminRoute`,+which is meant for development clusters.++For the router, `router.hostPort: 4501` binds TCP and UDP port 4501 on the+Kubernetes node where the router pod runs, and announces that node's IP.+`router.externalAddrs` replaces the announced addresses, for example with a+fixed DNS name:++```yaml+router:+ hostPort: 4501+ externalAddrs: ["/dnsaddr/bootstrap.example.com"]+```++A `/dnsaddr` needs TXT records that resolve to the routers' current+addresses. The testnets run a CronJob+(`.github/k8s/dns-sync-cronjob-template.yaml`) that reads the IPs of the+router pods and updates Cloud DNS. Any mechanism that keeps the records+current works.++## 3. Put a service on the mesh++A service on Kubernetes is a pod with your backend container and a+`sam-node` sidecar, both deployed by the `sam-node` chart. The node enrolls+with the pod's projected service account token, so its identity is+`user:system:serviceaccount:<namespace>:<release>-sam-node`. This is the+identity that the binding in step 1 named.++```yaml+# calc-mcp.values.yaml+controlPlaneUrl: http://sam-mesh-control-plane.sam.svc:8080+config:+ version: v1alpha1+ services:+ - type: mcp+ name: calculator+ description: "Arithmetic tools"+ target_url: http://127.0.0.1:7777/mcp+service:+ name: calc-mcp+ image: ghcr.io/example/calc-mcp:1.0+ ports: [{ containerPort: 7777 }]+```++```bash+helm upgrade --install calc-mcp ./charts/sam-node \+ --namespace sam-nodes --create-namespace -f calc-mcp.values.yaml+```++`config` is the node's `sam-node.yaml`. The pod restarts when it changes.+The sidecar and the backend share the pod's network, so `target_url` is+always `127.0.0.1`. `extraArgs` passes additional `sam-node run` flags. The+chart adds `--insecure-control-plane` for you when the control plane URL is+plain `http` inside the cluster. With a `replicaCount` above one, each+replica enrolls as its own node and offers the same service name.++`development/examples/` in the repository holds working values files for+several backends, and `make kind-up` brings up this whole setup in a local+kind cluster. See [Contributing](../../contributing/#a-local-mesh-in-kind).++## 4. Check it++```bash+kubectl -n sam-nodes logs deploy/calc-mcp -c sam-node | grep -E "Online|PeerID"+```++From a node enrolled anywhere in the mesh:++```bash+mcp-client -url http://127.0.0.1:8080/mcp -token "$TOKEN" \+ -tool discover_remote_services -args '{"type":"mcp","name":"calculator"}'+```++The console shows the same information: enrolled nodes, their reported+services, the router, and the policy. It is at `/console/` behind the+gateway, or you can port-forward `svc/sam-mesh-console`.++## Keeping it++The defaults suit a cluster that you rebuild often. For a cluster that you+keep, review these settings:++- **Database.** Set `database.postgres.deployInternal=false` and give the+ control plane the DSN of a managed PostgreSQL through `--db-dsn-path` or+ the `SAM_DB_DSN` environment variable. The DSN contains a password, so it+ should not be a flag value.+- **Enrollment.** `controlPlane.autoApproveEnrollment` defaults to `true`.+ That is fine when every enrollee holds an OIDC token from an issuer that+ you control. If you hand out bootstrap tokens, consider setting it to+ `false` and approving enrollments in the console.+- **Policy.** Grant nodes only the services they need. Do not bind+ `sam:system:authenticated` to a role with wide grants: on a public+ identity provider it means everyone. The testnets bind it on purpose. A+ private mesh should bind groups or service accounts.+- **Signing keys.** `--key-grace-period` defaults to one hour. A node that is+ down for longer must enroll again. The testnets use 48 hours. Pick a value+ that matches how long your nodes can legitimately be off.+- **Console origin.** When a proxy terminates TLS in front of the console,+ set `console.externalUrl` so that the OIDC redirect URI and the cookie+ `Secure` flag do not depend on forwarded headers.+- **Metrics.** `monitoring.podMonitoring.enabled` (Google Managed+ Prometheus) or `monitoring.podMonitor.enabled` (prometheus-operator)+ scrape the control plane and the router. Both metrics endpoints are+ unauthenticated, so keep them inside the cluster.++The chart's [README](https://github.com/google/sam/blob/main/charts/sam-mesh/README.md)+documents every value. The [control plane](../../reference/control-plane/)+and [router](../../reference/router/) references list the flags the chart+sets.diff --git a/site/content/docs/integrations/_index.md b/site/content/docs/integrations/_index.mddeleted file mode 100644index ecc45490..00000000--- a/site/content/docs/integrations/_index.md+++ /dev/null@@ -1,92 +0,0 @@-----title: "Agent Integration Guide"-linkTitle: "Agent Integration Guide"-weight: 2-----SAM is designed to be the networking layer for autonomous AI agents. The easiest way for your agent to interact with the mesh is through the **Model Context Protocol (MCP)** exposed locally by your node.--Every `sam-node` runs a local MCP server that allows agents to:-- Discover tools available on the mesh.-- Connect to remote peers securely.-- Query mesh information (e.g. `get_mesh_info`).-- Call tools remotely (via `call_remote_tool`).--## Supported Agent Integrations--Explore the step-by-step guides to integrate SAM with your favorite AI Agent systems:--- [Google Gemini](gemini/): Build an interactive client using the official `google-genai` Python SDK.-- [Google Antigravity](antigravity/): Connect your local node as a remote MCP server to Google Antigravity.-- [Claude Code](claude-code/): Connect your local node as a remote MCP server to Claude Code.-- [Claude Desktop](claude-desktop/): Use SAM to expose the P2P tool mesh to Claude Desktop.-- [VS Code and GitHub Copilot](vscode-copilot/): Register your node in `.vscode/mcp.json` and reach the mesh from Copilot's agent mode.-- [OpenClaw](openclaw/): Integrate your node as a remote tool bridge for OpenClaw.--## Connecting via MCP--The `sam-node` exposes the MCP server over Streamable HTTP. By default, it listens at `127.0.0.1:8080`.--The repository provides a Python SDK (`sam-mcp-python`) which implements the MCP client.--### Prerequisites--You need the `sam_mcp` package installed. From the repo root, run:--```bash-pip install ./sam-mcp-python-```--### Python SDK Demo--The following snippet demonstrates how to connect to the local node's MCP server, list the available tools, and call the `get_mesh_info` tool.--```python-import asyncio-import os-import sys-from sam_mcp.client import SamClient--async def main():- # Connect to the local SAM node's MCP SSE endpoint- # By default, sam-node listens at 127.0.0.1:8080- url = os.environ.get("SAM_MCP_URL", "http://127.0.0.1:8080/mcp")- print(f"Connecting to SAM Node at {url}")-- try:- async with SamClient(server_url=url) as client:- # Discover available tools provided by the SAM node- tools = await client.get_tools()- print(f"Discovered {len(tools)} tools:")- for tool in tools:- print(f" - {tool['name']}: {tool['description']}")-- # Call the get_mesh_info tool to get information about the mesh- print("\nCalling get_mesh_info tool...")- result = await client.call_tool("get_mesh_info", {})- print("Result:")- print(result)-- except Exception as e:- print(f"Error connecting to SAM Node: {e}")- sys.exit(1)--if __name__ == "__main__":- asyncio.run(main())-```--*(You can find this snippet at `site/content/docs/snippets/agent_demo.py`)*--### Example Output--When you run the demo while a `sam-node` is running locally, you'll see output similar to this:--```-Connecting to SAM Node at http://127.0.0.1:8080/mcp-Discovered tools:- - get_mesh_info: Get information about the mesh network- - call_remote_tool: Call an MCP tool on a remote agent--Calling get_mesh_info tool...-Result:-{'known_peers': [...], 'connected_peers': [...], 'dht_size': 1, 'router_peer_id': '...'}-```diff --git a/site/content/docs/integrations/antigravity.md b/site/content/docs/integrations/antigravity.mddeleted file mode 100644index 011b4b96..00000000--- a/site/content/docs/integrations/antigravity.md+++ /dev/null@@ -1,121 +0,0 @@-----title: "Integrating SAM with Google Antigravity"-linkTitle: "Integrating SAM with Google Antigravity"-----You can connect your `sam-node` to Google Antigravity as an MCP server. By exposing the SAM Model Context Protocol (MCP) server to Antigravity, the agent can dynamically discover tools hosted by other peers in the mesh, describe them, and execute them to solve tasks.--## Overview--Antigravity natively supports Streamable HTTP MCP servers via the `serverUrl` configuration. Since `sam-node` implements the Streamable HTTP transport, you can connect it directly without any bridge.--## Prerequisites--- `sam-node` installed and able to join a mesh (see the [Quick Start](../quickstart/)).-- The node API token (`SAM_API_TOKEN` env or `--api-token-path`) you'll launch it with.--## 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.--### 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- Socket /home/you/.config/sam-mesh/sam.sock- 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.--Antigravity's MCP client needs the HTTP endpoint, but the socket serves the same API for anything the agent runs in a shell — including mesh inference — without a token to pass around:--```bash-curl --unix-socket ~/.config/sam-mesh/sam.sock http://localhost/v1/models-```--### Alternative: a dedicated terminal--On 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.--### macOS / Linux-Simplest: leave the node running in its own terminal tab, then open a second tab for Antigravity:-```bash-# Terminal 1 — leave running-SAM_API_TOKEN=my-secret-token sam-node run --join --bind-addr 127.0.0.1:8080-```-```bash-# Terminal 2-agy-```--### Windows-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: Docker-The 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:-```bash-docker run -d --name sam-node \- --user "$(id -u):$(id -g)" \- -v $(pwd)/sam-data:/data \- -p 5001:5001/udp -p 5002:5002 -p 8080:8080 \- -e SAM_API_TOKEN=my-secret-token \- ghcr.io/google/sam-node:latest \- run --join --data-dir /data --bind-addr 0.0.0.0:8080-```--## Configuration--Edit your Antigravity MCP configuration file:--- Path: `~/.gemini/config/mcp_config.json`--Add the node directly using its HTTP endpoint (replace `<YOUR_TOKEN>` with your the node API token (`SAM_API_TOKEN` env or `--api-token-path`)):--```json-{- "mcpServers": {- "sam-mesh": {- "serverUrl": "http://localhost:8080/mcp",- "headers": {- "X-Sam-Authentication": "Bearer <YOUR_TOKEN>"- }- }- }-}-```--Antigravity 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 Tools--The tool flow for Antigravity is as follows:--1. `discover_remote_services` → list active services and obtain their `peer_id`s.-2. `find_remote_tools` (`peer_id`) → list the tools a peer hosts.-3. `describe_remote_tool` (`peer_id`, `tool_name`) → fetch the tool's `input_schema`.-4. `call_remote_tool` (`peer_id`, `tool_name`, `arguments`) → invoke it across the mesh.--## Troubleshooting--* **Connection errors**: verify `sam-node` is reachable at the configured URL and that the bearer token matches the node API token (`SAM_API_TOKEN` env or `--api-token-path`).-* **Running `sam-node` in WSL or a container**: the `mcp-remote` bridge runs on the host, so that host must be able to reach the node's bind address. Bind the node to an address the host can reach (e.g. `0.0.0.0`).diff --git a/site/content/docs/integrations/claude-code.md b/site/content/docs/integrations/claude-code.mddeleted file mode 100644index 711cc577..00000000--- a/site/content/docs/integrations/claude-code.md+++ /dev/null@@ -1,81 +0,0 @@-----title: "Integrating SAM with Claude Code"-linkTitle: "Integrating SAM with Claude Code"-----You can connect your `sam-node` to [Claude Code](https://claude.com/claude-code) as a remote MCP server, giving Claude Code agents the ability to discover and invoke tools across the SAM mesh.--## Overview--`sam-node` exposes a standard Model Context Protocol (MCP) server over Streamable HTTP. Claude Code is a generic MCP client, so once the server is registered its tools — `discover_remote_services`, `find_remote_tools`, `describe_remote_tool`, and `call_remote_tool` — are surfaced directly to your agent.--## Prerequisites--- A running `sam-node` with its local control-plane API reachable (default `http://localhost:8080`). See the [Quick Start](../quickstart/).-- The the node API token (`SAM_API_TOKEN` env or `--api-token-path`) you launched the node with.-- Claude Code installed (the `claude` CLI).--## Configuration--Register the node as an HTTP MCP server. Replace `<YOUR_TOKEN>` with your the node API token (`SAM_API_TOKEN` env or `--api-token-path`):--```bash-claude mcp add --transport http p2p-mesh-node \- http://localhost:8080/mcp \- --header "X-Sam-Authentication: Bearer <YOUR_TOKEN>"-```--By default the server is added at *local* scope (the current project only). Add `--scope user` to make it available in all your projects, or `--scope project` to write a shareable `.mcp.json` into your repository.--Alternatively, add it to a project `.mcp.json` directly:--```json-{- "mcpServers": {- "p2p-mesh-node": {- "type": "http",- "url": "http://localhost:8080/mcp",- "headers": {- "X-Sam-Authentication": "Bearer <YOUR_TOKEN>"- }- }- }-}-```--The `type` field is required for a remote server; omit it and the entry will not load.--## Verification--```bash-# Confirm the server is registered and connected-claude mcp list-claude mcp get p2p-mesh-node-```--A 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 Tools--Claude Code calls the tools `sam-node` exposes like any other tool. The flow mirrors the local MCP API:--1. **Discover services**: call `discover_remote_services` (e.g. with `{"type": "mcp"}`) to list active MCP services on the mesh and obtain their `peer_id`s.-2. **Find remote tools**: call `find_remote_tools`, passing the target `peer_id`, to list the tools that peer hosts.-3. **Describe a remote tool**: call `describe_remote_tool`, passing the `peer_id` and the namespaced `tool_name`, to fetch the tool's `input_schema` before invoking it.-4. **Invoke a remote tool**: call `call_remote_tool`, passing the `peer_id`, the namespaced `tool_name` (e.g. `everything.get-sum`), and the `arguments` matching that schema. Your local `sam-node` proxies the call across the P2P mesh and returns the result.--## Troubleshooting--* **Connection shows failed / 401**: verify the `X-Sam-Authentication` header matches the node's the node API token (`SAM_API_TOKEN` env or `--api-token-path`).-* **Server unreachable**: confirm `sam-node` is listening (default `http://localhost:8080`).-* **Tools not visible**: MCP servers load at session start — restart Claude Code and check `/mcp`.-* **Remove the server**: `claude mcp remove p2p-mesh-node -s user` (match the scope you used to add it).diff --git a/site/content/docs/integrations/claude-desktop.md b/site/content/docs/integrations/claude-desktop.mddeleted file mode 100644index 0fc0add6..00000000--- a/site/content/docs/integrations/claude-desktop.md+++ /dev/null@@ -1,68 +0,0 @@-----title: "Integrating SAM with Claude Desktop"-linkTitle: "Integrating SAM with Claude Desktop"-----You can connect your `sam-node` to the [Claude Desktop](https://claude.com/download) app as an MCP server. Unlike [Claude Code](./claude-code/), Claude Desktop has its own configuration and does **not** read Claude Code's MCP settings.--## Overview--Claude Desktop's `claude_desktop_config.json` natively launches **stdio** MCP servers (a local command). `sam-node` exposes an **SSE** server, so you bridge the two with [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) — a small stdio-to-remote proxy that Claude Desktop launches locally and that connects to your node's SSE endpoint.--> **Local node vs. Custom Connectors.** Use the `mcp-remote` bridge below for a `sam-node` running on your own machine: the bridge runs locally and can reach `localhost`. Claude's **Custom Connectors** UI is *not* suitable for a local node — Claude connects to connector URLs from Anthropic's cloud infrastructure, so the node would have to be reachable over the public internet. Reserve Custom Connectors for a publicly exposed SAM endpoint.--## Prerequisites--- A running `sam-node` (default `http://localhost:8080`) and its the node API token (`SAM_API_TOKEN` env or `--api-token-path`).-- [Node.js](https://nodejs.org) installed, which provides the `npx` used to run `mcp-remote`.-- Claude Desktop installed.--## Configuration--Edit `claude_desktop_config.json`:--- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`-- Windows: `%APPDATA%\Claude\claude_desktop_config.json`--Add the node through the `mcp-remote` bridge (replace `<YOUR_TOKEN>` with your the node API token (`SAM_API_TOKEN` env or `--api-token-path`)):--```json-{- "mcpServers": {- "p2p-mesh-node": {- "command": "npx",- "args": [- "mcp-remote",- "--sse",- "http://localhost:8080/mcp",- "--allow-http",- "--header",- "X-Sam-Authentication: Bearer <YOUR_TOKEN>"- ]- }- }-}-```--`--allow-http` is required because the node is served over plain HTTP on the loopback interface rather than HTTPS.--Restart 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 Tools--The tool flow is identical to the [Claude Code guide](./claude-code/#discovering-and-invoking-remote-tools):--1. `discover_remote_services` → list active services and obtain their `peer_id`s.-2. `find_remote_tools` (`peer_id`) → list the tools a peer hosts.-3. `describe_remote_tool` (`peer_id`, `tool_name`) → fetch the tool's `input_schema`.-4. `call_remote_tool` (`peer_id`, `tool_name`, `arguments`) → invoke it across the mesh.--## Troubleshooting--* **Tools don't appear**: fully quit and reopen Claude Desktop, and make sure npx is on your PATH. On Windows, you may need to use "command": "npx.cmd" instead of "command": "npx" in your configuration.-* **Connection errors**: verify `sam-node` is reachable at the configured URL and that the bearer token matches the node API token (`SAM_API_TOKEN` env or `--api-token-path`).-* **Running `sam-node` in WSL or a container**: the `mcp-remote` bridge runs on the Claude Desktop host, so that host must be able to reach the node's bind address. Bind the node to an address the host can reach (e.g. `0.0.0.0`) or set up port forwarding, rather than a container-only `127.0.0.1`.-* **Authentication header ignored**: if testing via the command line, the header value must be enclosed in quotes to be passed as a single argument (e.g., --header "Authorization: Bearer <YOUR_TOKEN>"). In the JSON configuration, they must remain as separate elements in the args array.diff --git a/site/content/docs/integrations/gemini.md b/site/content/docs/integrations/gemini.mddeleted file mode 100644index 1b662695..00000000--- a/site/content/docs/integrations/gemini.md+++ /dev/null@@ -1,90 +0,0 @@-----title: "Running a Gemini AI Agent on the Mesh"-linkTitle: "Running a Gemini AI Agent on the Mesh"-----This tutorial demonstrates how to connect a local AI Agent powered by Google Gemini (using the official `google-genai` SDK) to your local SAM node.--By exposing the SAM Model Context Protocol (MCP) server to Gemini, the agent can dynamically discover tools hosted by other peers in the mesh, describe them, and execute them to solve tasks.-------## Prerequisites--1. **Python 3.10+**: Ensure Python is installed on your host.-2. **SAM Node Running**: A local SAM node should be running and enrolled on the testnet (see the [Quick Start Guide](../quickstart/)).-3. **Gemini API Key**: Obtain an API key from Google AI Studio and export it:- ```bash- export GEMINI_API_KEY="your-api-key-here"- ```-------## 1. Setup the Python Client--Go to the `sam-mcp-python` directory in the repository:--```bash-cd sam-mcp-python-```--Create a virtual environment and install the required dependencies:--```bash-# Create and activate virtual environment-python3 -m venv .venv-source .venv/bin/activate--# Install the SAM Python SDK and Gemini SDK-pip install . google-genai-```-------## 2. Run the Gemini Agent--Start the interactive agent:--```bash-python3 examples/gemini_agent.py-```--Upon starting, the script will:-1. Connect to the local SAM node's MCP server at `http://localhost:8080/mcp`.-2. Discover all tools currently available in the mesh.-3. Map the mesh tools to Gemini-compatible OpenAPI schemas.-4. Spin up a chat loop with Gemini (`gemini-2.5-flash`).-------## 3. Interact with the Agent--Once the agent is online, you can prompt it in plain English. If a task requires tools registered in the mesh, Gemini will automatically call them.--### Example 1: Explore the Mesh-Ask the agent what it can see in the mesh:-```text-You > How many nodes are currently connected to the mesh? And what are their Peer IDs?--[Agent wants to call tool: get_mesh_info with args: {}]-[Tool Result]: {'connected_peers': ['12D3KooWD3m6Jfry...'], 'dht_size': 1, ...}--Agent > There is currently 1 active peer connected to the mesh with Peer ID 12D3KooWD3m6Jfry...-```--### Example 2: Call Remote Tools Dynamically-If another node on the mesh is hosting a tool (e.g. `everything.get-sum`), you can ask Gemini to compute a sum. It will find the tool, query its schema, and execute it:--```text-You > Can you sum 1234.5 and 5678.9 using a tool in the mesh?--[Agent wants to call tool: find_remote_tools with args: {}]-[Tool Result]: ... 'name': 'everything.get-sum', 'description': 'Sums two floats', 'peer_id': '12D3KooWD3m6Jfry...' ...--[Agent wants to call tool: describe_remote_tool with args: {'peer_id': '12D3KooWD3m6Jfry...', 'tool_name': 'everything.get-sum'}]-[Tool Result]: {'inputSchema': {'properties': {'a': {'type': 'number'}, 'b': {'type': 'number'}}, 'required': ['a', 'b']}}--[Agent wants to call tool: call_remote_tool with args: {'peer_id': '12D3KooWD3m6Jfry...', 'tool_name': 'everything.get-sum', 'arguments': {'a': 1234.5, 'b': 5678.9}}]-[Tool Result]: {'result': {'sum': 6913.4}}--Agent > The sum of 1234.5 and 5678.9 is 6913.4, calculated using the 'everything.get-sum' tool hosted on peer 12D3KooWD3m6Jfry...-```diff --git a/site/content/docs/integrations/openclaw.md b/site/content/docs/integrations/openclaw.mddeleted file mode 100644index e81789ad..00000000--- a/site/content/docs/integrations/openclaw.md+++ /dev/null@@ -1,59 +0,0 @@-----title: "Integrating SAM with OpenClaw"-linkTitle: "Integrating SAM with OpenClaw"-----You can seamlessly integrate your `sam-node` as a remote MCP server in [OpenClaw](https://openclaw.ai), allowing your agents to dynamically discover and invoke tools across the mesh.--## Overview--By configuring your `sam-node` as an MCP server, you enable your OpenClaw agents to access the P2P mesh, discovering tools from remote nodes and executing services as if they were local.--## Configuration--To bridge your local `sam-node` into your OpenClaw agent runtime, use the `openclaw mcp` CLI. Ensure your node is running and identify the API token configured in your `sam-node` launch arguments.--```bash-# Add your local sam-node as an MCP server-# Replace <YOUR_TOKEN> with the token used in --api-token-openclaw mcp set p2p-mesh-node '{- "url": "http://localhost:8080/mcp",- "transport": "sse",- "headers": {- "X-Sam-Authentication": "Bearer <YOUR_TOKEN>"- }-}'-```--## Verification--Once configured, restart your OpenClaw gateway to initialize the bridge. You can verify the configuration and connectivity with the following commands:--1. List configured servers: Ensure `p2p-mesh-node` appears in the registry.- ```bash- openclaw mcp list- ```--2. Inspect the bridged tools: Confirm the server entry and its connection details.- ```bash- openclaw mcp show p2p-mesh-node- ```--## Discovering and Invoking Remote Tools--OpenClaw is a generic MCP client and exposes no SAM-specific CLI flags. Once the bridge is active, the tools that `sam-node` provides — `discover_remote_services`, `find_remote_tools`, `describe_remote_tool`, and `call_remote_tool` — are surfaced directly to your agent, which calls them like any other tool. The flow mirrors the local MCP API:--1. **Discover services**: the agent calls `discover_remote_services` (e.g. with `{"type": "mcp"}`) to list active MCP services on the mesh and obtain their `peer_id`s.--2. **Find remote tools**: the agent calls `find_remote_tools`, passing the target `peer_id`, to list the tools that peer hosts.--3. **Describe a remote tool**: the agent calls `describe_remote_tool`, passing the target `peer_id` and the namespaced `tool_name`, to fetch the tool's `input_schema`. This is required to learn the expected argument structure before invoking it.--4. **Invoke a remote tool**: the agent calls `call_remote_tool`, passing the target `peer_id`, the namespaced `tool_name` (e.g. `everything.get-sum`), and the tool's `arguments` (matching the schema from the previous step). Your local `sam-node` proxies the call across the P2P mesh and returns the result.--Because these tools are surfaced automatically, no remote tool needs to be registered individually in OpenClaw.--## Troubleshooting--* Connection Issues: Ensure `sam-node` is reachable at the configured URL (default `http://localhost:8080/mcp`).-* Authentication: Double-check that the `X-Sam-Authentication` header matches the the node API token (`SAM_API_TOKEN` env or `--api-token-path`) provided to your `sam-node`.-* Gateway Status: Use `openclaw status` to confirm the gateway is running and the MCP bridge is active.diff --git a/site/content/docs/integrations/openrouter.md b/site/content/docs/integrations/openrouter.mddeleted file mode 100644index 033f6eb6..00000000--- a/site/content/docs/integrations/openrouter.md+++ /dev/null@@ -1,89 +0,0 @@-----title: "Exposing Inference Services: OpenRouter"-linkTitle: "OpenRouter Inference"-description: "How to deploy OpenRouter as a secure, mesh-native inference service in SAM"-weight: 40------# Exposing Inference Services: OpenRouter--In the Sovereign Agent Mesh (SAM), large language models (LLMs) and foundational model APIs are exposed across the mesh as **Inference Services**, not just standard Model Context Protocol (MCP) servers. This allows your deployed agents to dynamically discover, route, and consume inference capabilities directly through the P2P network, utilizing SAM's decentralized authorization (Biscuit) for access control.--This guide explains how to expose [OpenRouter](https://openrouter.ai/) as an inference service to the mesh, completely shielding your API keys from external peers.--## 1. The Proxy Architecture--SAM enforces a Zero Trust architecture. Rather than distributing your `OPENROUTER_API_KEY` to every agent in the network, you deploy a local proxy container alongside a dedicated `sam-node`.--The `sam-node` handles the P2P routing and mesh identity (validating incoming requests from other mesh agents). The proxy container (such as [`litellm`](https://litellm.ai/) or standard Nginx) holds the API key and securely forwards the requests upstream to `https://openrouter.ai/api/v1`.--```mermaid-sequenceDiagram- participant Agent as Remote Agent- participant Node as sam-node- participant Proxy as litellm Proxy- participant OpenRouter as OpenRouter API-- Agent->>Node: P2P Inference Request (Biscuit Auth)- Note over Node: Validates Biscuit Policy- Node->>Proxy: Forward Request (Localhost)- Note over Proxy: Injects OPENROUTER_API_KEY- Proxy->>OpenRouter: API Call- OpenRouter-->>Proxy: Streaming Response- Proxy-->>Node:- Node-->>Agent: P2P Response-```--## 2. Configuring the Inference Service--To expose the proxy to the mesh, you must define it as an `inference` service in your node's configuration (`sam-node.yaml`), and set the `target_url` to the proxy's local endpoint.--```yaml-version: "v1alpha1"-services:- - type: inference- name: openrouter- description: "OpenRouter Proxy Inference Service"- target_url: "http://localhost:4000" # Local endpoint of the proxy-```--## 3. Decentralized Authorization--By default, services on your node are completely locked down. To allow agents in the mesh to utilize your OpenRouter inference service, you must explicitly allow the service via the node's local `attenuation` policies.--The service format for an inference service is always `inference:<service-name>`.--To allow **any** authenticated mesh agent to use the service, no local attenuation policies are necessary—the control plane will manage access centrally based on the node's assigned roles.--If you only want to allow specific identities or groups (e.g., agents belonging to the "research" group) and want to enforce this restriction locally at the node (regardless of control plane configuration), you can add a local check based on the cryptographic facts injected by the control plane:-```yaml-version: "v1alpha1"-attenuation:- checks:- - 'check if group("research");'-```--## 4. Deploying the Node--When deploying (for instance, via Kubernetes), you deploy both containers in the same Pod so they can communicate over `localhost`.--```yaml- containers:- # 1. The litellm Proxy holding the secret key- - name: openrouter-proxy- image: ghcr.io/berriai/litellm:main-stable- command: ["litellm", "--model", "openrouter/auto", "--port", "4000"]- env:- - name: OPENROUTER_API_KEY- value: "sk-or-v1-..."-- # 2. The SAM node enforcing P2P authorization- - name: sam-node- image: ghcr.io/google/sam-node:latest- args:- - "run"- - "--config=/etc/sam/sam-node.yaml"- # ... (other required arguments like --jwt-path)-```--Once running, any authorized agent in the Sovereign Agent Mesh can discover the `inference` service via the catalog and route inference requests securely through your node!diff --git a/site/content/docs/integrations/vscode-copilot.md b/site/content/docs/integrations/vscode-copilot.mddeleted file mode 100644index 2100df91..00000000--- a/site/content/docs/integrations/vscode-copilot.md+++ /dev/null@@ -1,442 +0,0 @@-----title: "Integrating SAM with VS Code and GitHub Copilot"-linkTitle: "Integrating SAM with VS Code"-----You can connect your `sam-node` to VS Code as an MCP server, so GitHub Copilot's-agent mode can discover and call tools from anywhere on the SAM mesh.--## Overview--`sam-node` serves a standard Model Context Protocol endpoint over Streamable-HTTP. VS Code is a generic MCP client, so once the server is registered its-tools — `get_mesh_info`, `list_local_services`, `discover_remote_services`,-`find_remote_tools`, `describe_remote_tool` and `call_remote_tool` — appear-alongside Copilot's own.--Worth being clear about what this arrangement is. Copilot connects as an-ordinary MCP client over the node's API, not as a sandboxed agent behind a-`sam-box`. It gets the node's tools; it does not get a per-agent policy, an-egress allowance or a boundary. That is the right shape for a coding assistant-on your own machine, and the wrong one for untrusted code — for that, see-[Running agents on SAM]({{< relref "/docs/user/running-agents" >}}).--## Prerequisites--- A running `sam-node` serving its API (default `http://localhost:8080`). See- the [Quick Start]({{< relref "/docs/quickstart" >}}).-- The node's API token — the `SAM_API_TOKEN` you started it with, or the- contents of `--api-token-path`.-- VS Code with GitHub Copilot, in agent mode.--## Configuration--Create `.vscode/mcp.json` in your workspace:--```json-{- "inputs": [- {- "type": "promptString",- "id": "sam-api-token",- "description": "SAM node API token",- "password": true- }- ],- "servers": {- "sam-mesh": {- "type": "http",- "url": "http://localhost:8080/mcp",- "headers": {- "X-Sam-Authentication": "Bearer ${input:sam-api-token}"- }- }- }-}-```--The token is deliberately not in the file. `promptString` with-`"password": true` makes VS Code ask for it once and keep it in its own secret-store, which means the file is safe to commit and safe to share — useful,-because it is also the shortest description of how to attach an agent to a node.--For every workspace rather than one, put the same JSON in your user-level-`mcp.json` instead: run **MCP: Open User Configuration** from the command-palette.--`type` must be `http`. Without it the entry is read as a stdio server and will-not load.--## Start the server--Creating the file is not enough, and this is the step that most often looks like-a broken node. VS Code does not automatically run a server it has just been told-about: it waits to be asked.--Open `.vscode/mcp.json` and click the **Start** action VS Code-shows directly above the `"sam-mesh"` entry. It will prompt for the token the-first time.--If nothing seems to happen, run **MCP: List Servers** from the command palette.-That distinguishes the two failures cleanly:--- `sam-mesh` is missing entirely — the file is not being read. Check it is at- `.vscode/mcp.json` in the workspace root and is valid JSON.-- `sam-mesh` is listed but stopped — it was read and is simply waiting. Start it.--A useful property of the "waiting" case is that it leaves no trace: if the-server was never started, the MCP log has no entry for it at all, successful or-failed. An empty log is evidence of a server that was never asked to run, not of-one that ran and failed.--## Verification--Ask Copilot directly:--> What does `get_mesh_info` say about this node?--A healthy node reports a `router_peer_id`, a non-empty `connected_peers`, and a-`local_api_socket`.--New tools do not always appear in an in-progress chat. If Copilot claims it has-no mesh tools while **MCP: List Servers** shows the server running, start a new-chat, and check `sam-mesh` is ticked in the tools picker on the chat input.--## Install the SAM skill--The MCP tools let Copilot reach the mesh. The skill tells it when reaching for-the mesh is the right move, and how to go about it — discover before describing,-describe before calling.--```bash-sam-node skill install-```--This writes `~/.claude/skills/sam-mesh/SKILL.md`, which VS Code also reads.-`sam-node skill install --project` writes it into the current repository-instead, and `sam-node skill list` shows whether an installed copy is current:--```console-$ sam-node skill list-SAM skill (sam-mesh):- outdated ~/.claude/skills/sam-mesh/SKILL.md Claude-```--Reinstall when it says `outdated`, and reload the window afterwards.--## Examples--Copilot decides when to reach for these. What follows is what to ask, and the-real responses from a node attached to the public testnet — abridged where-marked, but not otherwise tidied up.--### Look at the mesh--> What's the state of the mesh from this node?--Calls `get_mesh_info` with `{}`:--```json-{- "connected_peers": [- "12D3KooWNuHQXgEu3fbaBPKnkPCfSsEVjNvpD5Rh3hcfGeJsDzm7",- "12D3KooWAjWy4GrQDq27AjXgBbKPrNgWhmmxN221mC9oAYNRcZcs"- ],- "dht_size": 3,- "local_api_socket": "/home/you/.config/sam-mesh/sam.sock",- "router_peer_id": "12D3KooWQQHDRrSfZp2S4RRTYz3pd3Fremsb5ZaP3XXg4CNZGDQj"-}-```--Two fields are easy to misread. `connected_peers` was 18 entries long in this-capture while `dht_size` was 3 — they count different things, so a small-`dht_size` next to a long peer list is not a fault. And `local_api_socket` is a-Unix socket that answers the same HTTP API without a token, because filesystem-permissions already decide who may open it. It is the easier way to script-against your own node.--### Find out what is out there--> What MCP services can this node reach?--Calls `discover_remote_services` with `{"type":"mcp"}`:--```json-[- {"peer_id": "12D3KooWFQrX…9Uwe1V", "srv_name": "everything",- "srv_description": "MCP everything test server (tools, resources, prompts)"},- {"peer_id": "12D3KooWAjWy…RcZcs", "srv_name": "everything",- "srv_description": "MCP everything test server (tools, resources, prompts)"}-]-```--Note `everything` appearing twice under different peers. Service names are-not unique across the mesh and were never meant to be — the `peer_id` is the-identity. Any step that remembers "the everything service" without remembering-which peer will eventually talk to the wrong one.--### Find tools, and read the failures--> List the tools available on the mesh.--Calls `find_remote_tools` with `{}`. The real answer mixes successes and-failures in one array:--```json-[- {"peer_id": "12D3KooWFQrX…9Uwe1V", "tool_name": "mcp://everything",- "error": "failed to connect: failed to connect client: calling \"initialize\": EOF"},- {"peer_id": "12D3KooWAjWy…RcZcs", "tool_name": "mcp://everything/get-sum",- "description": "Returns the sum of two numbers"},- {"peer_id": "12D3KooWAjWy…RcZcs", "tool_name": "mcp://everything/echo",- "description": "Echoes back the input string"}-]-```--Discovery is best-effort per peer. One of the two `everything` peers was-reachable enough to be listed but failed at `initialize`, and that is reported-as an `error` field on the entry rather than failing the whole call. A partly-broken mesh returns a partly populated array, so it is worth checking whether-the tool you wanted came back with a `description` or an `error`.--Narrow the search with `service_name` or `tool_name` when you already know the-target; `tool_name` is served from gossip announcements and is the fastest path.--### Call a tool on someone else's machine--> Use the everything service on the mesh to add 2 and 3.--`describe_remote_tool` first, with the peer and the namespaced name exactly as-discovery returned them:--```json-{- "tool_name": "mcp://everything/get-sum",- "description": "Returns the sum of two numbers",- "input_schema": {- "type": "object",- "properties": {- "a": {"type": "number", "description": "First number"},- "b": {"type": "number", "description": "Second number"}- },- "required": ["a", "b"]- }-}-```--Then `call_remote_tool` with `arguments` matching that schema — `{"a": 2, "b": 3}`-— which returned:--```text-The sum of 2 and 3 is 5.-```--The describe step is not ceremony. Names are namespaced `scheme://service/tool`,-not `service.tool`, and the arguments here are `a` and `b` rather than the-`numbers` array a guess might have produced. Both are the provider's to change.--### Use a model the mesh provides--Inference is not an MCP tool and is never called with `call_remote_tool`.-`discover_remote_services` with `{"type":"inference"}` inventories the providers-— on this mesh, a vLLM TPU service and an OpenRouter proxy — but to actually use-one you talk HTTP to the node's OpenAI-compatible facade at-`http://localhost:8080/v1`.--Over the tokenless local socket:--```console-$ curl -s --unix-socket ~/.config/sam-mesh/sam.sock http://localhost/v1/models-{"object":"list","data":[- {"id":"openrouter/auto","object":"model","created":0,- "owned_by":"12D3KooWHfiw…8T5YP"}-]}-```--`owned_by` is the peer serving the model. Note that two inference services were-discovered but only one model is listed: discovery inventories services, while-`/v1/models` lists models that answered the catalog walk. Ask for a model that-is not in this list and it resolves to no provider and comes back 404 — so read-the catalog rather than assuming a name.--A completion is the ordinary OpenAI shape, and took 3.3s here:--```bash-curl -s --unix-socket ~/.config/sam-mesh/sam.sock \- http://localhost/v1/chat/completions \- -H 'Content-Type: application/json' \- -d '{"model":"openrouter/auto",- "messages":[{"role":"user","content":"Reply with exactly: mesh inference works"}]}'-```--Over TCP instead of the socket, add-`-H "X-Sam-Authentication: Bearer $SAM_API_TOKEN"`. Any OpenAI SDK works too:-point `base_url` at `http://localhost:8080/v1`.--## Developing an agent against the mesh--Everything above treats Copilot as a client of your node. The other half of the-loop is writing an agent that runs *behind* a boundary, and VS Code is a-comfortable place to do it: edit the harness in the editor, run it in a-container with no network at all, and watch the boundary decide what it may-reach.--The example lives in `development/examples/agent-harness`. Build it with the-repository root as the build context, because the image compiles `nano-init`-from source:--```bash-docker build -t agent-harness -f development/examples/agent-harness/Dockerfile .-```--Start a boundary for it. `--sidecar-socket` is the node's local API socket, the-same tokenless socket `get_mesh_info` reported, so a node you are already-running is a node you can already develop against:--```bash-sam-box run \- --socket /tmp/sam-demo/agent.sock \- --sidecar-socket ~/.config/sam-mesh/sam.sock \- --bundle development/examples/agent-harness/bundle.yaml \- --insecure-unverified-bundle \- --metrics-addr 127.0.0.1:9600-```--It says what that insecure flag costs, and it is right to:--```text-WARN --insecure-unverified-bundle: this bundle is taken at its word, so- whoever can write it decides which agent this sandbox is-INFO Serving agent researcher-1.prod.acme.example-INFO Agents reach the mesh at http://mesh.sam.alt-```--That is fine on your laptop and not fine anywhere else. In production the-bundle's claim is checked against a platform-issued credential.--### Watch it bootstrap itself--Now run the agent with no network:--```bash-docker run --rm \- --network none \- --cap-add NET_ADMIN \- --device /dev/net/tun \- -v /tmp/sam-demo/agent.sock:/run/agent.sock \- agent-harness "Use your mesh tools to find out how many peers this node is connected to."-```--`--network none` is the assertion, not the arrangement. The container has no-interface, no resolver, no route and no credentials; `NET_ADMIN` and-`/dev/net/tun` exist only so `nano-init` can build the single `tun0` that leads-to the mounted socket. If this worked because the container could route-somewhere, it would prove nothing.--The real output:--```text-mesh offered model: openrouter/auto-mesh granted 6 tools: call_remote_tool, describe_remote_tool,- discover_remote_services, find_remote_tools, get_mesh_info,- list_local_services-step 1: get_mesh_info({})-This node is connected to **23 peers**.-```--Nothing was configured. The harness asked `mesh.sam.alt` for a model, asked it-for tools, was granted fifteen, chose one, called it, and answered — from inside-a container that cannot reach anything else. The catalog is answered per agent,-so the list is not a property of the node but of who is asking.--### Watch policy refuse something--The bundle allows `api.github.com` and `*.githubusercontent.com`, and nothing-else. Run a probe in the same sandbox:--```bash-docker run --rm --network none --cap-add NET_ADMIN --device /dev/net/tun \- -v /tmp/sam-demo/agent.sock:/run/agent.sock \- --entrypoint nano-init agent-harness \- run /run/agent.sock python -c '-import urllib.request as u-for url in ["https://api.github.com/zen", "https://example.com"]:- try:- r = u.urlopen(url, timeout=25)- print(url, "->", r.status, r.read(60))- except Exception as e:- print(url, "->", type(e).__name__, e)-'-```--```text-[TCP] dial 100.64.0.2:443: boundary refused: 403 Forbidden (not allowed by policy)-https://api.github.com/zen -> 200 b'Responsive is better than fast.'-https://example.com -> URLError: [Errno 104] Connection reset by peer-```--The agent sees a reset connection, which is all a denied agent should learn. The-reason lives outside the sandbox, on the boundary, in metrics you can read while-you develop:--```console-$ curl -s http://127.0.0.1:9600/metrics | grep sam_box_flows_total-sam_box_flows_total{outcome="allowed",route="external"} 1-sam_box_flows_total{outcome="allowed",route="mesh-entrypoint"} 19-sam_box_flows_total{outcome="denied",route="unresolved"} 1-```--Nineteen mesh flows for one short run — model catalog, tool listing, the tool-call — one allowed external flow, one denial. Editing `bundle.yaml` and-restarting `sam-box` changes those numbers without touching the agent at all,-which is the property worth developing against: policy is not in the code.--### A trap worth knowing--The harness asks the mesh for a model rather than hardcoding one, and takes the-first the catalog offers. On a mesh offering `google/gemma-2-2b-it` first, that-run fails:--```text-mesh offered model: google/gemma-2-2b-it-openai.BadRequestError: Error code: 400 -- {'error': {'message': 'System role not supported', ...}}-```--Not a mesh fault and not a policy denial — Gemma has no system role, and the-harness sends a system prompt. Pin a model with `-e SAM_MODEL=openrouter/auto`-while developing, and remember that "whatever the mesh offers first" is a-different model on different days.--## Troubleshooting--**401 from the server.** The token does not match the node's. It is the-`SAM_API_TOKEN` the node was started with. VS Code caches what you typed, so-clear it with **MCP: Reset Cached Tokens** and reconnect.--**Server unreachable.** Check the node is listening:--```bash-curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/mcp-```--`401` is a healthy answer — it means the endpoint is there and wants the token.-Connection refused means the node is not running.--**Tools do not appear.** Confirm the server is actually running with **MCP:-List Servers** — see [Start the server](#start-the-server). If it is running,-start a new chat: a chat already in progress may not pick up newly registered-tools.--**A tool is discovered but will not run.** Look for an `error` field on the-entry `find_remote_tools` returned. `failed to connect … calling "initialize":-EOF` means the peer is advertising a service whose backend is not answering —-that is the provider's problem, not yours, and another peer offering the same-service name may well work.--**No remote tools found at all.** Check `get_mesh_info` first. A `dht_size` of-zero means the node has not found the mesh, and no amount of discovery will help-until it has. An empty `connected_peers` means it has not even reached a router.--**Everything works but nothing is sandboxed.** That is by design here — see the-note at the top. Copilot is a client of your node, not an agent behind a-boundary.diff --git a/site/content/docs/manifests/mock-oidc.yaml b/site/content/docs/manifests/mock-oidc.yamldeleted file mode 100644index b654f027..00000000--- a/site/content/docs/manifests/mock-oidc.yaml+++ /dev/null@@ -1,149 +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.--apiVersion: v1-kind: ConfigMap-metadata:- name: mock-oidc-script-data:- server.py: |- import json- import time- import jwt- from http.server import BaseHTTPRequestHandler, HTTPServer-- # The signing key is generated fresh on every start and the JWKS derived from- # it, so no private key ships in this manifest. Even so: this issuer signs any- # identity it is asked for. Never point a reachable control plane at it.- from cryptography.hazmat.primitives import serialization- from cryptography.hazmat.primitives.asymmetric import rsa-- def _b64url_uint(n):- import base64- raw = n.to_bytes((n.bit_length() + 7) // 8, 'big')- return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')-- _KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)- PRIVATE_KEY = _KEY.private_bytes(- serialization.Encoding.PEM,- serialization.PrivateFormat.PKCS8,- serialization.NoEncryption(),- )- _PUB = _KEY.public_key().public_numbers()- JWKS = {- "keys": [- {- "kty": "RSA",- "alg": "RS256",- "use": "sig",- "kid": "test-key-id",- "n": _b64url_uint(_PUB.n),- "e": _b64url_uint(_PUB.e),- }- ]- }-- class Handler(BaseHTTPRequestHandler):- def do_GET(self):- if self.path == '/.well-known/openid-configuration':- body = {- 'issuer': 'http://mock-oidc:18080',- 'authorization_endpoint': 'http://mock-oidc:18080/auth',- 'token_endpoint': 'http://mock-oidc:18080/token',- 'jwks_uri': 'http://mock-oidc:18080/keys'- }- data = json.dumps(body).encode('utf-8')- self.send_response(200)- self.send_header('Content-Type', 'application/json')- self.send_header('Content-Length', str(len(data)))- self.end_headers()- self.wfile.write(data)- return- if self.path == '/keys':- data = json.dumps(JWKS).encode('utf-8')- self.send_response(200)- self.send_header('Content-Type', 'application/json')- self.send_header('Content-Length', str(len(data)))- self.end_headers()- self.wfile.write(data)- return- self.send_response(200)- self.end_headers()- self.wfile.write(b'ok')-- def do_POST(self):- if self.path == '/token':- payload = {- 'iss': 'http://mock-oidc:18080',- 'aud': 'sam-e2e',- 'sub': 'test-user',- 'exp': int(time.time()) + 3600,- 'roles': ['admin', 'user']- }- token = jwt.encode(payload, PRIVATE_KEY, algorithm='RS256', headers={'kid': 'test-key-id'})- body = {- 'access_token': token,- 'token_type': 'Bearer',- 'expires_in': 3600- }- data = json.dumps(body).encode('utf-8')- self.send_response(200)- self.send_header('Content-Type', 'application/json')- self.send_header('Content-Length', str(len(data)))- self.end_headers()- self.wfile.write(data)- return- self.send_response(404)- self.end_headers()-- print("Mock OIDC server ready", flush=True)- HTTPServer(('0.0.0.0', 18080), Handler).serve_forever()-----apiVersion: apps/v1-kind: Deployment-metadata:- name: mock-oidc-spec:- replicas: 1- selector:- matchLabels:- app: mock-oidc- template:- metadata:- labels:- app: mock-oidc- spec:- containers:- - name: mock-oidc- image: python:3.12- command: ["sh", "-c", "pip install pyjwt cryptography && python /app/server.py"]- volumeMounts:- - name: script-volume- mountPath: /app- volumes:- - name: script-volume- configMap:- name: mock-oidc-script-----apiVersion: v1-kind: Service-metadata:- name: mock-oidc-spec:- type: LoadBalancer- ports:- - port: 18080- targetPort: 18080- selector:- app: mock-oidcdiff --git a/site/content/docs/manifests/sam-control-plane.yaml b/site/content/docs/manifests/sam-control-plane.yamldeleted file mode 100644index a92901ce..00000000--- a/site/content/docs/manifests/sam-control-plane.yaml+++ /dev/null@@ -1,131 +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.--apiVersion: v1-kind: Secret-metadata:- name: sam-control-plane-secret-type: Opaque-stringData:- SAM_OIDC_ISSUER: "http://mock-oidc:18080"- # Authenticates the policy admin API. Replace before using this outside a demo.- SAM_ADMIN_TOKEN: "replace-me-with-a-generated-token"-----apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-control-plane- labels:- app: sam-control-plane-spec:- replicas: 1- selector:- matchLabels:- app: sam-control-plane- template:- metadata:- labels:- app: sam-control-plane- spec:- containers:- - name: sam-control-plane- image: sam-control-plane:local- imagePullPolicy: IfNotPresent- args:- - "--bind-address=0.0.0.0:8080"- - "--db-driver=sqlite"- - "--db-dsn=/data/control-plane.db"- - "--issuer=$(SAM_OIDC_ISSUER)"- - "--allowed-audiences=sam-mesh-audience,sam-control-plane-audience"- - "--insecure-skip-tls-verify"- ports:- - containerPort: 8080- name: http- env:- - name: SAM_OIDC_ISSUER- valueFrom:- secretKeyRef:- name: sam-control-plane-secret- key: SAM_OIDC_ISSUER- - name: SAM_ADMIN_TOKEN- valueFrom:- secretKeyRef:- name: sam-control-plane-secret- key: SAM_ADMIN_TOKEN- volumeMounts:- - name: db-data- mountPath: /data- volumes:- - name: db-data- emptyDir: {}-----apiVersion: v1-kind: Service-metadata:- name: sam-control-plane-spec:- type: ClusterIP- selector:- app: sam-control-plane- ports:- - protocol: TCP- port: 8080- targetPort: 8080- name: http-----# The control plane starts default closed: it has no policy until one is posted.-# Seed it over the admin API, which is the only way policy is ever set.-#-# SECURITY: a role names what its members may call; a binding names who they-# are. The special member "sam:system:authenticated" matches EVERY identity-# the configured OIDC issuer will vouch for — bound to a wildcard role it-# hands every tool on every node to anyone who can obtain a token from that-# issuer. Never ship that combination. Grant explicit services to explicit-# members, as below.-apiVersion: batch/v1-kind: Job-metadata:- name: sam-control-plane-seed-policy-spec:- template:- spec:- restartPolicy: OnFailure- containers:- - name: seed- image: curlimages/curl:8.6.0- env:- - name: SAM_ADMIN_TOKEN- valueFrom:- secretKeyRef:- name: sam-control-plane-secret- key: SAM_ADMIN_TOKEN- command:- - sh- - -c- - |- set -eu- until curl -sf -o /dev/null http://sam-control-plane:8080/healthz; do sleep 2; done- curl -sf -X POST \- -H "Content-Type: application/json" \- -H "Authorization: Bearer ${SAM_ADMIN_TOKEN}" \- -d '{- "roles": [- {"name": "demo-caller", "allowed_services": ["mcp://calculator", "system://sam.catalog"], "allowed_targets": ["user:test-user"]}- ],- "bindings": [- {"role": "demo-caller", "members": ["user:test-user"]},- {"role": "sam:role:node", "members": ["user:test-user"]}- ]- }' \- http://sam-control-plane:8080/policiesdiff --git a/site/content/docs/manifests/sam-router.yaml b/site/content/docs/manifests/sam-router.yamldeleted file mode 100644index 5567a6dd..00000000--- a/site/content/docs/manifests/sam-router.yaml+++ /dev/null@@ -1,89 +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.--apiVersion: v1-kind: ServiceAccount-metadata:- name: sam-router-sa-----apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-router- labels:- app: sam-router-spec:- replicas: 1- selector:- matchLabels:- app: sam-router- template:- metadata:- labels:- app: sam-router- spec:- serviceAccountName: sam-router-sa- containers:- - name: sam-router- image: sam-router:local- imagePullPolicy: IfNotPresent- args:- - "--control-plane=http://sam-control-plane:8080"- - "--insecure-control-plane"- - "--listen=/ip4/0.0.0.0/tcp/4501"- - "--listen=/ip4/0.0.0.0/udp/4501/quic-v1"- - "--jwt-path=/var/run/secrets/tokens/sam-token"- - "--keys-path=/data/router.key"- - "--allow-loopback"- ports:- - containerPort: 4501- protocol: TCP- name: p2p-tcp- - containerPort: 4501- protocol: UDP- name: p2p-udp- volumeMounts:- - name: sam-token- mountPath: /var/run/secrets/tokens- readOnly: true- - name: router-data- mountPath: /data- volumes:- - name: sam-token- projected:- sources:- - serviceAccountToken:- path: sam-token- expirationSeconds: 3600- audience: "sam-control-plane-audience"- - name: router-data- emptyDir: {}-----apiVersion: v1-kind: Service-metadata:- name: sam-router-spec:- type: LoadBalancer- selector:- app: sam-router- ports:- - protocol: TCP- port: 4501- targetPort: 4501- name: p2p-tcp- - protocol: UDP- port: 4501- targetPort: 4501- name: p2p-udpdiff --git a/site/content/docs/preview/_index.md b/site/content/docs/preview/_index.mdnew file mode 100644index 00000000..f1dded60--- /dev/null+++ b/site/content/docs/preview/_index.md@@ -0,0 +1,24 @@+---+title: "Preview"+linkTitle: "Preview"+weight: 6+---++Features that work end to end and are tested in CI, but whose interfaces,+flags or file formats may still change between releases. You can use them+today. Expect to adjust your configuration when you upgrade, and report what+you find.++- [Sandboxed agents](sandboxed-agents/): run an agent inside a sandbox that+ has no network interface and holds no credentials. A boundary process+ outside the sandbox decides which names the agent may reach.+- [Agent architecture](agent-architecture/): the design behind the+ sandbox: why the boundary uses named HTTP tunnels, how an agent gets an+ identity, and how an agent serves.+- [SAM Connect](mobile/): the Android and iOS app that turns a phone into a+ node.+- [Scale report](scale-report/) and [how to reproduce it](scale-experiment/):+ what a sandboxed agent costs, measured up to a thousand agents on one host.++Everything outside this section (the node, the routers, the control plane,+identity, policy and the deployment guides) is the stable core.diff --git a/site/content/docs/preview/agent-architecture.md b/site/content/docs/preview/agent-architecture.mdnew file mode 100644index 00000000..0f5a4788--- /dev/null+++ b/site/content/docs/preview/agent-architecture.md@@ -0,0 +1,481 @@+---+title: "Agent architecture"+linkTitle: "Agent architecture"+weight: 2+aliases:+ - /docs/agent-architecture/+---++{{% alert title="Preview" color="warning" %}}+This is the design behind [sandboxed agents](../sandboxed-agents/). The+decisions here are settled; the interfaces that implement them are still+being shaped, and the last section lists what is not built yet.+{{% /alert %}}++This page explains how an unmodified agent, running inside a sandbox with no+network of its own, is connected to the mesh. It covers the layers, the+reasons for each layer, the contracts between them, and the limits of what+the design guarantees. The [scale report](../scale-report/) measures what+the result costs.++## Goals++1. **The harness is unmodified and does not know about the mesh.** It opens+ ordinary sockets, resolves ordinary names and speaks ordinary HTTP. It+ needs no SDK, no `LD_PRELOAD`, and no proxy variables.+2. **One enforcement point.** Every flow that the sandbox emits is authorized+ in exactly one place, by name, against one policy.+3. **The sandbox has no network.** This means no network device other than+ the one the design gives it, and not a filtered network. Isolation is a+ property of the runtime and not of a firewall rule.+4. **The mesh looks like the internet.** Reaching a mesh model or tool is the+ same operation as reaching `api.github.com`: connect to a name. Which+ names are internal to the mesh is a policy decision on the host, not a+ code path in the agent.+5. **No new dependencies on the host.** The guest-side network stack lives in+ its own Go module.++## Why one enforcement point++There are three common ways to intercept a sandbox's traffic at the+application layer. Each of them requires the agent to cooperate with its own+confinement:++- **Proxy environment variables** are honoured only by HTTP-aware clients. A+ raw socket, a library with `trust_env=False`, gRPC or Postgres bypass+ them.+- **DNS spoofing** forces every flow through an interception point and+ answers with loopback addresses. This destroys the destination name, which+ is what the policy engine needs to reason about.+- **An `LD_PRELOAD` shim** must be built for each architecture and libc, and+ a statically linked binary bypasses it.++An agent that has to agree to be confined is not confined. Routing does not+have this problem, because nothing has to agree to a route. So the boundary+is a route and a socket, and there is exactly one of them.++## The layering++```text+┌─ sandbox (microVM, or container with network=none) ────────────────┐+│ harness (unmodified: sockets, DNS, HTTP) │+│ │ IP │+│ tun0 ── default route, the only device besides lo │+│ │ │+│ nano-init / tun2connect ── IP flows → CONNECT (TCP), connect-udp │+│ │ destination kept as a NAME (virtual DNS)│+└──────┼─────────────────────────────────────────────────────────────┘+ │ one byte stream per flow+ │ microVM: AF_VSOCK → firecracker → host UDS <path>_<port>+ │ container: bind-mounted UDS+┌──────┼─────────────────────────────────────────────────────────────┐+│ host ▼ │+│ sam-box (one per sandbox; no libp2p host, no enrollment) │+│ = CONNECT server = the policy enforcement point │+│ ├── mesh.sam.alt → /v1/* and /mcp only ──┐ │+│ ├── <svc>.<type>.sam.alt → discover, then ├─▶ sam-node+│ │ /sam/<peer>/<type>/… │ (UDS) │+│ └── anything else → deny-by-default egress → internet│+└────────────────────────────────────────────────────────────────────┘+```++### Named HTTP tunnels are the boundary protocol++The boundary speaks authority-form `CONNECT` (RFC 9110) for TCP and+connect-udp (RFC 9298, with capsules as in RFC 9297) for UDP, over a Unix+socket. Four properties decided this choice over the alternatives (an earlier+design used SOCKS5):++- **It carries the destination name.** `CONNECT api.github.com:443`+ authorizes `api.github.com`, and not an address. connect-udp carries the+ name in its URI template. No DNS interception is needed, and there are no+ IP allowlists that go stale.+- **It is protocol-agnostic.** After `200 OK` the tunnel is a byte pipe.+ HTTP is the handshake, and the payload can be any protocol.+- **It has a vocabulary for refusals.** A denial is `403` with a+ `Boundary-Reason` header, which the guest stack turns into `ECONNREFUSED`.+ The agent sees a refused connection, and the operator reads the reason in+ words.+- **Headers are the extension point, and one grammar serves both+ directions.** Ingress into a sandbox is `CONNECT <port>`. Sandbox identity+ for a boundary that serves many agents rides in `Proxy-Authorization`. UDP+ fits on the same stream as capsules. And `curl --proxy` speaks the TCP+ half, so the boundary can be tested with a tool that every operator has.++### Names are resolved on the host, never in the guest++The guest's virtual DNS answers every lookup with a synthetic address from+pools that it invents: IPv4 from `100.64.0.0/10` (CGNAT space; link-local+addresses would be safer against leaks, but SSRF guards in HTTP clients+commonly block `169.254/16`), and IPv6 from `100::/64` (the RFC 6666 discard+prefix, so a packet that escapes is dropped). The engine maps the address+back to the name when the flow opens, and the boundary receives the name. A+flow to an address that was never resolved has no name and is refused in the+guest. There is no resolver path out of the sandbox, so there is no DNS+exfiltration either.++### The host never speaks AF_VSOCK++Firecracker's vsock device terminates `AF_VSOCK` and gives the host a Unix+socket per guest port, named `<uds_path>_<port>`. The boundary therefore+always listens on a Unix socket, and a microVM and a `network=none`+container are the same code path:++| Sandbox | Guest side | Host side |+|---|---|---|+| Firecracker microVM | vsock CID 2, port *P* | listener on `<uds>_P` |+| container, `network=none` | `/run/sam/agent.sock` | listener on the bind-mounted path |++This keeps vsock out of the Go code. More importantly, it makes the whole+datapath testable in a Go integration test against a socket in a temporary+directory, without a VM.++### A mesh name is the service namespace in DNS shape++The mesh's namespace is `mcp://<service>`, `inference://<service>`,+`a2a://<service>` and `system://sam.catalog`. Sandbox names are a projection+of it, declared once in `api/names.go` so that the boundary and the node+cannot drift apart:++```text+inference://openrouter <-> openrouter.inference.sam.alt+mcp://code-reviewer <-> code-reviewer.mcp.sam.alt+(the mesh, curated) <-> mesh.sam.alt+```++`.alt` is the pseudo-TLD that RFC 9476 reserves for names that are not+resolved through the DNS. It cannot collide with a delegated TLD, and a name+that escapes the sandbox fails closed. `.local` belongs to mDNS and was+rejected.++Provider selection is not part of the name. `openrouter.inference.sam.alt`+says which service, never which peer. Pinning a peer would need a DNS-safe+encoding of peer IDs (base58 is case-sensitive, DNS labels are not) and is+deferred.++### The agent is the principal, and the node is the channel++Policy has to be able to say "agent `foo` may use `inference://X`, agent+`bar` may not". The whole mesh has to be able to evaluate that statement, and+it has to survive the agent being paused on one host and resumed on another.+So agent identity travels with the agent and never with the host.++A credential is bound to a peer ID, and a verifier checks that binding on+every connection. That is right for the channel and wrong for the question+"who is asking". The mesh already takes in a foreign identity once, at node+enrollment, by verifying an OIDC token and translating claims into facts.+Agents reuse that pattern one level down:++| | Asserted by | Verified against | When | On the datapath as |+|---|---|---|---|---|+| node identity | control plane | the OIDC issuer | enrollment | a credential |+| agent identity | the `sam-box` that admitted the agent | the platform's workload issuer | admission | a claim next to the credential |++The claim travels next to the credential (`X-Sam-Agent` on HTTP, `agent` in+the stream authentication frame), and not inside it. Biscuit lets a holder+append blocks to a token, but a verifier evaluates the facts of an appended+block only against that block's own checks, never against the authorizer's+policy. This is intentional, because otherwise attenuation could grant+instead of only narrow. `TestAttenuationBlockFactsAreInvisibleToTheAuthorizer`+in `internal/identity` pins this behaviour. Carrying the claim in a header+costs nothing cryptographically. Whoever can append a block can append any+block, so a node's claim about which agent it speaks for is worth exactly+what the node is worth, in either form.++The remaining trust is this: an enrolled node asserts its own agents. Mesh+policy limits this with the role's `allowed_agents`, the namespaces that a+node may name. A node with no grant can name no agent. The grant is keyed on+the node's role, which is resolved from verified claims against bindings+that an administrator wrote. It is not keyed on the node's labels, which the+node declares itself. Proof of possession by the agent would remove the+remaining trust. It needs a signer inside the sandbox and third-party blocks+in the Biscuit library, and it can be added later without a rewrite.++## Where the boundary lives++Two binaries with separate jobs. **`sam-node`** owns the libp2p host,+enrollment, identity, discovery and the local API. **`sam-box`**, one per+sandbox, owns none of those. It serves the tunnel boundary, enforces egress+policy, and reaches the mesh only by dialling the node's API socket as a+client.++This split has several benefits. *N* sandboxes on a host share one libp2p+host, so there are not *N* DHT clients, identify loops or router+connections, which would otherwise limit density. `sam-box` is small: a+CONNECT server and an HTTP client. A compromised sandbox affects only its+own boundary, which can be killed and started again on its own. And the+agent never touches the node's API socket. That matters because reaching+the socket is itself a credential: the socket can proxy to any peer and+service that the node's grants allow. `sam-box` is a client of the node. The+agent is a client of the mesh, through `sam-box`.++## Contracts++### What the harness sees++```text+OPENAI_BASE_URL=http://mesh.sam.alt/v1+MCP_URL=http://mesh.sam.alt/mcp+```++There is no proxy variable, no CA bundle and no token. A harness that wants+one specific service instead of policy-chosen routing uses the service's+mesh name: `http://code-reviewer.mcp.sam.alt/`. Mesh names use `http://` on+purpose. The transport underneath is libp2p, which is already authenticated+and encrypted, and plain HTTP avoids installing a CA in the guest.++### Dispatch++The boundary applies these rules to the tunnel's `(host, port)`, where+`host` is the preserved name, in this order:++1. **`mesh.sam.alt`**: the boundary's own surface, served in process:+ `/v1/models`, `/v1/chat/completions`, `/v1/completions`, `/mcp`. Any+ other path is `403` and never reaches the node. Discovery is not exposed+ here because MCP already provides it as tools.+2. **`<service>.<type>.sam.alt`**: the boundary terminates HTTP, asks the+ node's `/sam/service/discover` for a provider, and reverse-proxies to+ `/sam/<peer>/<type>/<service>/<path>`.+3. **Anything else**: the egress allowance from the bundle (or from+ `--egress-allow` for an unidentified sandbox). Allowed flows are dialled+ directly, by the name that was authorized. For TLS, the client's SNI must+ match that name.+4. **No match**: `403 Boundary-Reason: not allowed by policy`.++Only case 2 inspects the payload, and only because provider selection is an+HTTP-level decision.++### What a sandbox must provide++`nano-init` builds the route out of a sandbox. It does not build the sandbox+itself. Three runtimes are supported, and each must satisfy the same five+preconditions:++| Precondition | `docker --network none` | Firecracker | Kubernetes pod |+|---|---|---|---|+| a network namespace with no way out | the runtime | the guest kernel, given no NIC | **nothing provides it**; `nano-init --create-namespaces` builds it |+| a private `resolv.conf` | the container's mount namespace | the guest rootfs | **nothing provides it**; mount one per container |+| a Unix socket to the boundary | bind mount | vsock, exposed on the host as `<uds>_<port>` | shared `emptyDir` |+| a way to create a TUN | `--device /dev/net/tun --cap-add NET_ADMIN` | `CONFIG_TUN` in the guest kernel | `hostPath` of type `CharDevice`, no capability |+| PID 1 | the entrypoint | `/sbin/init` | the entrypoint |++A pod shares one network namespace and one `resolv.conf` across its+containers, so the sandbox has to create both for itself. It first creates a+user namespace, in which it holds `CAP_SYS_ADMIN` and `CAP_NET_ADMIN` over+what it creates next, so the container needs no capability. Granting+`CAP_SYS_ADMIN` alone is worse than granting nothing: the namespace is+created, and then the tun fails.++This failure produces no error (`tun0` next to `eth0` is a working network),+so `nano-init` refuses to start in a namespace that has any interface other+than loopback and its own tun, whichever runtime is in use.++## Agent identity++### Requirements++1. **Portable.** An agent paused on node A and resumed on node B is the same+ principal.+2. **Verifiable across the mesh.** Any peer can decide "agent `foo` may,+ agent `bar` may not" without asking anyone.+3. **Scalable.** There is no central per-agent record, no per-agent mint on+ the hot path, no list of agents in any policy, and no revocation list+ that grows with the agent population.++### Why it scales++**Admission is local.** The control plane never mints a credential per+agent. It grants a node's role authority over an agent namespace once. The+boundary then asserts a per-agent identity under that namespace, with no+round trip and no central state.++**Policy is written over namespaces.** The same machinery that compiles+`allowed_services` wildcards compiles `allowed_agents` into+`granted_agent_prefix`, `_suffix`, `_set` and `_exact`, and the destination+derives `agent_authorized()` from them. "Foo yes, bar no" is a namespace, a+set or a prefix, never a list of a billion names.++**Revocation has three levels.**++| What happened | Mechanism | Cost |+|---|---|---|+| the agent is done or misbehaving | kill the sandbox | instant, local |+| its credential must stop working elsewhere | the platform stops renewing the short-lived workload credential | a bounded window, no list |+| a node is compromised | ban the node | one entry ends every agent that it spoke for |++### Where identity comes from++Identity does not come from the agent, which is unmodified and could only+lie about itself. It comes from the credential that the platform already+issues to the workload: a Kubernetes projected service account token, a pod+certificate, a SPIFFE SVID. `sam-box` verifies the credential against the+issuer named by `--credential-issuer` and `--credential-audience` at+admission, which is cheap and stays inside the cluster. It accepts the bundle+only if the subject of the credential matches the bundle's `external_id`.+The subject check is the important one. Every sandbox on a platform holds a+valid credential, so a signature alone would let any sandbox claim to be any+other. The issuer is a flag and not a bundle field, because the bundle+travels with the agent.++Verification is the default. `--insecure-unverified-bundle` runs without it,+and the flag is visible in a process listing.++The identity is then bound to the channel, so nothing is asserted in-band.+By default there is one socket per agent, fixed when the sandbox is created.+A boundary that serves many agents over one socket takes the agent id per+connection in `Proxy-Authorization` Basic credentials.++### The bundle++What the platform provides per agent. It lives in the agent's own state+directory, so it migrates with the agent:++```yaml+version: v1+agent:+ id: reviewer-7.prod.acme.example # canonical mesh identifier+ external_id: spiffe://acme.example/prod/reviewer-7 # verbatim, for audit and the subject check+ credential: /var/run/secrets/platform/token # the platform's workload credential+egress:+ allow: ["api.github.com", "*.pypi.org"]+serves: # optional: the agent's own A2A service+ name: code-reviewer+ port: 8080+```++Parsing is strict. An unknown field is an error, because a typo that parsed+as "absent" would give an agent broader access than intended.++### The identifier++The identifier is dot-separated and DNS-shaped, with the most specific label+first: `reviewer-7.prod.acme.example`, matched by `*.prod.acme.example`. The+policy engine decided this shape. Wildcards compile to facts that keep their+anchoring dot, so `evil-acme.example` cannot match `*.acme.example`, and+every other name in the system (services, mesh hosts) has the same shape.++The identifier is a mesh convention, in the same way that `user`, `email`+and `group` are. External systems do not adopt it. A connector translates+into it, and the translation must be:++1. **Total**: every foreign identity maps to exactly one identifier.+2. **Injective**: no two foreign identities collide. The rightmost labels+ must be an authority that the platform controls.+3. **Hierarchy-preserving**: boundaries in the foreign hierarchy land on+ dots, otherwise wildcard policy cannot express them.+4. **Auditable**: the original travels unchanged as `external_id`.+5. **Bounded**: the name includes a label for the boundary where the workload+ credential stops being valid, usually the cluster. Node grants are+ written against that label. A mapping without it forces tenant-wide+ grants.++| Foreign identity | Mesh identifier |+|---|---|+| `spiffe://acme.example/prod/reviewer-7` | `reviewer-7.prod.acme.example` |+| Kubernetes SA `prod/reviewer` in cluster `c1.acme.example` | `reviewer.prod.c1.acme.example` |+| OIDC `iss=https://acme.example`, `sub=reviewer-7` | `reviewer-7.acme.example` |++Attributes that are not hierarchical do not belong in the name. Attested+labels exist for those.++### What the claim covers++The claim covers attribution and policy on both datapaths. A provider can+authorize and audit "agent `reviewer-7` called me" over HTTP for inference+and over the libp2p stream for tools, using the ordinary `agent()` fact. On+the stream path the claim is bound to the MCP session instead of the+request. This fits, because one boundary serves one agent, so a session+belongs to one agent for its whole life.++The claim is not a proof (it is the node's word, limited by+`allowed_agents`), and it does not cover anything that never leaves the+node. One consequence to design around: a node's own housekeeping carries no+agent. A provider whose policy demands an agent unconditionally therefore+also refuses that node's model-catalog probe, and its models disappear from+the peers' `/v1/models` even though agents can still call them. Policy that+intends to gate agent traffic should say so explicitly, instead of demanding+an agent everywhere.++## Agents that serve++An agent serves exactly one thing: itself, over A2A. Tools and models are+operator workloads declared in a node's configuration. An agent is not a+generic backend.++Nothing is registered at run time. A runtime declaration carries a name, so+an agent could advertise itself as `code-reviewer` under the node's identity+and take over someone else's traffic. If it could also give a URL, it could+point the mesh anywhere. So the route is contracted before the agent runs:++- The bundle's `serves` names the service and the port (like `$PORT` on a+ serverless runtime).+- The node's configuration declares the `a2a` service with the boundary's+ ingress listener as its backend.+- The node probes the agent's card through the boundary before it+ advertises the service, and keeps probing.++Readiness is observed, never assumed. When the sandbox goes away, the probe+fails and discovery converges. On resume on another host, the same bundle+produces the same contract, and the probe points discovery at the new+location.++Inbound traffic is the one place where the datapath is not shaped like+egress. The boundary cannot dial the agent, because the agent's loopback is+inside its own namespace. So the way in mirrors the way out: a second Unix+socket, served from inside by `nano-init --ingress-socket` and dialled by+`sam-box --agent-ingress-socket`, with one stream per request+(`CONNECT <port>`). This is the same handshake that Firecracker's vsock+uses, so a microVM offers it without any change in the boundary.++| Channel | Direction | Protocol | Who listens |+|---|---|---|---|+| egress | guest → host | CONNECT, connect-udp | host (`sam-box`) |+| ingress | host → guest | `CONNECT <port>`, one stream per request | guest (`nano-init`) |++Authorization needs nothing new. The caller's node authorized the caller,+with its agent claim, before the stream reached the boundary. "Agent `foo`+may call agent `bar`" is one policy statement, evaluated at the node of+`bar`, with both ends named by portable identities.++## The platform integration interface++This is the interface that a scheduler builds against, and the only place+where identity enters. It is small and versioned. It consists of the bundle+above (YAML, with its canonical copy as a file in the agent's state) and+four operations (`Attach`, `Detach`, `Refresh`, `Status`) whose request and+response messages are defined in `api/sam.proto`.++The interface gives a connector these guarantees:++- `Attach` is idempotent by agent id, so resume after a crash or migration+ is another `Attach`.+- Identity never arrives in-band from the sandbox.+- The agent id is stable across `Attach` calls on different hosts.+- `Detach` is complete, and leaves no advertisement behind.+- The schema is versioned.++## Not built yet++- The control socket that serves the four operations. Today the bundle is a+ file read at start, and the lifecycle of the boundary is the lifecycle of+ the process.+- Credential rotation (`Refresh`). The credential is verified once at start.+- Secret injection for external destinations. The ephemeral CA and header+ rewriting exist in `internal/sambox` but are not on this datapath.+- Peer-pinned mesh names, which need a DNS-safe peer ID encoding.+- Bulk pre-creation of agents. `Attach` is idempotent per id, so an+ `AttachBatch` can be added later.++## Testing++Coverage sits as low in the test pyramid as possible. Unit tests cover the+tunnel grammar, the capsule codec, name projection, dispatch classification+and allowlist matching. Integration tests (`tests/integration/`, under ten+seconds each) run the whole datapath without containers: nodes with fake+backends, a `sam-box` on a socket in a temporary directory, real `CONNECT`+tunnels, and assertions that mesh names reach the right peer, that allowed+names reach a local server, that refused names get `403`, and that no path+outside `/v1/*` and `/mcp` reaches the node. Two end-to-end tests exist: a+`--network none` container with the real harness, and the same rootfs under+Firecracker. The second is skipped without `/dev/kvm`, and it proves only+the vsock mapping.diff --git a/site/content/docs/preview/mobile.md b/site/content/docs/preview/mobile.mdnew file mode 100644index 00000000..7a8e5284--- /dev/null+++ b/site/content/docs/preview/mobile.md@@ -0,0 +1,140 @@+---+title: "SAM Connect (Android and iOS)"+linkTitle: "SAM Connect"+weight: 3+aliases:+ - /docs/user/mobile-app/+ - /docs/development/mobile/+---++{{% alert title="Preview" color="warning" %}}+The app is functional and tested in CI on an Android emulator. Its screens,+the on-device tools it exposes and the FFI surface may change.+{{% /alert %}}++SAM Connect is a Flutter app that runs `sam-node` on a phone. The Go node is+compiled into a shared library and driven over Dart FFI. The app is the UI+around it, plus a small MCP server that exposes the phone's sensors to the+mesh. A phone enrolled this way is a node like any other. It has a key, a+credential and a peer ID, and it appears in discovery with its+`phone-sensors` service.++## Using it++### Enroll++The first screen offers three ways to enroll:++- **Scan enrollment code**: point the camera at the `sam://enroll?...` QR+ code that `sam-one` prints at start, or that `sam-one token qr` creates.+ The app shows which control plane the code leads to before it uses the+ token. The phone's stock camera app opens the same link.+- **Enter details manually**: paste a control plane URL and a bootstrap+ token.+- **Login & Enroll** / **Device Login**: for a control plane with an identity+ provider, log in through the browser or with a device code.++The control plane URL must be `https`. The app accepts plaintext only for+`localhost`.++### Start++The **Start** button on the dashboard launches the node as a foreground+service, so it stays connected while the phone is idle. The dashboard shows+the peer ID (labelled **Node ID**), the connected peers and the DHT size.++### Services++The Services tab switches the built-in sensors on and off: **Battery+Status** (`get_battery_status`: level and charging state) and **Location**+(`get_location`: coordinates, with the OS permission). Enabled sensors are+published as the `phone-sensors` MCP service.++### Config++The Config tab holds what `sam-node.yaml` holds on a desktop: labels+(comma-separated `key=value`) and the attenuation rules, policies and checks+(one Datalog statement per line, with the same syntax and the same errors as+the file). Labels are attested at enrollment, so changing them requires+pressing **Re-enroll**. Re-enrollment uses the stored OIDC refresh token or+bootstrap identity and keeps the peer ID. The tab also shows the API token+that protects the node's local API on the phone.++On Android 16 the app also registers two AppFunctions, `getMeshStatus` and+`callRemoteMeshTool`, so an on-device assistant can use the mesh without the+app in the foreground.++## Calling the phone from elsewhere++From any enrolled node, the phone is a peer with an MCP service:++```bash+mcp-client -url "http://127.0.0.1:8080/sam/<phone-peer-id>/mcp/phone-sensors" -token "$TOKEN" -list+mcp-client -url "http://127.0.0.1:8080/sam/<phone-peer-id>/mcp/phone-sensors" -token "$TOKEN" -tool get_battery_status+```++```json+{"battery_level": 64, "charging": true}+```++An agent finds the phone in the usual way. `find_remote_tools` lists+`mcp://phone-sensors/get_location`, `describe_remote_tool` shows that it+takes no arguments, and `call_remote_tool` returns+`{"latitude": ..., "longitude": ...}`. The policy on the control plane+decides who may call it. The phone's own attenuation rules can narrow that+further.++## How it is built++```text+Flutter app (mobile/sam-node-app)+ lib/main.dart the UI; talks to the node's local API over 127.0.0.1+ lib/sam_ffi.dart Dart FFI wrapper+ │ C calls+Go FFI library (mobile/sam-node-ffi)+ StartNode, StopNode, EnrollNode, EnrollNodeBootstrap, ReEnrollNode,+ UnenrollNode, IsEnrolled, GetNodeID, GetMeshInfo, CallRemoteTool, ...+ │+sam-node (internal/node), unchanged+```++The FFI package is a thin export layer over the same node code that the CLI+uses, including `CompleteNodeConfig` for labels and attenuation, so both+agree on validation. Lifecycle operations go over FFI. Everything else the+UI does (listing peers, toggling services) goes over HTTP to the node's+loopback API with a token generated at each launch.++Make targets:++| Target | Output |+|---|---|+| `make mobile-ffi-host` | `bin/libsam.so` for the build host, for desktop tests of the FFI. |+| `make mobile-ffi-android` | `bin/android/libsam.so` (arm64-v8a). |+| `make mobile-ffi-android-x86_64` | `bin/android-x86_64/libsam.so`, for x86_64 emulators. Emulators on Apple Silicon run arm64 images and use the previous target. |+| `make mobile-ffi-ios` | `bin/ios/libsam.a`. |+| `make mobile-app-apk` | The FFI library copied into `jniLibs/` and a release APK. `mobile-app-apk-emulator` and `mobile-app-bundle` are the emulator and Play Store variants. |++For an edit-run loop on a device:++```bash+make mobile-ffi-android+mkdir -p mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a+cp bin/android/libsam.so mobile/sam-node-app/android/app/src/main/jniLibs/arm64-v8a/+cd mobile/sam-node-app && flutter run+```++Release builds read signing material from `ANDROID_KEYSTORE_PATH`,+`ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS` and `ANDROID_KEY_PASSWORD`,+and Firebase configuration from `GOOGLE_SERVICES_JSON` or its base64 form.+`mobile/sam-node-app/README.md` covers the toolchain setup.++## Testing++`mobile/mobile_e2e.sh` runs the end-to-end check that CI uses. It starts a+mock identity provider, a control plane, a router and a host node with a+test tool. It then boots an Android emulator with the app, enrolls it,+registers a tool inside the emulator, and checks that each side discovers+the other's tool through the mesh.++The app's privacy policy, for the store listing, is at+[/docs/privacy/](../../privacy/).diff --git a/site/content/docs/preview/sandboxed-agents.md b/site/content/docs/preview/sandboxed-agents.mdnew file mode 100644index 00000000..8a68c037--- /dev/null+++ b/site/content/docs/preview/sandboxed-agents.md@@ -0,0 +1,358 @@+---+title: "Sandboxed agents"+linkTitle: "Sandboxed agents"+weight: 1+aliases:+ - /docs/user/running-agents/+ - /docs/user/secure-gateway/+---++{{% alert title="Preview" color="warning" %}}+The sandbox works end to end and is exercised in CI, but `sam-box` flags,+the bundle format and `nano-init`'s options may change between releases.+{{% /alert %}}++An agent is a harness, a model and some tools. To deploy one you normally+ship all three, plus a key for the model, plus network access that is wide+enough for whatever the tools turn out to need. On SAM you ship only the+harness. The mesh provides the model and the tools by name, and the network+the agent gets is a list of names that is checked on every connection.++The agent holds no credential. There is no API key, mesh token or service+account file in the sandbox, and no proxy variable. An agent that holds a+key can leak it, and an agent that can be talked into leaking a key will+eventually do so.++## The pieces++```mermaid+flowchart LR+ subgraph sandbox["sandbox: no NIC, no DNS, no credentials"]+ H["agent harness<br/>(your code)"]+ T["nano-init (PID 1)<br/>tun0 · userspace TCP · virtual DNS"]+ H -- "plain HTTP to mesh.sam.alt" --> T+ end+ subgraph host["host"]+ B["sam-box<br/>one per agent<br/>holds no mesh identity"]+ N["sam-node<br/>one per host<br/>the mesh member"]+ end+ M(["the mesh"])+ T -- "named CONNECT tunnels<br/>over a Unix socket" --> B+ B -- "node API socket<br/>+ X-Sam-Agent" --> N+ N <--> M+ B -. "allowed names only" .-> E([internet])+```++**`nano-init`** is PID 1 inside the sandbox. It creates a `tun0` device,+makes it the default route, and terminates the sandbox's TCP/IP in userspace+(gVisor's netstack, through the `tun2connect` library). For each connection+the agent opens, it opens one named HTTP tunnel to the boundary:+`CONNECT host:port` for TCP and `connect-udp` for UDP. Its virtual DNS+answers every lookup with a synthetic address (from `100.64.0.0/10` or+`100::/64`) and remembers the pairing, so the tunnel carries the name that+the agent asked for. An address that the agent never resolved has no name+and is refused. `nano-init` also reaps orphan processes and forwards+signals. It lives in its own Go module, because a userspace network stack+does not belong in the dependency graph of the other binaries.++**`sam-box`** is the boundary. There is one per agent, on the host side of+the Unix socket. It has no libp2p host, no enrollment and no mesh identity.+It is a client of the local `sam-node`'s API socket. For each tunnel it+classifies the name and decides:++| Name | Decision |+|---|---|+| `mesh.sam.alt` | The mesh surface: `/v1/models`, `/v1/chat/completions`, `/v1/completions`, `/mcp`. Any other path is `403`. |+| `<service>.mcp.sam.alt` | One specific mesh service. Discovery chooses the provider. |+| anything else | Matched against the agent's egress allowance. A name that is not in the allowance is refused. |++A refusal fails the `CONNECT` with `403` and a `Boundary-Reason` header. The+sandbox's network stack turns this into an ordinary connection reset. The+agent sees a refused connection. The operator sees the reason in the+boundary's log and metrics.++**`sam-node`** is unchanged. It is the mesh member, one per host, and it+holds the identity. Adding an agent costs one `sam-box`, and no new+enrollment or new peer in the DHT.++The split matters because reaching the node's API socket is itself a+credential. The socket cannot register services (they are static), but it+can call anything that the node's grants allow. So the agent never touches+the socket. `sam-box` uses the node on the agent's behalf and offers the+agent a narrower surface.++## What the agent sees++```python+client = AsyncOpenAI(base_url="http://mesh.sam.alt/v1", api_key="unused")++async with streamable_http_client("http://mesh.sam.alt/mcp") as (read, write):+ async with ClientSession(read, write) as session:+ await session.initialize()+ tools = await session.list_tools()+```++These are ordinary SDK clients with nothing SAM-specific in them. The+`api_key` is a placeholder that the SDK requires. The agent does not know+which peer serves the model and cannot find out. Two agents behind the same+node can see different tool lists, because the mesh answers according to who+is asking. A refused tool call comes back as an error that the model can+read, not as a crash.++## Identity is asserted about the agent, not by the agent++`sam-box` reads a **bundle** that the platform writes outside the sandbox:++```yaml+version: v1+agent:+ id: researcher-1.prod.acme.example+ external_id: system:serviceaccount:agents:researcher+egress:+ allow:+ - api.github.com+ - "*.githubusercontent.com"+serves:+ name: code-reviewer+ port: 8080+```++Writing that file is not enough to become that agent. `sam-box` verifies a+platform credential (`--credential-issuer`, `--credential-audience`; on+Kubernetes this is a projected service account token) and accepts the bundle+only if the subject of the credential matches `external_id`. On every+request it then names the agent to the node in the `X-Sam-Agent` header,+replacing anything that the sandbox tried to set. The destination node+accepts that name only if the calling node's credential grants the namespace+through the role's `allowed_agents`. A node granted `*.c1.acme.example`+cannot speak for `researcher-1.prod.acme.example`. The namespace belongs to+the node and the identifier belongs to the agent. This is why an agent keeps+its name when it is paused on one host and resumed on another.++Wildcard egress entries match subdomains only: `*.pypi.org` matches+`files.pypi.org`, but not `pypi.org` and not `evilpypi.org`. Matching uses+the name that the agent asked for, never a resolved address.++The issuer is a flag and not a bundle field on purpose. The bundle travels+with the agent, so an issuer named inside it could be one that an attacker+controls.++## Running it++The example harness in+[`development/examples/agent-harness`](https://github.com/google/sam/tree/main/development/examples/agent-harness)+is about a hundred lines. It discovers tools, calls a model, runs the tool+loop, and stops.++Start a node that serves its API on a socket:++```bash+sam-node run --socket-path /run/sam/node.sock --data-dir /var/lib/sam --bind-addr=+```++Start a boundary for the agent:++```bash+sam-box run \+ --socket /run/sam/agent.sock \+ --sidecar-socket /run/sam/node.sock \+ --bundle ./bundle.yaml \+ --credential-issuer https://kubernetes.default.svc \+ --credential-audience sam \+ --metrics-addr 127.0.0.1:9600+```++On a laptop without a platform issuer, `--insecure-unverified-bundle` skips+the credential check. It logs what this means: whoever can write the bundle+decides which agent the sandbox is. This is a flag that shows in a process+listing, so the choice is visible.++Start the sandbox as a container:++```bash+docker run --rm \+ --network none \+ --cap-add NET_ADMIN --device /dev/net/tun \+ -v /run/sam/agent.sock:/run/agent.sock \+ agent-harness "Summarise the open issues in our repo"+```++`--network none` is what makes this a sandbox. `NET_ADMIN` and+`/dev/net/tun` are needed only so that `nano-init` can create the single+`tun0`. The image's entrypoint is `nano-init run /run/agent.sock <command>`.+`nano-init copy <dest>` copies the binary into an image that contains+nothing else.++Look at what happened:++```console+$ curl -s http://127.0.0.1:9600/metrics | grep sam_box_flows_total+sam_box_flows_total{outcome="allowed",route="external"} 1+sam_box_flows_total{outcome="allowed",route="mesh-entrypoint"} 19+sam_box_flows_total{outcome="denied",route="unresolved"} 1+```++Refusals do not show up as latency, so counting them is the only way to see+them. If you edit the bundle and restart `sam-box`, these numbers change+without any change to the agent.++## Sandbox types++The layers are the same in all three types. Only the way the sandbox reaches+the socket differs.++**Container with `--network none`.** The socket is bind-mounted into the+container. This is the setup shown above.++**Firecracker microVM.** Each agent gets its own kernel, which boots in a+few tens of milliseconds. The guest has no network device. `nano-init`+reaches the boundary over vsock (`vsock://2:1080`). Firecracker terminates+guest vsock connections on the host as `<uds_path>_<port>`, so for a guest+that dials CID 2 port 1080, `sam-box --socket` must serve exactly+`/var/run/sam-vm-1.vsock_1080`. The host never speaks `AF_VSOCK`, and this+is why the same `sam-box` serves containers and VMs. The guest kernel must+have `CONFIG_TUN=y`. The stock Firecracker CI kernels for 5.10 and 6.1 do+not have it. The 6.18 kernel does.++**Kubernetes pod.** The containers in a pod share one network namespace and+one `resolv.conf`, so there is no per-container `--network none`.+`nano-init run --create-namespaces` builds its own namespaces. It first+creates a user namespace, in which it holds `CAP_SYS_ADMIN` and+`CAP_NET_ADMIN` over what it creates next, and then a network namespace that+contains only `tun0`. The container itself needs no capability.++```yaml+apiVersion: v1+kind: Pod+metadata:+ name: agent+spec:+ volumes:+ - { name: sam-uds, emptyDir: {} }+ - { name: tun, hostPath: { path: /dev/net/tun, type: CharDevice } }+ - { name: resolv, configMap: { name: sandbox-resolv } }+ containers:+ - name: sam-node+ image: ghcr.io/google/sam-node:latest+ args: [run, --jwt-path=/var/run/secrets/tokens/sam-token, --bind-addr=, --socket-path=/var/run/sam/node.sock]+ volumeMounts: [{ name: sam-uds, mountPath: /var/run/sam }]+ - name: sam-box+ image: ghcr.io/google/sam-box:latest+ args: [run, --socket=/var/run/sam/agent.sock, --sidecar-socket=/var/run/sam/node.sock, --egress-allow=api.github.com]+ volumeMounts: [{ name: sam-uds, mountPath: /var/run/sam }]+ - name: agent+ image: your-agent-image+ command: [/usr/local/bin/nano-init, run, --create-namespaces, /var/run/sam/agent.sock, python3, /app/agent.py]+ volumeMounts:+ - { name: sam-uds, mountPath: /var/run/sam }+ - { name: tun, mountPath: /dev/net/tun }+ - { name: resolv, mountPath: /etc/resolv.conf, subPath: resolv.conf }+---+apiVersion: v1+kind: ConfigMap+metadata:+ name: sandbox-resolv+data:+ resolv.conf: "nameserver 100.127.255.253\n"+```++Three details are easy to get wrong without any error message:++- **The TUN device is only a `hostPath` mount.** The device cgroup does not+ deny `/dev/net/tun`. What is gated is the `TUNSETIFF` call, and that is a+ capability question that the user namespace answers.+- **No `securityContext`.** Granting `CAP_SYS_ADMIN` alone is worse than+ granting nothing. The namespace gets created, and then the tun fails+ because `CAP_NET_ADMIN` is missing.+- **The sandbox's `resolv.conf` is mounted per container.** `dnsConfig` is a+ pod-level field. It would point `sam-node` at a resolver that exists only+ inside the sandbox's namespace. With the file mounted, `nano-init` finds+ its resolver already configured and needs no bind mount. The bind mount is+ the one operation that containerd's default AppArmor profile denies.++The harness must be a child process of `nano-init`. The `command` above+arranges this. A container that starts the harness directly, or that runs+`nano-init` next to it, leaves the harness in the pod's network namespace,+with `eth0` and every route. It will run, and it will not be sandboxed.+Check:++```console+$ kubectl exec -c agent agent -- ip -o link show | cut -d: -f2+ lo+ tun0+```++Ubuntu 24.04 hosts set `kernel.apparmor_restrict_unprivileged_userns=1`.+This confines an unprivileged process that creates a user namespace to a+profile that denies every capability, and the tun then fails with+`operation not permitted`. Managed clusters apply their own AppArmor profile+and are not affected. A kind cluster on such a host needs the sysctl set to+`0`.++## Agents that serve++An agent can serve one thing: itself, as an A2A agent. Tools and models are+operator workloads declared in a node's configuration. An agent never+advertises one. The whole route is fixed before the agent runs, and nothing+is registered at run time:++- The bundle's `serves` names the service and the port that the agent must+ bind, in the same way `$PORT` works on a serverless runtime. `sam-box`+ routes that name to that port from startup. A name outside the contract+ cannot be expressed.+- The node's configuration declares the service with `type: a2a` and a+ `target_url` that points at the boundary's ingress listener+ (`--ingress-listen`, default `127.0.0.1:7080`).+- The node probes the agent's card through the boundary before it+ advertises the service, and it keeps probing. An agent that has not bound+ its port yet, or that has died, is not discoverable. When it answers, it+ is. Readiness is observed, never assumed. When the boundary stops, the+ probe fails and discovery converges.++Delivering a request into the sandbox cannot mean dialling the agent. The+agent's `127.0.0.1` is inside a namespace that the boundary is not in. So a+second Unix socket carries each inbound request to the contracted port.+`nano-init --ingress-socket` serves it from inside the sandbox, and+`sam-box --agent-ingress-socket` dials it. That flag is required whenever a+bundle has `serves`, and `sam-box` refuses to start without it. The only+other address available would be one in the boundary's own namespace, which+in a pod is the pod's namespace, where the node's API is listening. The+agent's node authorized the caller before the request reached the boundary,+so "agent `foo` may call agent `bar`" is one policy statement, evaluated at+the node of `bar`.++## Not yet built++- **Secret injection** for external destinations. The machinery exists+ (an ephemeral CA, header rewriting) but is not connected to this datapath.+- **Credential rotation.** The bundle's credential is verified when+ `sam-box` starts. Verifying it again when a platform rotates a projected+ token is the `Refresh` operation of the connector interface, which does+ not exist yet.+- **The connector control socket** (`Attach`, `Detach`, `Refresh`,+ `Status`), through which a scheduler would drive `sam-box`. Today the+ bundle is a file, and the lifecycle of the boundary is the lifecycle of+ the process.++## `sam-box run` flags++| Flag | Meaning |+|---|---|+| `--socket` | The sandbox-facing Unix socket, created with mode `0600`. Required. |+| `--sidecar-socket` | The local `sam-node` API socket. Required. |+| `--bundle` | The agent bundle. |+| `--credential-issuer`, `--credential-audience` | The issuer and audience of the platform credential that must back the bundle. Required with `--bundle`. |+| `--insecure-unverified-bundle` | Trust the bundle without a credential. |+| `--egress-allow` | Destination names that an unidentified sandbox may reach. Repeatable. Use the bundle instead when the agent has an identity. If empty, nothing outside the mesh is reachable. |+| `--agent-ingress-socket` | The reverse channel into the sandbox. Required when the bundle has `serves`. |+| `--ingress-listen` | Address on which the boundary's mesh-facing ingress listens. Default `127.0.0.1:7080`. The node's `a2a` service declaration points here. |+| `--metrics-addr` | Prometheus metrics (`sam_box_*`) without authentication. Off by default. |+| `--log-level` | `debug`, `info`, `warn`, `error`. |++## Further reading++- [Agent architecture](../agent-architecture/): the decisions behind this+ design and the reasons for them.+- [Scale report](../scale-report/): the measured cost of a boundary.+- [Authorization](../../concepts/authorization/#agents-acting-through-a-node):+ how `allowed_agents` and the `agent` claim are evaluated.diff --git a/site/content/docs/preview/scale-experiment.md b/site/content/docs/preview/scale-experiment.mdnew file mode 100644index 00000000..fc37114f--- /dev/null+++ b/site/content/docs/preview/scale-experiment.md@@ -0,0 +1,180 @@+---+title: "Scale experiment: reproducing the thousand-agent run"+linkTitle: "Scale experiment"+weight: 5+aliases:+ - /docs/scale-experiment/+---++{{% alert title="Preview" color="warning" %}}+The scripts under `tests/scale/` and `scripts/` are research tooling for the+[scale report](../scale-report/). They are kept working but are not a+supported product surface.+{{% /alert %}}++The report says what was measured and what it means. This page says how to+run it again. The setup is one host, one `sam-node`, and *N* agents. Each+agent is a Firecracker microVM with no network device, and its only way out+is a vsock to its own `sam-box`. A thousand agents have been run on one+`n2-standard-64`.++| Component | Role |+|---|---|+| host VM | `n2-standard-64` on GCP with nested virtualisation; runs the node and one `sam-box` per agent |+| guest | Firecracker microVM, Alpine, about 160 MiB, no network device |+| `nano-init` | PID 1 in the guest: builds `tun0`, carries its own TCP stack, keeps the mesh name on every flow |+| agent | the [example harness](https://github.com/google/sam/tree/main/development/examples/agent-harness), holding no credentials |++## Prerequisites++- A guest kernel with `CONFIG_TUN=y`. The Firecracker quickstart, 5.10 and+ 6.1 CI kernels do not have it. 6.18.41 does. `startup-script.sh` downloads+ a TUN-capable kernel, and fails with a clear error instead of booting a+ guest whose agent can never get a route.+- A bootstrap token at `/etc/sam-bootstrap-token` on the host. The launcher+ refuses to start without one.+- KVM, with `/dev/kvm` writable by the invoking user.++## 1. Build the guest image++Build once, locally, then upload:++```bash+./scripts/build-rootfs.sh gs://my-sam-bucket/scale-test+```++The image holds Alpine, Python, `nano-init` and the example harness as an+ext4 filesystem. It uses the harness and not the chaos agent, because a+scale run needs the same request every time. To build a different agent+into the image, point `AGENT_SRC` at it and give it enough space. An image+that is too small fails during the copy and not at boot:++```bash+ROOTFS_MB=2048 AGENT_SRC=cmd/chaos-agent ./scripts/build-rootfs.sh+```++## 2. Provision the host++```bash+./scripts/provision-scale-vm.sh \+ --prefix sam-minions --count 1 \+ --machine-type n2-standard-64 \+ --local-binaries gs://my-sam-bucket/scale-test \+ --no-spot+```++This builds your local binaries and injects them with a `startup-script.sh`+that downloads everything on boot. Use `--no-spot` for anything you intend+to keep. Spot capacity for this machine type is limited, a reclaimed run+produces no result, and spot instances are terminated by host maintenance+while standard ones are live-migrated. On `ZONE_RESOURCE_POOL_EXHAUSTED`,+try another zone.++## 3. Size the guest++Run once per agent image:++```bash+sudo tests/scale/measure-guest.sh+```++A guest with too little memory fails in ways that look like network faults.+A guest with too much memory wastes the memory that limits the population.+For the harness: 136 MiB fails, 144 MiB runs slowly, 160 MiB runs at full+speed, against a working set of about 206 MiB.++## 4. Launch++```bash+gcloud compute ssh sam-minions-1 --zone us-central1-c++sudo tests/scale/validate-launcher.sh # check that one works before asking for a thousand+sudo SANDBOX_LINGER=2400 /opt/microvm/launch-microvms.sh 1000+```++The launcher checks Firecracker, KVM, the kernel, the rootfs, the binaries+and the token. It then starts one `sam-box` per agent and one microVM per+`sam-box`, all against one node. The rootfs is shared read-only. A private+copy per agent would be half a terabyte at a thousand agents.++`SANDBOX_LINGER` keeps each sandbox open after its agent finishes. A density+measurement needs the whole population resident at the same time. By+default a sandbox powers off when it is done, so a thousand sandboxes+started in sequence are never a thousand at once. Zero is the right value+for real work.++| Variable | Meaning |+|---|---|+| `VM_MEM_MIB` | guest memory, default 160 |+| `SANDBOX_LINGER` | seconds to keep a sandbox after the agent exits, default 0 |+| `SAM_MODEL` | model to ask the mesh for; when unset, the first model in the catalog is used |+| `CONTROL_PLANE` | defaults to the `bananas` testnet |+| `AGENT_DOMAIN` | the domain under which agents are named |++These values reach the guest as kernel command-line pairs, which is the only+way to pass anything to PID 1, so they cannot contain spaces. The launcher+rejects values that do.++## 5. Collect++```bash+sudo tests/scale/collect-fleet.sh \+ --node-socket /var/run/sam-node.sock --duration 1500 --out fleet.jsonl+```++The headline number is how many agents the *node* is serving, and not how+many microVMs were started. A guest that booted and never reached its+boundary is a process, not an agent. The script asks the node and samples+over time, because the shape of the curve shows whether the population came+up smoothly. Watch `sam_node_agents_untracked_total`. If it is not zero, the+agent count is a lower bound and not a measurement.++## 6. Drive load++```bash+sudo tests/scale/load-fleet.sh --agents 200 --requests 200 --out /var/log/load+sudo tests/scale/load-fleet.sh --report /var/log/load+```++Load goes through one boundary per agent, so the node sees *N* principals+and the admission path is exercised as in practice. One generator against+one boundary would measure a socket, not a mesh.++## Watching++```bash+sudo tail -f /var/log/startup-script.log # host setup+sudo tail -f /var/log/fc-vm-1.log # one guest's console, agent output included+sudo curl -s --unix-socket /var/run/sam-node.sock http://localhost/metrics | grep sam_node_agents_seen+```++## The boundary sweep++The other half of the report needs no cloud. It starts a real mesh on kind+and attaches boundaries to it:++```bash+./tests/scale/run-density.sh --steps 1,2,4,8,16,32,64 --requests 500+```++Results are written to `tests/scale/results/` with `environment.json`, the+raw per-step observations and a rendered `table.md`.++## Chaos testing++`cmd/chaos-agent` is a LangChain agent pointed at whatever tools the mesh+grants it and told to abuse them. It answers the question "does the mesh+survive an autonomous caller", and not "what does anything cost", because+it never issues the same request twice.++```bash+ROOTFS_MB=2048 AGENT_SRC=cmd/chaos-agent ./scripts/build-rootfs.sh++sudo SAM_MODEL=google/gemma-2-2b-it CHAOS_SLEEP=30 VM_MEM_MIB=512 \+ /opt/microvm/launch-microvms.sh 25+```++It runs until stopped. It sleeps a random interval between rounds so that a+fleet does not arrive at the providers at the same time, and it treats its+own crashes as data. Like the harness, it holds no credentials and takes its+model from the catalog.diff --git a/site/content/docs/preview/scale-report.md b/site/content/docs/preview/scale-report.mdnew file mode 100644index 00000000..46efa301--- /dev/null+++ b/site/content/docs/preview/scale-report.md@@ -0,0 +1,293 @@+---+title: "Scale report: what an agent costs"+linkTitle: "Scale report"+weight: 4+aliases:+ - /docs/scale-report/+---++{{% alert title="Preview" color="warning" %}}+These measurements are of the sandbox datapath described in+[Sandboxed agents](../sandboxed-agents/). They were recorded on 2026-08-21+at commit `e5b2966`, when the boundary spoke SOCKS5. The boundary has since+moved to HTTP `CONNECT` and has not been measured again. The shape of the+results is what matters. Single figures are indicative.+{{% /alert %}}++The design gives every agent its own boundary, which resolves names and+enforces policy on each flow. That sounds expensive. This page measures it.+The method is written down so that the result can be challenged, and a+script is provided so that it can be run again. There are two experiments: a+sweep of boundaries attached to one node, and a thousand agents in microVMs+on one host.++## Experiment 1: the boundary++### Questions++1. **Density**: what does the *N*th boundary cost in memory?+2. **Startup**: how long does it take from launching a sandbox until it can+ call the mesh, and does that time grow with the population?+3. **Overhead**: how much latency does an agent pay for reaching the mesh+ through a policy instead of a socket?+4. **Enforcement**: does policy hold under load, and what does a refusal+ cost?++### Method++One real mesh (control plane, router, node) on a kind cluster, as in the+end-to-end suite. Boundaries were attached to the node one at a time, as+host processes and not as containers, because the question is what+`sam-box` costs. A container would measure the container runtime.++The load generator, `sam-bench`, issues the same request every time+(`GET /v1/models`) and enters the mesh in the same way an agent does,+through the boundary's socket. Each step of the sweep was measured in four+conditions:++| Condition | Isolates |+|---|---|+| baseline | the node answering over its own socket, with no boundary in the path |+| reused flow | what an agent normally experiences: one admitted flow, many requests |+| new flow per request | admission: the handshake and the policy decision paid every time |+| denied | enforcement, which leaves no latency behind and must be counted separately |++Client latency shows what an agent experienced. The counters on the servers+show what they did, including the flows they refused. Percentiles are+nearest-rank over the full sample, so every figure was observed. Failed+requests never enter the latency distribution. Warmup requests (20 per+condition) are reported separately, because a first call that pays for+discovery is a real cost.++Environment: Intel Xeon 2.60 GHz, 48 vCPU, 118 GiB, Linux 7.1.6, Go 1.26.5.+The sweep covered 1, 2, 4, 8, 16, 32 and 64 sandboxes, with 500 requests per+condition per step at concurrency 4.++### Results++Latency in milliseconds, memory in MB.++| sandboxes | reused p50 | reused p99 | new-flow p50 | new-flow p99 | admission (µs) | idle RSS | total RSS | denied | leaked |+|---|---|---|---|---|---|---|---|---|---|+| 1 | 1.36 | 2.30 | 1.55 | 78.15 | 19 | 20.2 | 0.02 GiB | 500 | 0 |+| 2 | 1.34 | 2.09 | 1.40 | 3.19 | 20 | 19.4 | 0.06 GiB | 500 | 0 |+| 4 | 1.33 | 2.92 | 1.44 | 3.90 | 19 | 19.0 | 0.12 GiB | 500 | 0 |+| 8 | 1.33 | 2.37 | 1.46 | 6.23 | 18 | 18.8 | 0.21 GiB | 500 | 0 |+| 16 | 1.39 | 3.37 | 1.44 | 2.38 | 19 | 18.9 | 0.39 GiB | 500 | 0 |+| 32 | 1.34 | 2.42 | 1.37 | 3.22 | 18 | 18.1 | 0.72 GiB | 500 | 0 |+| 64 | 1.30 | 1.80 | 1.41 | 4.62 | 18 | 17.4 | 1.37 GiB | 500 | 0 |+| *baseline* | *1.39* | *2.37* | | | | | | | |++Every allowed step served 500 of 500 requests. Every denied step served 0 of+500. "Admission" is the boundary's own mean time to classify a destination+and open it. "Leaked" counts requests that reached a destination that policy+forbade.++**Density.** A boundary settles at 17 to 20 MB resident once idle.+Sixty-four of them, with one under continuous load, came to 1.37 GiB. The+per-sandbox mean falls as the population grows because the same boundary+carries all the load at every step while the others sit idle. The marginal+cost of one more agent is the idle figure, not the mean.++**Startup.** Across 64 sandboxes: median 59 ms, min 58, p95 59, max 70,+where ready means that the socket accepts connections. The 64th sandbox+started as fast as the first.++**Overhead.** Baseline p50 was 1.39 ms. Through the boundary on a reused+flow, p50 ranged from 1.30 to 1.39 ms, at or below baseline at every+population size. The boundary did not make requests faster. Its end-to-end+overhead is smaller than the run-to-run variation of the measurement, so+this method cannot measure it. A fresh flow per request, which pays the+handshake and the policy decision each time, can be measured and is small:+p50 +9 to +157 µs over baseline. The boundary's own in-process+instrumentation put classifying and opening a destination at a mean of 18 to+20 µs, and this moved by less than 2 µs between one sandbox and sixty-four.++**Enforcement.** 3,500 attempts at forbidden destinations, zero successes, at+every population size. The boundary's counter agreed with the client's at+every step. Refusals ran at 24,000 to 28,000 per second, about ten times the+allowed rate, because a denied flow is decided from the name and never+dialled.++### Threats to validity++- One machine, one run, no confidence intervals. The overhead result in+ particular is a case where a single figure could be over-interpreted.+- A trivial request. `/v1/models` is a small response from a warm node. It+ isolates mesh overhead because it does almost no work, and for the same+ reason it says nothing about large payloads or streaming.+- Load through one boundary while the rest sit idle. This answers "do the+ others get in the way" and not "what happens when all *N* are busy".+- A reproducible tail anomaly. The single-sandbox, new-flow step showed p99+ excursions of 60 to 80 ms in every run, and this did not happen at higher+ populations. It is left in the record without an explanation.+- Host processes and not sandboxes. This measures the boundary and not the+ isolation around it. A microVM per agent costs much more, and none of that+ is counted here.++## Experiment 2: a thousand agents on one host++One `n2-standard-64`, one `sam-node` enrolled in the public `bananas`+testnet, and a thousand agents. Each agent is a Firecracker microVM with no+network device, and it reaches the mesh through its own `sam-box` over+vsock. The agent is the example harness: connect, discover tools, attempt a+model call, stop. Raw samples are in+[`tests/scale/results/fleet-1k`](https://github.com/google/sam/tree/main/tests/scale/results/fleet-1k).++### Cost++| | total | per agent |+|---|---|---|+| guest microVMs | 162.7 GiB | **167 MiB** |+| boundaries (`sam-box`) | 24.6 GiB | **25 MiB** |+| node (one, for all) | 386 MiB | 0.4 MiB |+| **together** | **187 GiB of 251 GiB** | **192 MiB** |++The node figure is the one that matters for the design. One `sam-node`+served a thousand distinct agent principals in 386 MB, because an agent is+not a peer. It has no enrollment, no key and no place in the DHT. The mesh+gained a thousand principals and no members.++### Startup++A thousand sandboxes launched in 149 seconds, 6.7 per second, with a median+of 153 ms each and a p95 of 245 ms. The population became reachable as fast+as it was started:++| elapsed | agents serving | microVMs | guest memory |+|---|---|---|---|+| 0 s | 71 | 120 | 17.2 GiB |+| 44 s | 328 | 383 | 62.1 GiB |+| 99 s | 691 | 734 | 119.7 GiB |+| 160 s | **1000** | 1000 | 162.7 GiB |+| 323 s | 1000 | 1000 | 162.7 GiB |++Agents trail microVMs by a few seconds and never by more than about fifty.+That gap is a guest booting and resolving its first mesh name, and not a+queue forming. `sam_node_agents_untracked_total` was 0, so the thousand is a+count and not a limit.++### Throughput++With the thousand agents resident, load was driven through 200 of them at+once, each through its own boundary, so the node saw 200 principals and not+200 connections from one client. Each agent sent 200 requests, with two in+flight at a time.++40,000 requests, none failed, in 0.43 s. That is an aggregate of roughly+92,000 requests per second while the other 800 sandboxes sat resident. Per+agent, the median was 534 req/s (min 490, max 652), so no principal was+starved. Client time to first byte: median 2.0 ms, p95 13 ms, p99 21 ms,+worst 98 ms.++This is an upper bound on what the enforcement path permits. It is not a+throughput claim for a deployed workload. The request was answered by the+node itself, so no upstream provider was in the path. The generator entered+at the boundary's socket and not from inside a guest, so the in-guest stack+and the vsock hop are not counted.++The node's own histogram of the 41,000 server-side durations (including+warmup):++| server-side duration | requests | share |+|---|---|---|+| under 0.5 ms | 35,580 | 86.8% |+| under 5 ms | 39,412 | 96.1% |+| under 10 ms | 40,207 | 98.1% |+| under 25 ms | 40,586 | 99.0% |+| 5 to 10 s | 400 | 1.0% |++The last row is not jitter. Those 400 requests took almost exactly 5.04 s+each, which is the node's DHT lookup timeout. `/v1/models` resolves providers+through the DHT. The walk found four peers, but it asks for up to twenty and+has no way to know that four is all there are, so it waited for the full+timeout and then cached the answer for thirty seconds. The cost is one slow+lookup per cache expiry, paid by whoever arrives on a cold cache. Everything+behind the cache is in the sub-millisecond rows above. It is still a real+problem: the two hundred callers who arrived together each paid the lookup+instead of sharing one.++### What an agent gets++Separately, one sandbox was booted and asked what the mesh would give it. The+sandbox was a microVM with no network device, no API key, no model endpoint+and no tool server address. It had only `mesh.sam.alt` to ask.++| | |+|---|---|+| tools | 15, discovered over MCP with their JSON schemas |+| models | `google/gemma-2-2b-it` (a vLLM instance on a TPU elsewhere in the mesh) and `openrouter/auto` (routed outward) |+| credentials in the sandbox | none |+| network devices in the sandbox | none |++Both models answered. A LangChain agent then ran inside the sandbox, took+its model name from the catalog, and produced output from the TPU-hosted+model, using the stock OpenAI and MCP clients without changes. This shows+that the mesh is reachable. It says nothing about how well a 2B model drives+a fifteen-tool loop.++### Threats to validity++- One host, one run.+- The agents are the example harness. A heavier agent needs more guest+ memory, and 167 MiB describes this workload only.+- Memory was measured with the population idle. Throughput came from a+ separate pass over the same resident fleet.+- Load was driven from the host into each boundary's socket, which skips the+ in-guest stack and the vsock hop. The real per-agent limit is lower.+- Only 200 of the thousand agents sent traffic.+- Inference was not exercised in the thousand-agent run. The agents asked for+ a model named `default`, which no catalog contains, and 998 of those calls+ returned `404`. The inference path is the separate demonstration above.+- A thousand is what fit comfortably in 251 GiB with this agent. Nothing here+ found a limit.+- Spot instances were preempted twice during measurement before this run.+ The final run used a standard instance.++## Conclusions++An agent costs about 192 MiB and 150 ms, and nearly all of that is the+microVM. The boundary is 25 MB of it, and the node's share is under half a+megabyte. The number of agents a host can run is decided by how much memory+the agents want.++The mesh does not grow when the agent population grows. A thousand agents+arrived as one member with one enrollment. This is the reason the principal+is separated from the peer.++Enforcement is not a latency problem. It takes 18 to 20 µs to classify and+open a flow, and the end-to-end cost is too small for this method to+separate from noise. Checking every flow does not have to be traded against+performance, which removes the usual reason for such checks being disabled.++Nothing degraded across the ranges tested, and there were no failures where+success was expected and no successes where it was not.++## Reproducing++[Scale experiment](../scale-experiment/) has the step-by-step procedure. In+short:++```bash+# Experiment 1: docker and kind; stands up a real mesh+./tests/scale/run-density.sh --steps 1,2,4,8,16,32,64 --requests 500++# Experiment 2: a host with KVM, a TUN-capable guest kernel, a bootstrap token+./scripts/provision-scale-vm.sh --no-spot --local-binaries gs://your-bucket/sam+# then on the host+SANDBOX_LINGER=2400 /opt/microvm/launch-microvms.sh 1000+/opt/microvm/collect-fleet.sh --node-socket /var/run/sam-node.sock --duration 1500+```++Results land in `tests/scale/results/` with `environment.json`, the raw+observations and a rendered `table.md`. Single measurements by hand:++```bash+# through a boundary, as an agent would+sam-bench run --socket /run/agent.sock --target http://mesh.sam.alt/v1/models \+ --requests 500 --concurrency 4 --scrape http://127.0.0.1:9600/metrics++# the same request with no boundary, for the baseline+sam-bench run --target-unix /run/node.sock --target http://localhost/v1/models \+ --requests 500 --concurrency 4+```diff --git a/site/content/docs/quickstart.md b/site/content/docs/quickstart.mddeleted file mode 100644index f8a62b3d..00000000--- a/site/content/docs/quickstart.md+++ /dev/null@@ -1,257 +0,0 @@-----title: "Quick Start"-linkTitle: "Quick Start"-weight: 1------# Quick Start--This guide gets you up and running with a SAM node connected to the public `bananas.sam-mesh.dev` developer testnet. You can run SAM either directly via a binary or using Docker.--> [!NOTE]-> **Developer Testnet Notice:**-> `bananas.sam-mesh.dev` is a free developer testnet created using community resources. It is provided strictly for developer testing and experimentation and carries **no guarantees, uptime commitments, or persistent warranties**. For production workloads or sovereign private meshes, please see the [Kubernetes Deployment Guide](../user/kubernetes-deployment/) and the [Digital & Data Sovereignty Architecture](../sovereignty/).--## 1. Install SAM--### Option A: Install Script (macOS / Linux)-The easiest way to install the latest binaries directly:-```bash-curl -sL https://sam-mesh.dev/install.sh | bash-```--### Option B: Go Install (macOS / Linux / Windows)-If you have Go installed, you can compile and install directly from the repository:-```bash-go install github.com/google/sam/cmd/sam-node@latest--# Optional: if you want to run your own control plane and router:-go install github.com/google/sam/cmd/sam-control-plane@latest-go install github.com/google/sam/cmd/sam-router@latest-```--### Option C: PowerShell (Windows)-For Windows users without WSL, you can download the latest release using PowerShell:-```powershell-$Release = Invoke-RestMethod -Uri "https://api.github.com/repos/google/sam/releases/latest"-$Version = $Release.tag_name-$Url = "https://github.com/google/sam/releases/download/$Version/sam_Windows_x86_64.zip"-Invoke-WebRequest -Uri $Url -OutFile "sam.zip"-Expand-Archive -Path "sam.zip" -DestinationPath "$env:ProgramFiles\sam"-```-------## 2. Connect Your Node to the Mesh--**Shortcut: let your agent do it.** If you use an agent that supports skills (Claude Code, Google Antigravity, …), install the [agent skill](#4-teach-your-ai-agent-to-use-the-mesh) with `sam-node skill install`, restart the agent, and ask it to connect to the mesh. The skill walks it through starting the node and registering the MCP endpoint on its own — the only thing it hands back to you is the one-time enrollment login below.--Getting a node onto the mesh takes two steps: **joining** — registering the node and obtaining its cryptographic identity (a Biscuit token) via an OIDC login — and **running** it. We recommend doing them as two explicit commands: enrollment is a one-time step per machine whose prompts (browser login, admin approval) are easier to follow on their own, and it is the same flow the [agent skill](#4-teach-your-ai-agent-to-use-the-mesh) guides your agent through. If you prefer a single command, see the [alternative below](#alternative-one-command).--### Recommended: Join, Then Run--Join once to enroll the node, then run it. The identity is stored in the node's data directory and reused on every later start.--#### Step 1: Join the Mesh--To register your node with the mesh and obtain a cryptographic identity token (Biscuit), you can use either the interactive OIDC authorization flow or the non-interactive bootstrap token flow.--##### Option A: Interactive OIDC Flow (Default)--The interactive flow uses your browser to authenticate your identity against Dex (OIDC):--###### Using the Binary-```bash-sam-node join https://bananas.sam-mesh.dev-```--###### Using Docker-```bash-mkdir -p $(pwd)/sam-data-docker run -it \- --user "$(id -u):$(id -g)" \- -v $(pwd)/sam-data:/data \- ghcr.io/google/sam-node:latest \- join --data-dir /data https://bananas.sam-mesh.dev-```--The CLI will output a Device Authorization URL (if headless/Docker) or open your browser natively. Once authenticated, the node registers and saves the identity database.--##### Option B: Non-Interactive Bootstrap Flow (Headless)--If you are deploying a headless server or router and have a generated bootstrap token from the Control Plane API:--###### Using the Binary-```bash-sam-node join --bootstrap-token <your-token> https://bananas.sam-mesh.dev-```--###### Using Docker-```bash-mkdir -p $(pwd)/sam-data-docker run -it \- --user "$(id -u):$(id -g)" \- -v $(pwd)/sam-data:/data \- ghcr.io/google/sam-node:latest \- join --data-dir /data --bootstrap-token <your-token> https://bananas.sam-mesh.dev-```--*Note: In non-interactive mode, unless the control plane runs with `--auto-approve-enrollment`, the enrollment request remains **PENDING** until approved manually by a network administrator.*--#### Step 2: Run the Node--Start your node in the background. We set a security API token (via the `SAM_API_TOKEN` environment variable or `--api-token-path` file) to protect access to the local control plane API. Tokens are never accepted as command-line values: they would be visible in process listings.--##### Using the Binary-```bash-SAM_API_TOKEN=my-secret-token sam-node run --bind-addr 127.0.0.1:8080-```-You should see in the logs:-```text-INFO sam-node [AuthN] Successfully authenticated with router via libp2p: ...-SAM Node Online.-PeerID: 12D3KooW...-```--##### Using Docker-Map the required ports (`5001/udp`, `5002/tcp` for libp2p, and `8080/tcp` for the local API):-```bash-mkdir -p $(pwd)/sam-data-docker run -d \- --name sam-node \- --user "$(id -u):$(id -g)" \- -v $(pwd)/sam-data:/data \- -p 5001:5001/udp \- -p 5002:5002 \- -p 8080:8080 \- -e SAM_API_TOKEN=my-secret-token \- ghcr.io/google/sam-node:latest \- run --data-dir /data --bind-addr 0.0.0.0:8080-```-Verify the node is running with `docker logs sam-node`.--#### 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. In headless mode, SAM prefers OAuth device flow automatically when the provider supports it, and falls back to OOB code-paste only when needed.--#### 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: One Command--The `--join` flag on `run` does both steps in one command: it enrolls the first time (when the node has no identity yet), then starts serving; on every later restart it's a no-op since the identity is already stored. By default `--join` enrolls with the public testnet (`bananas.sam-mesh.dev`); pass `--control-plane <url>` to enroll with a different mesh.--#### Using the Binary-```bash-SAM_API_TOKEN=my-secret-token sam-node run --join --bind-addr 127.0.0.1:8080-```-The CLI will open your browser for login (or print a device code if headless). Once authenticated:-```text-Successfully joined the Sovereign Agent Mesh!-INFO sam-node [AuthN] Successfully authenticated with router via libp2p: ...-SAM Node Online.-PeerID: 12D3KooW...-```--#### Using Docker-```bash-mkdir -p $(pwd)/sam-data-docker run -it \- --user "$(id -u):$(id -g)" \- -v $(pwd)/sam-data:/data \- -p 5001:5001/udp \- -p 5002:5002 \- -p 8080:8080 \- -e SAM_API_TOKEN=my-secret-token \- ghcr.io/google/sam-node:latest \- run --join --data-dir /data --bind-addr 0.0.0.0:8080-```-Use `-it` for this first run so you can complete the browser/device-code login; once enrolled, restart it detached with `-d` instead (`--join` is a no-op at that point, so it's safe to leave in your start command). If there's no interactive terminal attached (e.g. `-d` on the very first run), the node instead comes up as an unauthenticated sidecar waiting for out-of-band enrollment over MCP.--## 3. Query the Local MCP API--Your SAM node exposes a standard Model Context Protocol (MCP) server. The easiest way to interact with it is using the `mcp-client` CLI tool (which is installed alongside `sam-node`):--### List Local Control Plane Tools-Query the list of tools available on your local node (e.g. peer discovery, message broadcast, and remote tool execution):--```bash-mcp-client -url http://localhost:8080/mcp -token my-secret-token -list-```--### Discover Remote Services in the Mesh-List active MCP services currently registered across the public mesh network:--```bash-mcp-client -url http://localhost:8080/mcp \- -tool discover_remote_services \- -args '{"type":"mcp"}'-```--### Find Remote Tools on a Peer-Using a `peer_id` returned from the service discovery, find the tools available on that peer:--```bash-mcp-client -url http://localhost:8080/mcp \- -tool find_remote_tools \- -args '{"peer_id":"<target-peer-id>"}'-```--### Call a Remote Tool-Call a tool hosted on a remote peer through your local node's P2P stream reverse proxy:--```bash-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.--With the skill installed you can also skip the manual setup entirely and ask the agent to bring itself online (for example: *"connect to the sam mesh and show me what tools are available"*). The skill teaches it to start the node with `sam-node run --daemonize`, read the API token, and register the MCP endpoint itself; it only stops to hand you the one-time `sam-node join` login, which stays with a human by design.diff --git a/site/content/docs/reference/_index.md b/site/content/docs/reference/_index.mdnew file mode 100644index 00000000..3d20f847--- /dev/null+++ b/site/content/docs/reference/_index.md@@ -0,0 +1,9 @@+---+title: "Reference"+linkTitle: "Reference"+weight: 4+---++Flags, configuration keys, HTTP routes and policy fields, one page per+program or file. Defaults are as of the current release. `--help` on a+binary is authoritative for the version you have.diff --git a/site/content/docs/reference/control-plane.md b/site/content/docs/reference/control-plane.mdnew file mode 100644index 00000000..65f1746e--- /dev/null+++ b/site/content/docs/reference/control-plane.md@@ -0,0 +1,126 @@+---+title: "sam-control-plane"+linkTitle: "sam-control-plane"+weight: 2+aliases:+ - /docs/user/control-plane-configuration/+---++`sam-control-plane` admits nodes, mints credentials, holds the mesh policy+and tracks routers. It is an HTTP server over SQLite or PostgreSQL.++```text+sam-control-plane [flags] run the server+sam-control-plane admin ban --peer <id> ban a node directly in the database+sam-control-plane admin unban --peer <id> lift a ban+```++## Flags++| Flag | Default | Meaning |+|---|---|---|+| `--issuer` | required | OIDC issuer URL(s), comma-separated. The first is advertised to enrolling nodes on `/info`. Can also be set with `SAM_OIDC_ISSUER`. |+| `--allowed-audiences` | `sam-mesh-audience` | Audiences accepted in OIDC tokens, comma-separated. |+| `--oidc-client-id` | first audience | OAuth client ID advertised on `/info`, for providers where it differs from the audience. |+| `--insecure-skip-tls-verify` | `false` | Skip TLS verification when fetching issuer metadata and keys. For a cluster issuer served with the cluster CA, or a local development issuer. |+| `--bind-address` | `0.0.0.0:8080` | HTTP listen address. |+| `--db-driver` | `sqlite` | `sqlite` or `postgres`. |+| `--db-dsn` | `control-plane.db` | Database DSN. A PostgreSQL DSN contains a password, so the next two options are preferred for PostgreSQL. |+| `--db-dsn-path` | | File containing the DSN. Overrides `--db-dsn`. Can also be set with `SAM_DB_DSN`. |+| `--admin-token-path` | | File containing the bearer token for `/admin/*` and `POST /policies`. Can also be set with `SAM_ADMIN_TOKEN`. Without a token, the admin API cannot be used. |+| `--auto-approve-enrollment` | `false` | Issue credentials for valid bootstrap-token enrollments immediately instead of queueing them for approval. |+| `--biscuit-ttl` | `24h` | Lifetime of each credential. If the OIDC token expires sooner, the credential expires with it. |+| `--oidc-session-ttl` | `2160h` (90 days) | How long an OIDC enrollment may keep refreshing before the identity must log in again. |+| `--key-rotation-interval` | `24h` | How often a new signing key is generated. `0` disables rotation. |+| `--key-grace-period` | `1h` | How long a rotated-out key stays accepted. Credentials signed by a retired key cannot be verified or refreshed. |+| `--lease-duration` | `15m` | How long a router lease lasts without renewal. |+| `--node-retention` | `720h` (30 days) | How long the record of an enrolled node is kept after its session expires. Banned nodes are kept forever. `0` keeps every record. |+| `--log-level` | `info` | `debug`, `info`, `warn`, `error`. `LOG_FORMAT=json` selects JSON output. |++## HTTP API++Two encodings are in use. Routes that mesh components call use protobuf+(`application/x-protobuf`), with messages defined in `api/sam.proto`. Routes+for operators and the console use JSON. `POST /policies` accepts either.++Responses that carry credentials are sent with `Cache-Control: no-store`.++### Unauthenticated++| Route | Purpose |+|---|---|+| `GET /healthz` | Liveness. |+| `GET /readyz` | Readiness. Returns `503` when the database is unreachable. |+| `GET /metrics` | Prometheus metrics. |+| `GET /info` | `ControlPlaneInfoResponse`: the OIDC issuer, client ID and audience, the addresses of routers with live leases, and the list of banned peer IDs. This is what a node needs before it can enroll. |+| `GET /keys` | The current set of signing public keys, signed by every key in the set. A caller accepts the set only if one signature verifies under a key it already trusts. |++### Enrollment and refresh++Every request below carries a `timestamp` and a `challenge_signature`. The+enrollee signs `sam:<endpoint>:<peer_id>:<unix-millis>` with its key, and the+control plane accepts the signature within five minutes. This proves that the+caller holds the key behind the peer ID it names.++| Route | Body | Purpose |+|---|---|---|+| `POST /register` | `EnrollRequest` (OIDC token, public key, requested role, labels) | OIDC enrollment. Returns `EnrollResponse`: the credential, the control plane public key, router addresses and expiry. |+| `POST /enroll` | `BootstrapEnrollRequest` (bootstrap token, public key, requested role, labels) | Bootstrap enrollment. Returns `BootstrapEnrollResponse` with status `APPROVED` and the credential, or with status `PENDING`. For a peer that is already approved, a new credential is minted directly. |+| `GET /enroll/status?peer_id=` | headers `X-Sam-Challenge-Ts`, `X-Sam-Challenge-Sig` | Poll a pending enrollment. Any authentication failure answers `401`, so the credential is released only to the enrollee. |+| `POST /refresh` | `TokenRefreshRequest`, current credential as `Authorization: Bearer <base64>` | Exchange a credential for a new one. Refuses a replayed (superseded) credential, a banned node, an expired session, and a credential signed by a retired key unless the node has `autonomous_recovery`. |+| `POST /routers/lease` | `RouterLeaseRequest` (credential, addresses, telemetry) | Register or renew a router lease. Requires `role("sam:role:router")`. Announced addresses must end in the router's own peer ID. |+| `GET /policies` | credential as `Authorization: Bearer <base64>` | The mesh policy as `PolicyConfigGetResponse`. Also accepts the admin token. |+| `POST /nodes/catalog` | `NodeCatalogReport`, credential as bearer | A node's report of the services it publishes, for the console. Display only. Never used for authorization. |++### Admin++All routes require `Authorization: Bearer <admin-token>` and use JSON.++| Route | Purpose |+|---|---|+| `GET /admin/status` | Everything the console shows: routers, nodes, enrollment requests, tokens, users, and the policy as JSON. |+| `POST /policies`, `PUT /policies` | Replace the mesh policy. The JSON body is protojson of `PolicyConfigUpdateRequest`. Unknown fields are rejected, so a misspelt grant fails instead of being dropped. |+| `POST /admin/bootstrap-tokens` | Mint a token. Body: `role` (required), `ttl_hours` (default 24), `max_usages` (default 1), `description`, `autonomous_recovery` (default false). Returns `201` with `id`, `token` (shown once), `role`, `expires_at`. |+| `DELETE /admin/bootstrap-tokens/{id}` | Revoke a token. Can be repeated. The token stays in the list, marked as revoked. |+| `GET /admin/enrollments` | Pending bootstrap enrollment requests. |+| `POST /admin/enrollments/{id}/approve` | Approve. Spends a token usage. Checks the token again, and checks the labels against the role's `allowed_labels`. |+| `POST /admin/enrollments/{id}/reject` | Reject. |+| `POST /admin/revoke` | Body `{"peer_id": "..."}`. Ban the node and, for an OIDC enrollment, the identity behind it. |+| `POST /admin/nodes/{peer_id}/unban` | Lift both bans. |+| `POST /admin/nodes/{peer_id}/autonomous-recovery` | Body `{"enabled": true}`. Toggle the flag on an enrolled node. |++### User++For an OIDC user acting on their own nodes, authenticated with an ID token+from the configured issuer. The console uses these routes.++| Route | Purpose |+|---|---|+| `GET /user/status` | The caller's enrolled nodes and tokens. |+| `POST /user/bootstrap-tokens` | Mint a token owned by the caller. `role` defaults to `sam:role:node`. Banning the owner disables the tokens they minted. |+| `POST /user/revoke` | Ban one of the caller's own nodes. |++## Notes++- **A new control plane grants nothing.** With no policy in the database,+ enrollment succeeds only for identities bound to the requested role, and+ with no bindings there are none. A policy must be posted first.+- **Bootstrap tokens are spent atomically.** `max_usages` holds under+ concurrent enrollments, and a pending request is resolved exactly once.+- **An approved peer that enrolls again gets a new credential without+ approval**, as long as the token is valid, the role matches the record and+ the peer is not banned. This is how a bootstrap node recovers from a+ retired signing key.+- **Bans propagate in two ways.** `/info` lists banned peer IDs for nodes and+ routers that start or restart. A signed mesh event reaches the ones that+ are already running.+- **Node records are garbage-collected.** A node whose session has expired is+ deleted after `--node-retention`. A node without a persistent data+ directory enrolls a new identity on every restart, so without this the+ node table would only grow.++## Metrics++`/metrics` exposes `sam_control_plane_*` counters and gauges: enrolled nodes+by role and state, active routers, mesh-connected peers as reported by+router leases, per-route request counts and latencies, and the Go runtime.diff --git a/site/content/docs/reference/node-api.md b/site/content/docs/reference/node-api.mdnew file mode 100644index 00000000..6d596226--- /dev/null+++ b/site/content/docs/reference/node-api.md@@ -0,0 +1,203 @@+---+title: "Node API"+linkTitle: "Node API"+weight: 7+aliases:+ - /docs/development/testnet-validation/+---++The local API that `sam-node run` serves to agents and scripts on the same+machine. It is available on TCP (`--bind-addr`, default `127.0.0.1:8080`)+and on a Unix socket (`--socket-path`, default `<data-dir>/sam.sock`).++## Authentication++| Listener | Requirement |+|---|---|+| TCP | `X-Sam-Authentication: Bearer <api-token>` on every request, or a client certificate when `--tls-ca` is set. |+| Unix socket | None. The socket has mode `0600`. Being able to open it is the credential. |++`Authorization` is reserved for the credential of the service that is being+called through the node, and the proxy path forwards it. The endpoints that+never forward anything (`/mcp`, `/v1/*`, `/sam/service/*`, `/metrics`,+`/sam/identity`, `/sam/peer/*`, `/debug/*`) also accept the API token in+`Authorization: Bearer`, for clients that cannot set custom headers. The+proxy path does not accept it there.++## Routes++| Route | Auth | Purpose |+|---|---|---|+| `GET /healthz`, `GET /readyz` | none | `200` while the process is up. Every other route except `/debug/*` answers `503` until the node is connected to the mesh, so a `503` on `/mcp` is the practical readiness signal. |+| `GET /metrics` | token | Prometheus metrics (`sam_node_*`). |+| `POST /mcp` | token | The MCP server (Streamable HTTP). `/` is an alias. |+| `GET /v1/models` | token | Models served by every reachable inference provider. |+| `POST /v1/chat/completions`, `POST /v1/completions` | token | OpenAI-compatible inference, routed to a provider of the requested model. |+| `GET /sam/service/discover` | token | Discover services on the mesh. |+| `ANY /sam/{peer-id}/{type}/{name}[/{path}]` | token | Reverse proxy to one service on one peer. |+| `GET /sam/identity` | token, socket or mTLS only | This node's credential and the key it verifies under. |+| `GET /sam/peer/{peer-id}/evidence` | token, socket or mTLS only | A peer's credential as this node last verified it. |+| `GET /debug/*` | token | Operator diagnostics. These answer even when the mesh is unreachable. |++`--metrics-addr` serves `/metrics`, `/healthz` and `/readyz` on a second+listener without authentication, for scrapers that hold no token.++## MCP tools++The `/mcp` endpoint speaks Streamable HTTP. The older SSE transport is+refused with `400`. The server's instructions field tells a client how the+tools fit together. The tools are:++### `get_mesh_info`++No parameters. Returns `router_peer_id`, `connected_peers`, `dht_size` and+`local_api_socket`. `connected_peers` and `dht_size` count different things+(transport connections and routing-table entries), so a small `dht_size`+next to a long peer list is normal.++### `list_local_services`++| Parameter | Meaning |+|---|---|+| `type` | Optional filter: `mcp`, `inference`, `a2a`. |++Services this node publishes.++### `discover_remote_services`++| Parameter | Meaning |+|---|---|+| `type` | Required: `mcp`, `inference` or `a2a`. |+| `name` | Optional service name. Omit to list every reachable service of the type. |+| `limit`, `offset` | Pagination. Defaults are 20 and 0. |++Each result has `peer_id`, `srv_name`, `srv_description` and, when the+provider declared them, `labels`. Service names are not unique across the+mesh. The peer ID identifies the provider. For `type: inference` the+response adds a `local_proxy_url` per provider and a note that inference is+called over HTTP and not with `call_remote_tool`.++### `find_remote_tools`++| Parameter | Meaning |+|---|---|+| `peer_id` | Restrict the search to one peer. |+| `service_name` | Restrict the search to one service, bare (`code-reviewer`) or namespaced (`mcp://code-reviewer`). |+| `tool_name` | Exact tool name to locate across the mesh (`review_pr`). Answered from gossip announcements when they are fresh. |+| `intent` | Accepted and ignored. Reserved for later use. |++Returns one row per tool with `peer_id`, `tool_name` (namespaced as+`mcp://service/tool`), `description` and `labels`. A peer that could not be+queried appears as a row with an `error` field. The call itself does not+fail.++### `describe_remote_tool`++| Parameter | Meaning |+|---|---|+| `peer_id` | Required. |+| `tool_name` | Required, namespaced as returned by `find_remote_tools`. |++Returns `description`, `input_schema` and `output_schema`.++### `call_remote_tool`++| Parameter | Meaning |+|---|---|+| `peer_id` | Required. |+| `tool_name` | Required, namespaced. |+| `arguments` | Object matching the tool's `input_schema`. |+| `required_labels` | `key=value[,key=value]`. The call is refused unless the peer's credential attests at least one of them. |++Returns the tool's result content. A policy denial comes back as a tool+error that the caller can read, not as a transport failure.++### When the node has no credential++A node that starts without a credential and without a way to enroll serves+a reduced MCP server with one tool, `get_login_instructions`, and one+prompt, `help_user_login`. Both tell the client to run `sam-node join`.++## Service discovery over HTTP++`GET /sam/service/discover?type=mcp[&name=calculator][&limit=20&offset=0][&timeout=10s]`+returns the same JSON array as `discover_remote_services`. With+`&stream=true` or `Accept: text/event-stream`, results arrive as+server-sent events as they are found, and the stream ends with+`event: done`.++## The proxy path++```text+/sam/<peer-id>/<type>/<name>/<path...>+```++The node verifies the peer's credential and, if set, the operator's+`egress.require_labels`. It then opens an authenticated stream and forwards+the request to `/<type>/<name>/<path>` on the peer, which proxies it to the+backend. Headers pass through, including `Authorization`. Paths that contain+`..` are refused. For an `mcp` service, `<path>` is empty and the request+body is the JSON-RPC message. For `inference`, `<path>` is `v1/models` or+`v1/chat/completions`. For `a2a`, `<path>` is whatever the agent serves, and+`.well-known/agent-card.json` is rewritten for the mesh.++Two headers modify a proxied request:++| Header | Effect |+|---|---|+| `X-Sam-Required-Labels: k=v[,k=v]` | Verify that the peer attests at least one of the pairs before forwarding. Otherwise `403`. Removed before forwarding. Also honoured on `/v1/*`. |+| `X-Sam-Agent: <agent-id>` | Name the agent for which this request is made. Only meaningful when sent by a `sam-box`. See the [preview](../../preview/sandboxed-agents/). |++### Talking MCP through the proxy++An MCP session with a remote service, without using the node's own tools:++```bash+SOCK=~/.config/sam-mesh/sam.sock+URL=http://localhost/sam/<peer-id>/mcp/everything++# initialize; the Mcp-Session-Id response header identifies the session+curl -si --unix-socket $SOCK $URL \+ -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \+ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'++# subsequent calls carry the session id+curl -s --unix-socket $SOCK $URL \+ -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \+ -H 'Mcp-Session-Id: <id from above>' \+ -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'+```++Over TCP, add `-H "X-Sam-Authentication: Bearer $TOKEN"` and use+`http://127.0.0.1:8080` as the base URL.++## Inference++`/v1/models` collects the model list of every reachable `inference` provider+(cached for 30 seconds) and returns the union. `owned_by` on each entry is+the peer that serves the model. A completion request names a model, and the+node picks a provider that serves it. It prefers a local provider, and ranks+remote providers by the labels the caller required, the operator's floor,+and load. A model that no provider lists answers `404`.++Any OpenAI SDK works with `base_url` set to `http://127.0.0.1:8080/v1` and+the API token as `api_key`. The node accepts the token in `Authorization`+here because nothing on this path forwards that header. Streaming responses+are passed through.++## Identity evidence++`GET /sam/identity` returns the node's credential (base64), the control+plane public key it verifies under (SPKI DER), the peer ID, roles, labels+and expiry. `GET /sam/peer/{peer-id}/evidence` returns the same for a peer+that the node has authenticated. Both refuse plain TCP. They are reachable+only over the Unix socket or over an mTLS-verified connection, because this+material is meant for the node's owner and for auditors, not for agents.++## Debug++`GET /debug/mesh-info`, `GET /debug/connectivity`, `GET /debug/network-info`,+`GET /debug/token-info`, `GET /debug/logs` and `POST /debug/connect-peer`+report and probe the node's view of the mesh for troubleshooting, and answer+even while the mesh is unreachable. `sam-node debug` on the command line+wraps them. Their output is not stable across releases.diff --git a/site/content/docs/reference/node-config.md b/site/content/docs/reference/node-config.mdnew file mode 100644index 00000000..94e7e3f3--- /dev/null+++ b/site/content/docs/reference/node-config.md@@ -0,0 +1,152 @@+---+title: "Node configuration file"+linkTitle: "Node configuration"+weight: 5+aliases:+ - /docs/user/node-configuration/+---++`sam-node.yaml` declares what a node is (labels), what it publishes+(services), what it requires from callers (attenuation) and what it requires+from providers (egress). Both `sam-node join` and `sam-node run` read it from+`--config`, by default `./sam-node.yaml`. A missing file means an empty+configuration. Unknown keys are an error, because a typo under `attenuation`+would otherwise weaken the node without notice.++```yaml+version: "v1alpha1"++labels:+ region: eu-west-1+ team: platform++services:+ - type: mcp+ name: code-reviewer+ description: "Reviews diffs"+ target_url: "http://127.0.0.1:7777/mcp"+ - type: mcp+ name: filesystem+ command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/srv/docs"]+ env:+ NODE_OPTIONS: "--max-old-space-size=256"+ - type: inference+ name: vllm+ target_url: "http://127.0.0.1:8000"+ target_auth_path: /etc/sam/vllm-key+ - type: a2a+ name: triage+ target_url: "http://127.0.0.1:9999"++attenuation:+ rules:+ - 'maintenance() <- time($t), $t > 2026-12-31T00:00:00Z;'+ checks:+ - 'check if label("team", "platform");'+ policies:+ - 'deny if service("mcp", "filesystem"), group("contractors");'+ - 'deny if maintenance();'++egress:+ require_labels:+ jurisdiction: eu+```++## `version`++`"v1alpha1"`, or omitted (read as `v1alpha1`). A node refuses a version it+does not know.++## `labels`++A map of `key: value`. Keys are 1 to 63 characters from `[a-zA-Z0-9_.-]`.+Values are non-empty, at most 255 characters, and contain no `,`, `=` or+control characters, because the wire form is a comma-separated `key=value`+list. A malformed label stops the node at start.++Labels are sent at enrollment. The control plane writes them into the node's+credential as `label(key, value)` facts, but only if a role the node holds+allows them through `allowed_labels`. A label that the role does not permit+fails the enrollment. Changing labels requires a new enrollment. Matching is+exact and case-sensitive.++## `services`++A list. Each entry has these keys:++| Key | Required | Meaning |+|---|---|---|+| `type` | yes | `mcp`, `inference` or `a2a`. |+| `name` | yes | Unique on this node. DNS-style labels separated by dots (`db-reader`, `build.runner`). Policy grants refer to `type://name`. |+| `description` | no | Shown in discovery results and in the console. |+| `target_url` | `mcp`: this or `command`; `inference` and `a2a`: yes | Backend URL that the node proxies to. Embedded credentials (`http://user:pass@`) are refused. |+| `command` | `mcp` only: this or `target_url` | Argument vector of a subprocess that speaks MCP over stdio. The node starts and supervises it. |+| `env` | no | `command` only. Environment for the subprocess. |+| `target_auth_path` | no | `target_url` only. File whose contents the node presents to the backend: a bare token as `Authorization: Bearer <token>`, or `user:pass` as HTTP Basic. Read once at start, never logged or advertised. It overrides any `Authorization` header that a caller sent. |++Rules by type:++- **`mcp`**: `command` or `target_url`, not both. A `target_url` must be a+ Streamable HTTP MCP endpoint.+- **`inference`**: `target_url` only. It must be the root URL of the backend+ without `/v1`. The node adds the prefix. Callers reach the service through+ the node's `/v1` endpoint or at `/sam/<peer>/inference/<name>/v1/...`.+- **`a2a`**: `target_url` only. The agent card is fetched from+ `/.well-known/agent-card.json` on the backend and served again with mesh+ URLs. The card must use the A2A 1.0 format.++Before a service is advertised, the node probes the backend+(`--backend-probe-timeout`, 2 seconds). A backend that does not answer is+not advertised, and the log records this.++Services exist only through this file. There is no runtime API that adds a+service. An agent with access to the node's API therefore cannot point the+mesh at a new backend.++## `attenuation`++Biscuit Datalog that the node adds to every authorization decision for+requests it receives. Each entry is one statement. A trailing `;` is+optional. A statement that does not parse stops the node at start.++| Key | Meaning |+|---|---|+| `rules` | Derive new facts from existing ones: `head(...) <- body(...)`. |+| `checks` | Conditions that must all hold: `check if ...`. A failing check denies the request regardless of any policy. |+| `policies` | `allow if ...` and `deny if ...`, evaluated before the baseline policies. The first matching policy wins. A `deny` here overrides a mesh grant. An `allow` here admits a caller that the mesh did not grant, but never a caller that fails a check. |++Facts available:++| Fact | Source |+|---|---|+| `service($type, $name)` | The request: which service is being called. |+| `time($now)` | Injected at evaluation. |+| `connection_peer_id($id)` | The authenticated peer. |+| `user($sub)`, `email($e)`, `group($g)`, `idp_role($r)` | The caller's OIDC claims, from its credential. |+| `role($r)` | The caller's mesh roles. |+| `label($k, $v)` | The caller's attested labels. |+| `node($id)`, `client_peer_id($id)`, `expiration($t)` | The caller's credential binding and expiry. |+| `granted_service_*`, `granted_target_*`, `granted_agent_*` | The caller's grants. |+| `target_fact($name, $value)` | This node's own identity facts, for target matching. |+| `agent($id)` | The agent the caller says it acts for, when present. |++The mobile app has the same three lists in its settings, with the same+syntax and the same errors.++## `egress`++| Key | Meaning |+|---|---|+| `require_labels` | A map of `key: value`. Every remote provider that this node sends a request to must have all of these labels attested in its credential, whether or not the caller asked for labels. Same syntax rules as `labels`. |++This is the operator's floor. A caller's `X-Sam-Required-Labels` header is+checked separately. It can add requirements but cannot remove or relax the+floor. A floor that names a label which no provider carries makes the node+unable to reach any provider, which can serve as an egress kill switch. Omit+the block for no floor.++## Kubernetes++The `sam-node` Helm chart renders its `config:` value as this file and+restarts the pod when it changes. Because the backend runs in the same pod,+`target_url` there is always `http://127.0.0.1:<port>`.diff --git a/site/content/docs/reference/policy.md b/site/content/docs/reference/policy.mdnew file mode 100644index 00000000..6f92e32e--- /dev/null+++ b/site/content/docs/reference/policy.md@@ -0,0 +1,202 @@+---+title: "Mesh policy"+linkTitle: "Mesh policy"+weight: 6+aliases:+ - /docs/development/policy/+---++The mesh policy is one document held by the control plane: a list of roles+and a list of bindings. It is posted as JSON (protojson of+`PolicyConfigUpdateRequest` in `api/sam.proto`) to `POST /policies`, edited+in the console, or given to `sam-one --policy-file` for first boot.++```json+{+ "roles": [+ {+ "name": "sam:role:node",+ "allowed_services": ["system://sam.catalog"],+ "allowed_labels": ["region=*", "team=platform"]+ },+ {+ "name": "developer",+ "allowed_services": ["mcp://code-reviewer", "mcp://build-runner.*", "inference://*"],+ "allowed_targets": ["group:dev-nodes", "node:12D3KooWSpecialNode"],+ "allowed_agents": ["*.dev.acme.example"],+ "custom_datalog": ["tier(\"standard\");"]+ }+ ],+ "bindings": [+ { "role": "sam:role:node", "members": ["group:engineering", "user:system:serviceaccount:sam-nodes:calc-mcp-sam-node"] },+ { "role": "developer", "members": ["group:engineering"] }+ ]+}+```++The whole document is replaced on every post. Unknown fields are rejected,+so a misspelt key fails the request instead of dropping a grant without+notice.++## Roles++| Field | Type | Meaning |+|---|---|---|+| `name` | string, required, unique | The role name. `sam:role:node`, `sam:role:router` and `sam:role:sambox` are the roles that the three binaries request at enrollment. Any other name is an ordinary role. |+| `allowed_services` | list of service patterns | Services that holders may call. |+| `allowed_targets` | list of target patterns | Nodes that holders may call. If absent, any node may be called. |+| `allowed_labels` | list of label patterns | Labels that a node holding this role may declare at enrollment. If absent, no labels may be declared. |+| `allowed_agents` | list of agent patterns | Agent identifiers that a node holding this role may claim to act for. If absent, no agent may be named. |+| `custom_datalog` | list of Datalog statements | Facts are minted into the credentials of holders. Rules are distributed to nodes and applied when a holder is verified. |++### Service patterns++`type://name`, where `type` is `mcp`, `inference`, `a2a` or `system`, and+`name` consists of dot-separated DNS-style labels.++| Pattern | Compiles to | Matches |+|---|---|---|+| `mcp://calculator` | `granted_service_exact("mcp", "calculator")`. Several exact entries of one type are merged into one `granted_service_set`. | that service |+| `mcp://*.internal` | `granted_service_suffix("mcp", ".internal")` | `a.internal` and `b.c.internal`, but not `xinternal` |+| `mcp://build.*` | `granted_service_prefix("mcp", "build.")` | `build.runner`, but not `builder` |+| `mcp://*` | `granted_service_all("mcp")` | every MCP service |+| `*` | `granted_service_all_types()` | every service |++`system://sam.catalog` is the built-in discovery service that every node+runs. A role that should be able to list the tools of a node needs it.++### Target patterns++`fact:value`, where `fact` is one of the identity facts that a node's+credential can carry: `node` (peer ID), `user`, `email`, `group`,+`idp_role`. The values come from the destination node's own credential, so+`group:dev-nodes` means "nodes whose enrolling identity is in group+`dev-nodes`".++| Pattern | Matches |+|---|---|+| `node:12D3KooW...` | one node |+| `group:dev-nodes` | nodes enrolled by a member of that group |+| `email:*.acme.example` | suffix match on the email of the enrolling identity |+| `group:*` | any node with a `group` fact |+| `*` | any node |++Exact entries of one fact are merged into one `granted_target_set` fact.+`agent:` is not a valid target, because a node's identity does not say which+agents it hosts.++### Label patterns++| Pattern | Permits |+|---|---|+| `key=value` | exactly that pair |+| `key=*` | any value for that key |+| `*` | any label |++Keys match `[a-zA-Z0-9_.-]{1,63}`. Values are up to 255 characters with no+`,`, `=` or control characters. Every label that a node declares must be+permitted by a role it holds, or enrollment fails. Manual approval of a+bootstrap enrollment does not bypass this check.++### Agent patterns++An agent identifier is lowercase and dot-separated, with at least two labels+(`reviewer-7.prod.acme.example`). A pattern is an identifier, `*.<suffix>`,+`<prefix>.*`, or `*`. Wildcards are anchored on label boundaries. `*` lets+every holder name any agent, and nodes log a warning when they receive such+a grant. See the [sandboxed agents preview](../../preview/sandboxed-agents/).++### `custom_datalog`++Each entry is one Biscuit Datalog fact or rule. A **fact**+(`tier("standard");`) is minted into the credential of every holder, where+`attenuation` statements on any node can refer to it. A **rule**+(`head($x) <- body($x);`) is compiled into the node-side rule set and+applied when a holder is verified. `allow` and `deny` policies are not+accepted here. They belong in a node's `attenuation.policies`. An entry that+parses as neither a fact nor a rule fails validation.++## Bindings++| Field | Meaning |+|---|---|+| `role` | A role name from `roles`. A binding to an undefined role is rejected. |+| `members` | Identities that receive the role. At least one is required. |++A member is one of:++| Member | Matches |+|---|---|+| `user:<sub>` | the OIDC subject. For a Kubernetes service account: `user:system:serviceaccount:<namespace>:<name>`. |+| `email:<address>` | a verified email claim |+| `group:<name>` | an entry of the `groups` claim |+| `idp_role:<name>` | an entry of the issuer's `roles` claim |+| `node:<peer-id>` | one node, by key |+| `agent:<id>` | an agent identifier that a node names when acting for the agent. Only as trustworthy as the node's `allowed_agents` grant. |+| `sam:system:authenticated` | every identity that the identity provider authenticates |++`role:` is not a member, because a role cannot grant a role. A bootstrap+token enrollment carries no OIDC claims. Such a node receives exactly the+token's role and nothing that a binding on claims would add, so the grants+must be on the role itself.++## Evaluation++At enrollment and at refresh, the control plane resolves the identity's roles+from the bindings and mints into the credential one `role()` fact per role+and the compiled `granted_*` facts of every role. Nodes also fetch the policy+(`--policy-sync-interval`, 1 hour) and compile it into rules such as+`role("developer") <- group("engineering")` and+`granted_service_exact("mcp","code-reviewer") <- role("developer")`. These+rules run at verification time. Additions therefore reach nodes within the+sync interval, and removals within the credential TTL.++At the destination node, in this order:++1. Facts for the request: `service($type, $name)`, `connection_peer_id($id)`,+ `time($now)`, and `agent($id)` if a claim was made.+2. Checks that always apply: `client_peer_id($id), connection_peer_id($id)`,+ `time($t), expiration($e), $t <= $e`, and `agent_authorized()` when an+ agent was named.+3. The node's own identity as `target_fact($name, $value)` facts.+4. The node's `attenuation` rules, checks and policies.+5. Baseline policies: `allow if service($t,$n), granted_service_exact($t,$n)`+ and the set, prefix, suffix, per-type and global variants; the check+ `allow_network_target($f,$v) or target_unrestricted()`.+6. The synced mesh policy rules.++All checks must hold, and the first matching policy decides. Without a+matching `allow`, the request is denied.++## Limits++The control plane rejects a policy that could give one identity, through+overlapping bindings, more Datalog facts than the Biscuit authorizer can+evaluate. The limit is far above any ordinary policy. A policy that reaches+it should use wildcards or sets instead of listing every entry.++## Datalog vocabulary++Every fact name used by SAM, for writing `custom_datalog` or `attenuation`+statements.++| Fact | Terms | Minted by |+|---|---|---|+| `node` | peer ID | control plane |+| `client_peer_id` | peer ID | control plane |+| `expiration` | date | control plane |+| `role` | name | control plane |+| `user`, `email`, `group`, `idp_role` | string | control plane, from OIDC claims |+| `label` | key, value | control plane |+| `right` | `relay` | control plane, for routers |+| `target_unrestricted` | | control plane, for roles with `allowed_targets: ["*"]` or none |+| `granted_service_exact`, `_set`, `_prefix`, `_suffix`, `_all`, `_all_types` | type, name/set/pattern | control plane and node rules |+| `granted_target_exact`, `_set`, `_prefix`, `_suffix`, `_all`, `_all_facts` | fact, value/set/pattern | control plane and node rules |+| `granted_agent_exact`, `_set`, `_prefix`, `_suffix`, `_all` | pattern | control plane and node rules |+| `service` | type, name | destination node, per request |+| `connection_peer_id` | peer ID | destination node, per request |+| `time` | date | destination node, per request |+| `agent` | identifier | destination node, from the caller's claim |+| `target_fact` | fact, value | destination node, from its own credential |+| `allow_network_target` | fact, value | derived by baseline rules |+| `agent_authorized` | | derived by baseline rules |diff --git a/site/content/docs/reference/router.md b/site/content/docs/reference/router.mdnew file mode 100644index 00000000..15026c54--- /dev/null+++ b/site/content/docs/reference/router.md@@ -0,0 +1,71 @@+---+title: "sam-router"+linkTitle: "sam-router"+weight: 3+---++`sam-router` is a libp2p peer with a stable identity that new nodes connect+to first. It hosts the DHT, relays traffic between nodes that cannot reach+each other, and forwards the control plane's signed events. It has no policy+of its own.++```text+sam-router [flags]+```++## Enrollment++A router enrolls like a node, requesting `sam:role:router`, with one of:++| Flag | Meaning |+|---|---|+| `--jwt-path` | File containing an OIDC token (a projected service account token, for example). |+| `--bootstrap-token-path` | File containing a bootstrap token minted with `"role": "sam:role:router"`. |+| `--oidc-token`, `--bootstrap-token` | The same tokens as values. Visible in process listings. The file forms are preferred. |++The mesh policy must bind the router's identity to `sam:role:router`. The+`sam-mesh` Helm chart handles this: its bootstrap job binds the router's+service account and mints a bootstrap token with `max_usages` equal to the+replica count.++## Flags++| Flag | Default | Meaning |+|---|---|---|+| `--control-plane` | `http://127.0.0.1:8080` | Control plane URL. `https://` is required unless the host is loopback. |+| `--insecure-control-plane` | `false` | Accept plaintext `http://` to a non-loopback host, such as an in-cluster Service. |+| `--listen` | `/ip4/0.0.0.0/tcp/5001`, `/ip6/::/tcp/5001` | libp2p listen addresses. Repeatable. Add `/ip4/0.0.0.0/udp/5001/quic-v1` for QUIC. |+| `--external-addr` | none | Addresses to announce instead of the detected ones, such as `/dnsaddr/bootstrap.example.com` or `/ip4/<public-ip>/tcp/5001`. Repeatable. |+| `--keys-path` | `router.key` | The router's private key. It fixes the peer ID across restarts and belongs on persistent storage. |+| `--keys-sync-interval` | `5m` | How often `/keys` is polled for signing-key rotations. |+| `--lease-renew-interval` | `300s` | How often the lease is renewed. Must be well below the control plane's `--lease-duration`. |+| `--allow-loopback` | `false` | Announce and accept loopback and link-local addresses. For a router and nodes on one host. |+| `--conns-per-source-ip` | `8` (libp2p default) | Inbound connections accepted per source IP. Raise it behind a TLS-terminating proxy or a NAT that puts many peers on one address. |+| `--low-watermark`, `--high-watermark` | `1000`, `4000` | Connection manager limits. Above the high mark, connections are trimmed down to the low mark. |+| `--dht-provider-addr-ttl`, `--dht-max-record-age` | library defaults | DHT record lifetimes. |+| `--metrics-addr` | off | Serve `/metrics`, `/healthz` and `/readyz` without authentication on this address. `/readyz` returns `200` once the router is enrolled and the libp2p host is up. Keep this address separate from the libp2p ports and inside the cluster. |+| `--log-level` | `info` | `debug`, `info`, `warn`, `error`. `LOG_FORMAT=json` selects JSON output. |++## What it does at run time++1. Fetches `/keys` and enrolls. The credential carries+ `role("sam:role:router")` and the relay right.+2. Starts the libp2p host, the DHT in server mode, the relay service and+ GossipSub.+3. Registers a lease at `POST /routers/lease` with its announced addresses+ and renews it every `--lease-renew-interval`. The control plane lists the+ router on `/info` while the lease is live.+4. Runs the mutual credential handshake on every inbound connection and+ refuses peers whose credential does not verify and peers on the ban list.+5. Refreshes its own credential before it expires, like a node.++A router stores nothing except its key. Restarting a router loses no+important state. Nodes reconnect and publish their services again.++## Metrics++The metrics address exposes `sam_router_connected_peers`,+`sam_router_dht_routing_table_size`, `sam_router_auth_handshakes_total` (by+outcome) and `sam_router_lease_renewals_total` (by outcome), next to the Go+runtime metrics. `/healthz` and `/readyz` on the same address are the probes+to use in a pod spec.diff --git a/site/content/docs/reference/sam-node.md b/site/content/docs/reference/sam-node.mdnew file mode 100644index 00000000..9bd3bd9e--- /dev/null+++ b/site/content/docs/reference/sam-node.md@@ -0,0 +1,159 @@+---+title: "sam-node"+linkTitle: "sam-node"+weight: 1+---++`sam-node` is the mesh member that runs beside an agent or a service.++```text+sam-node join [control-plane-url] [flags] enroll and store a credential+sam-node run [flags] run the node+sam-node reset [--all] [--yes] forget the credential or everything+sam-node skill install|list|show manage the agent skill document+```++## Files++The data directory is `--data-dir` if set, otherwise `$SAM_DATA_DIR`,+otherwise the user configuration directory of the operating system+(`~/.config/sam-mesh` on Linux, `~/Library/Application Support/sam-mesh` on+macOS). It is created with mode `0700` and holds:++| File | Contents |+|---|---|+| `agent.db` | The node's key, credential, control plane URL and public key, router addresses, and OIDC refresh token. A running node holds a lock on this file. A second node started on the same directory refuses to start. |+| `sam.sock` | The local API Unix socket, mode `0600`, removed on exit. |+| `api-token` | Generated by `--daemonize` when no token is configured. |+| `sam-node.pid`, `sam-node.log` | Written by `--daemonize`. |++The configuration file is `--config`, by default `sam-node.yaml` in the+working directory. A missing file is treated as an empty one. See+[node configuration](../node-config/).++## Global flags++Accepted by every subcommand.++| Flag | Default | Meaning |+|---|---|---|+| `--control-plane` | stored value | Control plane URL. `join` takes it as a positional argument. `https://` is required unless the host is loopback. |+| `--insecure-control-plane` | `false` | Accept a plaintext `http://` URL to a non-loopback host. Whoever answers that URL becomes the node's trust root. Intended for networks that are already trusted, such as a cluster. |+| `--config` | `sam-node.yaml` | Node configuration file. |+| `--data-dir` | see above | Data directory. |+| `--audience` | `sam-mesh-audience` | OIDC audience to request. |+| `--oidc-issuer` | from `/info` | Override the identity provider that the control plane advertises. |+| `--device-auth-url` | discovered | Override the device authorization endpoint. |+| `--headless` | `false` | Force the out-of-band login flow. |+| `--auth-mode` | `auto` | Login flow: `auto`, `device`, `oob` or `browser`. `auto` uses the browser when one can be opened and the device flow otherwise. `device` fails if the provider has no device endpoint. |++## `join`++Enrolls the node with the control plane and stores the credential. Without a+bootstrap token, `join` runs an interactive OIDC login.++| Flag | Default | Meaning |+|---|---|---|+| `--bootstrap-token-path` | | File containing a bootstrap token. |+| `--bootstrap-token` | | The token as a value. Visible in process listings. The file form is preferred. |+| `--offline-access` | `false` | Request an OIDC refresh token, so that the node can re-enroll on its own when its credential expires. |+| `--allow-loopback` | `false` | Advertise and dial loopback and link-local addresses. For several nodes on one host. |+| `--announce-private` | `true` | Advertise RFC 1918 and ULA addresses. Turn off when peers are only reachable through a relay. |+| `--router-connect-timeout` | `5s` | Dial timeout per router. |++Labels declared in the configuration file are sent with the enrollment.+Running `join` for a node that already holds a credential for the same+control plane enrolls it again. For a different control plane, `join`+refuses until `sam-node reset` has been run.++## `run`++Starts the node. If the data directory holds a credential, the node uses it.+Otherwise the node enrolls if it has a way to (`--jwt-path`,+`--bootstrap-token-path`, `--client-id`, or `--join`). If it has none, it+starts an unauthenticated local MCP server whose only tool explains how to+enroll.++### Enrollment++| Flag | Default | Meaning |+|---|---|---|+| `--join` | `false` | Run the interactive login on first start if there is no credential. Needs a terminal and `--control-plane` (or a stored control plane). Does nothing once the node is enrolled. |+| `--jwt-path` | | File containing an OIDC token to enroll with, for example a projected service account token. |+| `--jwt` | | The token as a value. Logged as a warning. The file form is preferred. |+| `--bootstrap-token-path`, `--bootstrap-token` | | As for `join`. |+| `--client-id`, `--client-secret-path` | | OAuth client-credentials grant against `--oidc-issuer`. The secret can also come from `SAM_CLIENT_SECRET`. |+| `--offline-access` | `false` | With `--join`, as for `join`. |+| `--control-plane-public-key` | stored value | Control plane Ed25519 public key, 32 bytes in hex. Only needed when the store lacks it. |++### Local API++| Flag | Default | Meaning |+|---|---|---|+| `--bind-addr` | `127.0.0.1:8080` | TCP address for the local API. An empty value disables TCP. |+| `--socket-path` | `<data-dir>/sam.sock` | Unix socket for the same API. An empty value disables it. At least one listener is required. |+| `--api-token-path` | | File containing the bearer token for the TCP listener, or `SAM_API_TOKEN`. Required when TCP is enabled, unless mTLS is enabled. |+| `--tls-cert`, `--tls-key` | | Serve the TCP listener over TLS. |+| `--tls-ca` | | Require client certificates signed by this CA (mTLS). Callers with a verified certificate need no token. |+| `--metrics-addr` | off | Serve `/metrics`, `/healthz` and `/readyz` without authentication on this address, for scrapers. Do not expose it on shared networks. |+| `--daemonize` | `false` | Start detached, wait for the API to answer, print the endpoint, token file and log path, and exit. Safe to run repeatedly. Generates `api-token` if no token is configured. Refuses to run on a node that has never enrolled. |++### Mesh++| Flag | Default | Meaning |+|---|---|---|+| `--listen` | `/ip4/0.0.0.0/udp/5001/quic-v1`, `/ip4/0.0.0.0/tcp/5002` | libp2p listen addresses. Repeatable. |+| `--allow-loopback`, `--announce-private`, `--router-connect-timeout` | | As for `join`. |+| `--enable-relay` | `false` | Relay traffic for other peers. |+| `--mesh` | `public-mesh` | Mesh federation name. Must match the routers' name. |+| `--discovery-interval` | `30s` | DHT discovery polling interval. |+| `--dht-lookup-limit` | `20` | Providers to query per DHT lookup. |+| `--discovery-concurrency` | `10` | Concurrent catalog fetches during discovery. |+| `--dht-provider-addr-ttl`, `--dht-max-record-age` | library defaults | DHT record lifetimes. |+| `--backend-probe-timeout` | `2s` | How long a service backend may take to answer before the node declines to advertise it. Raise it for subprocesses that start slowly. |+| `--policy-sync-interval` | `1h` | How often the mesh policy is fetched again from the control plane. |+| `--key-grace-period` | `24h` | How long a rotated-out control plane key is still accepted for verifying peers. |+| `--monitor-bootstrap` | `2m` | Delay before the router-connection monitor starts. |+| `--monitor-interval` | `1m` | How often the monitor checks that a router is connected. |+| `--autorelay-min-interval`, `--autorelay-boot-delay`, `--autorelay-backoff` | `30s`, `0s`, `3s` | libp2p AutoRelay tuning. |+| `--log-level` | `info` | `debug`, `info`, `warn` or `error`. |++## `reset`++| Flag | Meaning |+|---|---|+| (none) | Delete the credential and control plane binding. The key and peer ID stay. |+| `--all` | Delete every file the node keeps: `agent.db`, `api-token`, `sam-node.pid`, `sam-node.log`. The node gets a new peer ID. Asks for confirmation. |+| `--yes` | Skip the confirmation, for scripts. |++Both variants refuse while a node has the store locked.++## `skill`++Installs the `SKILL.md` document that teaches an agent harness how to use the+node.++| Command | Effect |+|---|---|+| `skill install` | Write to `~/.claude/skills/sam-mesh/SKILL.md` and `~/.gemini/config/skills/sam-mesh/SKILL.md`. |+| `skill install --project` | Write to `./.claude/skills/sam-mesh/` and `./.agents/skills/sam-mesh/` in the current directory. |+| `skill install --dir DIR` | Write to `DIR/sam-mesh/SKILL.md`. |+| `skill list` | Show each install location and whether the copy matches this binary. |+| `skill show` | Print the document. |++## Environment variables++| Variable | Equivalent |+|---|---|+| `SAM_API_TOKEN` | `--api-token-path` contents |+| `SAM_CLIENT_SECRET` | `--client-secret-path` contents |+| `SAM_DATA_DIR` | `--data-dir` |++## Exit behaviour++The node exits when its credential can no longer be refreshed. The causes are+a ban, an expired session, or a signing key that was retired after its grace+period while the node had no way to enroll again. The last lines of the log+name the cause. A node that loses its routers keeps running and reconnects.+A node whose control plane is unreachable keeps serving with its current+credential until that credential expires.diff --git a/site/content/docs/reference/sam-one.md b/site/content/docs/reference/sam-one.mdnew file mode 100644index 00000000..cf52425e--- /dev/null+++ b/site/content/docs/reference/sam-one.md@@ -0,0 +1,114 @@+---+title: "sam-one"+linkTitle: "sam-one"+weight: 4+---++`sam-one` runs a control plane, a router and the web console in one process+on one port. The router's libp2p transport is WebSocket on the same port as+the HTTP API, so a node needs only one `https` URL. The same binary is also+the admin client for a running instance.++```text+sam-one [flags] run the mesh+sam-one token create|list|revoke|qr manage bootstrap tokens on a running instance+sam-one admin ban <peer-id> ban a node+```++## Files++Everything lives in `--data-dir` (default `.`): `sam.db` (SQLite), the+router key, `join-token` and `admin-token` when generated, and `bin/` for a+downloaded tunnel connector.++## Server flags++| Flag | Default | Meaning |+|---|---|---|+| `--bind-address` | `0.0.0.0` | Host to bind. |+| `--port` | `0` | TCP port. `0` picks a free one and prints it in the banner. |+| `--external-url` | | Public URL on which nodes reach this instance, for a reverse proxy or a hosted platform. Can also be set with `SAM_EXTERNAL_URL`. Sets the advertised `wss` address. |+| `--tunnel` | | Publish the port through a tunnel provider and use the resulting URL as the external URL. The only provider is `cloudflare` (a quick tunnel, no account needed). |+| `--tunnel-install` | `false` | Download the pinned, digest-verified `cloudflared` into `<data-dir>/bin` without asking. Implies acceptance of its license. |+| `--cloudflared-path` | `PATH`, then `<data-dir>/bin` | Explicit connector binary. |+| `--p2p-listen` | none | Extra native libp2p listen addresses, in addition to the WebSocket transport on the main port. |+| `--data-dir` | `.` | See above. |+| `--db-driver` | `sqlite` | `sqlite` or `postgres`. |+| `--db-dsn` | `<data-dir>/sam.db` | Database DSN. |+| `--token-path` | | File containing the standing join token. Can also be set with `SAM_TOKEN`. Generated and saved to the data directory when neither is set. |+| `--no-join-token` | `false` | Run without a standing join token. Devices can then enroll only with minted tokens or OIDC. |+| `--admin-token-path` | | File containing the admin token. Can also be set with `SAM_ADMIN_TOKEN`. Generated and saved to the data directory when neither is set. |+| `--policy-file` | | Protojson `PolicyConfigUpdateRequest` that seeds the mesh policy on first boot. Ignored once the database has a policy. Without it, first boot seeds an open development policy and logs a warning. |+| `--issuer` | | External OIDC issuer(s), comma-separated. Optional. Without an issuer, enrollment works by token only. |+| `--oidc-client-id` | first audience | Client ID advertised on `/info`. |+| `--allowed-audiences` | `sam-mesh-audience` | Accepted OIDC audiences. |+| `--enroll-qr` | when stdout is a terminal | Print a device-enrollment QR code at startup. Only for `https` URLs. |+| `--enroll-qr-max-usages` | `1` | How many devices the startup QR admits. |+| `--log-level` | `info` | `debug`, `info`, `warn`, `error`. `LOG_FORMAT=json` selects JSON output. |++### Embedded component tunables++These flags pass through to the embedded control plane and router. A value+of zero leaves the default of that component unchanged.++| Flag | Corresponds to |+|---|---|+| `--control-plane-lease-duration` | `sam-control-plane --lease-duration` |+| `--control-plane-key-rotation-interval` | `--key-rotation-interval` |+| `--control-plane-key-grace-period` | `--key-grace-period` |+| `--control-plane-biscuit-ttl` | `--biscuit-ttl` |+| `--control-plane-manual-enrollment` | The opposite of `--auto-approve-enrollment`: queue bootstrap enrollments for approval. |+| `--router-keys-sync-interval` | `sam-router --keys-sync-interval` |+| `--router-lease-renew-interval` | `--lease-renew-interval` |+| `--router-low-watermark`, `--router-high-watermark` | `--low-watermark`, `--high-watermark` |+| `--router-conns-per-source-ip` | `--conns-per-source-ip`. `0` follows the high watermark, because peers behind a proxy share source IPs. |+| `--router-dht-provider-addr-ttl`, `--router-dht-max-record-age` | The DHT record lifetimes. |+| `--router-allow-loopback` | `--allow-loopback`. Defaults to `true` here, for a laptop. Disable it on a public deployment. |++## The banner++On start, `sam-one` prints the API URL, the console URL, the router's peer+ID, the admin and join tokens, and the `sam-node join` command to use.+Tokens that the operator supplied (through a flag or the environment) are+shown as their source and not as their value, because stdout is often a log.+Tokens that `sam-one` generated are shown in full, because the banner is+where the operator learns them.++## The development policy++With no `--policy-file` and an empty database, first boot seeds three roles,+each with `allowed_services: ["*"]` and `allowed_targets: ["*"]`:+`sam-admin`, `sam:role:router`, and `sam:role:node`, the last one also with+`allowed_labels: ["*"]`. Any enrolled node can then call any service and+declare any label. Replace this policy before sharing the mesh with anyone.++## Admin client++The subcommands talk to a running instance over its HTTP API. Shared flags:++| Flag | Default | Meaning |+|---|---|---|+| `--server` | `http://127.0.0.1:8080` | Base URL of the instance. |+| `--admin-token-path` | | File containing the admin token. Can also be set with `SAM_ADMIN_TOKEN`, or read from `--data-dir`. |+| `--data-dir` | `.` | Where to find the saved admin token. |++| Command | Flags | Effect |+|---|---|---|+| `token create` | `--role` (`sam:role:node`), `--ttl-hours` (24), `--max-usages` (1), `--description`, `--autonomous-recovery` | Mint a token. Prints it once on stdout. |+| `token list` | | Tokens with usage count, status (`active`, `exhausted`, `expired`, `revoked`) and expiry. |+| `token revoke <id>` | | Revoke by ID or unambiguous ID prefix. Enrolled devices keep their identity. |+| `token qr` | `--enroll-url`, `--ttl-hours`, `--max-usages`, `--description`, `--autonomous-recovery` | Mint a node token and print `sam://enroll?server=<url>&token=<token>` as a terminal QR code. The URL must be `https`. |+| `admin ban <peer-id>` | | Ban a node. |++## Platforms++- **A laptop behind NAT**: `--tunnel cloudflare` gives a temporary `https`+ hostname. See [your own mesh](../../getting-started/your-own-mesh/).+- **A host with a name**: `--port 8080 --external-url https://mesh.example.com`+ behind a reverse proxy that forwards WebSockets.+- **Cloud Run**: pinned `SAM_TOKEN` and `SAM_ADMIN_TOKEN`, one instance, no+ CPU throttling. See the [Cloud Run guide](../../guides/cloud-run/).++`sam-one` is a single process by design. For more than one router, or for a+control plane that scales horizontally, use the separate binaries or the+Helm chart.diff --git a/site/content/docs/scale-experiment.md b/site/content/docs/scale-experiment.mddeleted file mode 100644index 5514ccae..00000000--- a/site/content/docs/scale-experiment.md+++ /dev/null@@ -1,227 +0,0 @@-----title: "Scale Experiment Guide"-description: "How to reproduce the thousand-agent Firecracker run on GCP"-weight: 100------## Overview--This is the operational companion to-[Scale: what an agent costs]({{< relref "/docs/scale-report" >}}). The report says-what was measured and what it means; this says how to run it again.--The arrangement is one host, one `sam-node`, and *N* agents. Each agent is a-Firecracker microVM with **no network device at all** — no NIC, no bridge, no-route anywhere. Its only way out is a vsock to its own `sam-box`, which resolves-mesh names and applies policy to every flow. A thousand of these have been run-on a single `n2-standard-64`.--### Components--| | |-| --- | --- |-| **Host VM** | `n2-standard-64` on GCP with nested virtualisation, running the node and one `sam-box` per agent |-| **Guest** | Firecracker microVM, Alpine, ~160 MiB, no network device |-| **`nano-init`** | PID 1 in the guest: builds `tun0`, carries its own TCP stack, and restores the mesh name when it opens a flow |-| **Agent** | The [canonical harness](https://github.com/google/sam/tree/main/development/examples/agent-harness), holding no credentials |--`nano-init` speaks netlink directly and carries its own TCP stack, so the guest-needs no proxy configuration, no helper binaries and nothing fetched at build-time.--## Prerequisites--- A guest kernel built with `CONFIG_TUN=y`. The quickstart, 5.10 and 6.1- Firecracker CI kernels **do not** have it; 6.18.41 does. `startup-script.sh`- downloads a TUN-capable kernel and fails loudly rather than booting a guest- whose agent can never get a route.-- A bootstrap token at `/etc/sam-bootstrap-token` on the host. The launcher- refuses to start without one, rather than discovering the problem a thousand- sandboxes later.-- KVM, with `/dev/kvm` writable by the invoking user.--## Step 1: build the guest image--Built once, locally, and uploaded — not rebuilt on every host.--```bash-# Alpine, python, nano-init and the agent, as an ext4 image-./scripts/build-rootfs.sh gs://my-sam-bucket/scale-test-```--The image ships the canonical harness rather than the chaos agent, deliberately:-a scale run wants the same request every time, and the chaos agent never issues-the same request twice.--To build a different agent in, point `AGENT_SRC` at it and give it room. The-size matters — an image that is too small fails during the copy, not at boot:--```bash-# The LangChain chaos agent needs roughly four times the harness's space-ROOTFS_MB=2048 AGENT_SRC=cmd/chaos-agent ./scripts/build-rootfs.sh-```-------## Step 2: provision the host--```bash-./scripts/provision-scale-vm.sh \- --prefix sam-minions --count 1 \- --machine-type n2-standard-64 \- --local-binaries gs://my-sam-bucket/scale-test \- --no-spot-```--The script builds your local Go binaries and injects them alongside a-`startup-script.sh` that pulls everything down on boot.--Use `--no-spot` for anything you intend to keep. Spot capacity for this machine-type is thin, and a run reclaimed halfway through produces no result while-costing the same as one that finished. Standard instances also live-migrate-through host maintenance; spot ones are terminated by it, so a soak on spot is a-soak with a deadline somebody else sets.--If provisioning reports `ZONE_RESOURCE_POOL_EXHAUSTED`, try another zone.-------## Step 3: size the guest--Once per agent image. An undersized guest fails in ways that look like network-faults, and an oversized one wastes the memory that decides the population-ceiling.--```bash-sudo tests/scale/measure-guest.sh-```--For the harness this found 136 MiB fails, 144 MiB runs slowly, and **160 MiB-runs at full speed**, against a working set of about 206 MiB.-------## Step 4: launch the fleet--The host's `startup-script.sh` has already verified nested virtualisation,-downloaded Firecracker and a TUN-capable kernel, and pulled down the rootfs and-your `sam-node` / `sam-box` binaries.--```bash-gcloud compute ssh sam-minions-1 --zone us-central1-c--# Prove the launcher works before asking it for a thousand of anything-sudo tests/scale/validate-launcher.sh--sudo SANDBOX_LINGER=2400 /opt/microvm/launch-microvms.sh 1000-```--The launcher preflights first — firecracker, KVM, a TUN-capable kernel, the-rootfs, the binaries and a non-empty bootstrap token — then starts one `sam-box`-per agent and one microVM per `sam-box`, all against a single node. The rootfs-is shared read-only: a private 500 MB copy per agent is half a terabyte at a-thousand agents, and the disk runs out before the memory does.--`SANDBOX_LINGER` holds each sandbox open after its agent finishes. A density-measurement needs the population resident *at the same time*; left alone a-sandbox powers off the moment it is done, so a thousand started in sequence are-never a thousand at once. Zero is the right value for real work.--Useful knobs, all environment variables:--| | |-| --- | --- |-| `VM_MEM_MIB` | Guest memory, default 160 |-| `SANDBOX_LINGER` | Seconds to hold a sandbox after the agent exits, default 0 |-| `SAM_MODEL` | Model to ask the mesh for; unset takes whatever the catalog offers |-| `CONTROL_PLANE` | Defaults to the `bananas` testnet |-| `AGENT_DOMAIN` | The domain agents are named under |--These reach the guest as kernel command-line pairs, which is the only way to-tell PID 1 anything — it is started with an empty environment. They therefore-**cannot contain spaces**, and the launcher rejects values that do.-------## Step 5: collect--```bash-sudo tests/scale/collect-fleet.sh \- --node-socket /var/run/sam-node.sock --duration 1500 --out fleet.jsonl-```--The headline number is how many agents the *node* is serving, not how many-microVMs somebody started: a guest that booted and never reached its boundary is-a process, not an agent. This asks the node, and samples over time rather than-once at the end, because the shape of the curve is what says whether a-population came up smoothly or fell over partway.--Watch `sam_node_agents_untracked_total`. If it is anything but zero, the agent-count is a ceiling rather than a measurement.-------## Step 6: drive load--Density is not throughput. With the fleet resident:--```bash-sudo tests/scale/load-fleet.sh --agents 200 --requests 200 --out /var/log/load-sudo tests/scale/load-fleet.sh --report /var/log/load-```--Load goes through one boundary per agent rather than many connections through-one, so the node sees *N* distinct principals and the admission path is-exercised as it would be in practice. Pointing a single generator at a single-boundary measures a socket, not a mesh.-------## Watching it--```bash-# Did the host finish setting itself up?-sudo tail -f /var/log/startup-script.log--# A guest's console, agent output included-sudo tail -f /var/log/fc-vm-1.log--# What the node thinks it is serving-sudo curl -s --unix-socket /var/run/sam-node.sock http://localhost/metrics \- | grep sam_node_agents_seen-```-------## The boundary measurements--The other half of the report needs no cloud at all. It stands up a real mesh on-kind and attaches boundaries to it:--```bash-./tests/scale/run-density.sh --steps 1,2,4,8,16,32,64 --requests 500-```--Results land in `tests/scale/results/`, with `environment.json`, the raw-per-step observations and a rendered `table.md`.-------## Chaos testing--`cmd/chaos-agent` is a LangChain agent pointed at whatever tools the mesh grants-it and told to abuse them. It is the right tool for asking whether the mesh-survives an autonomous caller, and the wrong one for asking what anything costs.--```bash-ROOTFS_MB=2048 AGENT_SRC=cmd/chaos-agent ./scripts/build-rootfs.sh--sudo SAM_MODEL=google/gemma-2-2b-it CHAOS_SLEEP=30 VM_MEM_MIB=512 \- /opt/microvm/launch-microvms.sh 25-```--It runs until stopped, sleeping a jittered interval between rounds so a fleet of-them does not arrive at the providers in lockstep, and it treats its own crashes-as data rather than as a reason to exit. Like the harness it holds no-credentials, addresses everything by mesh name, and takes its model from the-catalog rather than being told one.diff --git a/site/content/docs/scale-report.md b/site/content/docs/scale-report.mddeleted file mode 100644index 61ede66d..00000000--- a/site/content/docs/scale-report.md+++ /dev/null@@ -1,460 +0,0 @@-----title: "Scale: what an agent costs"-description: "A measured account of the price of giving every agent its own policy-enforced boundary"-weight: 99------## The question--SAM's design makes a claim that sounds expensive. Every agent is a principal,-and every agent reaches the network through its own boundary that resolves-names and enforces policy on each flow. Nothing an agent does escapes that-boundary, because in a properly built sandbox there is no other route out.--Architecture documents can argue for that. They cannot tell you whether it is-affordable. If a boundary costs a hundred megabytes and adds ten milliseconds,-the design is a nice idea for a dozen agents and useless for a thousand. So-this page is not an argument. It is a measurement, with the method written down-so you can disagree with it, and a script so you can re-run it.--Four questions, each phrased so that a bad answer would be visible:--1. **Density.** What does the *N*th boundary cost in memory?-2. **Startup.** How long from launching a sandbox to it being able to call the mesh, and does that grow with the population?-3. **Overhead.** What does an agent pay in latency for reaching the mesh through a policy instead of a socket?-4. **Enforcement.** Does policy still hold under load, and what does refusing cost?--## Method--### Apparatus--One real mesh: a control plane, a router and a node, all running as they do in-the end-to-end suite, on a kind cluster. Not a simulation and not a mock — the-node enrols, mints real tokens and answers real requests.--Sandbox boundaries are then attached to that node one at a time. They run as-**host processes rather than containers**, deliberately. The question is what-`sam-box` costs; wrapping each one in a container would measure the container-runtime instead.--### The workload--The load generator (`sam-bench`) issues exactly the same request every time.-This repo also ships a chaos agent driven by a real language model, and that is-the right tool for asking whether the mesh survives an autonomous caller — but-it is the wrong tool for asking what anything costs, because it never issues-the same request twice, so a difference between two runs cannot be attributed-to the mesh.--The generator reaches the mesh the way an agent does: over the boundary's-SOCKS5 socket. What it measures is therefore what an agent experiences, not-what an operator with host access would.--### Conditions--One number would have been misleading, so every step of the sweep is measured-four ways:--| Condition | What it isolates |-| --- | --- |-| **Baseline** | The same node answering the same request with no boundary in the path. |-| **Reused flow** | What an agent normally experiences: a flow admitted once, carrying many requests. |-| **New flow per request** | What admission costs, paying the handshake and the policy decision every time. |-| **Denied** | Enforcement, which never appears as a latency at all and so must be counted separately. |--The baseline reaches the node over its own Unix socket rather than through a-relay, so the comparison is not charged for a hop the mesh path does not make.--### What is recorded--Client-side latency says what an agent experienced. The servers' own counters-say what they did to produce it, including the flows they refused, which leave-no latency behind. Both are recorded, along with the machine, the commit and-whether the tree was dirty, because a latency with no machine attached to it is-not a result.--Percentiles are computed from the full sorted sample by nearest rank, so every-figure quoted below was actually observed rather than interpolated between two-figures that were. Failed requests never enter the latency distribution: a mesh-that refuses quickly must not be able to look like a mesh that answers quickly.--Warmup requests are issued and reported separately rather than discarded, since-a first call that pays for provider discovery is a real cost and hiding it-would flatter the result.--### Environment--| | |-| --- | --- |-| CPU | Intel Xeon @ 2.60 GHz, 48 vCPU |-| Memory | 118 GiB |-| Kernel | Linux 7.1.6 |-| Go | 1.26.5 |-| Sweep | 1, 2, 4, 8, 16, 32, 64 sandboxes |-| Load | 500 requests per condition per step, concurrency 4, 20 warmup |--## Results--_Recorded 2026-08-21 at commit `e5b2966`. Tables are generated by `sam-bench-report` from the raw observations, which are kept alongside them._--### The measurements--Latency in milliseconds, memory in MB, per population size.--| sandboxes | reused p50 | reused p99 | new-flow p50 | new-flow p99 | admission (µs) | idle RSS | total RSS | denied | leaked |-| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |-| 1 | 1.36 | 2.30 | 1.55 | 78.15 | 19 | 20.2 | 0.02 GiB | 500 | 0 |-| 2 | 1.34 | 2.09 | 1.40 | 3.19 | 20 | 19.4 | 0.06 GiB | 500 | 0 |-| 4 | 1.33 | 2.92 | 1.44 | 3.90 | 19 | 19.0 | 0.12 GiB | 500 | 0 |-| 8 | 1.33 | 2.37 | 1.46 | 6.23 | 18 | 18.8 | 0.21 GiB | 500 | 0 |-| 16 | 1.39 | 3.37 | 1.44 | 2.38 | 19 | 18.9 | 0.39 GiB | 500 | 0 |-| 32 | 1.34 | 2.42 | 1.37 | 3.22 | 18 | 18.1 | 0.72 GiB | 500 | 0 |-| 64 | 1.30 | 1.80 | 1.41 | 4.62 | 18 | 17.4 | 1.37 GiB | 500 | 0 |-| _baseline_ | _1.39_ | _2.37_ | — | — | — | — | — | — | — |--Every allowed step served 500 of 500 requests. Every denied step served 0 of-500. "Admission" is the boundary's own mean time to classify a destination and-open it; "leaked" is the number of requests that reached a destination policy-forbade.--### Density--A boundary settles at **17–20 MB of resident memory** once idle. Sixty-four of-them, attached to one node with one under continuous load, came to **1.37 GiB-in total**.--The per-sandbox mean falls as the population grows, which is an artefact worth-naming rather than a discovery: the same boundary carries the load at every-step, so its heap reflects the traffic while the others sit idle, and the mean-is diluted towards the idle cost as the population grows. The floor, not the-mean, is the marginal cost of one more agent.--### Startup--Across 64 sandboxes: **median 59 ms**, min 58 ms, p95 59 ms, max 70 ms.--Readiness here means the socket is accepting connections, not that the process-exists — a boundary that has not bound its socket yet is of no use to the agent-waiting on it.--The spread is the notable feature: the 64th boundary started as quickly as the-first, so attaching an agent is a constant-cost operation over this range rather-than one that degrades as the host fills up.--### Overhead--This is the result that came out differently from what the method expected, so-it is worth being precise about.--Baseline, no boundary in the path: **p50 1.39 ms**. Through the boundary on a-reused flow, p50 ranged from **1.30 to 1.39 ms** across the sweep — that is,-*at or below the baseline at every population size*. Taken literally the-boundary made things faster, which it obviously did not. The honest reading is-that **the end-to-end overhead of the boundary is smaller than the run-to-run-variation of the measurement itself**, so this method cannot resolve it. A-figure like "the boundary costs 60 µs" would be reading noise.--Opening a fresh flow for every request, which pays the SOCKS5 handshake and the-policy decision each time, is resolvable but small: p50 ran **+9 to +157 µs**-against the baseline.--The reliable number comes from the boundary's own instrumentation, which is-measured in-process and excludes everything downstream. Classifying a-destination and opening it took a mean of **18–20 µs**, and that figure moved-by less than 2 µs across the entire sweep, from one sandbox to sixty-four.--So: enforcement costs tens of microseconds, and whatever the boundary adds-end to end is lost in the noise of a millisecond-scale request.--### Enforcement--Every request to a destination policy did not allow was refused. **3,500-attempts, zero successes**, at every population size, and the boundary's own-counter agreed with the client's on the exact number refused at every step.--Refusal ran at **24,000–28,000 per second**, roughly ten times the rate of-allowed traffic, which is what should happen: a denied flow is decided from the-name and never dialled.--## Conclusions--**The per-agent boundary cost is small relative to the agent it contains.** At-~18 MB and ~59 ms to attach, the constraint on how many agents a host carries is-the agents themselves rather than the thing that contains them. Extrapolating-the floor, the boundaries for a thousand agents would be roughly 18 GB. That-extrapolation is precisely what the next experiment should test rather than-assume.--**Enforcement is not a latency problem.** 18–20 µs to classify and open a flow,-and an end-to-end cost too small for this method to separate from noise. The-design's insistence that every flow be checked does not have to be traded-against performance, which removes the usual reason such checks get quietly-disabled.--**Nothing degraded across the range tested.** Median latency was flat from 1 to-64 sandboxes, startup was constant, and the boundary's own admission cost moved-by under 2 µs across a 64-fold increase in population.--**10,500 requests. No failures where success was expected, and no successes-where it was not.**--## Threats to validity--Written down because a result without them is advocacy.--- **One machine, one run.** These are not confidence intervals over repeated- trials. Treat single figures as indicative and the shape of the trend as the- claim. The overhead result above is precisely a case where a single figure- would have been over-read.-- **A trivial request.** `/v1/models` is a small response from a warm node. It- isolates mesh overhead well precisely because it does almost no work, which- also means it says nothing about large payloads or streaming completions.-- **Load through one boundary.** Every step drives traffic through the first- sandbox while the rest are attached but idle. This answers "do the others get- in the way", which is the density question, but it is not the same experiment- as all *N* being busy at once.-- **A reproducible tail anomaly.** The single-sandbox, new-flow-per-request step- showed p99 excursions of 60–80 ms in every run, and did not recur at higher- populations. It is reproducible and unexplained; it is left in the record- rather than smoothed out.-- **Host processes, not sandboxes.** This measures the boundary, not the- isolation around it. A Firecracker microVM per agent costs far more than- 18 MB, and none of that cost is counted here.--## Reproducing this--```bash-# The boundary measurements: requires docker and kind, stands up a real mesh.-./tests/scale/run-density.sh --steps 1,2,4,8,16,32,64 --requests 500--# The thousand-agent run: needs a host with KVM, a guest kernel with-# CONFIG_TUN, and a bootstrap token for a control plane.-./scripts/provision-scale-vm.sh --no-spot --local-binaries gs://your-bucket/sam-# then, on the host:-SANDBOX_LINGER=2400 /opt/microvm/launch-microvms.sh 1000-/opt/microvm/collect-fleet.sh --node-socket /var/run/sam-node.sock --duration 1500-```--Results land in `tests/scale/results/`, including `environment.json` and the-raw per-step observations, with a rendered `table.md`.--Individual measurements can be taken by hand:--```bash-# Through a boundary, as an agent would-sam-bench run --socket /run/agent.sock --target http://mesh.sam.alt/v1/models \- --requests 500 --concurrency 4 --scrape http://127.0.0.1:9600/metrics--# The same request with no boundary in the path, for comparison-sam-bench run --target-unix /run/node.sock --target http://localhost/v1/models \- --requests 500 --concurrency 4-```--`sam-box` serves metrics only when asked, with `--metrics-addr`. It sits between-a sandbox and the mesh, so any listener it opens is one more thing reachable-from wherever it is bound.--## What this does not answer--This measures a boundary on a host. It says nothing yet about a thousand agents-in real sandboxes against a public testnet, where microVM memory, control-plane-enrolment and DHT behaviour all start to matter and none of them are exercised-above. That experiment is [below](#a-thousand-agents-on-one-host).--## A thousand agents on one host--The measurements above are of a boundary, not of a sandbox: host processes, no-kernel per agent, no mesh beyond the machine. The obvious objection is that-none of it survives contact with the real arrangement, where every agent is a-Firecracker microVM with its own kernel and the node has to be a real member of-a real mesh.--So: one `n2-standard-64`, one `sam-node` enrolled in the public `bananas`-testnet, and a thousand agents. Each agent is a microVM with **no network-device at all**, reaching the mesh through its own `sam-box` over vsock.--_Recorded 2026-08-21. Raw samples in-[`tests/scale/results/fleet-1k`](https://github.com/google/sam/tree/main/tests/scale/results/fleet-1k)._--### What a thousand agents cost--| | total | per agent |-| --- | --- | --- |-| Guest microVMs | 162.7 GiB | **167 MiB** |-| Boundaries (`sam-box`) | 24.6 GiB | **25 MiB** |-| Node (one, for all of them) | 386 MiB | 0.4 MiB |-| **Together** | **187 GiB of 251 GiB** | **192 MiB** |--The node figure is the one that bears on the design. One `sam-node` served a-thousand distinct agent principals in 386 MB, because an agent is not a peer: it-has no enrolment, no key and no place in the DHT. The mesh gained a thousand-principals and no members.--### How fast they came up--A thousand sandboxes launched in **149 seconds — 6.7 per second**, median-153 ms each, p95 245 ms. The population became reachable as fast as it was-started:--| elapsed | agents serving | microVMs | guest memory |-| --- | --- | --- | --- |-| 0 s | 71 | 120 | 17.2 GiB |-| 44 s | 328 | 383 | 62.1 GiB |-| 99 s | 691 | 734 | 119.7 GiB |-| 160 s | **1000** | 1000 | 162.7 GiB |-| 323 s | 1000 | 1000 | 162.7 GiB |--Agents trail microVMs by a few seconds and never by more than about fifty —-that gap is a guest booting and its agent resolving a mesh name, not a queue-forming. Nothing degraded as the population grew, and the last hundred came up-as quickly as the first.--`sam_node_agents_untracked_total` was **0**: every agent that ran was counted,-so the thousand is a thousand and not a ceiling.--### What they can push--Density is not throughput, so with the thousand still resident, traffic was-driven through 200 of them at once — each through its own boundary, so the node-saw 200 distinct principals rather than 200 connections from one client. 200-requests per agent, two in flight each.--**What the following number is, and is not.** It is the aggregate rate at which-a locally-served endpoint was reached through 200 concurrent policy boundaries,-with the load generated on the host. It is not an end-to-end figure for an agent-workload. The request is answered by the node itself, so no upstream provider is-in the path; and the generator enters at the boundary's SOCKS5 socket rather-than from inside a guest, so the in-guest network stack and the vsock hop are-not either. It should be read as an upper bound on what the enforcement path-permits, not as a throughput claim for the system as deployed.--Under those conditions: 40,000 requests, none failed, in 0.43 s — an aggregate-of roughly 92,000 requests per second, while the other 800 sandboxes sat-resident. Per agent that is a median of 534 req/s, with a minimum of 490 and a-maximum of 652, so no principal was starved. Client-observed time to first byte-was a median of 2.0 ms across agents, 13 ms at p95, 21 ms at p99, and 98 ms for-the single worst request in the run.--The node's own counters record **200 for all 41,000**:--| server-side duration | requests | share |-| --- | --- | --- |-| under 0.5 ms | 35,580 | 86.8% |-| under 5 ms | 39,412 | 96.1% |-| under 10 ms | 40,207 | 98.1% |-| under 25 ms | 40,586 | 99.0% |-| 5–10 s | 400 | 1.0% |--That last row is the interesting one, and it is not jitter. Those 400 requests-took almost exactly 5.04 seconds each, which is-[`dhtLookupTimeout`](https://github.com/google/sam/blob/main/internal/node/node.go)-to the millisecond. `/v1/models` resolves providers through the DHT, and the-node's own log shows that walk returning four peers — so it was not waiting on-an empty mesh. It was waiting because the walk has no reason to stop early: it-asks for up to twenty providers, four is not twenty, and nothing tells it that-four is all there are. So it runs out the clock, then caches the answer for-thirty seconds.--The cost is therefore not per agent and not per request. It is one slow lookup-per cache expiry, paid by whichever caller happens to arrive on a cold cache;-everything behind the cache is the sub-millisecond mass above.--It is still a fair thing to dislike. A lookup that already has its answers-should not wait five seconds to admit it, and the two hundred callers who-arrived together each paid it instead of sharing one lookup.--### What an agent actually gets--Everything above is a cost. None of it says what the agent receives in return,-and a boundary that is cheap but useless is not a result worth publishing. So,-separately from the thousand-agent run: a sandbox was booted and asked what the-mesh would give it.--It is a Firecracker microVM with **no network device** — no NIC, no bridge, no-route to anywhere. Its only path out is a vsock to its own `sam-box`. Inside it-there is no API key, no model endpoint, no tool server address and no-configuration naming any of them. The agent asks for `mesh.sam.alt`, which is-not in DNS and has no route to it, and the boundary decides what that means for-this particular agent.--What came back:--| | |-| --- | --- |-| Tools | **15**, discovered over MCP, with their real JSON schemas |-| Models | `google/gemma-2-2b-it` and `openrouter/auto` |-| Credentials in the sandbox | **none** |-| Network devices in the sandbox | **none** |--Both models answer. `google/gemma-2-2b-it` is served by a vLLM instance on a-TPU elsewhere in the mesh and replied `mesh ok`, reporting its own-`vllm-0.26.1rc1` fingerprint. `openrouter/auto` resolved outward and was routed-to `deepseek/deepseek-v4-flash-0731`. The agent asked for neither by address; it-asked for a model, and the mesh chose the provider.--The LangChain agent then ran inside that sandbox and produced model output from-the TPU-hosted vLLM, having taken its model name from the catalog rather than-being told one. Two ordinary SDKs, the OpenAI client and the MCP client, used-exactly as they are used anywhere — nothing in the sandbox is SAM-specific,-which is the point: an agent that needed a special client would be an agent-nobody could port onto this.--The honest limit of this demonstration: it establishes that tools and both-providers are reachable and answering from inside a network-less sandbox. It is-not a claim about how well a 2B model drives a fifteen-tool loop, which is a-question about the model and not about the mesh.--### What this run says--**An agent costs about 192 MiB and 150 ms**, nearly all of it the microVM. The-boundary is 25 MB of that and the node's share is under half a megabyte. A-host's agent count is decided by how much memory the agents themselves want.--**The mesh does not grow when the agent population does.** A thousand agents-arrived as one member with one enrolment. That is the reason for separating the-principal from the peer, and it is the difference between a mesh that can hold-this population and one that cannot.--**It ran against a real, shared control plane** — not a fixture — with one-bootstrap enrolment.--**The enforcement path did not limit throughput under these conditions.** 200-agents issued 40,000 requests in under half a second with no failures, and the-node served most of them in under half a millisecond while holding a thousand-principals. Since the endpoint was local and the load host-generated, this-bounds the enforcement path rather than characterising a deployed workload.--**Inference was not exercised in this run.** The agents' model calls returned-**404**, 998 of them: they asked for a model named `default`, and a name no-catalog contains resolves to no provider. The run demonstrates reach, admission-and MCP at a thousand agents; the inference path is-[demonstrated separately](#what-an-agent-actually-gets), and the two should not-be confused.--### Threats to validity--- **One host, one run.** No repetitions, no confidence intervals.-- **The agents are the example harness**, which connects, discovers tools,- attempts a model call and stops. A heavier agent needs more guest memory, and- 167 MiB is a statement about this workload rather than about agents in- general.-- **Memory was measured with the population idle.** The throughput numbers came- from a separate pass over the same resident fleet, so the 192 MiB/agent figure- and the 92k req/s figure are not from the same instant.-- **The load was driven from the host**, into each boundary's SOCKS5 socket —- the same entry point the guest uses, but skipping the in-guest netstack and- the vsock hop. It measures the mesh datapath, not the sandbox's own overhead,- and the real per-agent ceiling will be lower.-- **The load target is served by the local node.** `/v1/models` answers from the- node itself, so no upstream provider is in the path. That is deliberate — it- isolates SAM's cost from a backend's — but it is not an end-to-end figure.-- **Only 200 of the thousand pushed traffic.** The rest were resident and idle.- Nothing here says what all thousand at full rate would do.-- **A thousand is not a limit.** It is what fits comfortably in 251 GiB with- this agent. Nothing here found a ceiling, which also means nothing here- located one.-- **Spot instances were preempted twice** before this run, mid-measurement. The- final run used a standard instance. Worth knowing if you reproduce it: an- experiment that takes ten minutes and a machine that lasts ten minutes do not- mix.diff --git a/site/content/docs/sovereignty.md b/site/content/docs/sovereignty.mddeleted file mode 100644index 0eb28f82..00000000--- a/site/content/docs/sovereignty.md+++ /dev/null@@ -1,139 +0,0 @@-----title: "Digital & Data Sovereignty"-linkTitle: "Sovereignty Architecture"-weight: 12------# Digital & Data Sovereignty in SAM--This document articulates the architecture, technical mechanisms, and legal-regulatory foundations of digital and data sovereignty in the **Sovereign Agent Mesh (SAM)**.-------## 1. Core Distinctions: OSS Project vs. Products vs. Developer Testnets--To understand sovereignty in SAM, three fundamental distinctions must be established:--### 1.1 An Open-Source Software Project-SAM is an **open-source software project licensed under Apache-2.0**, developed in the open on [GitHub](https://github.com/google/sam).-* It is **an open, decentralized networking protocol and runtime**, not a closed SaaS offering.-* It contains **no telemetry, no tracking, no phone-home mechanisms**, and no hardcoded dependencies on any proprietary model provider.-* Operators have the unfettered right to inspect, audit, compile, and deploy the entire software stack on any compute environment worldwide.--### 1.2 Public Developer Testnets Have Zero Sovereign Value-The public endpoints maintained by project contributors (`bananas.sam-mesh.dev` tracking `main` and `hub.sam-mesh.dev` tracking release tags) are **free, public developer testnets created using community resources**:-* **Purpose:** They exist strictly as ephemeral testing sandboxes for continuous integration (CI/CD), interoperability checks, and developer rapid prototyping.-* **Community-Funded with No Guarantees:** Public testnets are hosted using donated community resources and carry **no guarantees, no uptime commitments, and zero SLA**. They hold no production data, provide no persistent storage warranties, and are inherently non-sovereign because you are interacting with a shared developer testing environment. **A shared public testnet is, by definition, not sovereign.**--### 1.3 Sovereignty Through Architectural & Cryptographic Control-In SAM, digital sovereignty is built on verifiable architectural control: cryptographic key custody, independent identity federation, and strict data residency enforcement. To establish a sovereign deployment, an organization deploys its control plane (`sam-control-plane`), routing layer (`sam-router`), and nodes (`sam-node`) on dedicated infrastructure (such as on-premise datacenters, bare metal, air-gapped environments, or dedicated sovereign cloud infrastructure including Google Cloud with Customer-Managed Keys and regional data residency) using the provided [Helm chart](https://github.com/google/sam/tree/main/charts/sam-mesh) or [Kubernetes deployment guide](../user/kubernetes-deployment/).-------## 2. Evaluation Against the Five Pillars of Sovereignty--Evaluating SAM in a dedicated sovereign deployment across the five industry-standard pillars of digital sovereignty:--| Pillar | How SAM Delivers Sovereignty | Regulatory & Standards Alignment |-| :--- | :--- | :--- |-| **01 · Territorial** | **Cryptographically Attested Egress Gates:** The data plane is direct P2P and end-to-end encrypted (relays carry only ciphertext). Attested label gates (`VerifyPeerLabels`) cryptographically guarantee that prompts, tools, and data never leave defined territorial or jurisdictional boundaries (e.g. `jurisdiction=eu`, `region=de-txl`). | **GDPR Chapter V (Arts. 44–49)** (Cross-border data transfers), **EU Cloud Sovereignty Framework (SEAL-3)** |-| **02 · Operational** | **Autonomous Key Custody & Local Veto:** The deploying organization generates and holds 100% of the root cryptographic signing keys. Local nodes enforce custom Datalog attenuation policies (`attenuation.checks`, `attenuation.policies`) that execute *before* control plane grants, providing an absolute local veto. | **NIS2 Directive**, **Zero Trust Architecture (NIST SP 800-207)** |-| **03 · Technological** | **100% Open Source & Uncooperative Sandbox Confinement:** Apache-2.0 license, built on open protocols (libp2p, Biscuit Datalog, MCP, standard OIDC). Agent sandboxes (`sam-box`, `nano-init`) run in `network=none` with structural route isolation, preventing leakage without relying on agent cooperation. | **EU Data Act**, **Open Source Initiative (OSI)** |-| **04 · Legal / Jurisdictional** | **Autonomous Cryptographic Custody:** By retaining complete custody of root signing keys (via local HSMs, KMS, or Cloud EKM) and identity infrastructure, all cryptographic material and data flows remain under the operator's direct jurisdiction and control, preventing unauthorized extraterritorial access. | **EU Data Protection Law**, **SecNumCloud / C5** |-| **05 · Financial** | **Zero Lock-In & Open Interoperability:** No license fees, no per-token meters, no proprietary runtime lock-in. Full portability across edge devices, local servers, and multi-cloud environments. | **EU Interoperability Framework (EIF)** |-------## 3. Concrete Sovereign Acts & Technical Mechanisms--SAM implements specific, verifiable cryptographic and networking mechanisms designed to enforce data and execution sovereignty:--```-┌────────────────────────────────────────────────────────────────────────────────────────┐-│ CONSUMER NODE (Local Sovereign Boundary) │-│ │-│ 1. Sandboxed Agent (network=none) │-│ └── Issues request: X-Sam-Required-Labels: jurisdiction=eu,compliance=gdpr │-│ │-│ 2. Local sam-box / sidecar (Fail-Closed Egress Enforcement) │-│ └── Intercepts request before network transmission │-│ └── Fetches candidate provider's Biscuit token │-│ └── VerifyPeerLabels(): Cryptographically validates control-plane signature, │-│ verifies peer ID binding, and evaluates attested label("jurisdiction", "eu") │-│ │-│ [ Verdict: PASS ] ────────────────────────────────────────────────────────┐ │-└───────────────────────────────────────────────────────────────────────────────┼────────┘- │ P2P e2e- │ encrypted-┌───────────────────────────────────────────────────────────────────────────────┼────────┐-│ PROVIDER NODE (Destination Sovereign Boundary) ▼ │-│ │-│ 3. Incoming Request Verification │-│ └── Authenticates caller Biscuit and token expiration │-│ │-│ 4. Local Attenuation Engine (Autonomous Local Veto) │-│ └── Evaluates local attenuation rules BEFORE control plane grants │-│ └── E.g.: check if label("jurisdiction", "eu"); │-│ deny if client_origin("untrusted_zone"); │-│ │-│ 5. Execution in Local Sandbox │-└────────────────────────────────────────────────────────────────────────────────────────┘-```--### 3.1 Attested Labels Gate: Territorial & Jurisdictional Containment--In cross-border and multi-tenant agent networks, gossiped metadata cannot be trusted at face value. SAM implements a **fail-closed, cryptographic label gate**:-1. **Operator-Declared & Authority-Attested:** When a provider node enrolls, its declared labels (e.g. `jurisdiction=eu`, `region=de-west`, `compliance=hipaa`) are verified by the control plane against its role policy and minted into the token authority block as immutable `label(key, value)` Datalog facts (`api.FactLabel`).-2. **Consumer-Side Verification Before Egress:** When an agent or consumer specifies required labels (via the `X-Sam-Required-Labels` HTTP header or `call_remote_tool` parameters), `VerifyPeerLabels` fetches the provider's Biscuit, verifies the signature against the trusted control plane public key, verifies peer binding, and proves the existence of the required label facts **before any payload byte leaves the local machine**.-3. **Anti-Exfiltration Guarantee:** If a provider does not present a valid control-plane-signed Biscuit attesting to the required jurisdiction or security label, the connection is aborted immediately. Gossiped DHT records are only used for discovery ranking; they are never trusted for authorization.--### 3.2 Autonomous Local Veto: Destination-Side Attenuation--Under Zero Trust and operational sovereignty, a centralized control plane must never possess absolute power over local compute and data.-* Local nodes configure an `attenuation` block containing local Datalog rules and policies.-* **Evaluation Order:** Local policies are evaluated **before** central control plane grants. Even if a central authority grants a remote agent access to a service (e.g. `mcp://*`), the destination node operator can unilaterally veto or restrict access using local rules:--```yaml-# Local node attenuation configuration (sam-node.yaml)-attenuation:- rules:- - 'time(2026-09-01T00:00:00Z) <- true;'- policies:- # Autonomous local veto: reject any caller not attested in the EU jurisdiction- - 'deny if !label("jurisdiction", "eu");'- - 'deny if user("revoked_contractor_id");'-```--### 3.3 Identity Evidence API: Independent Auditing Without Phone-Home--To comply with regulatory audit requirements (e.g., EU Cloud Sovereignty Framework SEAL-3, ISO 27001, SOC2), nodes expose local, cryptographically sealed evidence endpoints (`GET /sam/identity` and `GET /sam/peer/{peer_id}/evidence`):-* Allows auditors and local verification engines to inspect raw Biscuit tokens, SPKI DER public key certificates, role assignments, and attested labels.-* **Offline Verification:** Verification is mathematically self-contained using public-key cryptography; no live network calls or telemetry to external servers are required.-------## 4. Addressing Zero-Trust Invariants vs. "Kill Switch" Misconceptions--In discussions of cryptographic networks, bounded credentials and revocation mechanisms are occasionally misunderstood. It is vital to clarify the cryptographic purpose of these invariants:--### 4.1 Bounded Token Expiration (TTL)-* **Cryptographic Rationale:** In Zero-Trust architectures, bearer credentials must have finite lifetimes (e.g. 24 hours). This mitigates the risk of replay attacks, stolen token persistence, and long-term key compromise. This is the same principle underlying **SPIFFE/SPIRE SVID rotation**, **OAuth 2.0 access token TTLs**, and **Kerberos ticket lifetimes**.-* **Operator Control:** In a dedicated sovereign control plane, the token lifetime, renewal interval, and grace periods are fully configured by the local administrator.-* **Fail-Closed Principle:** When a cryptographic credential expires and cannot be renewed (for instance, if the node has been decommissioned or network partitioned), the node daemon terminates its active mesh routes to prevent unauthorized, unauthenticated state persistence.--### 4.2 Cryptographic Revocation-* **Security Function:** Revocation (`/admin/revoke`) allows network administrators to instantly ban a compromised node or rogue agent from the mesh.-* **Sovereign Authority:** In a dedicated deployment, the revocation authority belongs exclusively to the organization deploying the control plane. Nobody outside that organization possesses root keys or revocation privileges.-------## 5. Summary: The Sovereign Architecture Checklist--When deploying SAM for mission-critical, sovereign agent operations:--1. **Deploy Dedicated Control Plane Infrastructure:** Use the Helm chart or Kubernetes manifests to launch `sam-control-plane` on your chosen sovereign infrastructure (managed cloud with customer keys, private Kubernetes, or bare metal).-2. **Maintain Root Cryptographic Key Custody:** Generate, manage, and hold your own Ed25519 root signing keys (via KMS/Cloud EKM or HSMs).-3. **Use Your Own OIDC Identity Provider:** Point `--issuer` to your internal Keycloak, Dex, or corporate IdP.-4. **Declare & Attest Sovereignty Labels:** Declare `labels: {jurisdiction: eu, region: <your-region>}` in each node's `sam-node.yaml` and configure control plane roles with `allowed_labels`.-5. **Enforce Jurisdictional Egress:** Set `egress.require_labels` in `sam-node.yaml` (e.g. `jurisdiction: eu`) so every provider must attest the boundary before the node sends it anything. Agents may narrow further per request with `X-Sam-Required-Labels`, but cannot widen past the floor or waive it by omitting the header — the two are checked independently and every pair of the floor must hold. Independently of any floor, a node forwards nothing to a peer that has not shown a control-plane-signed identity bound to it; discovery names candidates, it does not vouch for them.-6. **Set Local Attenuation Vetoes:** Configure local node `attenuation.policies` to retain final destination-side access control.diff --git a/site/content/docs/use-cases/_index.md b/site/content/docs/use-cases/_index.mdindex e0aef097..102d0c02 100644--- a/site/content/docs/use-cases/_index.md+++ b/site/content/docs/use-cases/_index.md@@ -1,17 +1,17 @@----title: "Use Cases"-linkTitle: "Use Cases"+title: "Use cases"+linkTitle: "Use cases"weight: 5----Worked examples of what you can build **on top of the mesh** — patterns that-combine ordinary `sam-node` MCP services (discovery, remote tool calls, leasing)-into something larger, with no changes to the node itself.+Worked examples of things built on top of the mesh. Each pattern combines+ordinary `sam-node` features (discovery, remote tool calls, leasing) into+something larger, without changes to the node itself.-Each use case is harness-agnostic: the orchestrator is any MCP client — an agent-harness (Claude Code, Codex, Antigravity, …) or a custom program — talking to the-mesh MCP tools exposed by a local node.+None of the examples depends on a specific harness. The orchestrator is any+MCP client, whether an agent harness (Claude Code, Codex, Antigravity) or a+custom program, talking to the tools that a local node exposes.-The runnable source for every example lives under+The runnable source for every example is under[`development/examples/`](https://github.com/google/sam/tree/main/development/examples)-in the repository; each page here links to its example directory.+in the repository. Each page links to its directory.diff --git a/site/content/docs/use-cases/chat-a2a.md b/site/content/docs/use-cases/chat-a2a.mdindex 0eb1e4a7..414ba178 100644--- a/site/content/docs/use-cases/chat-a2a.md+++ b/site/content/docs/use-cases/chat-a2a.md@@ -5,69 +5,69 @@ weight: 30---Hold a multi-turn conversation with an [A2A](https://a2a-protocol.org/)-(Agent2Agent) agent hosted on a remote mesh node — using a **stock,-unmodified `a2a-sdk` client**. No SAM-specific client code: the mesh's-agent-card regeneration makes the standard SDK work as-is.+(Agent2Agent) agent hosted on a remote mesh node, using a stock, unmodified+`a2a-sdk` client. There is no SAM-specific client code. The mesh regenerates+the agent card, and that is enough for the standard SDK to work as it is.Source: [`development/examples/chat-a2a/`](https://github.com/google/sam/tree/main/development/examples/chat-a2a).## The idea-A2A is the mesh's southbound agent-to-agent wire: an agent process speaking-A2A over HTTP registers on its node as a `type: a2a` service, and remote-peers reach it through the raw egress path-`/sam/{peer}/a2a/{service}/...` (see-[A2A Service Routing](../../user/node-configuration/#a2a-service-routing)).+A2A is how agents talk to each other on the mesh. An agent process that+speaks A2A over HTTP is declared on its node as a `type: a2a` service, and+remote peers reach it through the proxy path `/sam/{peer}/a2a/{service}/...`+(see [A2A agents](../../guides/exposing-services/#a2a-agents)).-The problem with proxying A2A naively is the **agent card**. A2A clients-bootstrap from `/.well-known/agent-card.json`, and the card contains the-agent's own interface URLs — addresses that are only reachable on the+The problem with proxying A2A directly is the agent card. A2A clients start+from `/.well-known/agent-card.json`, and the card contains the agent's own+interface URLs, which are addresses that are only reachable on theprovider's machine. A stock client would fetch the card through the mesh,then try to talk to `http://127.0.0.1:7777/` and fail.-So the caller's node **impersonates the card endpoint**: it holds the-client's request, fetches the card from the agent over the mesh, and serves-a regenerated card — interface URLs point back at the mesh path the client-fetched from, protocol bindings the mesh cannot carry (gRPC needs its own-end-to-end connection) are dropped, and streaming is advertised off. The-client follows the regenerated card like it would for any A2A server —-discovery, JSON-RPC `message/send`, and `contextId` round-tripping all work-unmodified, while the traffic actually flows over libp2p between the nodes.+So the caller's node stands in for the card endpoint. It holds the client's+request, fetches the card from the agent over the mesh, and serves a+regenerated card whose interface URLs point back at the mesh path that the+client fetched from. Protocol bindings that the mesh cannot carry are+dropped (gRPC needs its own end-to-end connection), and streaming is+advertised as off. The client follows the regenerated card as it would for+any A2A server. Discovery, sending messages and `contextId` round-tripping+all work without changes, while the traffic flows over libp2p between the+nodes.-This example proves both halves:+This example demonstrates both halves:-- **Card regeneration** — the bundled REPL is a plain `a2a-sdk` client; it+- **Card regeneration**: the bundled REPL is a plain `a2a-sdk` client. Itworks only because the regenerated card sends it back through the mesh.-- **Conversation continuity** — the agent keeps one Gemini chat session per- A2A `contextId`. Tell it your name, ask for it back two turns later: the- answer shows the context survived the mesh hop. Each turn is still its own- short-lived A2A **task** (`taskId` changes every turn, created and- completed by each `message/send`); `contextId` is what persists and groups- them into one conversation.+- **Conversation continuity**: the agent keeps one Gemini chat session per+ A2A `contextId`. Tell it your name, then ask for it back two turns later.+ The answer shows that the context survived the mesh hop. Each turn is+ still its own short-lived A2A task (`taskId` changes every turn). The+ `contextId` is what persists and groups the turns into one conversation.## The pieces-- **`chat` service** (`agent.py`) — a Gemini-backed A2A agent built on the- Python `a2a-sdk`: serves its agent card, answers `message/send`, and holds- history server-side, one Gemini chat session per `contextId`. The node- proxies to it via `target_url`; the agent itself knows nothing about SAM.-- **REPL client** (`chat.py`) — a ~40-line stock `a2a-sdk` client: resolves- the card through the mesh, then loops `input()` → `message/send`, echoing- the `contextId` the server minted on the first reply.+- **`chat` service** (`agent.py`): a Gemini-backed A2A agent built on the+ Python `a2a-sdk`. It serves its agent card, answers messages, and holds+ history on the server side, one Gemini chat session per `contextId`. The+ node proxies to it through `target_url`. The agent knows nothing about+ SAM.+- **REPL client** (`chat.py`): a stock `a2a-sdk` client of about forty lines+ that resolves the card through the mesh, then loops `input()` to a message+ send, echoing the `contextId` that the server created on the first reply.## What you can do with it-- **Bring any A2A agent onto the mesh unchanged** — the example agent is- deliberately vanilla `a2a-sdk`; anything speaking A2A over HTTP (ADK,- LangGraph, a hosted agent) plugs in the same way, one `target_url` line in- the node config.-- **Use any stock A2A client** — `chat.py` is just the smallest one. The- regenerated card means SDKs, CLIs, and other agents resolve and call the- service without knowing SAM exists.-- **Let the agent own the conversation** — the same pattern as- [Gemini Buddy](../gemini-buddy/), but on the standard A2A wire instead of a- custom MCP tool: state lives with the agent, keyed by `contextId`, and- callers only ever send the next message.+- **Bring any A2A agent onto the mesh unchanged.** The example agent is+ plain `a2a-sdk` on purpose. Anything that speaks A2A over HTTP (ADK,+ LangGraph, a hosted agent) plugs in the same way, with one `target_url`+ line in the node configuration.+- **Use any stock A2A client.** `chat.py` is the smallest one. Because of the+ regenerated card, SDKs, CLIs and other agents resolve and call the service+ without knowing that SAM exists.+- **Let the agent own the conversation.** This is the same pattern as+ [Gemini Buddy](../gemini-buddy/), on the standard A2A protocol instead of+ a custom MCP tool. State lives with the agent, keyed by `contextId`, and+ callers only send the next message.## Try it on kind@@ -77,8 +77,8 @@ that brings the agent up with one command.### 1. Set a Gemini key for the agent image`agent.py` calls Gemini, so set your API key on the `ENV GEMINI_API_KEY`-line in `development/examples/chat-a2a/Dockerfile` before building (a free-Google AI Studio key is fine for the demo).+line in `development/examples/chat-a2a/Dockerfile` before building. A free+Google AI Studio key is enough for the demo.### 2. Bring the mesh up and deploy the agent@@ -95,11 +95,11 @@ helm --kube-context kind-sam-kind -n sam-kind install chat-a2a charts/sam-node \### 3. Enroll a local caller node```bash-make kind-local-node # local sam-node enrolled in the mesh — LEAVE RUNNING+make kind-local-node # a local sam-node enrolled in the mesh; leave it running```-The local node is your entry point: its sidecar API listens on-**`http://127.0.0.1:9099`** (bearer token `devtoken`), MCP tools at `/mcp`.+The local node is your entry point. Its API listens on+`http://127.0.0.1:9099` (token `devtoken`), with the MCP tools at `/mcp`.### 4. Find the provider peer@@ -108,12 +108,12 @@ The local node is your entry point: its sidecar API listens on-tool discover_remote_services -args '{"type":"a2a","name":"chat"}'```-Note the peer ID and export it as `PEER`. Discovery is gossip-fed; retry for-a few seconds after startup if the list comes back empty.+Note the peer ID and export it as `PEER`. Discovery is fed by gossip, so+retry for a few seconds after startup if the list comes back empty.### 5. Watch the card regeneration happen-Fetch the agent card through the mesh with nothing but `curl`:+Fetch the agent card through the mesh with `curl`:```bashcurl -s -H 'X-Sam-Authentication: Bearer devtoken' \@@ -121,9 +121,9 @@ curl -s -H 'X-Sam-Authentication: Bearer devtoken' \```The interface URLs in the response point back at this-`/sam/{peer}/a2a/chat` path — not at the agent's own `127.0.0.1:7777` — and-`capabilities.streaming` is `false`. That regenerated card is the whole-trick.+`/sam/{peer}/a2a/chat` path, and not at the agent's own `127.0.0.1:7777`.+`capabilities.streaming` is `false`. That regenerated card is what makes the+example work.### 6. Chat@@ -135,16 +135,16 @@ uv run --with-requirements requirements.txt chat.py \"http://127.0.0.1:9099/sam/$PEER/a2a/chat"```-Prove the continuity: introduce yourself in one turn, chat about something-else, then ask the agent what your name is. It answers from its own-server-side session — the client never re-sent the history, only the+To check the continuity: introduce yourself in one turn, chat about+something else, then ask the agent what your name is. It answers from its+own server-side session. The client never sent the history again, only the`contextId`.## Configuration| var | default | used by ||-----|---------|---------|-| `GEMINI_API_KEY` | *(placeholder — set in the Dockerfile)* | agent |+| `GEMINI_API_KEY` | *(placeholder, set in the Dockerfile)* | agent || `GEMINI_MODEL` | `models/gemini-3.5-flash-lite` *(set in the Dockerfile)* | agent |The listen port (`7777`) is a constant at the top of `agent.py`.diff --git a/site/content/docs/use-cases/gemini-buddy.md b/site/content/docs/use-cases/gemini-buddy.mdindex b9a592dc..ca923485 100644--- a/site/content/docs/use-cases/gemini-buddy.md+++ b/site/content/docs/use-cases/gemini-buddy.md@@ -4,69 +4,71 @@ linkTitle: "Gemini Buddy"weight: 20----Hold a real multi-turn conversation with a *second* LLM exposed as an ordinary-mesh service — where your agent never resends the conversation, because the-service remembers its own side.+Hold a real multi-turn conversation with a second LLM exposed as an ordinary+mesh service. Your agent never resends the conversation, because the service+remembers its own side.Source: [`development/examples/gemini-buddy-mcp/`](https://github.com/google/sam/tree/main/development/examples/gemini-buddy-mcp).## The idea-Sometimes you want your agent to *talk to another model* — a second opinion, a-peer to argue a design with, a specialist that builds up its own context over-many turns. The naive way is to carry both conversations in the orchestrator:-your agent would have to store the other model's transcript and replay all of it-on every turn.--This use case shows you don't have to. A **buddy** is a plain MCP service backed-by the Gemini CLI that **owns its own conversation**. Your agent sends one-message per turn and gets one reply; the buddy keeps the running transcript-server-side, keyed by a `session_id`. It's built from nothing but an ordinary-`sam-node` MCP service — the conversational evolution of the one-shot-[`code-reviewer`](https://github.com/google/sam/tree/main/development/examples/code-reviewer-mcp)+Sometimes you want your agent to talk to another model: for a second+opinion, to discuss a design, or to use a specialist that builds up its own+context over many turns. The simple approach is to carry both conversations+in the orchestrator. Your agent would have to store the other model's+transcript and replay all of it on every turn.++This use case shows that you do not have to. A **buddy** is a plain MCP+service backed by the Gemini CLI that owns its own conversation. Your agent+sends one message per turn and gets one reply. The buddy keeps the running+transcript on the server side, keyed by a `session_id`. It is built from an+ordinary `sam-node` MCP service, and it is the conversational version of the+one-shot+[`code-reviewer`](https://github.com/google/sam/tree/main/development/examples/code-reviewer-pool/reviewer)example.## Two conversations, two places-The confusion this example clears up: talking to another LLM does *not* mean-maintaining two conversations from your side.+This example clears up one common confusion: talking to another LLM does not+mean maintaining two conversations from your side.-- **Your conversation** (you ↔ your agent) lives in your agent's context.+- **Your conversation** (you and your agent) lives in your agent's context.- **The buddy's conversation** lives inside the buddy service process.-When your agent calls the buddy's `chat` tool it sends **only the next message**,-never the history. The buddy appends it to that session's transcript, replays the-whole transcript *locally* to a one-shot `gemini -p` call, stores the reply, and-returns just that reply. The reply naturally becomes part of your agent's context-like any other tool result — so neither side ever double-maintains the other's-transcript.+When your agent calls the buddy's `chat` tool, it sends only the next+message, never the history. The buddy appends the message to that session's+transcript, replays the whole transcript locally to a one-shot `gemini -p`+call, stores the reply, and returns only that reply. The reply becomes part+of your agent's context like any other tool result, so neither side+maintains the other's transcript.-That makes the buddy service the **conversation owner** and the model a-swappable, stateless backend: the same service works for any CLI (`gemini`,-`claude`, `codex`, …) by changing one `spawn` line.+The buddy service therefore owns the conversation, and the model is a+stateless backend that can be swapped. The same service works for any CLI+(`gemini`, `claude`, `codex`) by changing one `spawn` line.## The pieces-- **`gemini-buddy` service** — a normal MCP service exposing two tools:- - `chat` — takes `{ message, session_id? }` (session defaults to `"default"`),- appends the message to that session's in-memory transcript, runs one- `gemini -p` turn with the transcript on stdin, and returns the buddy's reply.- - `reset` — takes `{ session_id? }` and wipes that session so the next `chat`- starts fresh.-- **Orchestrator** — any mesh MCP client (an agent harness or a custom program).- It discovers the buddy with `find_remote_tools(gemini-buddy)` and drives it with- `call_remote_tool(peer, chat, …)` — one message at a time.+- **`gemini-buddy` service**: a normal MCP service that exposes two tools.+ `chat` takes `{ message, session_id? }` (the session defaults to+ `"default"`), appends the message to that session's in-memory transcript,+ runs one `gemini -p` turn with the transcript on stdin, and returns the+ buddy's reply. `reset` takes `{ session_id? }` and clears that session, so+ the next `chat` starts fresh.+- **Orchestrator**: any mesh MCP client (an agent harness or a custom+ program). It discovers the buddy with `find_remote_tools` and drives it+ with `call_remote_tool`, one message at a time.## What you can do with it-- **Second opinion / peer** — bounce a design or a tricky bug off a different- model across several turns without babysitting its context.-- **Specialist that accumulates context** — let the buddy build up domain- knowledge over many messages (walk it through a subsystem, then keep asking)- that your own agent never has to reload.-- **A reusable pattern** — swap the Gemini CLI for any other model CLI; the- service structure (own the transcript, shell a stateless one-shot per turn) is- identical. `reset` gives you clean, isolated sessions on demand.+- **Second opinion.** Discuss a design or a difficult bug with a different+ model across several turns, without managing its context.+- **A specialist that accumulates context.** Let the buddy build up domain+ knowledge over many messages (walk it through a subsystem, then keep+ asking questions) that your own agent never has to reload.+- **A reusable pattern.** Swap the Gemini CLI for any other model CLI. The+ service structure is the same: own the transcript, and run a stateless+ one-shot call per turn. `reset` gives you clean, isolated sessions on+ demand.## Try it on kind@@ -75,9 +77,9 @@ brings the buddy up with one command.### 1. Set an LLM key for the buddy image-The buddy shells out to the Gemini CLI, so set your API key on the API-key `ENV`-line in `development/examples/gemini-buddy-mcp/Dockerfile` before building (a free-Google AI Studio key is fine for the demo).+The buddy runs the Gemini CLI, so set your API key on the API-key `ENV` line+in `development/examples/gemini-buddy-mcp/Dockerfile` before building. A+free Google AI Studio key is enough for the demo.### 2. Bring the mesh up and deploy the buddy@@ -94,26 +96,26 @@ helm --kube-context kind-sam-kind -n sam-kind install gemini-buddy charts/sam-no### 3. Start a local orchestrator node```bash-make kind-local-node # local sam-node enrolled in the mesh — LEAVE RUNNING+make kind-local-node # a local sam-node enrolled in the mesh; leave it running```-`kind-local-node` runs in the foreground in its own shell and exposes the mesh-MCP tools at **`http://127.0.0.1:9099/mcp`** (bearer token `devtoken`) — no-`kubectl port-forward` needed. This local node is your orchestrator's entry point-into the mesh.+`kind-local-node` runs in the foreground in its own shell and exposes the+mesh MCP tools at `http://127.0.0.1:9099/mcp` (token `devtoken`). No+`kubectl port-forward` is needed. This local node is the entry point into+the mesh for your orchestrator.### 4. Point your harness at the local node-Add the local node as an MCP server in whatever harness you drive the mesh from.-The specifics differ per harness (some use a JSON/TOML config file, others a UI),-but the settings are always the same:+Add the local node as an MCP server in the harness you use to drive the+mesh. The details differ per harness (some use a JSON or TOML config file,+others a UI), but the settings are always the same:- **Transport:** HTTP (Streamable HTTP / `http`)- **URL:** `http://127.0.0.1:9099/mcp`- **Header:** `X-Sam-Authentication: Bearer devtoken`-For example, harnesses that use the common `mcpServers` JSON config (Claude Code,-Cursor, and others) would add:+For example, harnesses that use the common `mcpServers` JSON config (Claude+Code, Cursor, and others) would add:```json{@@ -127,45 +129,46 @@ Cursor, and others) would add:}```-Consult your harness's MCP documentation for its exact config format. Once-connected, the mesh exposes `find_remote_tools` and `call_remote_tool` as tools-your agent (or program) can call.+Check the MCP documentation of your harness for its exact config format.+Once connected, the mesh exposes `find_remote_tools` and `call_remote_tool`+as tools that your agent (or program) can call.### 5. Have a conversation-Just tell your agent what you want — the mesh tool descriptions and the buddy's-own instructions steer it to discover the service and route each turn, so you-don't have to name any tools. A natural first prompt:+Tell your agent what you want. The mesh tool descriptions and the buddy's+own instructions guide it to discover the service and route each turn, so+you do not have to name any tools. A natural first prompt:> Find the `gemini-buddy` service in the mesh, then introduce yourself and tell it> I'm planning a trip to Kyoto in spring and that I'm slightly obsessed with ramen.-Then, in a *separate* message, prove the buddy remembers without you resending-anything:+Then, in a separate message, check that the buddy remembers without you+resending anything:-> Ask the buddy where I'm headed and what food I'm into. Don't remind it — just ask.+> Ask the buddy where I'm headed and what food I'm into. Don't remind it, just ask.-The buddy answers correctly even though your agent never re-sent the first turn:-the transcript lives in the service, not in your context. Finally, wipe it:+The buddy answers correctly even though your agent never sent the first turn+again. The transcript lives in the service and not in your context. Finally,+clear it:> Reset the conversation with the buddy, then ask it where I'm going again.-After the reset it no longer knows — the service dropped that session's-transcript.+After the reset it no longer knows, because the service dropped that+session's transcript.-Once you've got the hang of it, hand the whole loop to your agent and have fun-watching two models converse:+Once you are comfortable with it, hand the whole loop to your agent and+watch two models converse:-> Find the `gemini-buddy` service on the SAM mesh, reset its session, then have a-> 10-turn conversation with it — one question per turn, each building on its last+> Find the `gemini-buddy` service on the mesh, reset its session, then have a+> 10-turn conversation with it, one question per turn, each building on its last> answer, and show me every question-and-answer pair as you go.## Configuration| var | default | used by ||-----|---------|---------|-| `GEMINI_API_KEY` | *(placeholder — set in the Dockerfile)* | buddy |+| `GEMINI_API_KEY` | *(placeholder, set in the Dockerfile)* | buddy || `GEMINI_CLI_TRUST_WORKSPACE` | `true` | buddy |-The listen port (`7780`) and model (`gemini-3.1-flash-lite`) are constants at the-top of `buddy_server.mjs`; change them there if needed.+The listen port (`7780`) and model (`gemini-3.1-flash-lite`) are constants at+the top of `buddy_server.mjs`. Change them there if needed.diff --git a/site/content/docs/use-cases/warm-agent-pool.md b/site/content/docs/use-cases/warm-agent-pool.mdindex 38102ec9..dcba6abb 100644--- a/site/content/docs/use-cases/warm-agent-pool.md+++ b/site/content/docs/use-cases/warm-agent-pool.md@@ -4,8 +4,9 @@ linkTitle: "Warm Agent Pool"weight: 10----Fan a batch of work across a pool of identical, already-running worker agents —-built entirely from ordinary mesh MCP services, no gossip and no node changes.+Spread a batch of work across a pool of identical, already-running worker+agents. The pool is built from ordinary mesh MCP services, with no gossip and+no changes to the node.<video autoplay loop muted playsinline controls style="width: 100%; border-radius: 8px;"><source src="../../../demo-warm-agent-pool.mp4" type="video/mp4">@@ -15,85 +16,91 @@ Source: [`development/examples/code-reviewer-pool/`](https://github.com/google/s## The idea-Some agent tools are expensive to stand up but cheap to reuse — a reviewer that-shells out to an LLM, a sandbox that boots a runtime, a service holding a warm-model in memory. You don't want to spawn one per request, and you don't want a-single instance serialising all your work. What you want is a **pool of-identical, already-running workers** and something that hands them out one job at-a time.+Some agent tools are expensive to start but cheap to reuse: a reviewer that+calls an LLM, a sandbox that boots a runtime, a service that holds a warm+model in memory. You do not want to start one per request, and you do not+want a single instance that handles all your work one job at a time. What+you want is a pool of identical, already-running workers, and something that+hands them out one job at a time.-This use case builds exactly that on the mesh, using **nothing but ordinary MCP-services**. The worked example is a *code reviewer*: several identical reviewer-workers, a manager that leases them, and an orchestrator that fans a batch of-files across the pool in parallel.+This use case builds that on the mesh, using only ordinary MCP services. The+worked example is a code reviewer: several identical reviewer workers, a+manager that leases them, and an orchestrator that spreads a batch of files+across the pool in parallel.## The pieces-- **Workers** — plain `code-reviewer` MCP services. Each exposes a single- `review_code` tool that pipes the snippet to an LLM and returns comments- grouped by severity. They're stateless and interchangeable; the pool's job is- to keep them busy.-- **Manager** — a normal MCP service exposing `acquire_worker` /- `release_worker` / `list_workers`. It's also a *northbound MCP client of its- own node*: every few seconds it calls `find_remote_tools(code-reviewer)` to- learn which worker peers exist (via the DHT), and it tracks which of them are- free or busy using **leases**.-- **Orchestrator** — any mesh MCP client (an agent harness or a custom program).- The loop per file is: `acquire_worker` → `call_remote_tool(peer, review_code)`- → `release_worker`. Run those chains concurrently and each acquire hands back a- *different* free worker, so parallel dispatch never collides.--## Why there's no readiness broadcast--A classic worker pool needs to know two things: *who exists* and *who's busy*.-The manager gets the first from **DHT discovery** and the second from **its own-leases** — the exact two facts a gossip/readiness broadcast would otherwise-provide. So the whole thing runs on discovery + leasing, no pub/sub. The-tradeoff: leasing is authoritative only while the manager is the *sole*-dispatcher — perfect for a single-manager pool, and the point at which you'd-reach for real coordination if you needed multiple managers.+- **Workers**: plain `code-reviewer` MCP services. Each exposes a single+ `review_code` tool that sends the snippet to an LLM and returns comments+ grouped by severity. They are stateless and interchangeable. The pool's job+ is to keep them busy.+- **Manager**: a normal MCP service that exposes `acquire_worker`,+ `release_worker` and `list_workers`. It is also an MCP client of its own+ node. Every few seconds it calls `find_remote_tools` to learn which worker+ peers exist (through the DHT), and it tracks which of them are free or busy+ with leases.+- **Orchestrator**: any mesh MCP client (an agent harness or a custom+ program). The loop per file is `acquire_worker`, then+ `call_remote_tool(peer, review_code)`, then `release_worker`. Run those+ chains concurrently and each acquire returns a different free worker, so+ parallel dispatch never collides.++## Why there is no readiness broadcast++A classic worker pool needs to know two things: who exists and who is busy.+The manager gets the first from DHT discovery and the second from its own+leases. These are exactly the two facts that a readiness broadcast would+otherwise provide. So the whole pool runs on discovery and leasing, without+pub/sub. The trade-off is that leasing is authoritative only while the+manager is the only dispatcher. That fits a single-manager pool. If you+needed several managers, that is the point where you would need real+coordination.## What makes it correct under concurrency-The interesting part is that "hand out a warm worker, one job at a time" stays-true even when acquires race and workers come and go:--- **No double-lease** — the manager is single-threaded and `leaseFree()` is fully- synchronous (no `await` between picking a worker and marking it busy), so two- concurrent `acquire_worker` calls can never be handed the same peer.-- **Grace eviction** — discovery never drops a *leased* worker on a transient- miss, and only drops a *free* one after `SAM_GRACE_MISSES` consecutive misses.- A slow, busy worker won't get evicted and re-handed-out mid-review.-- **Fencing tokens** — `acquire_worker` returns a `lease_id`; `release_worker`- only clears the lease if that id still matches, so a late release from an- expired lease can't free a *newer* holder's worker.-- **Single-flight backstop** — even if a lease race ever slipped through, the- worker itself returns `POOL_BUSY` for a second concurrent `review_code`, so the- one-at-a-time invariant holds at the source.--## Lease enforcement (workers trust the manager, not the caller)--Workers don't hand out reviews to anyone who can reach them. On `acquire_worker`-the manager **mints a short-lived HMAC token** bound to that worker and lease-expiry; the orchestrator forwards it in the `review_code` arguments, and the-worker **verifies it offline** (shared secret, no call back to the manager). Any-`review_code` without a valid, unexpired token gets `NO_LEASE`. Both sides-default to a hardcoded dev secret (`sam-dev-pool-secret`) so it enforces out of-the box; set a matching `SAM_POOL_SECRET` on the manager and every worker to-override it. Mismatched or one-sided secrets **fail closed** — every call returns+"Hand out a warm worker, one job at a time" stays true even when acquires+race and workers come and go:++- **No double lease.** The manager is single-threaded and `leaseFree()` is+ fully synchronous (there is no `await` between picking a worker and marking+ it busy), so two concurrent `acquire_worker` calls can never receive the+ same peer.+- **Grace eviction.** Discovery never drops a leased worker on a transient+ miss, and it drops a free one only after `SAM_GRACE_MISSES` consecutive+ misses. A slow, busy worker is not evicted and handed out again in the+ middle of a review.+- **Fencing tokens.** `acquire_worker` returns a `lease_id`. `release_worker`+ clears the lease only if that id still matches, so a late release from an+ expired lease cannot free a worker that belongs to a newer holder.+- **Single-flight guard.** Even if a lease race got through, the worker+ itself returns `POOL_BUSY` for a second concurrent `review_code`, so the+ one-at-a-time rule holds at the source.++## Lease enforcement++Workers trust the manager and not the caller. On `acquire_worker` the+manager creates a short-lived HMAC token bound to that worker and to the+lease expiry. The orchestrator forwards the token in the `review_code`+arguments, and the worker verifies it offline (shared secret, no call back to+the manager). Any `review_code` without a valid, unexpired token gets+`NO_LEASE`. Both sides default to a hardcoded development secret+(`sam-dev-pool-secret`), so enforcement works out of the box. Set a matching+`SAM_POOL_SECRET` on the manager and on every worker to override it.+Mismatched or one-sided secrets fail closed, and every call returns`NO_LEASE`.## What you can do with it-- **Parallel batch work** — fan a directory of files (or tasks) across N warm- workers and collect results as they land, bounded by pool size rather than- serialised.-- **Elastic capacity** — scale a worker deployment up or down mid-job; the- manager picks a new worker up on its next discovery pass and starts leasing it,- and drains one that disappears without corrupting in-flight leases.-- **A reusable pattern** — swap `code-reviewer` for any expensive-to-warm tool- (test runner, sandbox, embedder, browser). The manager is generic; it pools- whatever `SAM_POOL_SERVICE` names.+- **Parallel batch work.** Spread a directory of files (or tasks) across N+ warm workers and collect results as they arrive. The limit is the pool+ size, and the work is not serialised.+- **Elastic capacity.** Scale a worker deployment up or down in the middle of+ a job. The manager picks up a new worker on its next discovery pass and+ starts leasing it, and it drains a worker that disappears without+ corrupting in-flight leases.+- **A reusable pattern.** Swap `code-reviewer` for any tool that is expensive+ to warm up (test runner, sandbox, embedder, browser). The manager is+ generic. It pools whatever `SAM_POOL_SERVICE` names.## Try it on kind@@ -102,9 +109,9 @@ brings up the whole pool with one command.### 1. Set an LLM key for the reviewer image-The reviewer workers shell out to an LLM, so set your API key on the API-key-`ENV` line in `development/examples/code-reviewer-pool/reviewer/Dockerfile`-before building (a free key is fine for the demo).+The reviewer workers call an LLM, so set your API key on the API-key `ENV`+line in `development/examples/code-reviewer-pool/reviewer/Dockerfile` before+building. A free key is enough for the demo.### 2. Bring the mesh up and deploy the pool@@ -113,9 +120,9 @@ make build # builds ./bin/sam-node (once)make kind-up # control plane + router (no sam-nodes yet)```-Then build the two images and deploy the pool as `charts/sam-node` releases —-three reviewer replicas (each replica enrolls as its own mesh node, so the-pool is three same-named `code-reviewer` services) and one manager:+Then build the two images and deploy the pool as `charts/sam-node` releases:+three reviewer replicas and one manager. Each replica enrolls as its own+mesh node, so the pool is three `code-reviewer` services with the same name.```bashdocker build -t reviewer:local development/examples/code-reviewer-pool/reviewer@@ -133,19 +140,19 @@ helm --kube-context kind-sam-kind -n sam-kind install manager charts/sam-node \### 3. Start a local orchestrator node```bash-make kind-local-node # local sam-node enrolled in the mesh — LEAVE RUNNING+make kind-local-node # a local sam-node enrolled in the mesh; leave it running```-`kind-local-node` runs in the foreground in its own shell and exposes the mesh-MCP tools at **`http://127.0.0.1:9099/mcp`** (bearer token `devtoken`) — no-`kubectl port-forward` needed. This local node is your orchestrator's entry-point into the mesh.+`kind-local-node` runs in the foreground in its own shell and exposes the+mesh MCP tools at `http://127.0.0.1:9099/mcp` (token `devtoken`). No+`kubectl port-forward` is needed. This local node is the entry point into+the mesh for your orchestrator.### 4. Point your harness at the local node-Add the local node as an MCP server in whatever harness you drive the mesh from.-The specifics differ per harness (some use a JSON/TOML config file, others a UI),-but the settings are always the same:+Add the local node as an MCP server in the harness you use to drive the+mesh. The details differ per harness (some use a JSON or TOML config file,+others a UI), but the settings are always the same:- **Transport:** HTTP (Streamable HTTP / `http`)- **URL:** `http://127.0.0.1:9099/mcp`@@ -166,20 +173,20 @@ Cursor, and others) would add:}```-Consult your harness's MCP documentation for its exact config format. Once-connected, the mesh exposes `acquire_worker`, `release_worker`, `list_workers`,-`find_remote_tools`, and `call_remote_tool` as tools your agent (or program) can-call.+Check the MCP documentation of your harness for its exact config format.+Once connected, the mesh exposes `acquire_worker`, `release_worker`,+`list_workers`, `find_remote_tools` and `call_remote_tool` as tools that your+agent (or program) can call.### 5. Drive the pool-Have your orchestrator run, per file, in parallel:+Have your orchestrator run these steps per file, in parallel:-1. `acquire_worker` → returns `{peer_id, tool, lease_id, token}`.-2. `call_remote_tool(peer_id, review_code, {code, token})` — forward the `token`- in the tool arguments (the pool requires it).-3. `release_worker(peer_id, lease_id)` — pass the `lease_id` back so a stale- release can't free a newer holder.+1. `acquire_worker` returns `{peer_id, tool, lease_id, token}`.+2. `call_remote_tool(peer_id, review_code, {code, token})`. Forward the+ `token` in the tool arguments, because the pool requires it.+3. `release_worker(peer_id, lease_id)`. Pass the `lease_id` back, so that a+ stale release cannot free a worker that belongs to a newer holder.A natural prompt for an agent harness:@@ -188,13 +195,14 @@ A natural prompt for an agent harness:> `review_code` with the file contents (forwarding the token), and release it> (pass the `lease_id` back). Run them in parallel.-You'll watch the reviews come back concurrently, bounded by the number of workers-in the pool.+The reviews come back concurrently, limited by the number of workers in the+pool.-### 6. Elasticity beat (add a worker mid-job)+### 6. Elasticity (add a worker in the middle of a job)-Scale the reviewer pool down, start a larger job, then scale it back up — the-manager picks the new worker up on its next discovery pass and starts leasing it:+Scale the reviewer pool down, start a larger job, then scale it back up. The+manager picks up the new worker on its next discovery pass and starts+leasing it:```bashkubectl --context kind-sam-kind -n sam-kind scale deploy/reviewers-sam-node --replicas=2diff --git a/site/content/docs/user/_index.md b/site/content/docs/user/_index.mddeleted file mode 100644index f377a849..00000000--- a/site/content/docs/user/_index.md+++ /dev/null@@ -1,27 +0,0 @@-----title: "User and Operator Guides"-linkTitle: "User Guides"-weight: 3------Welcome to the User & Operator Guides. This section provides detailed documentation on how to configure, run, and manage Sovereign Agent Mesh (SAM) clusters, control planes, and node configurations.--### In This Section--1. **[Control Plane Configuration](control-plane-configuration/)**- Learn how to configure the OIDC identity bridge, set up cryptographic private keys, enforce TLS/mTLS, and write custom security role policy mappings.--2. **[Agent Usage & Connectivity](agent-usage/)**- Understand how nodes connect to the mesh via OIDC login, secure credentials, run local Model Context Protocol (MCP) servers, and expose secure remote tool access to agents (like Google Gemini and Claude).--3. **[Node Configuration](node-configuration/)**- Learn how to configure the local node, set up binding addresses, and manage local storage.--4. **[Production Kubernetes Deployment](kubernetes-deployment/)**- Deploy a production-grade mesh cluster in Kubernetes, including Dex OIDC setups, StatefulSet P2P routers, DNS A-record synchronizers, and Workload Identity ServiceAccount token projections.--5. **[SAM Connect](mobile-app/)**- Turn your mobile device into a SAM node, exposing sensors and telemetry securely to the mesh, and integrating with native OS assistants.--6. **[A Mesh in 30 Seconds](device-enrollment/)**- Run `sam-one` on a laptop, scan the QR code with SAM Connect, and call a sensor on the phone from the laptop through the mesh. Two devices behind NAT, no server, domain or identity provider to set up first.diff --git a/site/content/docs/user/agent-usage.md b/site/content/docs/user/agent-usage.mddeleted file mode 100644index 87e5ce6c..00000000--- a/site/content/docs/user/agent-usage.md+++ /dev/null@@ -1,153 +0,0 @@-----title: "Agent Usage & Connectivity Guide"-linkTitle: "Agent Usage"-weight: 20------SAM nodes (`sam-node`) act as local security gateways and tool proxies for your AI agents (such as Google Gemini, Claude Code, or Claude Desktop). This document explains how to authenticate a node to the mesh and configure your agents to use it.-------## 1. Node Lifecycle Overview--Connecting your AI agent to the Sovereign Agent Mesh involves two phases:-```mermaid-sequenceDiagram- actor User as Developer/Operator- participant Node as sam-node (Local)- participant ControlPlane as sam-control-plane (Mesh)- participant Agent as AI Agent (Gemini/Claude)-- Note over User,ControlPlane: Phase 1: Mesh Join (OIDC Authorization)- User->>Node: sam-node join <control-plane-url>- Node->>ControlPlane: Get OIDC Info- ControlPlane-->>Node: OIDC Issuer, Client ID- Node->>User: Display Login URL & Code- User->>User: Login in Browser- Node->>ControlPlane: Exchange Code for Biscuit Identity- Node->>Node: Persist Biscuit in Local Store (agent.db)-- Note over User,Agent: Phase 2: Agent Tool Invocation- User->>Node: sam-node run (SAM_API_TOKEN="secret-key")- Node->>Node: Start local MCP server on 127.0.0.1:8080- Agent->>Node: Connect to local MCP (X-Sam-Authentication: Bearer "secret-key")- Agent->>Node: Call Remote P2P Tool- Node->>ControlPlane: Verify Biscuit / Allowed Policies- Node-->>Agent: Execute tool and return result-```-------## 2. Phase 1: Joining the Mesh (`sam-node join`)--Before starting the node daemon, you must authorize your node and obtain a cryptographic Biscuit identity.--### Standard Login-Run the `join` command, pointing to the mesh control plane:-```bash-sam-node join https://bananas.sam-mesh.dev-```--* **Browser Flow**: The CLI will discover the OIDC credentials from the control plane, print an OIDC authorization URL, and attempt to open your system's default web browser automatically.-* **Approval**: Log in with your corporate or identity credentials (e.g. Google Accounts), approve the authorization request, and return to the terminal. The node will automatically exchange the credentials for a Biscuit token and save it to `~/.config/sam-mesh/agent.db`.--### Headless (Server) Login-If you are running the node on a remote server via SSH (without a web browser), force headless out-of-band mode:-```bash-sam-node join https://bananas.sam-mesh.dev --headless-```-When the OIDC provider supports device authorization, SAM automatically uses device flow (no pasted callback code required): it prints a verification URL/code and polls until approval. If device authorization is unavailable, SAM falls back to OOB code-paste flow.--### Choosing the Auth Flow Explicitly-By default (`--auth-mode auto`) SAM picks the flow for you: device flow in headless environments when available, the loopback browser flow otherwise (with an automatic device fallback if the browser can't be opened). For deterministic automation (e.g. CI/CUJ harnesses), force a specific flow instead of relying on environment detection:-```bash-# Force RFC 8628 device flow (no code to paste back)-sam-node join https://bananas.sam-mesh.dev --auth-mode device-```-Supported values: `auto` (default), `device`, `oob`, `browser`. `--auth-mode device` fails fast if the provider does not advertise a `device_authorization_endpoint`.--### Automatic Token Renewal-To allow long-lived nodes to automatically renew their tokens in the background, request offline access (refreshes the OIDC session):-```bash-sam-node join https://bananas.sam-mesh.dev --offline-access-```-------## 3. Phase 2: Running the Node daemon (`sam-node run`)--Once authorized, you start the node gateway. The gateway spins up a local Model Context Protocol (MCP) server.--Run the node daemon, securing the local API endpoint with a custom token:-```bash-SAM_API_TOKEN="my-agent-super-token-123" sam-node run --bind-addr "127.0.0.1:8080"-```--### Key CLI Parameters-* `--bind-addr`: The local TCP address where the node's local HTTP server runs (default: `127.0.0.1:8080`). Pass an empty value to serve only on the Unix socket.-* `--socket-path`: Unix socket serving the same API (default: `<data-dir>/sam.sock`). Pass an empty value to disable it.-* API token (`SAM_API_TOKEN` env or `--api-token-path` file): a security token required by any local AI agent attempting to connect to your node over TCP.-* `--data-dir`: Custom path to store configurations and Biscuit tokens (defaults to `~/.config/sam-mesh` or env `SAM_DATA_DIR`).-------## 4. Connecting your AI Agents--Your AI agent connects to the node's local MCP server. The local server translates standard MCP queries (like `listTools` or `callTool`) into secure P2P mesh commands.--### Exposing the API-The local MCP endpoint is served over **Streamable HTTP** at:-`http://127.0.0.1:8080/mcp`--The node serves the very same API on a Unix socket, `<data-dir>/sam.sock`-(usually `~/.config/sam-mesh/sam.sock`). Reaching that socket already proves-the caller is the user who owns it — the same bar as reading the token file —-so requests over it need no token, exactly like `docker.sock`:--```bash-curl --unix-socket ~/.config/sam-mesh/sam.sock \- http://localhost/v1/chat/completions \- -H 'Content-Type: application/json' \- -d '{"model": "mistralai/mistral-7b-instruct", "messages": [{"role": "user", "content": "Write a haiku about a decentralized mesh network."}]}'-```--(`http://localhost` is a placeholder host that clients ignore once they dial a-socket.) The socket is created with `0600` permissions inside the `0700` data-directory, and removed when the node stops.--Most MCP clients speak only stdio or HTTP, so the TCP listener stays on by-default and the socket is an addition rather than a replacement. Use-`--socket-path ""` to run without it, or `--bind-addr ""` to drop the TCP port-and serve the API exclusively over the socket, which leaves the node with no-listening port and no shared secret to manage.--### Authentication-When configuring your agent client, you must pass the API token in a SAM-specific-header — not the standard `Authorization` header:-```http-X-Sam-Authentication: Bearer my-agent-super-token-123-```-This leaves `Authorization` free to always mean the credential for whatever-remote service you're calling *through* the node (e.g. a `mcp://` or-`inference://` service that requires its own upstream credential) — it passes-straight through untouched and is never used to authenticate to the node itself.--> For MCP clients that only support a plain `Authorization` header, the `/mcp`-> endpoint (and the `/sam/service/*` control endpoints) also accept it as a-> compatibility alias, since they never forward it anywhere. The egress/inference-> proxy (`/sam/<peer>/...`) does **not** accept this fallback — there,-> `Authorization` is reserved exclusively for the destination's own credential.--### OpenAI Facade & Inference Connectivity--SAM nodes expose two ways for AI clients and OpenAI SDKs to interact with `type: inference` services across the mesh:--1. **OpenAI Facade Interface (Recommended)**: Point standard OpenAI SDKs to `base_url="http://127.0.0.1:8080/v1"`. The facade aggregates available mesh models on `/v1/models` and handles seamless load balancing and failover for `/v1/chat/completions`.-2. **Raw Egress Proxy Interface**: Power-users who want to explicitly route to a specific peer's inference backend use `/sam/{peer}/inference/{service}`. When targeting an OpenAI-compatible service via raw proxy, ensure `base_url` includes the explicit `/v1` namespace suffix (e.g. `http://127.0.0.1:8080/sam/{peer}/inference/{service}/v1`).--### Specific Integration Guides-Explore our step-by-step guides for integrating your node with popular agent clients:-* 🚀 **[Google Gemini AI Agent](../integrations/gemini.md)**: Connect using Python scripts and the google-genai SDK.-* 💻 **[Claude Desktop](../integrations/claude-desktop.md)**: Expose P2P tools directly to your Claude Desktop application menu.-* 🤖 **[Claude Code](../integrations/claude-code.md)**: Add your local node tools directly to the Claude CLI.-* 🔌 **[OpenClaw](../integrations/openclaw.md)**: Setup remote tool bridges for OpenClaw clusters.diff --git a/site/content/docs/user/cloud-run-deployment.md b/site/content/docs/user/cloud-run-deployment.mddeleted file mode 100644index 0e625e00..00000000--- a/site/content/docs/user/cloud-run-deployment.md+++ /dev/null@@ -1,207 +0,0 @@-----title: "Cloud Run Deployment"-linkTitle: "Cloud Run Deployment"-weight: 6------# Deploying a SAM Mesh on Cloud Run--`sam-one` is the all-in-one SAM distribution: control plane, libp2p router,-web console and storage in a single binary serving a single public port.-Because everything — REST API, console and mesh (WebSocket) traffic — is-multiplexed on one HTTP port, it runs on Cloud Run and any platform that-forwards HTTP/WebSockets to a container.--This guide was validated end to end on Cloud Run: node enrollment over-`wss`, a relayed service call between two NAT-hidden nodes through the-Cloud Run router, and the admin CLI against the public URL.--## 1. Build and push the image--```bash-# Pick your project/region and an Artifact Registry docker repository.-PROJECT=my-project-REGION=us-central1-IMG=${REGION}-docker.pkg.dev/${PROJECT}/sam-mesh/sam-one:latest--docker build -f Dockerfile.sam-one -t "$IMG" .-gcloud auth configure-docker ${REGION}-docker.pkg.dev-docker push "$IMG"-```--## 2. Deploy the service--Cloud Run has no persistent disk, so pass fixed join/admin tokens as-environment variables — otherwise fresh ones are generated on every-instance start:--```bash-JOIN_TOKEN="sam_tok_$(openssl rand -hex 16)"-ADMIN_TOKEN="sam_adm_$(openssl rand -hex 16)"--gcloud run deploy sam-one \- --project "$PROJECT" --region "$REGION" \- --image "$IMG" \- --allow-unauthenticated \- --min-instances 1 --max-instances 1 \- --port 8080 \- --no-cpu-throttling \- --timeout 3600 \- --set-env-vars "SAM_TOKEN=${JOIN_TOKEN},SAM_ADMIN_TOKEN=${ADMIN_TOKEN}"-```--Flag notes, all load-bearing:--* **`--min-instances 1 --max-instances 1`** — standalone mode is a- singleton: the router's DHT and relay state live in the one process.-* **`--no-cpu-throttling`** — the router runs background loops (leases,- key sync, DHT); request-based CPU throttling stalls them between- requests.-* **`--timeout 3600`** — Cloud Run caps streaming requests; WebSocket mesh- connections live inside that budget. Nodes reconnect automatically when- the cap severs a connection, but a low timeout means needless churn.-* **`--port 8080`** matches the image's default `--port 8080` argument- (see the `CMD` in `Dockerfile.sam-one`).--Then tell the router its public URL so it advertises a dialable `wss`-multiaddr (the URL is only known after the first deploy):--```bash-URL=$(gcloud run services describe sam-one --project "$PROJECT" \- --region "$REGION" --format='value(status.url)')--gcloud run services update sam-one \- --project "$PROJECT" --region "$REGION" \- --update-env-vars "SAM_EXTERNAL_URL=${URL}"-```--## 3. Verify--```bash-curl -s "$URL/readyz" # 200-curl -s "$URL/info" | head -c 200 # advertises /dns4/<host>/tcp/443/wss/p2p/<peer-id>-```--The web console is served from the same URL at `${URL}/console`.--> [!NOTE]-> `/healthz` returns a Google frontend 404 on `run.app` domains — the-> path is reserved by the platform and never reaches the container. Use-> `/readyz` for probes.--## 4. Join nodes from anywhere--```bash-sam-node run --control-plane "$URL" --bootstrap-token "$JOIN_TOKEN"-```--The node enrolls over HTTPS, discovers the router's `wss` multiaddr from-`/info`, and connects through the same public port. Nodes behind NAT are-reachable by other nodes via relay circuits through the Cloud Run router —-no inbound connectivity required on either side.--## 5. Example: share a service across the mesh--This walkthrough was run verbatim against a Cloud Run deployment: two-nodes on different networks, neither reachable from the other-(`--announce-private=false` withholds their private addresses, forcing all-traffic through the Cloud Run relay).--On the **provider** machine, start any local HTTP backend, declare it in a-node config file, and run a node with that config. Services only exist by-declaration at startup — there is no runtime registration endpoint — so-the backend comes up first and the node probes it before advertising:--```bash-mkdir -p /tmp/www && echo "hello from provider" > /tmp/www/hello.txt-python3 -m http.server 9000 --bind 127.0.0.1 --directory /tmp/www &--cat > ~/provider-services.yaml <<'EOF'-version: "v1alpha1"-services:- - type: "mcp"- name: "hello"- description: "example"- target_url: "http://127.0.0.1:9000"-EOF--sam-node run --control-plane "$URL" --bootstrap-token "$JOIN_TOKEN" \- --data-dir ~/provider --announce-private=false \- --config ~/provider-services.yaml &-```--Note the node's PeerID from its startup output.--On the **consumer** machine, run a node the same way, then call the-service by peer and name through the local egress proxy:--```bash-sam-node run --control-plane "$URL" --bootstrap-token "$JOIN_TOKEN" \- --data-dir ~/consumer --announce-private=false &--curl --unix-socket ~/consumer/sam.sock \- "http://localhost/sam/<provider-peer-id>/mcp/hello/hello.txt"-# -> hello from provider-```--The request crosses consumer → Cloud Run router (relay circuit) →-provider → backend, with mutual Biscuit authentication between the nodes-and policy enforced on the service name. Allow a few seconds after the-provider starts for propagation on first call.--## 6. Operate with the CLI--The `sam-one` binary doubles as an admin client for the running service.-It reads the admin credential from `SAM_ADMIN_TOKEN` or a file named by-`--admin-token-path`, never from a flag value:--```bash-export SAM_ADMIN_TOKEN="$ADMIN_TOKEN"--# Mint a scoped, single-use enrollment token-sam-one token create --server "$URL" --role sam:role:node --max-usages 1--# Same, rendered as a QR code for the SAM mobile app (add --max-usages N for a room)-sam-one token qr --server "$URL"--# List tokens with their usage and status; revoke one by id prefix-sam-one token list --server "$URL"-sam-one token revoke <token-id> --server "$URL"--# Ban a peer from the mesh-sam-one admin ban --server "$URL" <peer-id>-```--## Operational notes--* **State is ephemeral.** The SQLite database lives in the container's- in-memory filesystem: enrolled nodes and minted tokens are lost on- instance restart, and the router's peer identity rotates (nodes- re-discover it via `/info` and re-enroll with the join token). Keep- `SAM_TOKEN`/`SAM_ADMIN_TOKEN` pinned via env vars. For durable state,- run `sam-one` on a VM with a disk, or point `--db-driver postgres` at a- managed database.-* **Rollouts briefly overlap revisions.** During a deploy, `/info` may- advertise the new instance while some WebSocket upgrades still land on- the draining one; nodes refuse the peer-ID mismatch and retry. Joins- succeed once the old revision drains.-* **Proxied traffic shares source IPs.** All traffic reaches the- container from a handful of frontend proxy IPs. `sam-one` already- raises libp2p's per-source-IP connection and rate budgets for this- (`ConnsPerSourceIP`); if you front a discrete `sam-router` with a proxy- yourself, set `--conns-per-source-ip` accordingly.--## Anywhere else--The same single-port binary runs on any host without flags:--```bash-sam-one --data-dir /var/lib/sam-one-```--A free port is picked and published in the startup banner together with-the generated tokens; pass `--port 8080` (and optionally-`--bind-address`) for a fixed one, and `--external-url https://mesh.example.com`-when fronted by a reverse proxy or DNS name. On a laptop behind NAT,-`--tunnel cloudflare` publishes the port on a temporary public https URL-instead; see [A Mesh in 30 Seconds](../device-enrollment/).diff --git a/site/content/docs/user/control-plane-configuration.md b/site/content/docs/user/control-plane-configuration.mddeleted file mode 100644index 551d9aac..00000000--- a/site/content/docs/user/control-plane-configuration.md+++ /dev/null@@ -1,333 +0,0 @@-----title: "Control Plane & Router Configuration Guide"-linkTitle: "Control Plane & Router Configuration"-weight: 10------The SAM architecture separates the OIDC capabilities control plane (`sam-control-plane`) from the GossipSub network routers (`sam-router`).-------## 1. SAM Control Plane (`sam-control-plane`)--The Control Plane is responsible for bridging user identities from trusted OIDC providers, issuing cryptographically signed Biscuit authorization tokens, and distributing network/tool policies to routers and nodes.--### Command-Line Arguments & Environment Variables--| CLI Flag | Environment Variable | Default Value | Description |-| :--- | :--- | :--- | :--- |-| `--issuer` | `SAM_OIDC_ISSUER` | *None* (Required) | Comma-separated list of trusted OIDC Provider URLs. |-| `--bind-address` | *None* | `0.0.0.0:8080` | Host and port to listen on for HTTP web API service. |-| `--db-driver` | *None* | `sqlite` | Database driver (`sqlite` or `postgres`). |-| `--db-dsn` | *None* | `control-plane.db` | Database DSN/Connection URL (e.g. `postgres://user:pass@host:5432/db`). |-| `--allowed-audiences` | *None* | `sam-mesh-audience` | Comma-separated list of allowed JWT audiences. |-| `--admin-token-path` (or env `SAM_ADMIN_TOKEN`) | *None* | *None* | File containing the secret token required in the HTTP Header `Authorization: Bearer <token>` for admin operations. |-| `--insecure-skip-tls-verify` | *None* | `false` | Set to `true` to skip certificate validation for development/testing OIDC providers. |-| `--biscuit-ttl` | *None* | `24h` | Lifespan minted into every issued Biscuit token. Capped to the OIDC token's own expiry when shorter. |-| `--oidc-session-ttl` | *None* | `2160h` (90 days) | How long an OIDC enrollment stays refreshable before the identity must re-authenticate with the OIDC provider. Shorter values keep the provider authoritative for offboarding, at the cost of more frequent interactive re-enrollment. |-| `--key-rotation-interval` | *None* | `24h` | Key rotation interval (e.g. `24h`). `0s` disables rotation. |-| `--key-grace-period` | *None* | `1h` | How long a rotated-out signing key stays accepted. Once it is retired, Biscuits it signed can no longer be verified or refreshed; see [Signing-Key Retirement and Recovery](#signing-key-retirement-and-recovery). |-| `--lease-duration` | *None* | `15m` | Router lease registration TTL. |-| `--node-retention` | *None* | `720h` (30 days) | How long an enrolled node's record is kept after its session expired before it is deleted. Every restart without a persistent data directory enrolls a fresh identity, so without this the node table only grows. Banned nodes are always kept. `0s` keeps every record forever. |--The Control Plane serves Prometheus metrics on `/metrics` alongside the API: mesh size (`sam_control_plane_mesh_connected_peers`, `sam_control_plane_routers_active`, `sam_control_plane_enrolled_nodes{role,state}`), per-route request counts and latencies, and the Go runtime.-------## 2. SAM Router (`sam-router`)--The Router is a dedicated GossipSub helper that maintains stable network addresses (multiaddrs) and relays mesh overlays for discovery.--### Command-Line Arguments & Environment Variables--| CLI Flag | Default Value | Description |-| :--- | :--- | :--- |-| `--control-plane` | `http://127.0.0.1:8080` | Control Plane web service URL. Plaintext `http://` is accepted only for a loopback host. |-| `--insecure-control-plane` | `false` | Accept a plaintext `http://` control-plane URL to a non-loopback host (e.g. an in-cluster Service). Whoever answers that URL becomes the router's trust root, so leave this off outside a network you already trust. The same flag exists on `sam-node`. |-| `--listen` | `/ip4/0.0.0.0/tcp/5001`, `/ip6/::/tcp/5001` | Comma-separated libp2p multiaddrs to listen on. |-| `--external-addr` | *None* | External multiaddrs to announce to control plane. |-| `--keys-path` | `router.key` | Path to save/load persistent private key (determines Peer ID). |-| `--jwt-path` | *None* | Path to file containing OIDC JWT token for enrollment. |-| `--oidc-token` | *None* | Direct OIDC ID token or bootstrap secret token for enrollment. |-| `--keys-sync-interval` | `5m` | Key synchronization polling interval. `GET /keys` returns the valid key set signed by every key in it; the router (and nodes, at start-up) accept the set only if one of those signatures verifies under a key they already trust, so the first key always comes from enrollment and a rotation is learned from the retiring key. |-| `--lease-renew-interval` | `300s` | Lease renewal registration interval. |-| `--allow-loopback` | `false` | Allow loopback and link-local addresses for discovery (development only). |-| `--metrics-addr` | *None* | Serve Prometheus `/metrics`, `/healthz` and `/readyz` on this plain HTTP address (e.g. `0.0.0.0:9090`). Off by default: nothing on it is authenticated, so keep it off the libp2p ports and inside the cluster. `/readyz` turns `200` once the router is enrolled and its libp2p host is online. The same flag exists on `sam-node run`. |-------## 3. Configuring Role-Based Policies (Dynamic API)--The Control Plane dynamically issues permissions inside the Biscuit token based on identity claims (users or groups) mapped to specific roles in the database.--The policy defines what endpoints and services agents are permitted to use:-* **`allowed_targets`**: Restricts which logical endpoints the agent can route connections to. Use resolved Biscuit facts: `group:<name>`, `user:<sub-id>`, `email:<email>`, `idp_role:<role-name>` (the issuer's `roles` claim), or `node:<peer-id>`. Mesh roles (`role(...)`) are never a target or a binding member: they are what bindings grant, and an issuer must not be able to hand one out by emitting it as a claim.-* **`allowed_services`**: Restricts the application-level services the agent can invoke. Services are prefixed by their protocol type and URI scheme (e.g., `mcp://local-shell-tools` or `inference://openrouter`). Wildcards are supported (e.g., `mcp://*`). The service is deliberately the unit of authorization: a grant offers the service's whole tool surface, so publish different privilege tiers as different services (e.g. `mcp://db-reader` vs `mcp://db-writer`) rather than expecting the mesh to filter tools inside one backend.-* **`allowed_agents`**: The agent namespaces a node with this role can use. When a node forwards a request for a sandboxed agent, it sends the agent's name with it. The receiving node accepts that name only if it falls inside one of these namespaces. A node with no `allowed_agents` grant cannot name any agent. Accepted patterns are `*.prod.acme.example`, `acme.*`, an exact ID such as `reviewer-7.prod.acme.example`, or `*` for any agent.-* **`allowed_labels`**: The labels a node with this role may declare when it enrolls, as `*`, `key=*` or `key=value`. A node sends its own labels in its enrollment request, so this is what decides which of them the control plane is willing to sign into `label()` facts. A role granting none means a node holding it can declare none. Peers gate on those facts with `required_labels`, so a node that could declare anything could satisfy any such requirement.--> **`allowed_agents` and `allowed_targets` do different things.** `allowed_targets` controls which agents a node can send requests *to*. `allowed_agents` controls which agents a node can claim to be acting *for*. Setting `allowed_agents` to `*` lets any node with that role claim any agent identity in the mesh, so nodes log a warning when they receive such a grant.--> **`sam:system:authenticated` means everyone your issuer vouches for.** That-> special member matches every identity able to obtain a token from the-> configured OIDC provider — and enrollment is open to all of them. Binding it-> to a role with wildcard `allowed_services` therefore grants every tool on-> every node to anyone the issuer will authenticate, which for a public-> provider is the whole internet. Reserve it for intentionally public meshes,-> and pair it only with narrowly scoped roles (e.g. `system://sam.catalog`).--### Seeding Policies via REST API-Admins manage policies by sending a JSON payload to the `/policies` endpoint.--```json-{- "roles": [- {- "name": "developer-role",- "allowed_targets": ["group:dev-nodes", "email:[email protected]", "user:auth0|123456", "node:12D3KooWSpecificDevNodeId"],- "allowed_services": ["mcp://local-shell-tools", "mcp://git-helper", "inference://openrouter"],- "allowed_agents": ["*.dev.example.com"]- },- {- "name": "admin-role",- "allowed_targets": ["group:all-nodes", "idp_role:admin"],- "allowed_services": ["mcp://*", "inference://*", "system://*"]- }- ],- "bindings": [- {- "role": "admin-role",- "members": ["email:[email protected]", "user:auth0|123456"]- },- {- "role": "developer-role",- "members": ["group:eng-team"]- }- ]-}-```--### 3.1 Binary Capability Roles (Zero Trust)-To enforce the principle of least privilege, the Sovereign Agent Mesh implements binary-level capability authorization. Every binary connecting to the mesh must request its specific target role during enrollment:-- `sam-node` requests `sam:role:node` (Default agent capability)-- `sam-box` requests `sam:role:sambox` (Secure Gateway sidecar)-- `sam-router` requests `sam:role:router` (P2P routing and relay service)--The control plane control plane validates that the enrolling client is authorized for the requested role before issuing the Biscuit identity token:-1. **Explicit Bindings**: Every capability role — including `sam:role:node` — must be bound to the enrolling identity in mesh policy. There is no fallback: a mesh with no `sam:role:node` binding enrolls no nodes. To open node enrollment to every identity the OIDC issuer authenticates (an intentionally public mesh), bind it explicitly:--```json-"bindings": [- {- "role": "sam:role:node",- "members": ["group:eng-team"]- },- {- "role": "sam:role:router",- "members": ["group:mesh-routers"]- },- {- "role": "sam:role:sambox",- "members": ["user:gateway-pod-sa"]- }-]-```--If a binary requests a capability role it is not authorized for, enrollment fails immediately. If a client attempts to start using a token that lacks its binary's required role, startup aborts.-------## 4. Bootstrapping Example--Here is a script demonstrating how to boot both services in a secure development environment:--```bash-# 1. Start the Control Plane (using SQLite)-./bin/sam-control-plane \- --issuer "https://accounts.google.com" \- --allowed-audiences "my-google-client-id.apps.googleusercontent.com" \- --bind-address "0.0.0.0:8080" \- --admin-token-path /etc/sam/admin-token--# 2. Seed baseline policy via REST API-curl -X POST \- -H "Authorization: Bearer super-secret-admin-token" \- -H "Content-Type: application/json" \- -d '{- "roles": [{"name": "sam:role:node", "allowed_services": ["mcp://*"], "allowed_targets": ["*"]}],- "bindings": [{"role": "sam:role:node", "members": ["group:developers"]}]- }' \- http://127.0.0.1:8080/policies--# 3. In another shell, start the Router using a bootstrap JWT or token-./bin/sam-router \- --control-plane "http://127.0.0.1:8080" \- --listen "/ip4/0.0.0.0/tcp/5001" \- --listen "/ip4/0.0.0.0/udp/5001/quic-v1" \- --keys-path "./router.key" \- --oidc-token "my-router-jwt-token"-```-------## 5. Token Refresh & Session Revocation--To enforce centralized access control without sacrificing offline verification performance at the edge, SAM implements a decoupled token refresh and session revocation model.--### Lifespan Model--1. **Short-Lived Biscuit Tokens (TTL = 24 Hours)**:- All minted Biscuit tokens are cryptographically bound to a strict 24-hour expiration. Peers verify this expiration locally without hitting the Control Plane.-2. **Long-Lived Sessions (The Right to Refresh)**:- * **OIDC Interactive Enrollment**: 90-day database session limit. After 90 days, the user must re-enroll interactively.- * **Bootstrap Flow (Headless Nodes/Routers)**: Infinite session limit (sessions never expire). In practice the signing key's grace period bounds how long such a node can stay offline and still refresh; see [Signing-Key Retirement and Recovery](#signing-key-retirement-and-recovery).--### Proactive Refresh Lifecycle--Nodes and Routers run a background task that periodically checks the remaining Biscuit expiration:-* **Check Interval**: Every 10 minutes (`api.TokenRefreshCheckInterval`).-* **Threshold**: When the remaining token lifespan is less than 20% of its initial TTL (~4.8 hours remaining), the daemon proactively trades the expiring Biscuit for a fresh one.-* **Challenge Handshake**: The client signs a peer- and endpoint-bound timestamp challenge (`sam:refresh:<peer_id>:<unix-millis>`) with its private key and sends it to the Control Plane `/refresh` endpoint along with its expiring Biscuit in the `Authorization: Bearer <token>` header. The Control Plane verifies the signature against the registered node's public key in the database before issuing a new Biscuit.--The bootstrap surface requires the same proof of possession end to end. `POST /enroll` carries a signed timestamp challenge in the request body (`timestamp`/`challenge_signature`, and `peer_id` must be derived from the submitted `public_key`), so a bootstrap token alone can never mint — or re-fetch — another peer's Biscuit. `GET /enroll/status` answers only when the caller signs the peer-bound challenge with that same key, sent in the `X-Sam-Challenge-Ts` and `X-Sam-Challenge-Sig` headers (headers rather than query parameters, so signatures stay out of access logs). Anything else — no signature, a stale timestamp, another key, an unknown peer — receives a uniform `401`, so an approved enrollment's Biscuit is only ever released to the enrollee itself.--The OIDC surface and the router surface follow suit. `POST /register` carries the same `timestamp`/`challenge_signature` pair over `sam:register:…`, with `peer_id` derived from `public_key`: the ID token says who is asking, the signature says they hold the key they are binding, so an identity with a node binding cannot register — and overwrite — another node's `peer_id`. `POST /routers/lease` requires a challenge over `sam:routers-lease:…` signed with the key the router enrolled with; its Biscuit alone is not proof, because routers hand it to every peer they authenticate during the mutual handshake.--All five challenges share one shape — the UTF-8 bytes of `sam:<endpoint>:<peer_id>:<unix-millis>` (`sam:register:…`, `sam:enroll:…`, `sam:enroll-status:…`, `sam:refresh:…`, `sam:routers-lease:…`), signed by the peer's identity key and accepted within a ±5-minute freshness window. Binding the peer and the endpoint into the signed payload means a signature captured from any one request verifies nowhere else. Libp2p's secure channel already proves key possession on every peer-to-peer stream; these challenges exist because the Control Plane API is plain HTTP, where a `peer_id` in a request body is otherwise just a claim.--### Signing-Key Retirement and Recovery--Every `--key-rotation-interval` the Control Plane mints a new signing key. The previous key stays accepted for `--key-grace-period`, then it is retired: Biscuits it signed can no longer be verified by anyone, including the Control Plane. A node whose Biscuit is signed by a retired key is refused on `/refresh` (`401`), fails its role check at daemon start, and — for a router — has its lease renewal rejected. This is deliberate: the grace period is the deadline after which a node that has gone quiet cannot come back on its own, so a forgotten or stolen machine does not rejoin the mesh unnoticed.--How a node gets past that deadline depends on how it was enrolled.--* **OIDC nodes** recover on their own. The daemon exchanges its stored refresh grant for a fresh ID token and re-enrolls under the current key, keeping its PeerID. The identity provider stays authoritative: revoking the grant there ends this.-* **Bootstrap nodes and routers** (headless enrollment) have no such grant. By default they need an operator: mint a new bootstrap token and re-run `sam-node join` (or restart the router with the new token). `POST /enroll` for a peer that is already approved re-mints a fresh Biscuit under the active key instead of replaying the stored one — the role and labels come from the enrolled node record, never from the request, the peer must still prove possession of its key, a banned peer is refused, and the re-enrollment consumes one use of the token. The token's `max_usages` is therefore the operator's cap on how many times a given node can be brought back this way.--#### Autonomous recovery (opt-in)--For fleets where an operator round-trip per stale node is impractical, a bootstrap node can be allowed to recover on proof of possession alone. This is a per-node flag, `autonomous_recovery`, held only on the Control Plane's node record and never asserted by the node. It is **off by default**: a node carrying it can always renew on its own private key, so that key effectively becomes a credential that never expires. Only a ban (`POST /admin/revoke`) stops it.--Set it either when minting the bootstrap token — every node that token enrolls inherits it — or per node afterwards:--```bash-# At mint time (admin only): nodes enrolled with this token may recover autonomously-curl -X POST -H "Authorization: Bearer <your-admin-token>" -H "Content-Type: application/json" \- -d '{"role": "sam:role:router", "ttl_hours": 24, "max_usages": 3, "autonomous_recovery": true}' \- http://<control-plane-ip>:8080/admin/bootstrap-tokens--# Per node, for one that is already enrolled (toggle back with "enabled": false)-curl -X POST -H "Authorization: Bearer <your-admin-token>" -H "Content-Type: application/json" \- -d '{"enabled": true}' \- http://<control-plane-ip>:8080/admin/nodes/<peer-id>/autonomous-recovery-```--The console shows the flag in the **Recovery** column of the Nodes and Bootstrap Tokens views, with an enable/disable action for administrators.--With the flag set, `/refresh` accepts a Biscuit it can no longer verify when all of the following hold:--1. the request carries the node's `peer_id`, and an enrolled record exists for it with `autonomous_recovery` on;-2. the presented Biscuit is byte-for-byte the last one the Control Plane issued to that node — a replayed, superseded Biscuit is refused, and this is what authenticates the Biscuit in place of the signature that cannot be checked;-3. the fresh challenge is signed by the node's registered private key;-4. the node is not banned and its session has not expired.--The new Biscuit is minted under the active key with the role and labels from the node record. Until steps 1–3 all succeed, a request through this path is answered exactly like any other bad Biscuit, so the fallback does not reveal which peer IDs are enrolled. Nodes and routers send `peer_id` on every refresh; when the Biscuit verifies normally it is only cross-checked against the token.--### Administrative Revocation--Administrators can immediately revoke any active session to disable a node's ability to renew its token.-* **Endpoint**: `POST /admin/revoke`-* **Authentication**: Requires the admin token in the headers.-* **Payload**:- ```json- {- "peer_id": "12D3KooW..."- }- ```-* **Enforcement**: Revoked nodes are marked as banned in the database. When the node next attempts a proactive `/refresh` handshake, the request is denied with a `403 Forbidden` status, and the node's local daemon immediately terminates. When the node was enrolled through OIDC, the identity behind it (`issuer|subject`) is banned as well: it can no longer `/register` a fresh keypair, use the `/user/*` API, or enroll anything with bootstrap tokens it minted earlier, and a queued enrollment on such a token is refused at approval.-* **Lifting a ban**: `POST /admin/nodes/{peer_id}/unban` reverses both halves (node and identity). The `sam-control-plane admin ban|unban --peer` commands do the same directly against the database.--Bootstrap tokens are spent atomically: a token's `max_usages` holds under concurrent enrollments, an approval re-checks that the token is still valid and unspent, and a pending request can be resolved exactly once. A Control Plane with no mesh policy mints Biscuits that carry the role and no grants at all; nothing is reachable until an administrator posts a policy.-------## 6. Node Service Catalog--Each enrolled node periodically self-reports its locally registered services so the admin console's **Services** view can show what is running where, without the Control Plane joining the P2P mesh.--* **Endpoint**: `POST /nodes/catalog`-* **Authentication**: The node's own Biscuit as a `Bearer` token. The reporting peer is taken from the verified token, never from the body, so a node can only ever describe itself; reports from banned or expired enrollments are rejected.-* **Payload**: An `api.NodeCatalogReport` protobuf (`application/x-protobuf`) with up to 512 services per report.-* **Cadence**: Every minute by default (`node.Options.CatalogReportInterval`), with jitter.-* **Semantics**: A live-status cache, not authoritative state. It is display-only and never feeds authorization; the cache is in-memory and rebuilt by the nodes' next reports after a Control Plane restart. If you front the Control Plane with a Gateway allow-list, `/nodes/catalog` must be routed like the other node-facing endpoints.-------## 7. Headless Node Enrollment (Bootstrap Token Flow)--To enroll a headless server, router, or background daemon that cannot complete interactive OIDC authentication, SAM supports a **Bootstrap Token** flow.--### Step 1: Generate a Bootstrap Token--An administrator with the `admin-token` can dynamically generate a time-bounded, single-use bootstrap token:--```bash-curl -X POST \- -H "Authorization: Bearer <your-admin-token>" \- -H "Content-Type: application/json" \- -d '{"role": "sam:role:node", "ttl_hours": 24, "max_usages": 1, "description": "Headless node deployment token"}' \- http://<control-plane-ip>:8080/admin/bootstrap-tokens-```--This returns a JSON response containing the plaintext token:-```json-{- "id": "62e92ffca...",- "token": "sam-bt-72fb0175788dee0...",- "role": "sam:role:node",- "expires_at": "2026-07-12T15:00:00Z"-}-```--The request also accepts `"autonomous_recovery": true` (admin only), which lets every node enrolled with the token refresh its Biscuit after the signing key that issued it has been retired; see [Autonomous recovery](#autonomous-recovery-opt-in) before turning it on.--A token that is no longer wanted — a multi-use token being decommissioned early, or one that leaked — can be revoked before it expires. Revocation is a soft state on the token (it stays listed, marked revoked, so the audit trail of what it enrolled is kept), is idempotent, and is enforced on every `/enroll`, including re-enrollment of a node it previously approved:--```bash-curl -X DELETE -H "Authorization: Bearer <your-admin-token>" \- http://<control-plane-ip>:8080/admin/bootstrap-tokens/<token-id>-```--### Step 2: Request Enrollment on the Node--Run the node `join` command with the generated token:--```bash-sam-node join --bootstrap-token sam-bt-72fb0175788dee0... http://<control-plane-ip>:8080-```--The node submits its enrollment request and waits (polls) for approval.--### Step 3: Approve the Enrollment--Administrators can review pending enrollment requests:--```bash-# List all pending enrollments-curl -H "Authorization: Bearer <your-admin-token>" http://<control-plane-ip>:8080/admin/enrollments-```--To approve the request and issue the node its identity Biscuit:--```bash-curl -X POST \- -H "Authorization: Bearer <your-admin-token>" \- http://<control-plane-ip>:8080/admin/enrollments/<request-id>/approve-```--Alternatively, you can boot the control plane with `--auto-approve-enrollment` to automatically approve all valid bootstrap token requests without manual gates.--### Re-enrolling a node that is already approved--Running `sam-node join` again for a peer the Control Plane has already approved — after `sam-node reset`, or because its Biscuit was signed by a key that has since been retired — does not go back through the approval queue. As long as the token is valid, unrevoked and has usages left, the peer proves possession of the same key, its role matches the token's, and it is not banned, `POST /enroll` mints a fresh Biscuit under the current signing key from the stored node record and returns it immediately. This is the manual recovery path described in [Signing-Key Retirement and Recovery](#signing-key-retirement-and-recovery); no database intervention is needed.-diff --git a/site/content/docs/user/device-enrollment.md b/site/content/docs/user/device-enrollment.mddeleted file mode 100644index dff7b2a1..00000000--- a/site/content/docs/user/device-enrollment.md+++ /dev/null@@ -1,216 +0,0 @@-----title: "A Mesh in 30 Seconds"-linkTitle: "A Mesh in 30 Seconds"-weight: 7------# A Mesh in 30 Seconds--You have a laptop and a phone. Neither has a public IP address, they are-not on the same network, and you want a program on the laptop to read a-sensor on the phone, securely, without first setting up a server, a-domain, a certificate or an identity provider.--That is what `sam-one` is for: the whole SAM control plane, router and-database in one binary on one port, and it prints a QR code the phone-scans to join. Everything below was run exactly as written and timed from-the moment `sam-one` started, on a fresh data directory:--```- 10.3s sam-one: banner + QR printed- 13.7s phone: enrolled- 18.8s phone: node running, phone-sensors advertised- 19.6s laptop: enrolled- 24.9s laptop -> phone: {"battery_level": 64, "charging": true}-```--The taps on the phone were scripted; with a human reading the dialog it-lands around half a minute. The output is real, only the tokens are-shortened.--You need the `sam-one` and `sam-node` binaries on the laptop (`make` from-a checkout, or a [release](https://github.com/google/sam/releases)) and-**SAM Connect** on the phone, the Android app from the same release.--## 1. Start the control plane--```bash-sam-one --data-dir ~/sam-one --tunnel cloudflare-```--`--data-dir` holds the database, the router's identity and the generated-tokens; delete it and you have a brand new mesh. `--tunnel cloudflare`-publishes the single port on a temporary public `https` hostname through-a [Cloudflare quick tunnel](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/),-which needs no account. If `cloudflared` is not installed, `sam-one`-offers to download the pinned release (checksum-verified, into-`~/sam-one/bin`) once you accept Cloudflare's license at the prompt;-`--tunnel-install` accepts it up front.--A few seconds later (`sam-one` waits until the new hostname is actually-published in DNS before it prints anything, so what you see is live):--```-══════════════════════════════════════════════════════════════════-SAM standalone mesh is ready!--API URL: https://fairy-museum-built-wing.trycloudflare.com-Tunnel: https://fairy-museum-built-wing.trycloudflare.com -> http://0.0.0.0:33775-Web Console: https://fairy-museum-built-wing.trycloudflare.com/console-Router Peer: 12D3KooWBzUDQCkZhz2rWrYBhpjcCH8VnrRNcwCW6DoF36iADYrY-Admin Token: sam_adm_…-Join Token: sam_tok_…--To enroll a node:- sam-node join https://fairy-museum-built-wing.trycloudflare.com --bootstrap-token-path /home/you/sam-one/join-token-══════════════════════════════════════════════════════════════════--Scan with the SAM app to enroll a device into fairy-museum-built-wing.trycloudflare.com-(single use, valid for 1h0m0s):--█████████████████████████████████████████████-████ ▄▄▄▄▄ ██▄ █ █ ▀ █▀▄▄▄▀ ▄▄▄ ▄▀▀ ▄▄▄▄▄ ████-████ █ █ █ ████ ▀▀▄▄█▀▀▀▄▀█▀▄▄ ▀ █ █ ████-████ █▄▄▄█ █ ▄███▀▀▀▀▀▄ ▄ ▄▄▄ █▄ ▄▀ █▄▄▄█ ████- …-sam://enroll?server=https%3A%2F%2Ffairy-museum-built-wing.trycloudflare.com&token=sam_dev_…-Token ID: 0b7acf609466 (revoke early with: sam-one token revoke 0b7acf609466)-```--That is a running mesh. The web console is live at the URL shown, the-join token lets `sam-node` processes in, and the QR code carries a fresh-**single-use** token for one phone.--## 2. Enroll the phone--Open SAM Connect, tap **Scan enrollment code** and point it at the-terminal. The app shows where the code leads before it spends the token;-tap **Join**.--| Confirm the mesh | Running |-|:---:|:---:|-|  |  |--On the **Services** tab switch **Battery Status** on, go back to the-dashboard and tap **Start**. The phone is now a node: it generated its own-key, was issued a credential bound to that key, connected to the router-through the tunnel and advertised a `phone-sensors` service to the mesh.-Note the **Node ID** on the dashboard; you will use it in a moment.--Scanning with the phone's stock camera app works too: the `sam://` link-opens SAM Connect with the same dialog. Without a camera, **Enter details-manually** takes the printed `sam://enroll…` line pasted as text.--## 3. Join the laptop and call the phone--```bash-sam-node run --control-plane https://fairy-museum-built-wing.trycloudflare.com \- --bootstrap-token-path ~/sam-one/join-token \- --data-dir ~/laptop-node --bind-addr=-```--The node enrolls with the join token the banner pointed at. An empty-`--bind-addr=` keeps its local API on a Unix socket only,-`~/laptop-node/sam.sock`, so nothing on the laptop needs a token to use-it. Now ask the phone for its battery, through the mesh:--```bash-PHONE=12D3KooWSCnbUoZ8Jv3EKGv17LqEWtnTMfZ3XYJUg2WTm5Gz2hUK # Node ID from the phone's dashboard--curl -s --unix-socket ~/laptop-node/sam.sock \- -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \- -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_battery_status","arguments":{}}}' \- http://localhost/sam/$PHONE/mcp/phone-sensors/-```--```json-{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"battery_level\": 46, \"charging\": true}"}]}}-```--That request left the laptop's socket, crossed the tunnel to the router-inside `sam-one`, was relayed to the phone over a connection the phone had-opened outbound, and came back the same way. Both devices are behind NAT;-neither accepted an inbound connection. Every hop was authenticated with-the credentials minted at enrollment, and the phone's node checked the-mesh policy before letting the call through.--Any MCP client can do the same: the path is-`/sam/<node-id>/mcp/<service>/` over that socket, and `tools/list` on it-shows what the phone offers (`get_battery_status`, and `get_location` once-you enable Location).--## 4. Add more devices--A second phone is another QR code. `sam-one token qr` mints one on a-running mesh, and `--max-usages 50` makes a single code, projected on a-screen, admit a whole room:--```bash-sam-one token qr --server https://fairy-museum-built-wing.trycloudflare.com --data-dir ~/sam-one-```--A second laptop gets a scoped, single-use token instead of the standing-join token:--```bash-# On the sam-one host: mint the token straight into a file.-sam-one token create --server https://fairy-museum-built-wing.trycloudflare.com \- --data-dir ~/sam-one --description "second laptop" \- | awk '/^Token:/{print $2}' > enroll-token--# On the second laptop, with that file copied over:-sam-node run --control-plane https://fairy-museum-built-wing.trycloudflare.com \- --bootstrap-token-path enroll-token --data-dir ~/node --bind-addr=-```--The same `curl` from that laptop returns the same battery reading.-`sam-one token list` shows every token with its usage and status, and-`sam-one token revoke <id>` ends one early. A device that is already-enrolled stays enrolled until you say otherwise:-`sam-one admin ban <node-id>` removes it.--(`--data-dir` tells the CLI where to read the admin token; on another-machine, export `SAM_ADMIN_TOKEN` or pass `--admin-token-path` instead. It-is never a flag value.)--## Why this is not a toy--* **The phone's identity is a key it generated.** The token in the QR code- is spent once at `POST /enroll` and worthless afterwards; what the phone- keeps is a short-lived credential bound to its own key, renewed- automatically and revocable by node ID. The app runs the same renewal- loop as `sam-node`.-* **The URL must be `https`.** The control plane is each device's trust- root, so SAM Connect refuses plaintext to anything but `localhost`, and- `sam-one` will not print a QR code for a plaintext address. The tunnel- is the zero-setup way to get `https` on a laptop; Cloud Run and a- reverse proxy with `--external-url` are the others (see the [Cloud Run- guide](../cloud-run-deployment/)).-* **Nothing is routed by IP.** Services are found by name and called by- node ID; policy is evaluated on the service name, deny by default.-* **`sam-one` is the real thing.** It runs the same control plane, router- and store as a Kubernetes deployment, in one process. What works here- works there.--## Before you take it beyond a demo--A quick tunnel changes hostname every start and comes with no uptime-promise, and the first boot seeds an *open* development policy (the log-says so). For anything with more than a handful of devices:--* Give the mesh a stable `https` name and keep `~/sam-one`, or point- `--db-driver postgres` at a database.-* Seed a real policy with `--policy-file`, and run with `--no-join-token`- so devices enroll only with tokens you mint.-* Read the admin token from `SAM_ADMIN_TOKEN` or `--admin-token-path`- rather than the banner; `--enroll-qr=false` keeps codes out of- non-interactive logs.-* Decide what happens to devices that go dark for more than a day: widen- `--control-plane-key-grace-period`, or mint their tokens with- `--autonomous-recovery`. The trade-off is how long a lost device can- keep renewing.-* Want OIDC instead of tokens? Give `sam-one` an issuer (`--issuer`,- `--allowed-audiences`, `--oidc-client-id`) and the app's **Login &- Enroll** and **Device Login** flows work unchanged.--Those are flags, not a different product.diff --git a/site/content/docs/user/kubernetes-deployment.md b/site/content/docs/user/kubernetes-deployment.mddeleted file mode 100644index e7d53e77..00000000--- a/site/content/docs/user/kubernetes-deployment.md+++ /dev/null@@ -1,335 +0,0 @@-----title: "Production Kubernetes Deployment"-linkTitle: "Kubernetes Deployment"-weight: 30------This guide explains how to deploy a production-grade SAM cluster (control plane, router, DNS synchronizer, OIDC bridge, and Nodes) in a Kubernetes environment (like GKE, EKS, AKS, or custom bare-metal clusters), based on our official public testnet architectures.-------## 1. Architecture Overview--A production SAM deployment consists of:-* **Dex (OIDC Provider)**: Serves as the identity bridge, federation point, and login broker.-* **SAM Control Plane (`sam-control-plane`)**: Runs as a stateless **Deployment** to verify OIDC tokens and issue capabilities (Biscuits) based on identity policies.-* **SAM Router (`sam-router`)**: Runs as a **StatefulSet** to maintain stable network identity. P2P nodes use these bootstrap routers to connect to the GossipSub mesh overlay.-* **DNS Sync CronJob**: Dynamically queries the `sam-router` StatefulSet pod IP addresses and updates DNS A/AAAA records for P2P bootstrap resolution.-* **SAM Nodes (`sam-node`)**: Deployed as containerized gateways that authenticate securely to the control plane using Kubernetes Workload Identity (ServiceAccount token projection).--```mermaid-graph TD- User([User / Client]) -->|HTTPS / OIDC| Dex[Dex Identity Bridge]- Node[sam-node Gateway Pod] -->|HTTPS Enroll| CP[sam-control-plane Deployment]- Router[sam-router StatefulSet] -->|HTTPS Enroll| CP- Node -->|P2P Mesh Overlay| Router- CP -->|OIDC Discovery Check| Dex- Cron[DNS Sync CronJob] -->|Poll Pod IPs| K8sApi[Kubernetes API]- Cron -->|Update A Records| CloudDNS[Cloud DNS / DNS Registry]- Node -->|Bootstrap DNS Resolution| CloudDNS-```-------## 2. Step 1: Deploying the OIDC Provider (Dex)--Dex maps external accounts (Google, GitHub, LDAP) to standard OIDC identities in the cluster.--### 1. Provision Dex Secrets-Idempotently create the secret containing your OAuth client applications' credentials:-```bash-kubectl create secret generic dex-secrets \- --namespace=dex \- --from-literal=google-client-id="<my-google-client-id>" \- --from-literal=google-client-secret="<my-google-client-secret>" \- --from-literal=github-client-id="<my-github-client-id>" \- --from-literal=github-client-secret="<my-github-client-secret>" \- --from-literal=cli-oauth-secret="<my-ephemeral-cli-oauth-secret>" \- --dry-run=client -o yaml | kubectl apply -f --```--### 2. Apply Dex Manifests-Deploy the Dex deployment and configuration mapping:-```yaml-# dex-config.yaml-apiVersion: v1-kind: ConfigMap-metadata:- name: dex-config- namespace: dex-data:- config.yaml: |- issuer: https://AUTH.YOUR-DOMAIN.COM- storage:- type: kubernetes- config:- inCluster: true- web:- http: 0.0.0.0:5556- connectors:- - type: google- id: google- name: Google- config:- clientID: $GOOGLE_CLIENT_ID- clientSecret: $GOOGLE_CLIENT_SECRET- redirectURI: https://AUTH.YOUR-DOMAIN.COM/callback- staticClients:- - id: YOUR-CLI-AUDIENCE- name: 'SAM Mesh native client'- secret: $CLI_OAUTH_SECRET- redirectURIs:- - 'urn:ietf:wg:oauth:2.0:oob'- - 'http://localhost:8000'-```-Deploy the deployment manifests located in the repository's `.github/k8s/dex-deployment.yaml` and wait for readiness:-```bash-kubectl rollout status deployment/dex -n dex-```-------## 3. Step 2: Deploying SAM Control Plane and Router--The Control Plane verifies OIDC tokens and manages access policies. The Routers handle peer discovery and routing within the GossipSub mesh.--### 1. Deploy SAM Control Plane-The Control Plane is stateless and can scale horizontally. It connects to a shared PostgreSQL database to persist active leases and rotated capability signing keys.--```yaml-apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-control-plane- namespace: sam-spec:- replicas: 3- selector:- matchLabels:- app: sam-control-plane- template:- metadata:- labels:- app: sam-control-plane- spec:- containers:- - name: sam-control-plane- image: ghcr.io/google/sam-control-plane:latest- args:- - "--bind-address=0.0.0.0:8080"- - "--db-driver=postgres"- - "--db-dsn=postgres://sam:password@sam-db-service:5432/sam_mesh?sslmode=disable"- - "--issuer=https://AUTH.YOUR-DOMAIN.COM"- - "--allowed-audiences=YOUR-CLIENT-AUDIENCE"- ports:- - containerPort: 8080- name: http-```--### 2. Configure Access Control Policies-The Control Plane starts **default closed**: until a policy is posted it authorizes-nothing. Policy lives in the database, not on disk, so seed it through the admin-API. Roles and bindings use the same schema everywhere, including the Mesh Policy-editor in the console.--```bash-curl -sf -X POST \- -H "Content-Type: application/json" \- -H "Authorization: Bearer ${SAM_ADMIN_TOKEN}" \- -d '{- "roles": [- {"name": "node-role", "allowed_services": ["mcp://calculator", "system://sam.catalog"], "allowed_targets": ["user:system:serviceaccount:sam-nodes:sam-node-sa"]}- ],- "bindings": [- {"role": "node-role", "members": ["user:system:serviceaccount:sam-nodes:sam-node-sa"]},- {"role": "sam:role:node", "members": ["user:system:serviceaccount:sam-nodes:sam-node-sa"]}- ]- }' \- https://CONTROL-PLANE.YOUR-DOMAIN.COM/policies-```--> **Grant the least privilege that works.** A role's `allowed_services` names the-> exact backends its members may invoke — list them explicitly rather than using-> `["*"]`. Be especially careful with the member `sam:system:authenticated`: it-> matches every identity your OIDC issuer will authenticate, and enrollment is-> open to any of them, so binding it to a wildcard role gives every tool on every-> node to anyone who can obtain a token from that issuer.--The `sam-mesh` Helm chart runs this as a bootstrap Job for you; see-`charts/sam-mesh/templates/bootstrap-job.yaml`.--### 3. Deploy SAM Router StatefulSet-The Router must be deployed as a StatefulSet to allocate a persistent volume for storing its libp2p identity key, ensuring a stable Peer ID across pod restarts.--```yaml-apiVersion: v1-kind: ServiceAccount-metadata:- name: sam-router-sa- namespace: sam-----apiVersion: apps/v1-kind: StatefulSet-metadata:- name: sam-router- namespace: sam-spec:- serviceName: "sam-router"- replicas: 3- selector:- matchLabels:- app: sam-router- template:- metadata:- labels:- app: sam-router- spec:- serviceAccountName: sam-router-sa- containers:- - name: sam-router- image: ghcr.io/google/sam-router:latest- ports:- - containerPort: 4501- protocol: TCP- name: p2p-tcp- - containerPort: 4501- protocol: UDP- name: p2p-udp- args:- - "--control-plane=http://sam-control-plane.sam.svc.cluster.local:8080"- # In-cluster plaintext; the cluster network is the trust boundary.- - "--insecure-control-plane"- - "--listen=/ip4/0.0.0.0/tcp/4501"- - "--listen=/ip4/0.0.0.0/udp/4501/quic-v1"- - "--jwt-path=/var/run/secrets/tokens/sam-token"- - "--keys-path=/data/router.key"- volumeMounts:- - name: sam-token- mountPath: /var/run/secrets/tokens- readOnly: true- - name: router-data- mountPath: /data- volumes:- - name: sam-token- projected:- sources:- - serviceAccountToken:- path: sam-token- expirationSeconds: 3600- audience: "sam-control-plane-audience"- volumeClaimTemplates:- - metadata:- name: router-data- spec:- accessModes: [ "ReadWriteOnce" ]- resources:- requests:- storage: 1Gi-```-------## 4. Step 3: DNS Synchronization (DHT Bootstrapping)--In a decentralized DHT network, nodes need stable DNS multiaddrs (`/dnsaddr/BOOTSTRAP.YOUR-DOMAIN.COM`) to resolve bootstrap peers. Since Kubernetes StatefulSet pod IP addresses change on restart, you must deploy a sync cronjob that updates A/AAAA records on your DNS provider.--### DNS Sync CronJob Example-The sync script:-1. Queries the Kubernetes API for the external/internal IP addresses of the `sam-router` pods.-2. Updates your Cloud DNS zone (e.g. Google Cloud DNS, AWS Route53) dynamically.-3. Announce new multiaddrs via TXT records.--Refer to [dns-sync-cronjob-template.yaml](https://github.com/google/sam/blob/main/.github/k8s/dns-sync-cronjob-template.yaml) for our official Cloud DNS sync cronjob.-------## 5. Step 4: Deploying SAM Nodes (Workload Identity)--To secure nodes without distributing static passwords, configure nodes to authenticate via **ServiceAccount projected tokens** (Workload Identity Federation).--> [!TIP]-> The repository ships this pattern as a Helm chart: `charts/sam-node`-> renders the ServiceAccount, config ConfigMap and Deployment below from a-> small values file (see the chart's README). The manifests that follow show-> what it produces.--### 1. Create a ServiceAccount-```yaml-apiVersion: v1-kind: ServiceAccount-metadata:- name: sam-node-sa- namespace: sam-nodes-```--### 2. Configure Node Identity and Services-Create a ConfigMap defining the node's local services and local security target identity (see the [Node Configuration Guide](../node-configuration/) for schema details):--```yaml-apiVersion: v1-kind: ConfigMap-metadata:- name: sam-node-config- namespace: sam-nodes-data:- sam-node.yaml: |- version: "v1alpha1"- services:- - type: mcp- name: db-agent- command: ["echo", "placeholder db-agent service"]- attenuation:- rules:- - 'department("analytics") <- true;'- policies:- - 'deny if user("untrusted_user");'-```--### 3. Deploy Nodes using Token Projection-Deploy the nodes. We use a `projected` volume to request a short-lived token containing the audience expected by the control plane (`sam-control-plane-audience`):--```yaml-apiVersion: apps/v1-kind: Deployment-metadata:- name: sam-node- namespace: sam-nodes-spec:- replicas: 5- template:- spec:- serviceAccountName: sam-node-sa- containers:- - name: sam-node- image: ghcr.io/google/sam-node:latest- args:- - "run"- - "--config=/etc/sam/sam-node.yaml"- - "--control-plane=http://sam-control-plane.sam.svc.cluster.local:8080"- - "--insecure-control-plane"- - "--jwt-path=/var/run/secrets/tokens/sam-token"- - "--api-token-path=/var/run/secrets/sam/api-token"- volumeMounts:- - name: config-volume- mountPath: /etc/sam- - name: sam-token- mountPath: /var/run/secrets/tokens- readOnly: true- volumes:- - name: config-volume- configMap:- name: sam-node-config- - name: sam-token- projected:- sources:- - serviceAccountToken:- path: sam-token- expirationSeconds: 3600- audience: "sam-control-plane-audience" # Match this with what the control plane expects-```-------## 6. Local Sandbox Testing (Kind)--If you are looking to test Kubernetes deployments locally in a sandboxed cluster without external cloud dependencies, please follow the [Local Kubernetes Testing Guide](../../development/kubernetes-deployment/).diff --git a/site/content/docs/user/mobile-app.md b/site/content/docs/user/mobile-app.mddeleted file mode 100644index 09d633d1..00000000--- a/site/content/docs/user/mobile-app.md+++ /dev/null@@ -1,92 +0,0 @@-----title: "SAM Connect (Android/iOS)"-linkTitle: "SAM Connect"-weight: 5------# SAM Connect (Flutter Client)--SAM Connect is a Flutter application that packages and runs the native Go-based `sam-node` mesh client on mobile devices using Go's CGO compiler and Dart FFI (Foreign Function Interface).--It allows you to turn your phone into a fully functional node in the Sovereign Agent Mesh, exposing device sensors and capabilities securely to AI agents.-------## Features & Capabilities--### 📱 1. Embedded MCP Server & Real Telemetry-The app includes an embedded MCP server that exposes real-time telemetry from your device:-* **Battery Status**: Level and charging state.-* **Location**: Coarse/Fine coordinates (requires permissions).-* **Foreground Service**: Keeps the node alive and connected even when the phone is idle or backgrounded (Android 14+ compatible).--### 🤖 2. Android 16 AppFunctions (On-Device MCP)-Exposes capabilities directly to the OS registry, allowing native assistants (like Gemini) to orchestrate tasks without manual app navigation.-* `getMeshStatus`: Returns node stats and connected peers.-* `callRemoteMeshTool`: Proxy to invoke tools on remote mesh peers.-------## Screenshots--| Node Status / Dashboard | Services & Telemetry |-|:---:|:---:|-|  |  |-------## How to Use the Application--1. **Enrollment**: Tap **Scan enrollment code** and scan the `sam://enroll` QR code printed by `sam-one` (see [A Mesh in 30 Seconds](../device-enrollment/)), or open **Enter details manually** to paste a bootstrap token, or sign in through the control plane's identity provider (browser or device login) with its **Control plane URL** (e.g., `https://bananas.sam-mesh.dev`).-2. **API Token**: A local API token securing local access is generated on first launch; view or regenerate it on the Config tab.-3. **Start Node**: Launches the background Go node runtime.-4. **Dashboard**: Monitor connected peers and DHT size.-5. **Services Tab**: Enable/Disable embedded sensors (Battery/Location) to expose them to the mesh.-------## Developer Integration & Usage Examples--### Option 1: CLI Usage (Technical Verification)--You can query the phone's telemetry from a remote machine (or another node) using the repository's `mcp-client` utility.--1. **Discover tools on the remote phone service**:- ```bash- # Query the local SAM node proxy for tools hosted by the phone-sensors peer- go run cmd/mcp-client/main.go \- -url "http://localhost:8080/sam/<PHONE_PEER_ID>/mcp/phone-sensors" \- -token "secret-token" \- -list- ```- *Output:*- * `get_battery_status`: Returns the current battery level and charging status of the device.- * `get_location`: Returns the current coarse location of the device.--2. **Query the location**:- ```bash- go run cmd/mcp-client/main.go \- -url "http://localhost:8080/sam/<PHONE_PEER_ID>/mcp/phone-sensors" \- -token "secret-token" \- -tool "get_location"- ```- *Output:* `{"latitude": 42.2805588, "longitude": -8.6124088}`-------### Option 2: AI Agent Interaction Flow--Clean, successful flow of an AI agent discovering and querying the mesh.--| Step | Action | Details / Tool | Result |-|---|---|---|---|-| 1 | Discover Peers & Tools | `find_remote_tools` | Found peer `<PHONE_PEER_ID>` hosting service `phone-sensors` with tool `mcp://phone-sensors/get_location`. |-| 2 | Verify Schema | `describe_remote_tool` | Confirmed `get_location` requires no input parameters: `{"input_schema": {"type": "object", "properties": {}}}`. |-| 3 | Query Location | `call_remote_tool` | Received: `{"latitude": 42.2805588, "longitude": -8.6124088}` |-| 4 | Resolve Address | Web Search | Geolocated to Vigo / Redondela area, Galicia, Spain. |-------## Compilation Instructions--For instructions on how to build the application from source, please refer to the [Mobile App README](https://github.com/google/sam/tree/main/mobile/sam-node-app).diff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.mddeleted file mode 100644index c38d2bd0..00000000--- a/site/content/docs/user/node-configuration.md+++ /dev/null@@ -1,178 +0,0 @@-----title: "Node Configuration Guide"-linkTitle: "Node Configuration"-weight: 15------The `sam-node` acts as a local security gateway and tool proxy for AI agents. While the control plane is the central authority, each Node independently defines its own local tool catalogue and enforces its own local security identity.-------## 1. Node Configuration File (`sam-node.yaml`)--By default, `sam-node` runs without exposing any local tools to the mesh. To expose local tools or strictly enforce your node's network identity, you must create a Node configuration file and pass it to the daemon using the `--config` flag:--```bash-SAM_API_TOKEN="secret" sam-node run --config ./sam-node.yaml-```--### Configuration Schema--The `sam-node.yaml` file supports declaring the node's **Labels**, its local **Services**, and local **Attenuation** security rules.--```yaml-version: "v1alpha1"--# 1. Declare this node's operator labels (see section 4)-labels:- region: us-east-1- team: platform--# 2. Define Local Services-services:- # Example: Expose a local CLI MCP server to the mesh (stdio subprocess)- - type: mcp- name: local-shell-tools- description: "Execute bash commands safely in a local container"- command: ["npx", "-y", "@modelcontextprotocol/server-everything"]-- # Example: Expose an existing HTTP MCP server to the mesh (no subprocess)- - type: mcp- name: remote-docs-server- description: "Proxy an already-running Streamable HTTP MCP server"- target_url: "http://localhost:9001/mcp"-- # Example: Expose a local inference endpoint- - type: inference- name: local-ollama- description: "DeepSeek local inference proxy"- target_url: "http://localhost:11434"--# 3. Define Local Security Identity (Zero Trust)-attenuation:- rules:- # Example: Inject custom Datalog facts asserting local node state- - 'time(2026-06-30T00:00:00Z) <- true;'- policies:- # Example: Custom local deny rule restricting access from untrusted users- - 'deny if user("untrusted_sub_id");'-```-------## 2. Defining Local Services--The `services` array allows you to register endpoints that remote peers in the SAM Network can discover and execute (provided they possess the proper `granted_service_*` credentials issued by the control plane).--| Property | Description |-| :--- | :--- |-| `type` | The protocol protocol type. Supported values are `mcp` (Model Context Protocol), `inference`, or `a2a`. |-| `name` | The unique name of the service (e.g., `git-helper`). This must exactly match the name authorized by the control plane's mesh policy (e.g., `mcp://git-helper`). |-| `description` | A human-readable description published to the mesh discovery catalogue. |-| `command` | *(For MCP)* The executable command array to spawn as a local subprocess, speaking MCP over stdio (e.g. `["node", "index.js"]`). Mutually exclusive with `target_url`. |-| `env` | *(For MCP)* Key-value environment variables passed to the subprocess. |-| `target_url` | *(For MCP/Inference/A2A)* The upstream URL to proxy traffic to. For `type: mcp`, this points to an already-running Streamable HTTP MCP server; SAM does not spawn or manage its lifecycle, but only proxies to it. Mutually exclusive with `command`. Must not carry a credential (`http://user:pass@...` is refused); use `target_auth_path`. |-| `target_auth_path` | *(Optional, with `target_url`)* Path to a file holding the credential the backend requires: a bare `TOKEN` is sent as `Authorization: Bearer TOKEN`, `user:pass` as HTTP Basic. The node reads the file once at start, presents the credential on every request to the backend (overriding any `Authorization` a caller sent) and never advertises or logs it. A file, not a value, because `sam-node.yaml` is copied, committed and rendered into ConfigMaps; mount a Secret and point here, as with `--api-token-path`. |--### Inference Service Path Standards & Proxy Routing--When configuring `target_url` for `type: inference` services (e.g. Ollama, vLLM, OpenAI-compatible backends):-* **Root Target URL Standard**: Always register `target_url` using the base root URL (e.g. `http://localhost:11434` or `http://localhost:8000`), strictly omitting `/v1`.-* **OpenAI Facade Access**: Clients connecting via the node's local OpenAI Facade (`http://localhost:8080/v1`) request paths like `/v1/chat/completions`. SAM automatically proxies these to the backend's root URL.-* **Raw Proxy Access**: If bypassing the Facade and making requests directly via the local egress proxy (`/sam/{peer}/inference/{service}`), the request path must include the explicit `/v1` namespace suffix (e.g. `http://localhost:8080/sam/{peer}/inference/{service}/v1/chat/completions`).--### A2A Service Routing--When configuring `type: a2a` services (Agent2Agent protocol agents):-* **URL backends only**: register the agent's local HTTP endpoint as `target_url`. `command` backends are rejected.-* **Raw Proxy Access**: remote peers reach the agent at `http://localhost:8080/sam/{peer}/a2a/{service}/...`. For the agent card at `.../.well-known/agent-card.json`, the caller's node impersonates the endpoint: it fetches the card from the agent (A2A v1.0 format) and serves a regenerated one whose interface URLs point back at this mesh path; protocol bindings the mesh cannot carry (gRPC) are dropped, streaming is advertised off, and the original signatures are removed since the content changed.-* **Label-gated egress**: setting `X-Sam-Required-Labels: key=value[,key=value]` on a raw a2a request makes the caller's node verify the provider's control-plane-attested labels and refuse fail-closed (HTTP 403) before any data leaves the node. The header is stripped before forwarding.-* **Runnable example**: the [A2A Chat use case](../../use-cases/chat-a2a/) walks through hosting an a2a agent on a kind mesh and talking to it with a stock `a2a-sdk` client.-------## 3. Defining Local Security (Target Attenuation)--In a Zero Trust architecture, the destination node is entirely responsible for verifying that it is the intended recipient of an incoming request.--While the control plane limits token capabilities based on target restrictions (e.g., `target_restricted()` or `target_unrestricted()`), the destination node evaluates these dynamically. The node automatically resolves its local identity context based on its configuration, generating facts internally (such as `allow_network_target($fact, $value)`).--If the caller's token has target restrictions, the connection will only be allowed if the token's `granted_target_*` facts match the dynamically injected identity of the node. You do **not** need to write manual Datalog rules to enforce this mechanism; it is baked directly into the node middleware via baseline policies.--### Local Custom Policies-You can further restrict access using the `attenuation` block. Local policies defined here are evaluated **before** the baseline rules. This means local administrators can write custom rules that explicitly `deny` access based on custom logic, overriding broad access granted by the control plane.--1. **`rules`**: Inject custom Datalog facts asserting local node state (e.g., `time($time)`).-2. **`policies`**: Add local restrictions (e.g., `deny if user("banned_user");`).-3. **`checks`**: Require a condition for any connection to succeed (e.g., `check if label("region", "eu-west-1");`).-------## 4. Labels & Data Sovereignty--SAM supports attested key=value labels (e.g. `region`, `team`) so a request never leaves a required scope. Cloud providers, on-prem operators, and countries all name regions differently, so SAM imposes no built-in taxonomy or hierarchy: composition (e.g. also attesting a coarser value) is entirely up to the operator.--### Declaring labels (provider)--Declare the node's operator labels in its configuration file:--```yaml-version: "v1alpha1"-labels:- region: us-east-1- team: platform-```--Both `sam-node join` and `sam-node run` read this file (`--config` is a global flag), so the labels are declared on whichever of them enrols the node. Keys are 1-63 characters of `[a-zA-Z0-9_.-]`; a value must be non-empty, at most 255 characters, and free of `,`, `=` and control characters, since the wire format is a comma-separated `key=value` list. A malformed entry stops the node at startup.--Labels are declared at enrollment and **attested by the control plane**, but only the ones a role permits. Set `allowed_labels` on the node's role (see [control plane configuration](../control-plane-configuration/)); a role granting none means the node can declare none, and enrollment is refused if it tries. This applies to all three enrollment paths, including bootstrap requests an administrator approves by hand: approving says the identity may join, so the role grant is what says which labels it may carry. The control plane then mints one signed `label(key, value)` fact per declared label into the node's Biscuit. Matching is exact and case-sensitive; an empty value means no claim for that key.--### Requiring labels (consumer)--On the sidecar's OpenAI-compatible endpoints, constrain a request with the `X-Sam-Required-Labels` header (comma-separated `key=value` pairs, any-of):--```bash-curl http://localhost:8080/v1/chat/completions \- -H "Authorization: Bearer $SAM_API_TOKEN" \- -H "X-Sam-Required-Labels: region=us-east-1" \- -d '{"model":"test-model","messages":[{"role":"user","content":"hi"}]}'-```--The `call_remote_tool` MCP tool accepts the same requirement via its `required_labels` parameter.--Enforcement is fail-closed and cryptographic: gossiped labels only rank candidate providers, and before any request data leaves your node the sidecar verifies the provider's control-plane-signed Biscuit and checks its attested `label()` facts. Providers that return no identity or lack a matching fact are rejected.--### Requiring labels of every provider (operator floor)--The header above is the caller's requirement, and a caller that sends no header is unconstrained. To hold a boundary the caller cannot waive, set a floor in the node config:--```yaml-egress:- require_labels: # every pair must hold, and callers cannot widen it- jurisdiction: eu- compliance: gdpr-```--Every remote provider must then attest all of these before the node sends it anything, whether or not the caller asked for labels. A caller may still narrow the choice further with `X-Sam-Required-Labels`; the two are checked independently, so a caller naming an unrelated label cannot stand in for the floor.--Note the difference in meaning between the two, which follows from what each is for:--| | Semantics |-|---|---|-| `X-Sam-Required-Labels` (caller) | **any** pair is enough — the caller is choosing among acceptable providers |-| `egress.require_labels` (operator) | **every** pair must hold — the operator is drawing a boundary |--A floor naming a label no provider attests reaches nothing, which makes it a usable egress kill switch. Omit the block entirely to keep the previous behaviour, where the requirement is whatever the caller supplied.--### Restricting callers by label (provider)--Because every enrolled node's token carries its attested label facts, a provider can require callers to hold a label with a single local check in its `attenuation` block:--```yaml-attenuation:- checks:- - 'check if label("region", "us-east-1");'- - 'check if label("jurisdiction", "eu");'-```--For full details on territorial enforcement, regulatory compliance (GDPR Art 44-49, EU Cloud Sovereignty Framework), and cryptographic evidence verification, see the **[Digital & Data Sovereignty Guide](../sovereignty/)**.diff --git a/site/content/docs/user/running-agents.md b/site/content/docs/user/running-agents.mddeleted file mode 100644index 6d8fd4a4..00000000--- a/site/content/docs/user/running-agents.md+++ /dev/null@@ -1,527 +0,0 @@-----title: "Running agents on SAM"-description: "The canonical way to deploy an agent: ship the harness, let the mesh provide the model, the tools and the network"-weight: 15------## What you actually deploy--An agent is usually three things bolted together: some logic that decides what-to do next, a model that does the thinking, and a set of tools it can act-with. Deploying one normally means deploying all three, plus the credentials-for the model, plus network access broad enough for the tools to work — which-in practice means the agent can reach the whole internet, because nobody knows-in advance which addresses it will need.--On SAM you deploy **only the first one**. The mesh provides the other two, and-the network the agent gets is exactly the network its policy describes.--The piece you write and ship is the **harness**: the loop that holds the-conversation, decides when to call a tool, and knows when the work is done.-Everything else is asked for by name at runtime.--| | Who provides it | How the agent asks |-| --- | --- | --- |-| **Harness** | You. This is your code. | — |-| **Inference** | The mesh, from whichever peer policy allows | `http://mesh.sam.alt/v1` |-| **Tools (MCP)** | The mesh, local and remote peers alike | `http://mesh.sam.alt/mcp` |-| **Network** | The boundary, per flow, by name | ordinary HTTP to allowed names |--The consequence worth pausing on: **the harness holds no credentials**. There-is no model API key in the sandbox, no mesh token, no service account file.-This is not a convenience. An agent that holds a key can leak a key, and an-agent that can be prompt-injected into leaking one will eventually be.--## The three concepts--### Inference is a name, not an endpoint--The agent asks `mesh.sam.alt` for a model. It does not know which peer answers,-and it cannot find out. Policy decides which providers this agent may use, and-the mesh picks among them.--```python-client = AsyncOpenAI(base_url="http://mesh.sam.alt/v1", api_key="unused")-```--That is an ordinary OpenAI SDK client. Nothing about it is SAM-specific, which-matters: if running on the mesh required a bespoke client, every existing agent-would have to be rewritten to move onto it.--The `api_key` is a placeholder because the SDK insists on one. The real-authentication happens outside the sandbox, where the agent cannot reach it.--### Tools arrive over MCP, and the list is per-agent--The same name serves tools:--```python-async with streamable_http_client("http://mesh.sam.alt/mcp") as (read, write):- async with ClientSession(read, write) as session:- await session.initialize()- tools = await session.list_tools()-```--The transport is Streamable HTTP, which is what the mesh serves. The older SSE-transport is answered with 400, and that arrives late enough to look like a-network problem rather than a protocol one.--Two agents on the same node can list different tools, because the mesh answers-according to who is asking. Tools hosted by other peers appear alongside local-ones and are called identically — the agent cannot tell, and does not need to.--A refused tool call comes back as an error the model can read, not a crash. A-denial is information the agent should reason about, not an outage.--### The boundary is the only way out--The sandbox has no network interface, no DNS resolver and no route. It has a-single Unix socket, on which `sam-box` serves named HTTP tunnels: CONNECT for-TCP, connect-udp for UDP.--Every connection the agent opens arrives there as a **name**, and the boundary-decides what it is:--- `mesh.sam.alt` — the mesh's own surface: inference and tools.-- `<service>.mcp.sam.alt` — a specific mesh service, provider chosen by discovery.-- anything else — matched against the agent's egress allowance, and refused if absent.--Because the destination arrives as a name rather than an address, policy can be-written about `api.github.com` rather than about whatever IP that resolves to-this week. And because the sandbox has no other route, a refusal is not a-speed bump the agent can route around — there is nothing to route around it-with.--### Identity is asserted about the agent, never by it--`sam-box` reads a **bundle** that names the agent and describes what it may-reach. The bundle lives outside the sandbox. The agent never sees it and cannot-change it.--```yaml-version: v1-agent:- id: researcher-1.prod.acme.example- external_id: system:serviceaccount:agents:researcher-egress:- allow:- - api.github.com-```--Writing that file is not enough to become that agent. `sam-box` verifies a-platform credential — a Kubernetes projected service account token, for example-— and accepts the bundle only if the credential's subject matches-`external_id`. The mesh identity is a claim about a platform identity that-something else already vouched for.--On every request the gateway asserts the agent to the node, overwriting-anything the sandbox tried to set. Mesh policy can then be written about the-agent rather than about the host it happens to run on.--The agent ID in the bundle is not free-form. Every node has a set of agent-namespaces it is allowed to use, set by its mesh role (`allowed_agents`, see-[control plane configuration](../control-plane-configuration/)). The `agent.id`-in the bundle has to fall inside one of them.--For example, if the node is granted `*.c1.acme.example` and the bundle says-`researcher-1.prod.acme.example`, other nodes reject the request, because the-node is claiming an agent it has no grant for. A node with no grant cannot name-any agent at all.--The namespace belongs to the node and the identifier belongs to the agent. That-is why an agent keeps its name when it moves: pause it, migrate it, resume it-behind another node in the same namespace, and nothing downstream changes.--## The architecture--```mermaid-flowchart LR- subgraph sandbox["sandbox: no network, no DNS, no credentials"]- H["agent harness<br/>(your code)"]- end-- subgraph host["host"]- B["sam-box<br/>one per agent<br/>holds no mesh identity"]- N["sam-node<br/>one per host<br/>the mesh member"]- end-- M(["the mesh<br/>models · tools · peers"])-- H -- "CONNECT over a unix socket" --> B- B -- "node API socket<br/>+ X-Sam-Agent" --> N- N <--> M- B -. "allowed names only" .-> E([internet])-```--Two separations do the work.--**One `sam-node` per host, one `sam-box` per agent.** The node is the mesh-member: it enrols, holds the mesh identity and maintains peer connections. The-box holds no identity of its own — it consumes the node's API socket on the-agent's behalf and names the agent on every request. Adding an agent therefore-costs a `sam-box`, not a mesh member: [measured at about 25 MB and 150 ms](../../scale-report/),-rather than a new enrolment and a new peer in the DHT. One node has been run-with a thousand agents behind it.--**The node's API stays on the node's side of the boundary.** An agent never-reaches it. What the agent gets is the curated surface the gateway builds on-top: inference, tools, and permitted egress. The node's own control endpoints —-service registration, peer management — are not part of it.--## Running the example--The example harness is in-[`development/examples/agent-harness`](https://github.com/google/sam/tree/main/development/examples/agent-harness).-It is about a hundred lines and does something real: discovers tools, calls a-model, runs the tool loop, stops when done.--### 1. A node--You need a `sam-node` enrolled in a mesh, serving its API on a socket:--```bash-sam-node run --socket-path /run/sam/node.sock --data-dir /var/lib/sam-```--### 2. A boundary for the agent--```bash-sam-box run \- --socket /run/sam/agent.sock \- --sidecar-socket /run/sam/node.sock \- --bundle ./bundle.yaml \- --credential-issuer https://kubernetes.default.svc \- --credential-audience sam-```--Credential verification is on by default. For a local experiment where there is-no issuer to verify against, `--insecure-unverified-bundle` turns it off and-says plainly what you are giving up: whoever can write the bundle decides which-agent this sandbox is.--### 3. The sandbox--The agent needs the boundary socket and nothing else. For a container:--```bash-docker run --rm \- --network none \- --cap-add NET_ADMIN \- --device /dev/net/tun \- -v /run/sam/agent.sock:/run/agent.sock \- agent-harness "Summarise the open issues in our repo"-```--`--network none` is the assertion, not just the arrangement. If any of this-worked because the container could route somewhere, it would be proving nothing.--Notice what is *not* passed: no API key, no mesh token, no endpoint, and **no-proxy variable**. `nano-init` runs as PID 1, builds one `tun0`, makes it the-default route and terminates the sandbox's TCP itself, opening a named CONNECT-tunnel to the boundary per connection. The agent asks for `mesh.sam.alt` like-any other host and its traffic leaves through the tun because there is nowhere-else for it to go.--That distinction is worth dwelling on, because the obvious alternative is to set-`HTTP_PROXY` and be done. That is the wrong layering: an agent that has to-*cooperate* with its own confinement is not confined. The next library that-ignores the convention, the next subprocess that clears its environment, the-next protocol that is not HTTP — each one is outside the boundary. Routing does-not have that failure mode, because nothing has to agree to it.--The sandbox image needs nothing else: no proxy helper, no `socat`, no-`iproute2`. That matters more than tidiness, since image size is what decides-how many agents fit on a host.--### 4. Watch what it did--```bash-curl -s http://127.0.0.1:9600/metrics | grep sam_box_flows_total-```--Every flow the agent opened, by route class and outcome, including the ones-that were refused. Refusals never appear as latency, so counting them is the-only way to see them.--## In a microVM--A container shares the host kernel. For an agent running code a model wrote, or-code from somewhere you do not control, that may not be a boundary you want to-rely on. Firecracker gives each agent its own kernel for a few tens of-milliseconds of boot time.--The layering is unchanged, and that is the useful part — the microVM swaps out-how the sandbox reaches the socket, not what the agent does. The same-`nano-init` binary runs as PID 1 in both:--```mermaid-flowchart LR- subgraph vm["Firecracker microVM: own kernel, no NIC"]- A["agent harness"]- T["nano-init<br/>tun0, default route<br/>gVisor TCP stack"]- A -- "plain HTTP to mesh.sam.alt" --> T- end- T -- "vsock CID 2" --> V["host: <uds>_1080"]- V --> B["sam-box"]-```--The guest has no network device at all. `nano-init` presents a `tun0` that is-the default route, terminates TCP on it, and opens a named CONNECT tunnel to-the boundary for each connection. The harness makes ordinary HTTP requests-and needs no configuration, because from inside the VM there is nothing else it-could be doing.--The only difference from the container is how the boundary is named: a path when-it is bind-mounted in, `vsock://2:1080` when there is no shared filesystem.-Nothing else in the sandbox knows which kind it is.--Names are resolved by the boundary rather than in the guest, which is why the-sandbox needs no resolver: the virtual DNS answers with a synthetic address per-name and remembers the pairing, so `mesh.sam.alt` reaches the boundary as a-name and the boundary chooses a provider for it. An address the guest never-resolved stands for no name, and a flow to one is refused.--Every address inside the sandbox is synthetic: IPv4 out of `100.64.0.0/10`-(CGNAT space, RFC 6598) and IPv6 out of `100::/64` (the discard-only prefix,-RFC 6666). Link-local would have been the leak-proof choice, but SSRF guards-in HTTP clients commonly block `169.254/16` and would break legitimate egress;-the discard prefix keeps the leak-proofing for IPv6, since a packet that ever-escapes through a stray interface is blackholed by the first conforming-router. Neither range can be confused with a real destination — a sandbox-numbered out of `10.0.0.0/8` will eventually be deployed somewhere that-already uses it.--One detail costs people an afternoon: Firecracker's vsock multiplexes guest-connections onto **`<uds_path>_<port>`** on the host. A guest connecting to CID-2 port 1080 arrives on `/var/run/sam-vm-1.vsock_1080`, so that is the exact path-`sam-box --socket` must serve. The host never speaks AF_VSOCK itself, which is-why the same `sam-box` works for containers and microVMs with no code in it that-knows the difference.--Another costs a day: **the guest kernel must have `CONFIG_TUN=y`**. The stock-Firecracker CI kernels do not — they carry vsock and virtio and little else — so-a sandbox on one of them cannot build a tun, has no route, and its init exits-before it can explain why. Of the published CI kernels, 6.18 has it and 5.10 and-6.1 do not; the `.config` is published next to each image, so this is worth-checking before building a rootfs around one.--## In a Kubernetes pod--The two profiles above are handed a network namespace with nowhere to go: one by-`--network none`, one by having its own kernel. **A pod gives you neither.**-Every container in a pod shares a single network namespace, so there is no-per-container `--network none`, and the `/etc/resolv.conf` the kubelet writes is-shared by all of them. Left alone, an agent container would sit on the pod's-network with the pod's DNS, and `nano-init` would add a `tun0` beside `eth0`-that the agent could simply route around.--So for this profile `nano-init` builds the namespaces itself, with-`--create-namespaces`:--```yaml-apiVersion: v1-kind: Pod-metadata:- name: agent-spec:- volumes:- - name: sam-uds # the only thing the three containers share- emptyDir: {}- - name: scratch # somewhere to put a private resolv.conf- emptyDir: {}- - name: tun- hostPath:- path: /dev/net/tun- type: CharDevice- containers:- # The mesh member. It owns the identity; the agent never sees it.- - name: sam-node- image: ghcr.io/google/sam-node:latest- args:- - run- - --jwt-path=/var/run/secrets/tokens/sam-token- - --bind-addr= # no TCP listener, so there is no token to leak- - --socket-path=/var/run/sam/node.sock- volumeMounts:- - { name: sam-uds, mountPath: /var/run/sam }-- # The boundary. Reaches the mesh only by dialling the node's socket.- - name: sam-box- image: ghcr.io/google/sam-box:latest- args:- - run- - --socket=/var/run/sam/agent.sock- - --sidecar-socket=/var/run/sam/node.sock- - --egress-allow=api.github.com- volumeMounts:- - { name: sam-uds, mountPath: /var/run/sam }-- # The sandbox. No capabilities, no credential, and after nano-init- # starts, no network.- - name: agent- image: your-agent-image- command: ["/usr/local/bin/nano-init", "run", "--create-namespaces",- "/var/run/sam/agent.sock", "python3", "/app/agent.py"]- volumeMounts:- - { name: sam-uds, mountPath: /var/run/sam }- - { name: scratch, mountPath: /tmp }- - { name: tun, mountPath: /dev/net/tun }- # The sandbox's own resolver, supplied by the kubelet.- - { name: resolv, mountPath: /etc/resolv.conf, subPath: resolv.conf }-```--With the matching volume and a ConfigMap holding one line:--```yaml- - name: resolv- configMap:- name: sandbox-resolv-----apiVersion: v1-kind: ConfigMap-metadata:- name: sandbox-resolv-data:- resolv.conf: |- nameserver 100.127.255.253-```--Note what is **not** there: no `securityContext`, no added capabilities, no-privileged flag, and no device plugin. Three things are needed instead, and each-is easy to get wrong in a way that does not name itself.--**The TUN device, bind-mounted.** That is all — the `hostPath` above. It is-worth saying plainly because the obvious worry turns out not to apply: the-device cgroup does *not* deny `/dev/net/tun`, so `open()` succeeds without a-device plugin and without `--device`. What is actually gated is the `TUNSETIFF`-that follows, and that is a capability question rather than a device one.--**No capabilities, deliberately.** Creating a network namespace normally needs-`CAP_SYS_ADMIN`, and creating a tun needs `CAP_NET_ADMIN`. Rather than asking-for either, `nano-init` creates a **user namespace** first, where it is root and-holds both over the namespaces it then makes. Granting `CAP_SYS_ADMIN` alone is-in fact worse than granting nothing: the namespace gets created, and then the-tun fails for want of `CAP_NET_ADMIN`.--**The sandbox needs a `resolv.conf` of its own, and the kubelet should supply-it.** A pod's `resolv.conf` is one file shared by every container, so pointing-DNS at the sandbox's resolver by writing that file would point `sam-node` at it-too — at an address that only exists inside the sandbox's network namespace.-`nano-init` can bind-mount a private one, but that bind is the single operation-containerd's default AppArmor profile denies:--```console-user+net : ok-user+mount (unchanged propagation): ok-bind mount inside : FAILED-```--Mounting the file per container avoids the question. `nano-init` checks whether-`/etc/resolv.conf` already names its resolver and, if so, does nothing — so the-container needs no `securityContext` at all: no capabilities, not privileged, no-AppArmor exception.--**Why not `dnsConfig`?** Because `dnsPolicy` and `dnsConfig` are PodSpec fields-and apply to every container in the pod. Measured on GKE, the per-container-mount gives you this:--```console-[sandbox] nameserver 100.127.255.253-[node] search default.svc.cluster.local ... nameserver 34.118.224.10-[node] cluster DNS works-```--With `dnsConfig`, `sam-node` would get `100.127.255.253` as well and could no-longer resolve the control plane.--**If you do not supply one, it needs somewhere writable.** Without the mount-above, `nano-init` falls back to bind-mounting a private `resolv.conf` itself,-which needs a real file to bind and therefore a writable path — an `emptyDir` on-`/tmp` will do. That path also needs a mount namespace, and the bind is what-AppArmor refuses, so on a default GKE node the fallback fails and the supplied-file is the way through. Verified on GKE 1.35: with the file mounted, the-sandbox starts under `cri-containerd.apparmor.d` with no `securityContext`;-without it, `nano-init` reports `permission denied` creating the namespaces.--### The harness must be nano-init's child--This is the part to get right, and it is easy to get wrong precisely because the-wrong version appears to work.--`nano-init` creates the namespaces and then **starts the agent as its own child-process**, which is how the agent inherits them. So the container's `command`-has to be `nano-init`, with the harness as its arguments:--```yaml-command: ["/usr/local/bin/nano-init", "run", "--create-namespaces",- "/var/run/sam/agent.sock", "python3", "/app/agent.py"]-```--A container that starts the harness directly — or that starts `nano-init`-alongside it rather than in front of it — leaves the harness in the pod's-network namespace, with `eth0` and the cluster's routes. It will run, it will-reach the boundary if you point it there, and it will not be sandboxed at all.--Check it rather than assume it:--```console-$ kubectl exec -c agent agent -- ip -o link show | cut -d: -f2- lo- tun0-```--### If the agent serves the mesh--An agent can publish an MCP service of its own, and delivering a request to it-means reaching *into* the sandbox — which is the direction all of this exists to-prevent. The gateway cannot dial the agent, because the agent's `127.0.0.1` is-inside a namespace the gateway is not in.--The answer is a second Unix socket, for the same reason the first one works: a-pathname socket is a filesystem object, so network namespaces do not apply to-it. `nano-init` serves it from inside the sandbox and connects each arriving-request to the agent's port.--```yaml-# in the agent container-command: ["/usr/local/bin/nano-init", "run", "--create-namespaces",- "--ingress-socket", "/var/run/sam/agent-ingress.sock",- "/var/run/sam/agent.sock", "python3", "/app/agent.py"]--# in the sam-box container-args:- - run- - --socket=/var/run/sam/agent.sock- - --sidecar-socket=/var/run/sam/node.sock- - --agent-ingress-socket=/var/run/sam/agent-ingress.sock- - --bundle=/etc/sam/bundle.yaml-```--`--agent-ingress-socket` is required whenever the bundle grants ingress, and-`sam-box` refuses to start without it. There is no fallback on purpose: the only-other address available is one in the gateway's own network namespace, which in-a pod is the pod's — where `sam-node`'s API and every sidecar are listening —-and the port would be the agent's to choose. An agent could otherwise announce-a service whose backend was the node that vouches for it.--What the agent may serve is still the bundle's decision, not the agent's. The-agent chooses the port, because that is the part only it knows.--## Why this shape--The tempting alternative is to give the agent a token and a proxy and trust it-to behave. That fails in a specific way: the agent is driven by a model, the-model is driven by text it did not write, and any instruction that can reach-the model can attempt to reach the network. Holding a credential is what makes-that attempt worth making.--Here the agent has nothing to steal and nowhere to go. Its identity is asserted-by something it cannot influence, its model and tools are granted per-agent, and-its network is a list of names checked on every flow. What it may do is a-property of the deployment, not of how well the prompt was written.--## See also--- [Agent architecture](../../agent-architecture/) — the design decisions and why the boundary is named HTTP tunnels-- [What an agent costs](../../scale-report/) — measured memory, startup and enforcement overhead-- [Secure gateway](../secure-gateway/) — the gateway's configuration surfacediff --git a/site/content/docs/user/secure-gateway.md b/site/content/docs/user/secure-gateway.mddeleted file mode 100644index 09370848..00000000--- a/site/content/docs/user/secure-gateway.md+++ /dev/null@@ -1,162 +0,0 @@-----title: "Sandbox Gateway Guide"-linkTitle: "Sandbox Gateway"-weight: 30------`sam-box` is the sandbox gateway: one per agent sandbox, serving the boundary an-agent's traffic leaves through. An unmodified agent reaches mesh inference and-tools by name, reaches allowlisted destinations on the internet, and reaches-nothing else.--For the reasoning behind the design, see-[Agent Architecture]({{< relref "/docs/agent-architecture" >}}).-------## 1. What it is, and is not--`sam-box` holds **no libp2p host, no enrolment and no mesh identity**. It-consumes a local `sam-node` over that node's API socket, and offers the sandbox-a curated surface built on top of it.--```mermaid-sequenceDiagram- participant Agent as Agent (inside the sandbox)- participant Box as sam-box (sandbox boundary)- participant Node as sam-node (mesh member)- participant Mesh as The mesh / the internet-- Agent->>Box: CONNECT mesh.sam.alt:80- Box->>Box: Classify by name, apply policy- Box->>Node: /v1/chat/completions over the node's API socket- Node->>Mesh: Route to a provider, authorized by the node's Biscuit- Mesh-->>Agent: Response-```--The split matters. A `sam-node`'s API can register services under the node's-identity and proxy to any peer, and reaching its socket is itself the-credential. So an agent never touches it: `sam-box` is the node's consumer, the-agent is the mesh's consumer through `sam-box`.-------## 2. Running it--```bash-sam-box run \- --socket=/var/run/sam/agent.sock \- --sidecar-socket=/var/run/sam/node.sock \- --egress-allow=api.github.com \- --egress-allow='*.pypi.org'-```--| Flag | Meaning |-|---|---|-| `--socket` | The sandbox-facing socket. Created 0600: its permissions are the credential. |-| `--sidecar-socket` | The local `sam-node`'s API socket (`sam-node run --socket-path`). |-| `--bundle` | The agent's identity and egress allowance, declared by the platform. |-| `--egress-allow` | A destination outside the mesh the agent may reach. Repeatable. **Empty means nothing is reachable.** |-| `--credential-issuer`, `--credential-audience` | The issuer whose credentials attest an agent's identity. **Required with `--bundle`.** |-| `--insecure-unverified-bundle` | Trust the bundle without a credential behind it. An explicit choice, not a default. |--Egress entries are matched on the name the agent asked for, never on a resolved-address. A wildcard covers subdomains only: `*.pypi.org` matches-`files.pypi.org` but not `pypi.org`, and never `evilpypi.org`.--A bundle names an agent, and that name is what the whole mesh then authorizes-against — so by default it has to be backed by the credential the platform-issued to that workload. Running without that check is available, because some-deployments have no platform issuer, but it takes a flag that is visible in a-process listing and a pod spec rather than something quietly left unset.--The issuer is a flag rather than a bundle field on purpose: the bundle travels-with the agent, so an issuer named there could be one an attacker controls, and-their self-signed credential would verify perfectly.-------## 3. What the agent sees--```bash-OPENAI_BASE_URL=http://mesh.sam.alt/v1-MCP_URL=http://mesh.sam.alt/mcp-```--No proxy variables, no CA bundle, no token: the agent holds no credential at-all. `mesh.sam.alt` serves exactly four paths — `/v1/models`,-`/v1/chat/completions`, `/v1/completions` and `/mcp`. Anything else is refused-with 403 and never reaches the node.--A specific service can be addressed by its own name instead of letting policy-choose: `http://code-reviewer.mcp.sam.alt/`.--Destinations that policy refuses fail the CONNECT handshake with a 403 and a-`Boundary-Reason` header, which the sandbox's own network stack turns into an-ordinary connection refusal — so an agent sees "refused" rather than a hang,-and an operator reading the log sees the reason in words.-------## 4. Connecting a sandbox to the socket--The sandbox has no network of its own. `nano-init` terminates its TCP/IP in-userspace on a `tun` device and points every flow at the boundary socket as a-named HTTP tunnel — CONNECT for TCP, connect-udp for UDP — carrying the-destination *name*:--| sandbox | how it reaches the socket |-|---|---|-| Firecracker microVM | vsock; firecracker terminates it as `<uds_path>_<port>` on the host |-| container with `network=none` | the socket is bind-mounted in |--For a quick test without a sandbox, curl speaks the TCP half natively through-any HTTP proxy client; bridge a TCP port to the socket first:--```bash-socat TCP-LISTEN:1080,fork,reuseaddr UNIX-CONNECT:/var/run/sam/agent.sock &-curl --proxy http://127.0.0.1:1080 http://mesh.sam.alt/v1/models-```-------## 5. Serving a mesh service--An agent can serve, not only call. Its bundle says what it is allowed to serve;-the agent itself says when it is ready and on which port:--```yaml-ingress:- - {name: code-reviewer, type: mcp}-```--```bash-curl -X POST http://mesh.sam.alt/ingress \- -d '{"name":"code-reviewer","type":"mcp","port":8080}'-```--The gateway then registers the service with the node. The agent never does: it-cannot name the URL the mesh routes to, and it cannot claim a name its bundle-does not list. When the gateway stops, the service is withdrawn, so a suspended-agent stops being advertised without anyone reconciling anything.--Reaching back into the sandbox cannot mean dialling the agent: a sandbox has a-network namespace of its own, so the gateway's `127.0.0.1` is its own loopback-and not the agent's. Delivery therefore goes over a second Unix socket, served-from inside the sandbox by `nano-init --ingress-socket` and dialled by-`sam-box --agent-ingress-socket`. That flag is required whenever a bundle grants-ingress: the gateway refuses to start without it, because the only other address-available is one in its own network namespace, on a port the agent chooses.-------## 6. Not yet implemented--Deliberately absent, and tracked in the architecture document:--* **Secret injection** for external destinations. The ephemeral CA and the- injection machinery exist, but are not wired into this datapath.-* **The ingress reverse channel**, for sandboxes the gateway cannot dial.-* **Credential rotation.** A bundle's credential is verified when the gateway- starts. Platforms rotate projected tokens, and re-verifying on rotation is- the connector interface's `Refresh` operation, which is not built yet.diff --git a/site/hugo.toml b/site/hugo.tomlindex d06e2060..ce55e13b 100644--- a/site/hugo.toml+++ b/site/hugo.toml@@ -21,54 +21,55 @@ contentDir = "content"[markup.goldmark.renderer]unsafe = true-# Enable Docsy's navigation structure-sectionPagesMenu = "main"-[module][[module.imports]]path = "github.com/google/docsy"[[module.imports]]path = "github.com/google/docsy/dependencies"+# Top navigation. The section _index.md files carry no menu entries of their+# own; everything is listed here so the order is in one place.[menu][[menu.main]]identifier = "docs"- name = "Overview"- title = "Overview"+ name = "Docs"+ title = "Documentation"url = "/docs/"weight = 1[[menu.main]]- identifier = "quickstart"- name = "Quick Start"- title = "Quick Start"- url = "/docs/quickstart/"+ identifier = "getting-started"+ name = "Getting started"+ url = "/docs/getting-started/"weight = 2[[menu.main]]- identifier = "user"- name = "User Guides"- title = "User Guides"- url = "/docs/user/"+ identifier = "concepts"+ name = "Concepts"+ url = "/docs/concepts/"weight = 3[[menu.main]]- identifier = "integrations"- name = "Agent Integrations"- title = "Agent Integrations"- url = "/docs/integrations/"+ identifier = "guides"+ name = "Guides"+ url = "/docs/guides/"weight = 4[[menu.main]]- identifier = "development"- name = "Developer Guides"- title = "Developer Guides"- url = "/docs/development/"+ identifier = "reference"+ name = "Reference"+ url = "/docs/reference/"weight = 5+ [[menu.main]]+ identifier = "preview"+ name = "Preview"+ url = "/docs/preview/"+ weight = 6+[params]github_repo = "https://github.com/google/sam"- github_subdir = "docs"+ github_subdir = "site"github_branch = "main"[params.ui]diff --git a/site/layouts/index.html b/site/layouts/index.htmlindex f5086c37..55adaf6b 100644--- a/site/layouts/index.html+++ b/site/layouts/index.html@@ -14,13 +14,13 @@<!-- Hero Branding --><div class="hero-brand-col" style="align-items: center;"><h1 class="landing-title">SAM</h1>- <p class="landing-subtitle">Sovereign Agent Mesh</p>+ <p class="landing-subtitle">An agent mesh</p><p class="landing-description" style="text-align: center; max-width: 600px; margin-left: auto; margin-right: auto;">- A zero-config, zero-trust decentralized P2P network built specifically for autonomous AI agents.+ A private network for AI agents: publish tools and models, find and call them across machines, with every call authenticated and authorized by name.</p><div class="landing-actions" style="justify-content: center;">- <a href="{{ "/docs/" | relURL }}" class="btn-sleek btn-cyan">Enter Mesh Docs</a>+ <a href="{{ "/docs/" | relURL }}" class="btn-sleek btn-cyan">Documentation</a><a href="{{ .Site.Params.github_repo }}" target="_blank" rel="noopener" class="btn-sleek btn-dark">GitHub</a></div></div>