Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: a browser page as a member of a sam-one mesh, tested
Antonio Ojea7ce454df022a
diff --git a/sdk/js/examples/browser/app.js b/sdk/js/examples/browser/app.jsnew file mode 100644index 00000000..75276b73--- /dev/null+++ b/sdk/js/examples/browser/app.js@@ -0,0 +1,176 @@+// 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.++// A member of the mesh in a browser page: the same Echo agent as+// a2a-agent.ts, answering with a fetch handler instead of an Express app,+// and the same caller as a2a-call.ts. Bundle it for the page with+//+// npm run build && node scripts/bundle-browser.mjs examples/browser/app.js <outdir>+//+// and serve <outdir> together with index.html. The page's identity and+// credential are kept in IndexedDB, so a reload resumes the same peer+// without a token.++import { A2A_PROTOCOL_VERSION, AGENT_CARD_PATH, Message, Role } from "@a2a-js/sdk";+import { ClientFactory, DefaultAgentCardResolver, JsonRpcTransportFactory } from "@a2a-js/sdk/client";+import { AgentEvent, DefaultRequestHandler, InMemoryTaskStore, JsonRpcTransportHandler, ServerCallContext } from "@a2a-js/sdk/server";+import { AgentMesh, MeshSession } from "@sam-mesh/sdk";++const $ = (id) => document.getElementById(id);+const params = new URLSearchParams(location.search);+$("control-plane-url").value = params.get("controlPlaneUrl") ?? location.origin;+$("bootstrap-token").value = params.get("bootstrapToken") ?? "";+$("target-peer").value = params.get("peerId") ?? "";++let session;++function log(line) {+ $("log").textContent += line + "\n";+}++/** The Echo agent: answers every message with what it said and who sent it. */+class EchoExecutor {+ async execute(context, eventBus) {+ const said = context.userMessage.parts.map((p) => (p.content?.$case === "text" ? p.content.value : "")).join("");+ const caller = context.context.user?.userName ?? "someone";+ log(`message from ${caller}: ${said}`);+ eventBus.publish(+ AgentEvent.message({+ messageId: crypto.randomUUID(),+ contextId: context.contextId,+ taskId: "",+ role: Role.ROLE_AGENT,+ parts: [{ content: { $case: "text", value: `${caller} said: ${said}` }, filename: "", mediaType: "text/plain", metadata: undefined }],+ metadata: undefined,+ extensions: [],+ referenceTaskIds: [],+ }),+ );+ eventBus.finished();+ }++ async cancelTask() {}+}++function agentCard(url) {+ return {+ name: "Echo agent (browser)",+ description: "Answers every message with what it said and who sent it.",+ version: "1.0.0",+ supportedInterfaces: [{ url, protocolBinding: "JSONRPC", tenant: "", protocolVersion: A2A_PROTOCOL_VERSION }],+ provider: undefined,+ documentationUrl: "",+ capabilities: { streaming: true, pushNotifications: false, extendedAgentCard: false, extensions: [] },+ securitySchemes: {},+ securityRequirements: [],+ defaultInputModes: ["text/plain"],+ defaultOutputModes: ["text/plain"],+ skills: [{ id: "echo", name: "Echo", description: "Repeats the message.", tags: ["echo"], examples: ["hello"], inputModes: [], outputModes: [], securityRequirements: [] }],+ signatures: [],+ iconUrl: "",+ };+}++/**+ * The handler behind a2a://agent. The SDK has already authorized the caller;+ * `caller` is its verified biscuit, so the A2A user is the peer ID it is+ * bound to, never anything the request said about itself.+ */+function a2aHandler(card) {+ const transport = new JsonRpcTransportHandler(new DefaultRequestHandler(card, new InMemoryTaskStore(), new EchoExecutor()));+ return async (request, caller) => {+ const path = new URL(request.url).pathname;+ if (request.method === "GET" && path === `/${AGENT_CARD_PATH}`) {+ return Response.json(card);+ }+ if (request.method !== "POST") {+ return new Response("not found\n", { status: 404 });+ }+ const context = new ServerCallContext({ user: { isAuthenticated: true, userName: caller.peerId }, requestedVersion: request.headers.get("a2a-version") ?? undefined });+ const result = await transport.handle(await request.text(), context);+ if (Symbol.asyncIterator in result) {+ // message/stream: one SSE event per JSON-RPC response, as it is produced.+ const encoder = new TextEncoder();+ const body = new ReadableStream({+ async pull(controller) {+ const next = await result.next();+ if (next.done) {+ controller.close();+ } else {+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(next.value)}\n\n`));+ }+ },+ });+ return new Response(body, { headers: { "content-type": "text/event-stream" } });+ }+ return Response.json(result);+ };+}++async function join(controlPlaneUrl, bootstrapToken) {+ $("status").textContent = "enrolling";+ const mesh = await AgentMesh.enroll({+ controlPlaneUrl,+ // Empty resumes the enrollment saved in IndexedDB under this name.+ ...(bootstrapToken !== "" ? { bootstrapToken } : {}),+ stateDir: "browser-agent",+ // A plaintext http:// control plane is otherwise accepted only on loopback.+ allowInsecure: params.get("allowInsecure") === "true",+ });+ $("status").textContent = "joining";+ session = await mesh.join();+ const url = MeshSession.meshURL(session.peerId, "a2a://agent");+ await session.acceptA2A({ handler: a2aHandler(agentCard(url)) });+ $("peer-id").textContent = session.peerId;+ $("status").textContent = `on the mesh, accepting a2a://agent`;+ window.addEventListener("pagehide", () => void session.close());+ return session.peerId;+}++async function call(peerId, text) {+ const fetchImpl = session.fetch();+ const factory = new ClientFactory({+ transports: [new JsonRpcTransportFactory({ fetchImpl })],+ cardResolver: new DefaultAgentCardResolver({ fetchImpl }),+ });+ const client = await factory.createFromUrl(MeshSession.meshURL(peerId, "a2a://agent") + "/");+ const card = await client.getAgentCard();+ const answer = await client.sendMessage({+ tenant: "",+ message: Message.fromJSON({ messageId: crypto.randomUUID(), role: Role[Role.ROLE_USER], parts: [{ text }] }),+ configuration: undefined,+ metadata: undefined,+ });+ const parts = "parts" in answer ? answer.parts : (answer.status?.message?.parts ?? []);+ const reply = parts.map((p) => (p.content?.$case === "text" ? p.content.value : "")).join("");+ $("answer").textContent = `${card.name}: ${reply}`;+ return reply;+}++$("join-form").addEventListener("submit", (event) => {+ event.preventDefault();+ join($("control-plane-url").value, $("bootstrap-token").value).catch((err) => {+ $("status").textContent = `failed: ${err.message}`;+ });+});++$("call-form").addEventListener("submit", (event) => {+ event.preventDefault();+ call($("target-peer").value, $("message").value).catch((err) => {+ $("answer").textContent = `failed: ${err.message}`;+ });+});++// For scripts and tests driving the page.+window.sam = { join, call, get session() { return session; } };diff --git a/sdk/js/examples/browser/index.html b/sdk/js/examples/browser/index.htmlnew file mode 100644index 00000000..1d60ca41--- /dev/null+++ b/sdk/js/examples/browser/index.html@@ -0,0 +1,53 @@+<!doctype html>+<!--+ 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.+-->+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>SAM browser agent</title>+ <style>+ body { font: 14px system-ui, sans-serif; margin: 2rem; max-width: 48rem; }+ label { display: block; margin-top: 0.75rem; }+ input { width: 100%; box-sizing: border-box; padding: 0.4rem; font: inherit; }+ button { margin-top: 0.75rem; padding: 0.4rem 1rem; font: inherit; }+ code, pre { font: 13px ui-monospace, monospace; }+ pre { background: #f4f4f4; padding: 0.75rem; white-space: pre-wrap; }+ </style>+ </head>+ <body>+ <h1>SAM browser agent</h1>+ <p>+ This page is a member of the mesh: it enrolls with the control plane, joins through a router over WebSocket and Noise,+ answers A2A requests as <code>a2a://agent</code> and calls other agents by peer ID.+ </p>+ <form id="join-form">+ <label>Control plane URL <input id="control-plane-url" name="controlPlaneUrl" required /></label>+ <label>Join token (empty to resume a saved enrollment) <input id="bootstrap-token" name="bootstrapToken" autocomplete="off" /></label>+ <button type="submit" id="join">Join</button>+ </form>+ <p>Status: <span id="status">not joined</span></p>+ <p>Peer ID: <code id="peer-id"></code></p>+ <form id="call-form">+ <label>Agent peer ID <input id="target-peer" name="peerId" required /></label>+ <label>Message <input id="message" name="text" value="hello from a browser" /></label>+ <button type="submit" id="call">Call</button>+ </form>+ <p>Answer: <span id="answer"></span></p>+ <h2>Requests received</h2>+ <pre id="log"></pre>+ <script type="module" src="./app.js"></script>+ </body>+</html>diff --git a/sdk/js/scripts/bundle-browser.mjs b/sdk/js/scripts/bundle-browser.mjsindex 77891fdb..1d95020c 100644--- a/sdk/js/scripts/bundle-browser.mjs+++ b/sdk/js/scripts/bundle-browser.mjs@@ -81,7 +81,7 @@ const result = await esbuild.build({});// The bytes the stub fetches: copy every .wasm the graph touched beside the bundle.-const { copyFile, mkdir } = await import("node:fs/promises");+const { copyFile, mkdir, readdir } = await import("node:fs/promises");await mkdir(outdir, { recursive: true });for (const input of Object.keys(result.metafile.inputs)) {if (input.startsWith("wasm-esm:")) {@@ -89,6 +89,12 @@ for (const input of Object.keys(result.metafile.inputs)) {await copyFile(file, join(outdir, basename(file)));}}+// A page's static files beside the entry (index.html) go with it.+for (const name of await readdir(dirname(entry))) {+ if (name.endsWith(".html") || name.endsWith(".css")) {+ await copyFile(join(dirname(entry), name), join(outdir, name));+ }+}const nodeBuiltins = Object.keys(result.metafile.inputs).filter((p) => p.startsWith("node:"));if (nodeBuiltins.length > 0) {console.error(`browser bundle reaches Node: ${nodeBuiltins.join(", ")}`);diff --git a/sdk/js/src/controlplane.test.ts b/sdk/js/src/controlplane.test.tsindex a368ae55..06408150 100644--- a/sdk/js/src/controlplane.test.ts+++ b/sdk/js/src/controlplane.test.ts@@ -257,3 +257,15 @@ test("keys() fetches and verifies against the enrollment key", async () => {assert.deepEqual(await client.keys([cpKey.publicKeyRaw]), [cpKey.publicKeyRaw]);await assert.rejects(client.keys([Identity.generate().publicKeyRaw]), /not signed by any trusted/);});++test("an injected fetch is called unbound, as a browser's window.fetch requires", async () => {+ const inner = fakeFetch({ "GET /keys": () => proto(toBinary(KeysResponseSchema, signedKeys([cpKey]))) });+ let receiver: unknown = "unset";+ const strict = function (this: unknown, input: Parameters<typeof fetch>[0], init?: RequestInit) {+ receiver = this;+ return inner(input, init);+ } as typeof fetch;+ const client = new ControlPlaneClient({ url: "http://127.0.0.1:1", fetch: strict });+ await client.keys([cpKey.publicKeyRaw]);+ assert.equal(receiver, undefined);+});diff --git a/sdk/js/src/controlplane.ts b/sdk/js/src/controlplane.tsindex 9149d692..cb711a83 100644--- a/sdk/js/src/controlplane.ts+++ b/sdk/js/src/controlplane.ts@@ -226,7 +226,9 @@ export class ControlPlaneClient {constructor(options: ControlPlaneClientOptions) {this.url = validateControlPlaneURL(options.url, options.allowInsecure ?? false);- this.#fetch = options.fetch ?? globalThis.fetch;+ // Unbound: a browser's fetch refuses to run as a method of anything else.+ const f = options.fetch ?? globalThis.fetch;+ this.#fetch = (input, init) => f(input, init);this.#timeoutMs = options.timeoutMs ?? 30_000;}diff --git a/sdk/js/src/host.ts b/sdk/js/src/host.tsindex 93f09b8c..e3c21de5 100644--- a/sdk/js/src/host.ts+++ b/sdk/js/src/host.ts@@ -66,6 +66,13 @@ export async function createMeshHost(identity: Identity, options: MeshHostOptiondenyDialPeer: denyBanned,denyInboundEncryptedConnection: denyBanned,denyInboundRelayedConnection: (_relay, remotePeer) => denyBanned(remotePeer),+ // The addresses dialled are the routers' as the control plane+ // published them, and every connection is authenticated by peer ID+ // whatever the address, so no address is refused for its shape. In a+ // browser js-libp2p would otherwise skip loopback and plain ws://+ // addresses, which is what sam-one on the same machine advertises; a+ // page on https cannot open ws:// anyway, the browser sees to that.+ denyDialMultiaddr: () => false,},services: {identify: identify(),diff --git a/sdk/js/src/platform/transports.ts b/sdk/js/src/platform/transports.tsindex 7ed3e374..f37910df 100644--- a/sdk/js/src/platform/transports.ts+++ b/sdk/js/src/platform/transports.ts@@ -13,9 +13,11 @@// limitations under the License.// How a member on Node reaches the mesh: TCP and WebSocket, the transports-// the routers listen on, secured with TLS 1.3, which every peer offers-// first (internal/node/node.go).+// the routers listen on. TLS 1.3 first, as every Go peer and the Python SDK+// offer it (internal/node/node.go); Noise accepted, so a member in a+// browser, which speaks Noise alone, is reached end to end through a relay.+import { noise } from "@chainsafe/libp2p-noise";import { tcp } from "@libp2p/tcp";import { tls } from "@libp2p/tls";import { webSockets } from "@libp2p/websockets";@@ -26,5 +28,5 @@ export function transports(): NonNullable<Libp2pOptions["transports"]> {}export function connectionEncrypters(): NonNullable<Libp2pOptions["connectionEncrypters"]> {- return [tls()];+ return [tls(), noise()];}diff --git a/sdk/python/src/agent_mesh/host.py b/sdk/python/src/agent_mesh/host.pyindex c91b7e79..3d04b651 100644--- a/sdk/python/src/agent_mesh/host.py+++ b/sdk/python/src/agent_mesh/host.py@@ -14,8 +14,8 @@"""The libp2p host a member joins the mesh with, configured the way sam-node'sis (internal/node/node.go): TLS for the security protocol, which every peer-offers first, and yamux the muxer. py-libp2p is trio-based, so everything here-is trio async."""+offers first, Noise accepted beside it, and yamux the muxer. py-libp2p is+trio-based, so everything here is trio async."""from __future__ import annotations@@ -34,10 +34,13 @@ from cryptography.x509.oid import NameOIDfrom libp2p import new_hostfrom libp2p.abc import IHost, INetStreamfrom libp2p.crypto.ed25519 import create_new_key_pair+from libp2p.crypto.x25519 import create_new_key_pair as create_new_x25519_key_pairfrom libp2p.custom_types import TProtocolfrom libp2p.network.config import ConnectionConfigfrom libp2p.peer.id import IDfrom libp2p.peer.peerinfo import PeerInfo, info_from_p2p_addr+from libp2p.security.noise.transport import PROTOCOL_ID as NOISE_PROTOCOL_ID+from libp2p.security.noise.transport import Transport as NoiseTransportfrom libp2p.security.tls.transport import PROTOCOL_ID as TLS_PROTOCOL_IDfrom libp2p.security.tls.transport import IdentityConfig, TLSTransportfrom libp2p.stream_muxer.exceptions import MuxedStreamError@@ -164,9 +167,13 @@ def create_mesh_host(identity: Identity, listen_addrs: Sequence[str] = ()) -> tu# but does not complete it, and go-libp2p then refuses the mux upgrade.# Without it the muxer is negotiated with multistream-select as before.tls = TLSTransport(key_pair, identity_config=IdentityConfig(cert_template=_certificate_template()))+ # TLS first, as every Go peer and the JS SDK offer it; Noise accepted, so+ # a member in a browser, which speaks Noise alone, is reached end to end+ # through a relay. Both bind the connection to the peer ID.+ noise = NoiseTransport(key_pair, noise_privkey=create_new_x25519_key_pair().private_key)host = new_host(key_pair=key_pair,- sec_opt={TLS_PROTOCOL_ID: tls},+ sec_opt={TLS_PROTOCOL_ID: tls, NOISE_PROTOCOL_ID: noise},muxer_opt={TProtocol(YAMUX_PROTOCOL_ID): Yamux},enable_websocket=True,# py-libp2p 0.7 dials wss with certificate verification off unlessdiff --git a/tests/ui/browser-sdk.spec.js b/tests/ui/browser-sdk.spec.jsnew file mode 100644index 00000000..94809917--- /dev/null+++ b/tests/ui/browser-sdk.spec.js@@ -0,0 +1,99 @@+// 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.++// The JS SDK in a browser page (sdk/js/examples/browser) as a member of a+// sam-one mesh: the page enrolls with the join token from an origin of its+// own, joins the router over WebSocket and Noise, answers A2A requests from+// a Node member, calls a Node agent, and after a reload resumes the saved+// enrollment without a token. Once against sam-one directly and once behind+// a TLS-terminating edge reached by name, the topology `sam-one --tunnel`+// leaves the page in, where the router is advertised as wss.++const { test, expect } = require('@playwright/test');+const stack = require('./lib/sam-one');++test.use({ ignoreHTTPSErrors: true });+test.describe.configure({ mode: 'serial' });+test.setTimeout(120_000);++const topologies = [+ { name: 'direct', edge: false },+ { name: 'behind a TLS edge', edge: true },+];++for (const topology of topologies) {+ test(`a browser page is a member of a sam-one mesh (${topology.name})`, async ({ page }) => {+ const why = stack.missing();+ test.skip(why !== '', why);++ const stops = [];+ try {+ let samOne;+ let caFile;+ if (topology.edge) {+ const cert = stack.selfSignedCert('localhost');+ test.skip(cert === null, 'openssl is not installed');+ caFile = cert.certFile;+ // The edge's port must be known before sam-one starts, since sam-one+ // advertises it; the edge then proxies to wherever sam-one bound.+ const edgePort = await stack.freePort();+ samOne = await stack.startSamOne({ externalUrl: `https://localhost:${edgePort}` });+ stops.push(() => samOne.stop());+ const edge = await stack.startTLSEdge({ host: 'localhost', origin: samOne.localUrl.replace('http://', ''), cert: cert.cert, key: cert.key, port: edgePort });+ stops.push(() => edge.stop());+ } else {+ samOne = await stack.startSamOne();+ stops.push(() => samOne.stop());+ }+ const site = await stack.serveStatic(stack.PAGE_DIR);+ stops.push(() => site.stop());++ // Enroll and join from the page, on an origin of its own.+ const query = new URLSearchParams({ controlPlaneUrl: samOne.publicUrl, bootstrapToken: samOne.joinToken, allowInsecure: 'true' });+ await page.goto(`${site.url}/?${query}`);+ await page.getByRole('button', { name: 'Join' }).click();+ await expect(page.locator('#status')).toContainText('accepting a2a://agent', { timeout: 30_000 });+ const browserPeer = (await page.locator('#peer-id').textContent()).trim();+ expect(browserPeer).toMatch(/^12D3Koo/);++ // A Node member calls the page's agent through the router.+ const nodeEnv = stack.exampleEnv({ publicUrl: samOne.publicUrl, joinToken: samOne.joinToken, caFile }, 'caller');+ const callOut = await stack.runExample('a2a-call', nodeEnv, [browserPeer, 'hello from node']);+ const nodePeer = /on the mesh as (\S+)/.exec(callOut)?.[1];+ expect(nodePeer, callOut).toBeTruthy();+ expect(callOut).toContain('agent: Echo agent (browser)');+ expect(callOut).toContain(`${nodePeer} said: hello from node`);+ await expect(page.locator('#log')).toContainText(`message from ${nodePeer}: hello from node`);++ // The page calls a Node agent.+ const agent = await stack.startExampleAgent('a2a-agent', stack.exampleEnv({ publicUrl: samOne.publicUrl, joinToken: samOne.joinToken, caFile }, 'agent'));+ stops.push(() => agent.stop());+ await page.locator('#target-peer').fill(agent.peerId);+ await page.locator('#message').fill('hello from a browser');+ await page.getByRole('button', { name: 'Call' }).click();+ await expect(page.locator('#answer')).toContainText(`Echo agent: ${browserPeer} said: hello from a browser`, { timeout: 30_000 });++ // A reload resumes the saved enrollment: same peer, no token.+ const resume = new URLSearchParams({ controlPlaneUrl: samOne.publicUrl, allowInsecure: 'true' });+ await page.goto(`${site.url}/?${resume}`);+ await page.getByRole('button', { name: 'Join' }).click();+ await expect(page.locator('#status')).toContainText('accepting a2a://agent', { timeout: 30_000 });+ expect((await page.locator('#peer-id').textContent()).trim()).toBe(browserPeer);+ } finally {+ for (const stop of stops.reverse()) {+ stop();+ }+ }+ });+}diff --git a/tests/ui/lib/sam-one.js b/tests/ui/lib/sam-one.jsnew file mode 100644index 00000000..e906730a--- /dev/null+++ b/tests/ui/lib/sam-one.js@@ -0,0 +1,249 @@+// 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.++// The pieces the browser SDK test stands up around Chromium: sam-one from+// bin/, a TLS-terminating edge in front of it that routes by name the way+// `sam-one --tunnel` puts one there, a static server for the page, and the+// Node example programs from sdk/js as the other members.++const { spawn, spawnSync } = require('node:child_process');+const fs = require('node:fs');+const http = require('node:http');+const https = require('node:https');+const net = require('node:net');+const os = require('node:os');+const path = require('node:path');+const tls = require('node:tls');++const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');+const SDK_JS = path.join(REPO_ROOT, 'sdk', 'js');+const PAGE_DIR = path.join(SDK_JS, 'build', 'browser-example');++/** Why the test cannot run here, or '' when everything is in place. */+function missing() {+ if (!fs.existsSync(path.join(REPO_ROOT, 'bin', 'sam-one'))) {+ return 'bin/sam-one is not built (make build)';+ }+ if (!fs.existsSync(path.join(PAGE_DIR, 'index.html')) || !fs.existsSync(path.join(SDK_JS, 'build', 'examples', 'a2a-call.js'))) {+ return 'the sdk/js browser example is not built (tests/ui/run.sh builds it)';+ }+ return '';+}++function freePort() {+ return new Promise((resolve, reject) => {+ const srv = net.createServer();+ srv.listen(0, '127.0.0.1', () => {+ const { port } = srv.address();+ srv.close(() => resolve(port));+ });+ srv.on('error', reject);+ });+}++async function waitFor(url, what, tries = 100) {+ for (let i = 0; i < tries; i++) {+ try {+ const res = await fetch(url);+ if (res.ok) {+ return;+ }+ } catch {+ // not up yet+ }+ await new Promise((r) => setTimeout(r, 100));+ }+ throw new Error(`timed out waiting for ${what} at ${url}`);+}++/** Runs bin/sam-one on a free loopback port; externalUrl is what it advertises. */+async function startSamOne({ externalUrl } = {}) {+ const port = await freePort();+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sam-one-ui-'));+ const args = ['--bind-address', '127.0.0.1', '--port', String(port), '--data-dir', dataDir, '--log-level', 'warn'];+ if (externalUrl) {+ args.push('--external-url', externalUrl);+ }+ const proc = spawn(path.join(REPO_ROOT, 'bin', 'sam-one'), args, { stdio: ['ignore', 'pipe', 'pipe'] });+ let output = '';+ proc.stdout.on('data', (d) => (output += d));+ proc.stderr.on('data', (d) => (output += d));+ const localUrl = `http://127.0.0.1:${port}`;+ try {+ await waitFor(`${localUrl}/readyz`, 'sam-one');+ } catch (err) {+ proc.kill();+ throw new Error(`${err.message}\n${output}`);+ }+ return {+ localUrl,+ publicUrl: externalUrl ?? localUrl,+ joinToken: fs.readFileSync(path.join(dataDir, 'join-token'), 'utf8').trim(),+ get output() {+ return output;+ },+ stop() {+ proc.kill();+ fs.rmSync(dataDir, { recursive: true, force: true });+ },+ };+}++/** A self-signed certificate for host, from openssl; null when openssl is not installed. */+function selfSignedCert(host) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sam-edge-'));+ const cert = path.join(dir, 'cert.pem');+ const key = path.join(dir, 'key.pem');+ const r = spawnSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', key, '-out', cert, '-days', '1', '-subj', `/CN=${host}`, '-addext', `subjectAltName=DNS:${host}`], { stdio: 'pipe' });+ if (r.error || r.status !== 0) {+ fs.rmSync(dir, { recursive: true, force: true });+ return null;+ }+ return { certFile: cert, cert: fs.readFileSync(cert), key: fs.readFileSync(key), dir };+}++function hostOf(req) {+ const h = req.headers.host ?? '';+ return h.includes(':') ? h.slice(0, h.lastIndexOf(':')) : h;+}++/**+ * Terminates TLS 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, as an edge that routes by name treats a client+ * that reached it by IP.+ */+async function startTLSEdge({ host, origin, cert, key, port = 0 }) {+ const [originHost, originPort] = origin.split(':');+ const context = tls.createSecureContext({ cert, key });+ const server = https.createServer(+ {+ cert,+ key,+ SNICallback: (name, cb) => (name.toLowerCase() === host ? cb(null, context) : cb(new Error(`edge: unknown server name ${name}`))),+ },+ (req, res) => {+ if (hostOf(req).toLowerCase() !== host) {+ res.writeHead(403, { 'content-type': 'text/plain' });+ res.end(`403 Forbidden (edge: unknown host ${req.headers.host})\n`);+ return;+ }+ const upstream = http.request({ host: originHost, port: Number(originPort), method: req.method, path: req.url, headers: { ...req.headers, host: origin } }, (ur) => {+ res.writeHead(ur.statusCode, ur.headers);+ ur.pipe(res);+ });+ upstream.on('error', () => {+ res.writeHead(502);+ res.end();+ });+ req.pipe(upstream);+ },+ );+ server.on('upgrade', (req, socket, head) => {+ if (hostOf(req).toLowerCase() !== host) {+ socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');+ return;+ }+ const upstream = net.connect(Number(originPort), originHost, () => {+ const lines = [`${req.method} ${req.url} HTTP/1.1`];+ for (let i = 0; i < req.rawHeaders.length; i += 2) {+ const name = req.rawHeaders[i];+ lines.push(`${name}: ${name.toLowerCase() === 'host' ? origin : req.rawHeaders[i + 1]}`);+ }+ upstream.write(lines.join('\r\n') + '\r\n\r\n');+ if (head.length > 0) {+ upstream.write(head);+ }+ socket.pipe(upstream).pipe(socket);+ });+ upstream.on('error', () => socket.destroy());+ socket.on('error', () => upstream.destroy());+ });+ await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve));+ return { url: `https://${host}:${server.address().port}`, port: server.address().port, stop: () => server.close() };+}++const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.map': 'application/json', '.wasm': 'application/wasm' };++/** Serves a directory of static files on a free loopback port. */+async function serveStatic(dir) {+ const server = http.createServer((req, res) => {+ const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';+ const file = path.join(dir, rel);+ if (!file.startsWith(dir) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {+ res.writeHead(404);+ res.end();+ return;+ }+ res.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream' });+ fs.createReadStream(file).pipe(res);+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ return { url: `http://127.0.0.1:${server.address().port}`, stop: () => server.close() };+}++/** Runs one of sdk/js's built examples to completion and returns its output. */+function runExample(name, env, args = []) {+ return new Promise((resolve, reject) => {+ const proc = spawn('node', [path.join(SDK_JS, 'build', 'examples', `${name}.js`), ...args], { cwd: REPO_ROOT, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });+ let out = '';+ proc.stdout.on('data', (d) => (out += d));+ proc.stderr.on('data', (d) => (out += d));+ const timer = setTimeout(() => proc.kill(), 30_000);+ proc.on('close', (code) => {+ clearTimeout(timer);+ code === 0 ? resolve(out) : reject(new Error(`${name} exited with ${code}:\n${out}`));+ });+ });+}++/** Starts one of sdk/js's built example agents and waits for the line that names its peer. */+function startExampleAgent(name, env, ready = /accepting a2a:\/\/agent as (\S+)/) {+ return new Promise((resolve, reject) => {+ const proc = spawn('node', [path.join(SDK_JS, 'build', 'examples', `${name}.js`)], { cwd: REPO_ROOT, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });+ let out = '';+ const timer = setTimeout(() => {+ proc.kill();+ reject(new Error(`${name} did not come up:\n${out}`));+ }, 30_000);+ const onData = (d) => {+ out += d;+ const m = ready.exec(out);+ if (m) {+ clearTimeout(timer);+ resolve({ peerId: m[1], stop: () => proc.kill(), get output() { return out; } });+ }+ };+ proc.stdout.on('data', onData);+ proc.stderr.on('data', onData);+ proc.on('close', () => {+ clearTimeout(timer);+ reject(new Error(`${name} exited:\n${out}`));+ });+ });+}++/** The environment the Node examples take to join sam-one at publicUrl. */+function exampleEnv({ publicUrl, joinToken, caFile }, stateName) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `sam-${stateName}-`));+ fs.writeFileSync(path.join(dir, 'join-token'), joinToken + '\n', { mode: 0o600 });+ return {+ SAM_CONTROL_PLANE_URL: publicUrl,+ SAM_BOOTSTRAP_TOKEN_PATH: path.join(dir, 'join-token'),+ SAM_STATE_DIR: path.join(dir, 'state'),+ ...(caFile ? { NODE_EXTRA_CA_CERTS: caFile } : {}),+ };+}++module.exports = { PAGE_DIR, missing, freePort, startSamOne, selfSignedCert, startTLSEdge, serveStatic, runExample, startExampleAgent, exampleEnv };diff --git a/tests/ui/run.sh b/tests/ui/run.shindex a5461e09..6b64471c 100755--- a/tests/ui/run.sh+++ b/tests/ui/run.sh@@ -32,6 +32,14 @@ export SAM_CONSOLE_URL="${STACK_CONSOLE_URL}"stack_start+# The browser SDK test (browser-sdk.spec.js) runs sdk/js in a page against+# bin/sam-one; the page and the Node examples it talks to are built here.+cd "${REPO_ROOT}/sdk/js"+npm ci --no-audit --no-fund+npm run build+npm run examples+node scripts/bundle-browser.mjs examples/browser/app.js build/browser-example+cd "${REPO_ROOT}/tests/ui"npm ci --no-audit --no-fund# --with-deps needs root to install OS libraries; only CI runners allow that.