Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: dial routers over WebSocket, so both SDKs join sam-one
Antonio Ojeab4a92f09226e
diff --git a/sdk/README.md b/sdk/README.mdindex 0ad47dae..1475825d 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -40,7 +40,7 @@ Milestones 1 to 5 are implemented and tested in both languages:| Signed key-set sync (`GET /keys`) | yes | yes || Persisted state (identity and credential, owner-only files) | yes | yes || Biscuit verification of a peer's credential (signature, expiry, peer binding, roles, labels) | yes | yes |-| libp2p host as `sam-node` configures it (TCP, TLS, yamux) | yes | yes |+| libp2p host as `sam-node` configures it (TCP and WebSocket, TLS, yamux) | yes | yes || `/sam/auth/1.0.0`, both sides; join = handshake with a router and check its role | yes | yes || Circuit relay v2 reservation on the router; dial and accept through it | yes | yes || Service discovery in the mesh DHT (`/sam/kad/1.0.0`) | yes | yes |@@ -373,8 +373,12 @@ holds against the control plane's records.### Milestone 2 — join the mesh (done)-- libp2p host per SDK, configured as `sam-node`'s: TCP, TLS, yamux,- identify, circuit relay v2 client. JS: `libp2p`, `@libp2p/tcp`,+- libp2p host per SDK, configured as `sam-node`'s: TCP and WebSocket, TLS,+ yamux, identify, circuit relay v2 client. The testnets' routers listen on+ TCP; `sam-one`'s router is a WebSocket listener on the port that serves+ its API (`/ws`, or `/wss` behind a tunnel), so a member reaches it over+ WebSocket or not at all; `tests/integration/standalone_sdk_test.go` holds+ both SDKs to it. JS: `libp2p`, `@libp2p/tcp`, `@libp2p/websockets`,`@libp2p/tls`, `@chainsafe/libp2p-yamux`, `@libp2p/circuit-relay-v2`,`@libp2p/identify`. Python: `libp2p>=0.7` (`security.tls`,`stream_muxer.yamux`) plus the SDK's own relay client; py-libp2p is@@ -586,8 +590,11 @@ same commit as the Go components they talk to.- Publishing services from an SDK: an MCP server, a named inference or A2Aservice, a DHT record or a catalog entry. That is `sam-node`'s job; see[Agents, not services](#agents-not-services).-- A browser build. Node.js only until the transport story for browsers- (WebTransport or WebRTC to routers) is designed.+- A browser build. The JS SDK dials routers over WebSocket, which a browser+ can do, but it still runs on Node.js only: the routers and nodes accept+ libp2p TLS alone, which a browser cannot speak (it would need Noise on the+ Go side), and the SDK reads its state and speaks HTTP/1.1 on streams with+ Node's `fs` and `http`.- Any SDK-only wire protocol. If an SDK needs something the Go node does notspeak, the Go node learns it first.diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.jsonindex 9147e19d..73101ea1 100644--- a/sdk/js/package-lock.json+++ b/sdk/js/package-lock.json@@ -23,6 +23,7 @@"@libp2p/tcp": "^11.0.28","@libp2p/tls": "^3.1.10","@libp2p/utils": "^7.4.1",+ "@libp2p/websockets": "^10.1.21","@modelcontextprotocol/sdk": "^1.30.1","@multiformats/multiaddr": "^13.0.3","libp2p": "^3.3.11",@@ -657,6 +658,32 @@"uint8arrays": "^6.0.0"}},+ "node_modules/@libp2p/websockets": {+ "version": "10.1.21",+ "resolved": "https://registry.npmjs.org/@libp2p/websockets/-/websockets-10.1.21.tgz",+ "integrity": "sha512-2iItZGEfTlGFUEcFCghtlsIiQ+fBowopysBB/8ya0MvZkRic/6o9oSklWT5pWDmXtmqmbp1Dko/iLcBOhDOgFw==",+ "dependencies": {+ "@libp2p/interface": "^3.3.0",+ "@libp2p/utils": "^7.4.1",+ "@multiformats/multiaddr": "^13.0.3",+ "@multiformats/multiaddr-matcher": "^3.0.2",+ "@multiformats/multiaddr-to-uri": "^12.0.0",+ "main-event": "^1.0.1",+ "p-event": "^7.0.0",+ "progress-events": "^1.0.1",+ "uint8arraylist": "^3.0.2",+ "uint8arrays": "^6.1.1",+ "ws": "^8.18.3"+ }+ },+ "node_modules/@libp2p/websockets/node_modules/uint8arraylist": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/uint8arraylist/-/uint8arraylist-3.0.2.tgz",+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",+ "dependencies": {+ "uint8arrays": "^6.0.0"+ }+ },"node_modules/@modelcontextprotocol/sdk": {"version": "1.30.1","resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.1.tgz",@@ -732,6 +759,14 @@"@multiformats/multiaddr": "^13.0.0"}},+ "node_modules/@multiformats/multiaddr-to-uri": {+ "version": "12.0.0",+ "resolved": "https://registry.npmjs.org/@multiformats/multiaddr-to-uri/-/multiaddr-to-uri-12.0.0.tgz",+ "integrity": "sha512-3uIEBCiy8tfzxYYBl81x1tISiNBQ7mHU4pGjippbJRoQYHzy/ZdZM/7JvTldr8pc/dzpkaNJxnsuxxlhsPOJsA==",+ "dependencies": {+ "@multiformats/multiaddr": "^13.0.0"+ }+ },"node_modules/@noble/curves": {"version": "2.4.0","resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",@@ -3297,6 +3332,26 @@"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==","license": "ISC"},+ "node_modules/ws": {+ "version": "8.21.3",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",+ "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },"node_modules/zod": {"version": "4.6.5","resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",diff --git a/sdk/js/package.json b/sdk/js/package.jsonindex 144056fe..544d401e 100644--- a/sdk/js/package.json+++ b/sdk/js/package.json@@ -48,6 +48,7 @@"@libp2p/tcp": "^11.0.28","@libp2p/tls": "^3.1.10","@libp2p/utils": "^7.4.1",+ "@libp2p/websockets": "^10.1.21","@modelcontextprotocol/sdk": "^1.30.1","@multiformats/multiaddr": "^13.0.3","libp2p": "^3.3.11",diff --git a/sdk/js/src/host.test.ts b/sdk/js/src/host.test.tsnew file mode 100644index 00000000..590d1bb4--- /dev/null+++ b/sdk/js/src/host.test.ts@@ -0,0 +1,92 @@+// 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.++import assert from "node:assert/strict";+import net from "node:net";+import { test } from "node:test";+import { multiaddr } from "@multiformats/multiaddr";+import { createMeshHost } from "./host.ts";+import { Identity } from "./identity.ts";++const ECHO = "/test/echo/1.0.0";++// A TLS-terminating edge in front of the router (sam-one behind a tunnel)+// selects the origin by the name in the TLS SNI and the Host header, so a+// /dns4 WebSocket address is dialed by its name, not by what it resolves to.+// Pinned on the Host header of the upgrade request; the SNI is the same string.+test("a /dns4 WebSocket address is dialed by its name", async () => {+ const server = net.createServer();+ const request = new Promise<string>((resolve) => {+ server.once("connection", (socket) => {+ socket.once("data", (data) => {+ resolve(data.toString());+ socket.destroy();+ });+ });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const port = (server.address() as net.AddressInfo).port;+ try {+ const client = await createMeshHost(Identity.generate());+ try {+ const addr = multiaddr(`/dns4/localhost/tcp/${port}/ws/p2p/${Identity.generate().peerId}`);+ await assert.rejects(client.dial(addr, { signal: AbortSignal.timeout(5_000) }));+ const head = (await request).split("\r\n").map((l) => l.toLowerCase());+ assert.ok(head.includes(`host: localhost:${port}`), `upgrade request:\n${head.join("\n")}`);+ } finally {+ await client.stop();+ }+ } finally {+ server.close();+ }+});++// A mesh host reaches a peer over WebSocket as it does over TCP: sam-one's+// router listens on /ws alone, on the port that also serves its HTTP API.+for (const listen of ["/ip4/127.0.0.1/tcp/0", "/ip4/127.0.0.1/tcp/0/ws"]) {+ test(`a mesh host dials ${listen} and opens a TLS+yamux stream`, async () => {+ const server = await createMeshHost(Identity.generate(), { listenAddrs: [listen] });+ const client = await createMeshHost(Identity.generate());+ try {+ await server.handle(ECHO, (stream) => {+ stream.addEventListener("message", (ev) => {+ stream.send(ev.data.subarray());+ });+ stream.addEventListener("remoteCloseWrite", () => {+ void stream.close();+ });+ });+ const addr = server.getMultiaddrs()[0];+ assert.ok(addr !== undefined, "the server listens on nothing");+ assert.equal(addr.toString().endsWith("/ws/p2p/" + server.peerId.toString()), listen.endsWith("/ws"), `listening on ${addr.toString()}`);++ const stream = await client.dialProtocol(addr, ECHO);+ const answer = new Promise<string>((resolve) => {+ stream.addEventListener("message", (ev) => resolve(new TextDecoder().decode(ev.data.subarray())), { once: true });+ });+ stream.send(new TextEncoder().encode("hello"));+ assert.equal(await answer, "hello");+ await stream.close();++ const conn = client.getConnections(server.peerId)[0];+ assert.ok(conn !== undefined, "no connection to the server");+ assert.equal(conn.encryption, "/tls/1.0.0");+ assert.equal(conn.multiplexer, "/yamux/1.0.0");+ assert.equal(conn.remoteAddr.toString().includes("/ws"), listen.endsWith("/ws"));+ } finally {+ await client.stop();+ await server.stop();+ }+ });+}diff --git a/sdk/js/src/host.ts b/sdk/js/src/host.tsindex 852df2e3..cc1ddc73 100644--- a/sdk/js/src/host.ts+++ b/sdk/js/src/host.ts@@ -15,7 +15,8 @@// The libp2p host a member joins the mesh with, configured the way// sam-node's is (internal/node/node.go): TLS is the only security// protocol, yamux the muxer, circuit relay v2 for reachability through-// the routers.+// the routers. TCP and WebSocket are the transports: the testnets' routers+// listen on TCP, sam-one's single port is a WebSocket listener.import { yamux } from "@chainsafe/libp2p-yamux";import { circuitRelayTransport } from "@libp2p/circuit-relay-v2";@@ -27,6 +28,7 @@ import { kadDHT, passthroughMapper } from "@libp2p/kad-dht";import { ping } from "@libp2p/ping";import { tcp } from "@libp2p/tcp";import { tls } from "@libp2p/tls";+import { webSockets } from "@libp2p/websockets";import type { Multiaddr } from "@multiformats/multiaddr";import { createLibp2p, type Libp2pOptions } from "libp2p";import { DHT_PROTOCOL } from "./discovery.ts";@@ -34,8 +36,9 @@ import type { Identity } from "./identity.ts";export interface MeshHostOptions {/**- * Addresses to accept direct connections on, e.g. "/ip4/0.0.0.0/tcp/0".- * Empty by default: an agent is reached through a router's relay.+ * Addresses to accept direct connections on, e.g. "/ip4/0.0.0.0/tcp/0"+ * or "/ip4/0.0.0.0/tcp/0/ws". Empty by default: an agent is reached+ * through a router's relay.*/listenAddrs?: string[];/**@@ -58,7 +61,7 @@ export async function createMeshHost(identity: Identity, options: MeshHostOptionprivateKey: privateKeyFromProtobuf(identity.toLibp2pPrivateKey()),addresses: { listen: options.listenAddrs ?? [] },...(options.dns !== undefined ? { dns: options.dns } : {}),- transports: [tcp(), circuitRelayTransport()],+ transports: [tcp(), webSockets(), circuitRelayTransport()],connectionEncrypters: [tls()],streamMuxers: [yamux()],connectionGater: {diff --git a/sdk/python/src/agent_mesh/host.py b/sdk/python/src/agent_mesh/host.pyindex 3f7c4621..9bb0504b 100644--- a/sdk/python/src/agent_mesh/host.py+++ b/sdk/python/src/agent_mesh/host.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport importlib.metadataimport osimport re+import sslimport structfrom datetime import datetime, timedelta, timezonefrom typing import Sequence@@ -42,6 +43,7 @@ from libp2p.stream_muxer.exceptions import MuxedStreamErrorfrom libp2p.stream_muxer.yamux.yamux import FLAG_SYN, TYPE_WINDOW_UPDATE, YAMUX_HEADER_FORMATfrom libp2p.stream_muxer.yamux.yamux import PROTOCOL_ID as YAMUX_PROTOCOL_IDfrom libp2p.stream_muxer.yamux.yamux import Yamux, YamuxStream+from libp2p.transport.websocket.transport import WebsocketTransportfrom multiaddr.resolvers import DNSResolverfrom .identity import Identity@@ -152,8 +154,10 @@ def _certificate_template() -> x509.CertificateBuilder:def create_mesh_host(identity: Identity, listen_addrs: Sequence[str] = ()) -> tuple[IHost, list[multiaddr.Multiaddr]]:"""Builds the host for `identity`. Run it with `async with host.run(addrs)`.- listen_addrs are for direct connections, e.g. "/ip4/0.0.0.0/tcp/0"; an- agent is normally reached through a router's relay instead."""+ listen_addrs are for direct connections, e.g. "/ip4/0.0.0.0/tcp/0" or+ "/ip4/0.0.0.0/tcp/0/ws"; an agent is normally reached through a router's+ relay instead. The host dials TCP and WebSocket: the testnets' routers+ listen on TCP, sam-one's single port is a WebSocket listener."""key_pair = create_new_key_pair(identity.seed)# No ALPN muxer list: py-libp2p 0.7 advertises early muxer negotiation# but does not complete it, and go-libp2p then refuses the mux upgrade.@@ -163,6 +167,10 @@ def create_mesh_host(identity: Identity, listen_addrs: Sequence[str] = ()) -> tukey_pair=key_pair,sec_opt={TLS_PROTOCOL_ID: tls},muxer_opt={TProtocol(YAMUX_PROTOCOL_ID): Yamux},+ enable_websocket=True,+ # py-libp2p 0.7 dials wss with certificate verification off unless+ # given a context; the system roots, as go-libp2p and js-libp2p use.+ tls_client_config=ssl.create_default_context(),# A member connects to its routers and to the peers it calls or that# call it. py-libp2p's AutoConnector would otherwise dial every peer# in the peerstore every 30s while under 100 connections, including@@ -178,11 +186,30 @@ def create_mesh_host(identity: Identity, listen_addrs: Sequence[str] = ()) -> tu# The Swarm's own limits (max_connections, max_connections_per_peer)# do not depend on the manager and stay in force.host.get_network().set_resource_manager(None) # type: ignore[attr-defined]+ for transport in host.get_network().transport_manager.get_transports(): # type: ignore[attr-defined]+ if isinstance(transport, WebsocketTransport):+ _dial_websockets_by_name(transport)if str(host.get_id()) != identity.peer_id:raise RuntimeError(f"libp2p derived peer {host.get_id()} for identity {identity.peer_id}")return host, [multiaddr.Multiaddr(a) for a in listen_addrs]+def _dial_websockets_by_name(transport: WebsocketTransport) -> None:+ """py-libp2p 0.7 resolves a `/dns4/<host>/tcp/443/wss` address to its IP+ before dialing and then names the IP in the TLS SNI and the Host header,+ which a TLS-terminating edge (sam-one behind a tunnel) answers with 403.+ The transport's own dial of an unresolved address keeps the name; the+ dial here goes straight to it, as go-libp2p and js-libp2p do. Fixed+ upstream by libp2p/py-libp2p#1549; drop this with the release that has it."""+ # Bound here so a py-libp2p that renamed it fails at host construction.+ dial_resolved = transport._dial_resolved # noqa: SLF001++ async def dial(maddr: multiaddr.Multiaddr): # noqa: ANN202 - py-libp2p's RawConnection+ return await dial_resolved(maddr)++ transport.dial = dial # type: ignore[method-assign]++async def open_stream(host: IHost, peer_id: ID, protocol: TProtocol, timeout: float) -> INetStream:"""host.new_stream bounded by a timeout. py-libp2p bounds the protocolnegotiation but not the muxer, and a muxer that cannot open a stream@@ -195,8 +222,9 @@ async def open_stream(host: IHost, peer_id: ID, protocol: TProtocol, timeout: fl_DNS_PROTOCOLS = frozenset({"dnsaddr", "dns", "dns4", "dns6"})-# py-libp2p dials TCP only; a resolved address on another transport is noise.-_UNDIALABLE_PROTOCOLS = frozenset({"quic", "quic-v1", "ws", "wss", "webtransport", "webrtc", "webrtc-direct"})+# The host dials TCP and WebSocket; a resolved address on another transport is noise.+_UNDIALABLE_PROTOCOLS = frozenset({"quic", "quic-v1", "webtransport", "webrtc", "webrtc-direct"})+_WEBSOCKET_PROTOCOLS = frozenset({"ws", "wss"})_DNS_TIMEOUT = 10.0@@ -205,10 +233,14 @@ async def dial_addrs(addr: multiaddr.Multiaddr) -> list[multiaddr.Multiaddr]:hands out router addresses as `/dnsaddr/<host>/p2p/<id>`, resolved herethrough the host's `_dnsaddr` TXT records (and `/dns4`, `/dns6`, `/dns`through A and AAAA records) the way go-libp2p and js-libp2p do before- dialing; py-libp2p does not, and would report no transport for them.+ dialing; py-libp2p's TCP transport does not, and would report no+ transport for them. A WebSocket address keeps its DNS name: the name is+ the TLS server name and the Host header, which a TLS-terminating edge in+ front of the router (sam-one behind a tunnel) selects the origin by.Addresses on transports this host lacks are left out."""protocols = [p.name for p in addr.protocols()]- if protocols and protocols[0] in _DNS_PROTOCOLS:+ first = protocols[0] if protocols else ""+ if first == "dnsaddr" or (first in _DNS_PROTOCOLS and not set(protocols) & _WEBSOCKET_PROTOCOLS):resolved: list[multiaddr.Multiaddr] = []with trio.move_on_after(_DNS_TIMEOUT):resolved = list(await DNSResolver().resolve(addr))@@ -222,7 +254,7 @@ async def dial_addrs(addr: multiaddr.Multiaddr) -> list[multiaddr.Multiaddr]:if "tcp" in names and not names & _UNDIALABLE_PROTOCOLS:dialable.append(m)if not dialable:- raise RuntimeError(f"{addr} offers no TCP address; this host dials TCP only")+ raise RuntimeError(f"{addr} offers no TCP or WebSocket address; this host dials those only")return dialablediff --git a/sdk/python/tests/test_host.py b/sdk/python/tests/test_host.pyindex a0fbe802..09a191a9 100644--- a/sdk/python/tests/test_host.py+++ b/sdk/python/tests/test_host.py@@ -18,6 +18,7 @@ address through its TXT records and keep the transports this host hasstream must do: come back after the 256th one on a connection (py-libp2p0.7 leaks its yamux backlog slots), or fail at a deadline."""+import sslimport structimport multiaddr@@ -28,6 +29,7 @@ from libp2p.custom_types import TProtocolfrom libp2p.peer.id import IDfrom libp2p.peer.peerinfo import PeerInfo, info_from_p2p_addrfrom libp2p.stream_muxer.yamux.yamux import FLAG_SYN, YAMUX_HEADER_FORMAT+from libp2p.transport.websocket.transport import WebsocketTransportfrom multiaddr.resolvers import DNSResolverfrom agent_mesh.host import LIBP2P_LEAKS_CONNECTION_SCOPES, LIBP2P_LEAKS_STREAM_SLOTS, create_mesh_host, dial_addrs, open_stream, peer_info@@ -100,8 +102,67 @@ def test_addresses_without_a_transport_this_host_has_are_an_error(testnet_dns):def test_a_concrete_address_passes_through():async def main():- ma = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/4001/p2p/{ROUTER}")- assert await dial_addrs(ma) == [ma]+ for text in (f"/ip4/127.0.0.1/tcp/4001/p2p/{ROUTER}", f"/ip4/127.0.0.1/tcp/8080/ws/p2p/{ROUTER}", f"/dns4/mesh.example/tcp/443/tls/ws/p2p/{ROUTER}"):+ ma = multiaddr.Multiaddr(text)+ assert await dial_addrs(ma) == [ma]++ trio.run(main)+++def test_a_websocket_address_is_dialed_by_its_name():+ """A TLS-terminating edge in front of the router (sam-one behind a tunnel)+ selects the origin by the name in the TLS SNI and the Host header.+ py-libp2p 0.7 resolves the name first and sends the IP; the host sends+ the name. Pinned on the Host header of the upgrade request, the SNI is+ the same string."""+ seen: dict[str, str] = {}++ async def record(stream):+ seen["request"] = (await stream.receive_some(4096)).decode(errors="replace")+ await stream.aclose()++ async def main():+ listeners = await trio.open_tcp_listeners(0, host="127.0.0.1")+ port = listeners[0].socket.getsockname()[1]+ client, _ = create_mesh_host(Identity.generate())+ async with trio.open_nursery() as nursery:+ nursery.start_soon(trio.serve_listeners, record, listeners)+ async with client.run(listen_addrs=[]):+ addr = multiaddr.Multiaddr(f"/dns4/localhost/tcp/{port}/ws/p2p/{ROUTER}")+ assert await dial_addrs(addr) == [addr]+ with pytest.raises(Exception), trio.fail_after(10):+ await client.connect(await peer_info(addr))+ nursery.cancel_scope.cancel()+ assert f"\r\nhost: localhost:{port}\r\n" in seen["request"].lower(), seen["request"]++ trio.run(main)+++def test_a_websocket_listener_is_reached_with_tls_and_yamux():+ """sam-one's router listens on /ws alone, on the port that also serves+ its HTTP API; a member reaches it as it reaches a TCP router."""++ async def echo(stream):+ try:+ await stream.write(await stream.read(64))+ finally:+ await stream.close()++ async def main():+ server, server_listen = create_mesh_host(Identity.generate(), ["/ip4/127.0.0.1/tcp/0/ws"])+ client, _ = create_mesh_host(Identity.generate())+ server.set_stream_handler(ECHO, echo)+ async with server.run(listen_addrs=server_listen), client.run(listen_addrs=[]):+ addr = server.get_addrs()[0]+ assert "/ws/p2p/" in str(addr), f"listening on {addr}"+ with trio.fail_after(10):+ await client.connect(await peer_info(addr))+ stream = await open_stream(client, server.get_id(), ECHO, 5)+ try:+ await stream.write(b"ping")+ assert await stream.read(4) == b"ping"+ finally:+ await stream.close()trio.run(main)@@ -215,6 +276,19 @@ def test_the_stream_slot_workaround_retires_with_libp2p_0_8():assert LIBP2P_LEAKS_STREAM_SLOTS == ((major, minor) < (0, 8))+def test_wss_is_dialed_with_certificate_verification():+ """py-libp2p 0.7 dials wss with verification off unless given a TLS+ client context; the host gives it the system roots, so an edge's+ certificate is checked as go-libp2p and js-libp2p check it."""+ host, _ = create_mesh_host(Identity.generate())+ transports = host.get_network().transport_manager.get_transports() # type: ignore[attr-defined]+ ws = next(t for t in transports if isinstance(t, WebsocketTransport))+ context = ws._config.tls_client_config # noqa: SLF001 - py-libp2p offers no getter+ assert context is not None+ assert context.verify_mode == ssl.CERT_REQUIRED+ assert context.check_hostname++def test_the_host_runs_without_a_resource_manager_and_a_background_dialer():"""py-libp2p 0.7 leaks a ResourceManager connection slot per connectionand per failed security upgrade; at 1000 the manager degrades to onediff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.mdindex 9a8d37d8..2b9f12f0 100644--- a/site/content/docs/guides/native-sdks.md+++ b/site/content/docs/guides/native-sdks.md@@ -925,8 +925,10 @@ or a pattern) and the members it may reach; seepolicy enforcement of `sam-box` runs beside a `sam-node`.- They do not serve the discovery table. A member is a client of it; therouters hold the records.-- They do not run in a browser. Node.js and CPython only, until the transport- to routers from a browser is designed.+- They do not run in a browser. Node.js and CPython only. The JS SDK+ dials routers over WebSocket, which a browser can do, but routers and+ nodes accept libp2p TLS alone, which a browser cannot speak, and the SDK+ keeps its state and speaks HTTP on streams with Node's own modules.The wire contract and the interoperability facts the tests pin are in[`sdk/README.md`](https://github.com/google/sam/blob/main/sdk/README.md).diff --git a/tests/integration/sdk_a2a_test.go b/tests/integration/sdk_a2a_test.goindex bf28eac9..56122a98 100644--- a/tests/integration/sdk_a2a_test.go+++ b/tests/integration/sdk_a2a_test.go@@ -107,7 +107,7 @@ func TestNativeSDKA2A(t *testing.T) {}env := []string{"SAM_CONTROL_PLANE_URL=" + mesh.baseURL, "SAM_STATE_DIR=" + filepath.Join(t.TempDir(), "state"), "SAM_BOOTSTRAP_TOKEN_PATH=" + tokenPath}- out := runExample(t, mesh, l, env, "a2a-call", target.peerID, "hello from "+l.name)+ out := runExample(t, mesh.root, l, env, "a2a-call", target.peerID, "hello from "+l.name)caller := expectLine(t, out, "on the mesh as ")expectLine(t, out, "agent: Echo agent, ")// The agent's server saw the verified caller, never a name thediff --git a/tests/integration/sdk_examples_test.go b/tests/integration/sdk_examples_test.goindex e28d4f2f..9d2cbefd 100644--- a/tests/integration/sdk_examples_test.go+++ b/tests/integration/sdk_examples_test.go@@ -165,7 +165,7 @@ func TestNativeSDKExamples(t *testing.T) {// The first run spends the token: the sam-node's calc over MCP,// found by name.- out := runExample(t, mesh, l, withToken, "call", "mcp://calc", "add", `{"a": 1, "b": 2}`)+ out := runExample(t, mesh.root, l, withToken, "call", "mcp://calc", "add", `{"a": 1, "b": 2}`)caller := expectLine(t, out, "on the mesh as ")expectLine(t, out, "mcp://calc is served by "+mesh.samNode.peerID.String())expectLine(t, out, "tools: add")@@ -178,7 +178,7 @@ func TestNativeSDKExamples(t *testing.T) {if err := os.Remove(tokenPath); err != nil {t.Fatal(err)}- out = runExample(t, mesh, l, withoutToken, "call", target.peerID, "a2a://agent", "/card")+ out = runExample(t, mesh.root, l, withoutToken, "call", target.peerID, "a2a://agent", "/card")if got := expectLine(t, out, "on the mesh as "); got != caller {t.Fatalf("second run joined as %s, want the identity of the first run %s", got, caller)}@@ -201,7 +201,7 @@ func TestNativeSDKExamples(t *testing.T) {if other.name == l.name {continue}- out := runExample(t, mesh, other, withoutToken, "call", target.peerID, "a2a://agent", "/card")+ out := runExample(t, mesh.root, other, withoutToken, "call", target.peerID, "a2a://agent", "/card")if got := expectLine(t, out, "on the mesh as "); got != caller {t.Fatalf("%s resumed %s's state directory as %s, want %s", other.name, l.name, got, caller)}@@ -305,16 +305,16 @@ func startExampleAgent(t *testing.T, name string, cmd *exec.Cmd) (*sdkExampleAge}// runExample runs an example that exits on its own to completion and returns its stdout.-func runExample(t *testing.T, mesh *sdkMesh, l sdkExampleLauncher, env []string, example string, args ...string) string {+func runExample(t *testing.T, root string, l sdkExampleLauncher, env []string, example string, args ...string) string {t.Helper()ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()- cmd, skip := l.cmd(ctx, mesh.root, example, args...)+ cmd, skip := l.cmd(ctx, root, example, args...)if skip != "" {t.Fatalf("%s: %s", l.name, skip)}cmd.Env = append(os.Environ(), env...)- cmd.Dir = mesh.root+ cmd.Dir = rootstderr := &bytes.Buffer{}cmd.Stderr = stderrstdout, err := cmd.Output()diff --git a/tests/integration/standalone_sdk_test.go b/tests/integration/standalone_sdk_test.gonew file mode 100644index 00000000..452764d9--- /dev/null+++ b/tests/integration/standalone_sdk_test.go@@ -0,0 +1,232 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package integration_test++import (+ "context"+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/tls"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/pem"+ "errors"+ "fmt"+ "math/big"+ "net"+ "net/http"+ "net/http/httputil"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/google/sam/internal/standalone"+)++// TestStandaloneSDKAgents pins that both SDKs work with sam-one. Its+// embedded router listens on WebSocket alone, on the single port that also+// serves the control plane, so a member that dials TCP only never gets on.+// One agent example per language (sdk/js/examples/a2a-agent.ts,+// sdk/python/examples/a2a_agent.py) enrolls with the join token and accepts+// A2A requests; the other language's caller (its own when the other+// toolchain is missing) reaches it by peer ID through the router with the+// A2A SDK's client and gets an answer naming the verified caller. A language+// whose toolchain or A2A SDK is missing is skipped.+func TestStandaloneSDKAgents(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ srv := startStandalone(t, ctx, standalone.Options{BindAddress: "127.0.0.1:0", DataDir: t.TempDir()})+ runStandaloneSDKAgents(t, ctx, srv, srv.PublicURL(), nil)+}++// TestStandaloneSDKAgentsBehindTLSEdge is the same pair behind what+// `sam-one --tunnel` puts in front of it: a TLS-terminating edge reached by+// name, which selects the origin by the TLS server name and the Host header+// and answers anything else with 403, as Cloudflare does. sam-one advertises+// its router as /dns4/localhost/tcp/<edge>/wss/p2p/<id>, so each SDK must+// carry the name to the edge instead of what it resolves to. Both SDKs+// trust the edge's certificate through the file their TLS stacks read+// (NODE_EXTRA_CA_CERTS, SSL_CERT_FILE).+func TestStandaloneSDKAgentsBehindTLSEdge(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ edge, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ edgeURL := "https://localhost:" + fmt.Sprint(edge.Addr().(*net.TCPAddr).Port)+ srv := startStandalone(t, ctx, standalone.Options{BindAddress: "127.0.0.1:0", DataDir: t.TempDir(), ExternalURL: edgeURL})+ caFile := serveTLSEdge(t, edge, "localhost", srv.Addr())+ runStandaloneSDKAgents(t, ctx, srv, edgeURL, []string{"NODE_EXTRA_CA_CERTS=" + caFile, "SSL_CERT_FILE=" + caFile})+}++func startStandalone(t *testing.T, ctx context.Context, opts standalone.Options) *standalone.Server {+ t.Helper()+ srv, err := standalone.New(opts)+ if err != nil {+ t.Fatal(err)+ }+ if err := srv.Start(ctx); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = srv.Close() })+ return srv+}++// runStandaloneSDKAgents runs each language's A2A agent example against+// sam-one at publicURL and calls it with the other language's A2A caller.+func runStandaloneSDKAgents(t *testing.T, ctx context.Context, srv *standalone.Server, publicURL string, extraEnv []string) {+ t.Helper()+ root := repoRoot(t)+ var launchers []sdkExampleLauncher+ for _, l := range sdkExampleLaunchers {+ _, skip := l.cmd(ctx, root, "a2a-agent")+ if skip == "" {+ skip = a2aSDKMissing(root, l.name)+ }+ if skip != "" {+ t.Logf("%s SDK skipped: %s", l.name, skip)+ continue+ }+ launchers = append(launchers, l)+ }+ if len(launchers) == 0 {+ t.Skip("no SDK toolchain with the A2A SDK available; see sdk/README.md")+ }++ tokenPath := filepath.Join(t.TempDir(), "join-token")+ if err := os.WriteFile(tokenPath, []byte(srv.JoinToken()+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ env := func(stateDir string) []string {+ return append([]string{+ "SAM_CONTROL_PLANE_URL=" + publicURL,+ "SAM_BOOTSTRAP_TOKEN_PATH=" + tokenPath,+ "SAM_STATE_DIR=" + filepath.Join(t.TempDir(), stateDir),+ "PYTHONUNBUFFERED=1",+ }, extraEnv...)+ }++ agents := make([]*sdkExampleAgent, len(launchers))+ errs := make([]error, len(launchers))+ var wg sync.WaitGroup+ for i, l := range launchers {+ cmd, _ := l.cmd(context.Background(), root, "a2a-agent")+ cmd.Env = append(os.Environ(), env(l.name+"-agent")...)+ cmd.Dir = root+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ agents[i], errs[i] = startExampleAgent(t, launchers[i].name, cmd)+ }(i)+ }+ wg.Wait()+ for _, err := range errs {+ if err != nil {+ t.Fatal(err)+ }+ }++ for i, l := range launchers {+ l, target := l, agents[(i+1)%len(agents)]+ t.Run(l.name+"-calls-"+target.name, func(t *testing.T) {+ t.Parallel()+ out := runExample(t, root, l, env(l.name+"-caller"), "a2a-call", target.peerID, "hello from "+l.name)+ caller := expectLine(t, out, "on the mesh as ")+ expectLine(t, out, "agent: Echo agent, ")+ if want := caller + " said: hello from " + l.name; !strings.Contains(out, want) {+ t.Fatalf("%s calling the %s agent through sam-one: want %q in\n%s", l.name, target.name, want, out)+ }+ })+ }+}++// serveTLSEdge terminates TLS on the listener for host and proxies to+// origin, HTTP and WebSocket upgrades alike. A handshake for another server+// name fails and a request for another host gets 403, the way an edge that+// routes by name treats a client that reached it by IP. Returns the path of+// the certificate the clients must trust.+func serveTLSEdge(t *testing.T, ln net.Listener, host, origin string) string {+ t.Helper()+ certPEM, keyPEM := selfSignedCert(t, host)+ cert, err := tls.X509KeyPair(certPEM, keyPEM)+ if err != nil {+ t.Fatal(err)+ }+ caFile := filepath.Join(t.TempDir(), "edge-ca.pem")+ if err := os.WriteFile(caFile, certPEM, 0o644); err != nil {+ t.Fatal(err)+ }+ target := &url.URL{Scheme: "http", Host: origin}+ proxy := &httputil.ReverseProxy{Rewrite: func(pr *httputil.ProxyRequest) {+ pr.SetURL(target)+ pr.Out.Host = origin+ }}+ server := &http.Server{+ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if h, _, err := net.SplitHostPort(r.Host); (err == nil && !strings.EqualFold(h, host)) || (err != nil && !strings.EqualFold(r.Host, host)) {+ http.Error(w, "403 Forbidden (edge: unknown host "+r.Host+")", http.StatusForbidden)+ return+ }+ proxy.ServeHTTP(w, r)+ }),+ TLSConfig: &tls.Config{+ MinVersion: tls.VersionTLS12,+ GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {+ if !strings.EqualFold(hello.ServerName, host) {+ return nil, errors.New("edge: unknown server name " + hello.ServerName)+ }+ return &cert, nil+ },+ },+ }+ go func() { _ = server.ServeTLS(ln, "", "") }()+ t.Cleanup(func() { _ = server.Close() })+ return caFile+}++// selfSignedCert is a self-signed certificate for host; clients trust it by adding it to their roots.+func selfSignedCert(t *testing.T, host string) (certPEM, keyPEM []byte) {+ t.Helper()+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ tmpl := &x509.Certificate{+ SerialNumber: big.NewInt(1),+ Subject: pkix.Name{CommonName: host},+ DNSNames: []string{host},+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: time.Now().Add(24 * time.Hour),+ KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},+ BasicConstraintsValid: true,+ IsCA: true,+ }+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)+ if err != nil {+ t.Fatal(err)+ }+ keyDER, err := x509.MarshalECPrivateKey(key)+ if err != nil {+ t.Fatal(err)+ }+ return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})+}