Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: hold two routers chosen by load and labels, and handle router go-away
Antonio Ojea1af6b7e89a87
diff --git a/sdk/README.md b/sdk/README.mdindex d9c7f850..90fc6f08 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -41,8 +41,9 @@ Milestones 1 to 5 are implemented and tested in both languages:| Persisted state (identity and credential, owner-only files; IndexedDB in a browser) | yes | yes || Biscuit verification of a peer's credential (signature, expiry, peer binding, roles, labels) | yes | yes || libp2p host as `agentmesh-node` configures it (TCP and WebSocket, TLS first and Noise, yamux) | yes | yes |-| `/mesh/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 |+| `/mesh/auth/1.0.0`, both sides; join = pick `k` routers (default 2) by selector, preference and load, handshake and check role | yes | yes |+| Circuit relay v2 reservation on each held router; dial and accept through them | yes | yes |+| `/mesh/goaway/1.0.0`: shun a draining or overloaded router for `retry_after` and replace it from the catalog; redial (`2s, 4s, 8s`) before failing over on a dropped connection | yes | yes || Service discovery in the mesh DHT (`/mesh/kad/1.0.0`) | yes | yes || `/mesh/mcp/1.0.0` client: list and call a provider's tools, or its catalog | yes | yes || Caller-side label requirements on the provider's credential | yes | yes |@@ -50,7 +51,7 @@ Milestones 1 to 5 are implemented and tested in both languages:| The mesh as a transport for HTTP clients: `session.fetch()` for fetch-based clients, `MeshTransport` for httpx, so the official A2A SDK's client works unchanged | `fetch` | httpx || Provider authorizer: the baseline Datalog and the mesh policy (`GET /policies`), evaluated as `agentmesh-node` does | yes | yes || A2A ingress for the agent: `/libp2p-http` for `a2a://<name>`, forwarded to an A2A server beside the process or answered in it; not announced anywhere | yes | yes |-| Control plane pull before join and on `agentmesh-node`'s interval: `/keys` verified against the trusted set, credential refresh after a rotation, `/info` bans and router addresses | yes | yes |+| Control plane pull before join and on `agentmesh-node`'s interval: `/keys` verified against the trusted set, credential refresh after a rotation, `/info` bans and router catalog (`routers` and `router_addresses`) | yes | yes || Gossip events from the control plane (`/mesh/events/v1`, StrictSign): ban enforced at once, key rotation adopted, policy update pulls | yes | yes || Banned peers refused: connections dropped and denied, handshakes and requests refused, dials refused | yes | yes || Runs in a browser page: WebSocket and Noise to the router, state in IndexedDB, the agent answered by a fetch handler; `sdk/js/examples/browser` against `agentmesh-one`, tested in Chromium | yes | — |@@ -324,12 +325,14 @@ length, then the bytes), with a 64 KiB cap on the first frame.- `/mesh/goaway/1.0.0` (`HandleGoAway`). A router opens it to a member itwill no longer hold and sends one `RouterGoAway{reason, retry_after}`:`DRAINING` when it is stopping, `OVERLOADED` when it holds more members- than its high watermark. The member closes the stream once it has acted,- attaches to another router and does not dial this one again before- `retry_after`; the router closes the connection 5 seconds after the- message either way. A member that does not register the protocol only- sees the connection close, which is what the SDKs do today: they redial- the routers on `/info` as before. Handling the message is an open item.+ than its high watermark. Both SDKs register the protocol, act only on a+ message from a router the session holds, close the stream, record the+ router as shunned for `retry_after` (default 5m, cap 1h), and immediately+ attach and reserve on another router from the catalog; the router closes+ the connection 5 seconds after the message either way. When a held+ router's connection drops without a go-away, the member redials it first+ (`2s, 4s, 8s`) and, if it does not come back or refuses auth, shuns it and+ tops up from the catalog.### Discovery (`internal/node/service.go`)diff --git a/sdk/js/src/auth.ts b/sdk/js/src/auth.tsindex 78c6794a..835deb09 100644--- a/sdk/js/src/auth.ts+++ b/sdk/js/src/auth.ts@@ -21,16 +21,31 @@ import type { Connection, Stream, StreamHandler } from "@libp2p/interface";import { lpStream } from "@libp2p/utils";import { BiscuitVerificationError, verifyPeerBiscuit, type VerifiedBiscuit } from "./biscuit.ts";import { decodeAuthResponse } from "./credential.ts";-import { AuthFrameSchema, AuthResponseSchema } from "./gen/agentmesh_pb.ts";+import {+ AuthFrameSchema,+ AuthResponseSchema,+ RouterGoAwaySchema,+ RouterGoAway_Reason,+ type RouterGoAway,+} from "./gen/agentmesh_pb.ts";export const AUTH_PROTOCOL = "/mesh/auth/1.0.0";export const MCP_PROTOCOL = "/mesh/mcp/1.0.0";+export const GOAWAY_PROTOCOL = "/mesh/goaway/1.0.0";/** The first frame on a stream is capped, as msgio.NewVarintReaderSize(s, 64 KiB). */export const MAX_AUTH_FRAME_BYTES = 64 * 1024;/** How long either side waits for the other's frame. */export const AUTH_HANDSHAKE_TIMEOUT_MS = 10_000;+/** The go-away message on /mesh/goaway/1.0.0 is capped at 1 KiB, with a 5s read timeout. */+export const MAX_GOAWAY_MESSAGE_BYTES = 1024;+export const GOAWAY_STREAM_TIMEOUT_MS = 5_000;+/** Default duration a router is shunned when retry_after is unset or non-positive (5 minutes). */+export const ROUTER_SHUN_DURATION_MS = 5 * 60_000;+/** Maximum duration a router go-away retry_after can shun a router (1 hour). */+export const GOAWAY_MAX_RETRY_AFTER_MS = 60 * 60_000;+export class AuthRejectedError extends Error {constructor(peerId: string, reason: string) {super(`peer ${peerId} rejected the auth handshake: ${reason}`);@@ -114,3 +129,70 @@ export function authStreamHandler(options: AuthServerOptions): StreamHandler {}};}++/** Returns the canonical proto enum name for a RouterGoAway_Reason value. */+export function goAwayReasonName(reason: RouterGoAway_Reason): string {+ switch (reason) {+ case RouterGoAway_Reason.DRAINING:+ return "DRAINING";+ case RouterGoAway_Reason.OVERLOADED:+ return "OVERLOADED";+ default:+ return "REASON_UNSPECIFIED";+ }+}++/**+ * Computes the shun duration in milliseconds from a RouterGoAway message:+ * defaults to ROUTER_SHUN_DURATION_MS (5m) when retry_after <= 0, capped at+ * GOAWAY_MAX_RETRY_AFTER_MS (1h).+ */+export function clampGoAwayRetryAfterMs(msg: RouterGoAway): number {+ let ms = 0;+ if (msg.retryAfter !== undefined) {+ ms = Number(msg.retryAfter.seconds) * 1000 + Math.floor(msg.retryAfter.nanos / 1_000_000);+ }+ if (ms <= 0) {+ return ROUTER_SHUN_DURATION_MS;+ }+ if (ms > GOAWAY_MAX_RETRY_AFTER_MS) {+ return GOAWAY_MAX_RETRY_AFTER_MS;+ }+ return ms;+}++export interface GoAwayServerOptions {+ /** Whether peerId is currently a router this member holds. */+ isHeldRouter(peerId: string): boolean;+ /** Called once a held router's RouterGoAway message has been read and the stream closed. */+ onGoAway(peerId: string, msg: RouterGoAway, retryAfterMs: number): void | Promise<void>;+}++/**+ * Server side of /mesh/goaway/1.0.0, mirroring agentmesh-node's HandleGoAway:+ * reads one varint-prefixed RouterGoAway message (1024 B cap, 5s timeout) only+ * from a router the member currently holds, closes the stream, and notifies+ * the session to shun the router and top up from the catalog.+ */+export function goAwayStreamHandler(options: GoAwayServerOptions): StreamHandler {+ return async (stream: Stream, connection: Connection) => {+ const peerId = connection.remotePeer.toString();+ if (!options.isHeldRouter(peerId)) {+ stream.abort(new Error(`ignoring go-away from unattached peer ${peerId}`));+ return;+ }+ const signal = AbortSignal.timeout(GOAWAY_STREAM_TIMEOUT_MS);+ let msg: RouterGoAway;+ try {+ const lp = lpStream(stream, { maxDataLength: MAX_GOAWAY_MESSAGE_BYTES });+ msg = fromBinary(RouterGoAwaySchema, (await lp.read({ signal })).subarray());+ } catch (err) {+ stream.abort(err instanceof Error ? err : new Error(String(err)));+ return;+ }+ await stream.close().catch(() => stream.abort(new Error("goaway stream close failed")));+ const retryAfterMs = clampGoAwayRetryAfterMs(msg);+ await options.onGoAway(peerId, msg, retryAfterMs);+ };+}+diff --git a/sdk/js/src/conformance-join.ts b/sdk/js/src/conformance-join.tsindex a0d6bd83..74409cf5 100644--- a/sdk/js/src/conformance-join.ts+++ b/sdk/js/src/conformance-join.ts@@ -139,7 +139,13 @@ async function handle(session: MeshSession, command: Command): Promise<unknown>case "peers":return { cmd: "peers", authenticated_peers: [...session.authenticatedPeers.keys()].sort() };case "routers":- return { cmd: "routers", ok: true, routers: session.routers.map((r) => r.peerId), relay_addresses: session.relayAddresses.map((ma) => ma.toString()) };+ return {+ cmd: "routers",+ ok: true,+ routers: session.routers.map((r) => r.peerId),+ relay_addresses: session.relayAddresses.map((ma) => ma.toString()),+ go_away_received: Object.fromEntries(session.goAwayReceived),+ };case "sync": {const result = await session.sync();return {@@ -204,6 +210,13 @@ async function main(): Promise<void> {// is the floor every provider this member calls must attest.const labels = labelsFromEnv("AGENTMESH_SDK_LABELS");const egressRequireLabels = labelsFromEnv("AGENTMESH_SDK_EGRESS_REQUIRE_LABELS");+ const routerSelector = labelsFromEnv("AGENTMESH_SDK_ROUTER_SELECTOR");+ const routerPrefer = labelsFromEnv("AGENTMESH_SDK_ROUTER_PREFER");+ const routerCount = process.env.AGENTMESH_SDK_ROUTER_COUNT;+ const redialBackoffs = (process.env.AGENTMESH_SDK_REDIAL_BACKOFF_SECONDS ?? "")+ .split(",")+ .filter((s) => s.trim() !== "")+ .map((s) => Number(s.trim()) * 1000);// AGENTMESH_SDK_RELAY_CHECK_SECONDS shortens how often the relay reservation is// checked, so a test that moves a router sees the member follow it within// its budget.@@ -227,6 +240,10 @@ async function main(): Promise<void> {const session = await mesh.join({listenAddrs,...(routerAddresses !== undefined ? { routerAddresses } : {}),+ ...(routerCount !== undefined && routerCount !== "" ? { routers: Number(routerCount) } : {}),+ ...(Object.keys(routerSelector).length > 0 ? { routerSelector } : {}),+ ...(Object.keys(routerPrefer).length > 0 ? { routerPrefer } : {}),+ ...(redialBackoffs.length > 0 ? { routerRedialBackoffsMs: redialBackoffs } : {}),...(Object.keys(egressRequireLabels).length > 0 ? { egressRequireLabels } : {}),...relayOptions,signal: AbortSignal.timeout(20_000),diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.tsindex ebb306d6..fe486479 100644--- a/sdk/js/src/index.ts+++ b/sdk/js/src/index.ts@@ -52,7 +52,20 @@ export {registerChallenge,revocationsChallenge,} from "./challenges.ts";-export { MeshSession, type AdmittedRouter, type DiscoveredProvider, type JoinOptions, type Peer, type ToolCallResult } from "./session.ts";+export {+ DEFAULT_ROUTERS,+ MeshSession,+ ROUTER_REDIAL_BACKOFFS_MS,+ candidatesFromRouterInfos,+ selectRouters,+ type AdmittedRouter,+ type DiscoveredProvider,+ type JoinOptions,+ type Peer,+ type RouterCandidate,+ type SelectRoutersOptions,+ type ToolCallResult,+} from "./session.ts";export {BiscuitVerificationError,ROLE_ROUTER,@@ -78,7 +91,23 @@ export {validateTaskRule,type TaskRequestContext,} from "./tar.ts";-export { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, authenticateWithPeer, authStreamHandler } from "./auth.ts";+export {+ AUTH_HANDLER_OPTIONS,+ AUTH_PROTOCOL,+ GOAWAY_MAX_RETRY_AFTER_MS,+ GOAWAY_PROTOCOL,+ GOAWAY_STREAM_TIMEOUT_MS,+ MAX_GOAWAY_MESSAGE_BYTES,+ MCP_PROTOCOL,+ ROUTER_SHUN_DURATION_MS,+ AuthRejectedError,+ authenticateWithPeer,+ authStreamHandler,+ clampGoAwayRetryAfterMs,+ goAwayReasonName,+ goAwayStreamHandler,+ type GoAwayServerOptions,+} from "./auth.ts";export { createMeshHost, type MeshHost, type MeshHostOptions } from "./host.ts";export { DHT_PROTOCOL, isServiceType, parseServiceTarget, serviceCID, type ServiceType } from "./discovery.ts";export { LabelsNotSatisfiedError, StreamTransport, openMCPSession, requireEgressLabels, requireLabels, type MCPSession, type MCPSessionOptions } from "./mcp.ts";diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.tsindex c92da972..9f34ac6f 100644--- a/sdk/js/src/mesh.ts+++ b/sdk/js/src/mesh.ts@@ -26,7 +26,7 @@ import {withCredentialMethods,type MeshCredential,} from "./credential.ts";-import type { TaskAuthorizationRuleSchema } from "./gen/agentmesh_pb.ts";+import type { RouterInfo, TaskAuthorizationRuleSchema } from "./gen/agentmesh_pb.ts";import { Identity } from "./identity.ts";import { openState, readTextFile } from "./platform/state.ts";import type { StateStore } from "./platform/types.ts";@@ -126,6 +126,8 @@ export interface ControlPlaneSync {refreshed: boolean;/** The control plane's ban set, when /info answered. */bannedPeerIds: string[] | undefined;+ /** Every router with a live lease reported by /info, when present. */+ routers?: RouterInfo[] | undefined;/** When /info was asked; a ban recorded later cannot be in the answer. */fetchedAt: Date;/** One entry per part that failed; empty when everything landed. */@@ -141,6 +143,7 @@ export class AgentMesh {readonly identity: Identity;readonly controlPlane: ControlPlaneClient;#credential: MeshCredential;+ #routers: RouterInfo[] = [];readonly #state: StateStore | undefined;readonly #jwtSource: (() => Promise<string>) | undefined;// Refreshes run one after another, as agentmesh-node's refreshMu: the control@@ -170,6 +173,11 @@ export class AgentMesh {return this.#credential;}+ /** The router catalog last returned by /info; empty when the control plane only listed router_addresses. */+ get routers(): RouterInfo[] {+ return this.#routers;+ }+/** Returns a new MeshCredential with a tar_block appended offline in memory. */attenuate(rule: MessageInitShape<typeof TaskAuthorizationRuleSchema>): Promise<MeshCredential> {return attenuateCredential(this.#credential, rule);@@ -391,13 +399,20 @@ export class AgentMesh {}let bannedPeerIds: string[] | undefined;+ let routers: RouterInfo[] | undefined;// Taken before the request: a ban recorded after this instant cannot be// in the answer, so its absence must not be read as an unban.const fetchedAt = new Date();try {const info = await this.controlPlane.info();- if (info.routerAddresses.length > 0) {- this.#credential = withCredentialMethods({ ...this.#credential, routerAddresses: info.routerAddresses });+ routers = info.routers;+ this.#routers = info.routers;+ const discovered =+ info.routerAddresses.length > 0+ ? info.routerAddresses+ : info.routers.flatMap((r) => r.addresses).filter((a) => a.length > 0);+ if (discovered.length > 0) {+ this.#credential = withCredentialMethods({ ...this.#credential, routerAddresses: discovered });}bannedPeerIds = info.bannedPeerIds;} catch (err) {@@ -406,7 +421,7 @@ export class AgentMesh {if (keysChanged || bannedPeerIds !== undefined) {await this.save();}- return { keysChanged, refreshed, bannedPeerIds, fetchedAt, errors };+ return { keysChanged, refreshed, bannedPeerIds, routers, fetchedAt, errors };}/**diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.tsindex fe59c5f0..e5334bb3 100644--- a/sdk/js/src/session.test.ts+++ b/sdk/js/src/session.test.ts@@ -18,7 +18,7 @@// plane are exercised by tests/integration/sdk_join_test.go.import { create, fromBinary, toBinary } from "@bufbuild/protobuf";-import { timestampFromMs } from "@bufbuild/protobuf/wkt";+import { durationFromMs, timestampFromMs } from "@bufbuild/protobuf/wkt";import { yamux } from "@chainsafe/libp2p-yamux";import { circuitRelayServer, circuitRelayTransport } from "@libp2p/circuit-relay-v2";import { privateKeyFromProtobuf } from "@libp2p/crypto/keys";@@ -26,6 +26,7 @@ import { identify } from "@libp2p/identify";import type { Libp2p } from "@libp2p/interface";import { tcp } from "@libp2p/tcp";import { tls } from "@libp2p/tls";+import { lpStream } from "@libp2p/utils";import { multiaddr } from "@multiformats/multiaddr";import { createLibp2p } from "libp2p";import assert from "node:assert/strict";@@ -33,15 +34,15 @@ import { mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { after, before, test } from "node:test";-import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, AuthRejectedError, authenticateWithPeer, authStreamHandler } from "./auth.ts";+import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, AuthRejectedError, GOAWAY_MAX_RETRY_AFTER_MS, GOAWAY_PROTOCOL, ROUTER_SHUN_DURATION_MS, authenticateWithPeer, authStreamHandler, clampGoAwayRetryAfterMs } from "./auth.ts";import { BiscuitVerificationError, ROLE_ROUTER, loadBiscuit, verifyPeerBiscuit } from "./biscuit.ts";import { ROLE_NODE } from "./controlplane.ts";-import { BootstrapEnrollRequestSchema, BootstrapEnrollResponseSchema, ControlPlaneInfoResponseSchema, EnrollmentStatus, KeysResponseSchema, AuthFrameSchema, TokenRefreshRequestSchema, TokenRefreshResponseSchema } from "./gen/agentmesh_pb.ts";+import { BootstrapEnrollRequestSchema, BootstrapEnrollResponseSchema, ControlPlaneInfoResponseSchema, EnrollmentStatus, KeysResponseSchema, AuthFrameSchema, RouterGoAwaySchema, RouterGoAway_Reason, RouterInfoSchema, TokenRefreshRequestSchema, TokenRefreshResponseSchema, type RouterInfo } from "./gen/agentmesh_pb.ts";import { Identity } from "./identity.ts";import { HTTP_HANDLER_OPTIONS, HTTP_PROTOCOL, a2aEndpoint, httpIngressHandler } from "./libp2p-http.ts";import { LabelsNotSatisfiedError } from "./mcp.ts";import { AgentMesh } from "./mesh.ts";-import { MeshSession, type JoinOptions } from "./session.ts";+import { MeshSession, candidatesFromRouterInfos, selectRouters, type JoinOptions } from "./session.ts";type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;type KeyPair = InstanceType<Wasm["KeyPair"]>;@@ -90,7 +91,7 @@ function proto(bytes: Uint8Array): Response {* /info lists routerAddresses as they are at the time of the request, so a* test that changes the array has the member pull the change.*/-function fakeControlPlane(routerAddresses: string[]): typeof fetch {+function fakeControlPlane(routerAddresses: string[], routers: RouterInfo[] = []): typeof fetch {return (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {const req = new Request(input, init);const path = new URL(req.url).pathname;@@ -114,7 +115,7 @@ function fakeControlPlane(routerAddresses: string[]): typeof fetch {return proto(toBinary(KeysResponseSchema, create(KeysResponseSchema, { publicKeys: [cpKey], signTime: timestampFromMs(Date.now()) })));}if (req.method === "GET" && path === "/info") {- return proto(toBinary(ControlPlaneInfoResponseSchema, create(ControlPlaneInfoResponseSchema, { routerAddresses: [...routerAddresses] })));+ return proto(toBinary(ControlPlaneInfoResponseSchema, create(ControlPlaneInfoResponseSchema, { routerAddresses: [...routerAddresses], routers: [...routers] })));}return new Response(`no route for ${req.method} ${path}`, { status: 404 });}) as typeof fetch;@@ -627,3 +628,195 @@ test("session.attenuate and session.seal narrow outbound requests across hops anawait Promise.all([session.close(), provider.stop()]);}});++test("selectRouters filters by selector, orders by prefer and load, and clampGoAwayRetryAfterMs bounds durations", () => {+ const infos: RouterInfo[] = [+ create(RouterInfoSchema, {+ peerId: "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",+ addresses: ["/ip4/127.0.0.1/tcp/5001/p2p/12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"],+ labels: { region: "us-west", zone: "b" },+ connections: 80,+ connectionLimit: 100,+ }),+ create(RouterInfoSchema, {+ peerId: "12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC",+ addresses: ["/ip4/127.0.0.1/tcp/5002/p2p/12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC"],+ labels: { region: "us-west", zone: "a" },+ connections: 90,+ connectionLimit: 100,+ }),+ create(RouterInfoSchema, {+ peerId: "12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD",+ addresses: ["/ip4/127.0.0.1/tcp/5003/p2p/12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD"],+ labels: { region: "us-west", zone: "b" },+ connections: 10,+ connectionLimit: 100,+ }),+ create(RouterInfoSchema, {+ peerId: "12D3KooWD4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSE",+ addresses: ["/ip4/127.0.0.1/tcp/5004/p2p/12D3KooWD4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSE"],+ labels: { region: "eu-west", zone: "a" },+ connections: 1,+ connectionLimit: 100,+ }),+ ];+ const catalog = candidatesFromRouterInfos(infos, []);+ assert.equal(catalog.length, 4);++ // Filter to region=us-west, prefer zone=a first, then lower load (10/100 before 80/100).+ const picked = selectRouters(catalog, 10, {+ selector: { region: "us-west" },+ prefer: { zone: "a" },+ random: () => 0,+ });+ assert.deepEqual(+ picked.map((c) => c.peerId),+ [+ "12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC",+ "12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD",+ "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",+ ],+ );++ // Shunned routers are excluded.+ const withoutPreferred = selectRouters(catalog, 10, {+ selector: { region: "us-west" },+ prefer: { zone: "a" },+ shunned: new Map([["12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC", Date.now() + 60_000]]),+ random: () => 0,+ });+ assert.deepEqual(+ withoutPreferred.map((c) => c.peerId),+ [+ "12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD",+ "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",+ ],+ );++ // Fallback to routerAddresses when routers is empty.+ const fallback = candidatesFromRouterInfos([], ["/ip4/127.0.0.1/tcp/5001/p2p/12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"]);+ assert.equal(fallback.length, 1);+ assert.equal(fallback[0]?.peerId, "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB");++ // Retry-after clamping: default 5m when absent/non-positive, cap at 1h.+ assert.equal(clampGoAwayRetryAfterMs(create(RouterGoAwaySchema, {})), ROUTER_SHUN_DURATION_MS);+ assert.equal(clampGoAwayRetryAfterMs(create(RouterGoAwaySchema, { retryAfter: durationFromMs(0) })), ROUTER_SHUN_DURATION_MS);+ assert.equal(clampGoAwayRetryAfterMs(create(RouterGoAwaySchema, { retryAfter: durationFromMs(-1000) })), ROUTER_SHUN_DURATION_MS);+ assert.equal(clampGoAwayRetryAfterMs(create(RouterGoAwaySchema, { retryAfter: durationFromMs(600_000) })), 600_000);+ assert.equal(clampGoAwayRetryAfterMs(create(RouterGoAwaySchema, { retryAfter: durationFromMs(7_200_000) })), GOAWAY_MAX_RETRY_AFTER_MS);+});++test("join holds two routers chosen by load and labels, handles /mesh/goaway/1.0.0, and redials before failing over", async () => {+ const startRouterHost = async () => {+ const host = await createLibp2p({+ addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },+ transports: [tcp()],+ connectionEncrypters: [tls()],+ streamMuxers: [yamux()],+ services: { identify: identify(), relay: circuitRelayServer() },+ connectionManager: { inboundConnectionThreshold: Infinity },+ });+ const peerId = host.peerId.toString();+ const biscuit = mint(peerId, ROLE_ROUTER);+ const handshakes: string[] = [];+ await host.handle(+ AUTH_PROTOCOL,+ authStreamHandler({ ownBiscuit: () => biscuit, trustedKeys: () => [cpKey], onAuthenticated: (p) => handshakes.push(p) }),+ );+ const addr = (host.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString();+ return { host, peerId, addr, handshakes };+ };++ const r1 = await startRouterHost();+ const r2 = await startRouterHost();+ const r3 = await startRouterHost();+ try {+ // r1 (low load, preferred) and r2 (medium load) should be chosen over r3 (high load).+ const routerInfos: RouterInfo[] = [+ create(RouterInfoSchema, { peerId: r3.peerId, addresses: [r3.addr], labels: { region: "us", tier: "backup" }, connections: 90, connectionLimit: 100 }),+ create(RouterInfoSchema, { peerId: r1.peerId, addresses: [r1.addr], labels: { region: "us", tier: "primary" }, connections: 50, connectionLimit: 100 }),+ create(RouterInfoSchema, { peerId: r2.peerId, addresses: [r2.addr], labels: { region: "us", tier: "backup" }, connections: 10, connectionLimit: 100 }),+ ];+ const allAddrs = [r3.addr, r1.addr, r2.addr];+ const mesh = await AgentMesh.enroll({+ controlPlaneUrl: "http://127.0.0.1:1",+ bootstrapToken: "sbt",+ fetch: fakeControlPlane(allAddrs, routerInfos),+ });+ const session = await mesh.join({+ refreshLeadMs: 0,+ routers: 2,+ routerSelector: { region: "us" },+ routerPrefer: { tier: "primary" },+ relayCheckIntervalMs: 200,+ routerRedialBackoffsMs: [30, 60],+ });+ try {+ // Only r1 and r2 were authenticated and reserved on at join; r3 is untouched in the catalog.+ assert.deepEqual(+ session.routers.map((r) => r.peerId).sort(),+ [r1.peerId, r2.peerId].sort(),+ );+ assert.deepEqual(r3.handshakes, []);+ assert.equal(session.relayAddresses.length, 2);+ assert.ok(session.relayAddresses.some((ma) => ma.toString().startsWith(r1.addr)));+ assert.ok(session.relayAddresses.some((ma) => ma.toString().startsWith(r2.addr)));++ // A go-away from a peer we do NOT hold (r3) is ignored.+ await session.handleGoAway(r3.peerId, create(RouterGoAwaySchema, { reason: RouterGoAway_Reason.DRAINING }), 600_000);+ assert.equal(session.goAwayReceived.size, 0);++ // Now r1 opens a /mesh/goaway/1.0.0 stream over its existing connection to the member.+ const r1Conns = r1.host.getConnections(session.node.peerId);+ assert.ok(r1Conns.length > 0, "r1 should have an active connection to the member");+ const stream = await r1Conns[0]!.newStream(GOAWAY_PROTOCOL);+ const goAwayBytes = toBinary(+ RouterGoAwaySchema,+ create(RouterGoAwaySchema, { reason: RouterGoAway_Reason.DRAINING, retryAfter: durationFromMs(600_000) }),+ );+ await lpStream(stream).write(goAwayBytes);+ await stream.close();++ // Wait for the member to drop r1, shun it, and top up with r3 from the catalog.+ const deadline = Date.now() + 10_000;+ while (+ (!session.routers.some((r) => r.peerId === r3.peerId) ||+ session.routers.some((r) => r.peerId === r1.peerId) ||+ !session.relayAddresses.some((ma) => ma.toString().startsWith(r3.addr))) &&+ Date.now() < deadline+ ) {+ await new Promise((r) => setTimeout(r, 50));+ }+ assert.deepEqual(+ session.routers.map((r) => r.peerId).sort(),+ [r2.peerId, r3.peerId].sort(),+ );+ assert.deepEqual(Object.fromEntries(session.goAwayReceived), { DRAINING: 1 });+ assert.ok(session.shunnedRouters.has(r1.peerId), "r1 should be shunned after go-away");+ assert.ok(session.relayAddresses.some((ma) => ma.toString().startsWith(r2.addr)));+ assert.ok(session.relayAddresses.some((ma) => ma.toString().startsWith(r3.addr)));+ assert.ok(!session.relayAddresses.some((ma) => ma.toString().startsWith(r1.addr)));++ // Stop r3 completely so redialing r3 fails and shuns r3.+ await r3.host.stop();+ const dropDeadline = Date.now() + 10_000;+ while (!session.shunnedRouters.has(r3.peerId) && Date.now() < dropDeadline) {+ await new Promise((r) => setTimeout(r, 50));+ }+ assert.ok(session.shunnedRouters.has(r3.peerId), "stopped router r3 should be shunned after redial attempts fail");+ assert.deepEqual(+ session.routers.map((r) => r.peerId),+ [r2.peerId],+ );+ } finally {+ await session.close();+ }+ } finally {+ await Promise.all([+ Promise.resolve(r1.host.stop()).catch(() => {}),+ Promise.resolve(r2.host.stop()).catch(() => {}),+ Promise.resolve(r3.host.stop()).catch(() => {}),+ ]);+ }+});+diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.tsindex 7f588907..6474b19c 100644--- a/sdk/js/src/session.ts+++ b/sdk/js/src/session.ts@@ -18,13 +18,22 @@ import { timestampMs } from "@bufbuild/protobuf/wkt";import { TopicValidatorResult } from "@libp2p/gossipsub";import { peerIdFromString } from "@libp2p/peer-id";import { isMultiaddr, multiaddr, type Multiaddr } from "@multiformats/multiaddr";-import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts";+import {+ AUTH_HANDLER_OPTIONS,+ AUTH_PROTOCOL,+ GOAWAY_PROTOCOL,+ ROUTER_SHUN_DURATION_MS,+ authenticateWithPeer,+ authStreamHandler,+ goAwayReasonName,+ goAwayStreamHandler,+} from "./auth.ts";import { ROLE_ROUTER, attenuateBiscuit, requireRole, sealBiscuit, type VerifiedBiscuit } from "./biscuit.ts";import { ROLE_NODE } from "./controlplane.ts";import { encodeAuthFrame } from "./credential.ts";import { canonicalPeerId } from "./identity.ts";import { isServiceType, parseServiceTarget, serviceCID } from "./discovery.ts";-import type { TaskAuthorizationRuleSchema } from "./gen/agentmesh_pb.ts";+import type { RouterGoAway, RouterInfo, TaskAuthorizationRuleSchema } from "./gen/agentmesh_pb.ts";import { createMeshHost, listenThroughRelay, type MeshHost, type MeshHostOptions, type RelayListener } from "./host.ts";import { openMCPSession, requireEgressLabels, type MCPSession, type MCPSessionOptions } from "./mcp.ts";import type { AgentMesh, ControlPlaneSync } from "./mesh.ts";@@ -45,6 +54,11 @@ import {import { ingressHandler } from "./platform/ingress.ts";import { BanSet, GOSSIP_EVENTS_TOPIC, MeshEvent_Type, verifyMeshEvent } from "./sync.ts";+/** Default number of routers a member attaches to and reserves on at join. */+export const DEFAULT_ROUTERS = 2;+/** Default backoff delays before replacing a dropped held router. */+export const ROUTER_REDIAL_BACKOFFS_MS: readonly number[] = [2_000, 4_000, 8_000];+export interface JoinOptions extends MeshHostOptions {/*** The routers to join through, `/…/p2p/<router>` multiaddrs, instead of@@ -54,8 +68,29 @@ export interface JoinOptions extends MeshHostOptions {*/routerAddresses?: string[];/**- * Reserve a relay slot on the first router that admits us, so peers can- * reach this member through the router. On by default; a member that+ * Number of routers to hold and reserve on at a time (agentmesh-node's --routers).+ * Defaults to DEFAULT_ROUTERS (2).+ */+ routers?: number;+ /**+ * Required router labels (agentmesh-node's --router-selector): every pair must+ * match the router's labels in ControlPlaneInfoResponse.routers.+ */+ routerSelector?: Record<string, string>;+ /**+ * Preferred router labels (agentmesh-node's --router-prefer): routers matching+ * more pairs are chosen ahead of others before comparing load.+ */+ routerPrefer?: Record<string, string>;+ /**+ * Backoff delays (ms) when redialing a held router whose connection dropped+ * before shunning it and failing over to another router from the catalog.+ * Defaults to ROUTER_REDIAL_BACKOFFS_MS ([2000, 4000, 8000]).+ */+ routerRedialBackoffsMs?: readonly number[];+ /**+ * Reserve a relay slot on each held router that admits us, so peers can+ * reach this member through the routers. On by default; a member that* only calls out can turn it off.*/reserveRelay?: boolean;@@ -103,6 +138,15 @@ export interface AdmittedRouter {credential: VerifiedBiscuit;}+/** One router candidate from the control plane's /info catalog. */+export interface RouterCandidate {+ peerId: string;+ addresses: Multiaddr[];+ labels: Record<string, string>;+ connections: number;+ connectionLimit: number;+}+/** A peer the DHT names as offering a service. */export interface DiscoveredProvider {peerId: string;@@ -158,6 +202,10 @@ export class MeshSession {readonly authenticatedPeers: Map<string, Date>;/** Peers the control plane has banned; connections to and from them are refused. */readonly banned: BanSet;+ /** Count of /mesh/goaway/1.0.0 frames received from held routers, keyed by reason name (DRAINING, OVERLOADED, REASON_UNSPECIFIED). */+ readonly goAwayReceived: Map<string, number>;+ /** Routers currently shunned (after a go-away or failed redial), mapped to the unix ms when the shun expires. */+ readonly shunnedRouters: Map<string, number>;/** This member's agent, once acceptA2A was called. */endpoint: A2AEndpoint | undefined;#refreshTimer: ReturnType<typeof setTimeout> | undefined;@@ -166,7 +214,16 @@ export class MeshSession {#relayTimer: ReturnType<typeof setInterval> | undefined;#syncing: Promise<ControlPlaneSync> | undefined;#keepingRelay: Promise<void> | undefined;- readonly #relayListener: RelayListener | undefined;+ #keepRelayPending = false;+ readonly #heldRouterIds: Set<string>;+ readonly #relayListeners: Map<string, RelayListener>;+ readonly #freeRelayListeners: RelayListener[];+ readonly #reserveRelay: boolean;+ readonly #targetRouters: number;+ readonly #routerSelector: Record<string, string> | undefined;+ readonly #routerPrefer: Record<string, string> | undefined;+ readonly #pinnedRouterAddresses: string[] | undefined;+ readonly #redialBackoffsMs: readonly number[];readonly #refreshLeadMs: number;readonly #refreshRetryMs: number;readonly #policySyncMs: number;@@ -187,15 +244,31 @@ export class MeshSession {authenticatedPeers: Map<string, Date>,banned: BanSet,options: JoinOptions,- relayListener?: RelayListener,+ relayListeners?: Map<string, RelayListener>,taskBiscuit?: Uint8Array,+ sharedState?: {+ heldRouterIds: Set<string>;+ freeRelayListeners: RelayListener[];+ goAwayReceived: Map<string, number>;+ shunnedRouters: Map<string, number>;+ },) {this.mesh = mesh;this.node = node;this.routers = routers;this.authenticatedPeers = authenticatedPeers;this.banned = banned;- this.#relayListener = relayListener;+ this.goAwayReceived = sharedState?.goAwayReceived ?? new Map<string, number>();+ this.shunnedRouters = sharedState?.shunnedRouters ?? new Map<string, number>();+ this.#heldRouterIds = sharedState?.heldRouterIds ?? new Set(routers.map((r) => r.peerId));+ this.#relayListeners = relayListeners ?? new Map<string, RelayListener>();+ this.#freeRelayListeners = sharedState?.freeRelayListeners ?? [];+ this.#reserveRelay = options.reserveRelay ?? true;+ this.#targetRouters = options.routers !== undefined && options.routers > 0 ? options.routers : DEFAULT_ROUTERS;+ this.#routerSelector = options.routerSelector;+ this.#routerPrefer = options.routerPrefer;+ this.#pinnedRouterAddresses = options.routerAddresses;+ this.#redialBackoffsMs = options.routerRedialBackoffsMs ?? ROUTER_REDIAL_BACKOFFS_MS;this.#refreshLeadMs = options.refreshLeadMs ?? DEFAULT_REFRESH_LEAD_MS;this.#refreshRetryMs = options.refreshRetryMs ?? DEFAULT_REFRESH_RETRY_MS;this.#policySyncMs = options.policySyncIntervalMs ?? DEFAULT_POLICY_SYNC_MS;@@ -211,10 +284,8 @@ export class MeshSession {if (this.#syncIntervalMs > 0) {this.#scheduleSync(Math.min(FIRST_CONTROL_PLANE_SYNC_MS, this.#syncIntervalMs));}- if (relayListener !== undefined) {- this.#relayTimer = setInterval(() => void this.keepRelay().catch(() => {}), options.relayCheckIntervalMs ?? DEFAULT_RELAY_CHECK_MS);- this.#relayTimer.unref?.();- }+ this.#relayTimer = setInterval(() => void this.keepRelay().catch(() => {}), options.relayCheckIntervalMs ?? DEFAULT_RELAY_CHECK_MS);+ this.#relayTimer.unref?.();}}@@ -253,9 +324,20 @@ export class MeshSession {policySyncIntervalMs: this.#policySyncMs,controlPlaneSyncIntervalMs: 0,controlPlaneSyncJitterMs: this.#syncJitterMs,+ reserveRelay: this.#reserveRelay,+ routers: this.#targetRouters,+ routerRedialBackoffsMs: this.#redialBackoffsMs,+ ...(this.#routerSelector !== undefined ? { routerSelector: this.#routerSelector } : {}),+ ...(this.#routerPrefer !== undefined ? { routerPrefer: this.#routerPrefer } : {}),+ ...(this.#pinnedRouterAddresses !== undefined ? { routerAddresses: this.#pinnedRouterAddresses } : {}),...(this.#egressRequireLabels !== undefined ? { egressRequireLabels: this.#egressRequireLabels } : {}),};- return new MeshSession(this.mesh, this.node, this.routers, this.authenticatedPeers, this.banned, opts, this.#relayListener, taskBiscuit);+ return new MeshSession(this.mesh, this.node, this.routers, this.authenticatedPeers, this.banned, opts, this.#relayListeners, taskBiscuit, {+ heldRouterIds: this.#heldRouterIds,+ freeRelayListeners: this.#freeRelayListeners,+ goAwayReceived: this.goAwayReceived,+ shunnedRouters: this.shunnedRouters,+ });}/**@@ -277,9 +359,130 @@ export class MeshSession {return this.node.getMultiaddrs();}- /** The `.../p2p-circuit/p2p/<self>` addresses reserved on routers. */+ /** The `.../p2p-circuit/p2p/<self>` addresses reserved on held routers. */get relayAddresses(): Multiaddr[] {- return this.node.getMultiaddrs().filter((ma) => ma.toString().includes("/p2p-circuit"));+ return this.node+ .getMultiaddrs()+ .filter((ma) => {+ const s = ma.toString();+ return s.includes("/p2p-circuit") && [...this.#heldRouterIds].some((id) => s.includes(`/p2p/${id}/p2p-circuit`));+ });+ }++ /** Whether peerId is currently one of the routers this member holds. */+ isHeldRouter(peerId: string): boolean {+ return this.#heldRouterIds.has(peerId);+ }++ /** Handles a /mesh/goaway/1.0.0 message from a held router: shuns it, detaches it, and tops up from the catalog. */+ async handleGoAway(peerId: string, msg: RouterGoAway, retryAfterMs: number): Promise<void> {+ if (!this.#heldRouterIds.has(peerId)) {+ return;+ }+ const reason = goAwayReasonName(msg.reason);+ this.goAwayReceived.set(reason, (this.goAwayReceived.get(reason) ?? 0) + 1);+ this.#shunRouter(peerId, retryAfterMs);+ await this.#detachRouter(peerId);+ await this.keepRelay().catch(() => {});+ }++ #shunRouter(peerId: string, durationMs: number): void {+ this.shunnedRouters.set(peerId, Date.now() + durationMs);+ }++ #isRouterShunned(peerId: string, nowMs = Date.now()): boolean {+ const expiry = this.shunnedRouters.get(peerId);+ if (expiry === undefined) {+ return false;+ }+ if (expiry <= nowMs) {+ this.shunnedRouters.delete(peerId);+ return false;+ }+ return true;+ }++ async #detachRouter(peerId: string): Promise<void> {+ this.#heldRouterIds.delete(peerId);+ const idx = this.routers.findIndex((r) => r.peerId === peerId);+ if (idx !== -1) {+ this.routers.splice(idx, 1);+ }+ const listener = this.#relayListeners.get(peerId);+ if (listener !== undefined) {+ this.#relayListeners.delete(peerId);+ this.#freeRelayListeners.push(listener);+ }+ try {+ await this.node.hangUp(peerIdFromString(peerId));+ } catch {+ // Already disconnected.+ }+ }++ async #reserveOnRouter(peerId: string, addr: Multiaddr): Promise<void> {+ const existing = this.#relayListeners.get(peerId);+ if (existing !== undefined) {+ await existing.listen(addr.encapsulate("/p2p-circuit"));+ return;+ }+ const free = this.#freeRelayListeners.pop();+ if (free !== undefined) {+ await free.listen(addr.encapsulate("/p2p-circuit"));+ this.#relayListeners.set(peerId, free);+ return;+ }+ const listener = await listenThroughRelay(this.node, addr);+ this.#relayListeners.set(peerId, listener);+ }++ #upsertHeldRouter(router: AdmittedRouter): void {+ this.#heldRouterIds.add(router.peerId);+ const idx = this.routers.findIndex((r) => r.peerId === router.peerId);+ if (idx !== -1) {+ this.routers[idx] = router;+ } else {+ this.routers.push(router);+ }+ }++ #candidatesForHolding(): RouterCandidate[] {+ if (this.#pinnedRouterAddresses !== undefined) {+ return candidatesFromRouterInfos([], this.#pinnedRouterAddresses, this.mesh.routers);+ }+ return candidatesFromRouterInfos(this.mesh.routers, this.mesh.credential.routerAddresses);+ }++ #wantRouters(): number {+ const candidates = this.#candidatesForHolding();+ let matched = 0;+ for (const c of candidates) {+ if (matchesLabels(c.labels, this.#routerSelector)) {+ matched++;+ }+ }+ if (matched > 0 && matched < this.#targetRouters) {+ return matched;+ }+ return this.#targetRouters;+ }++ #candidateAddressesFor(peerId: string, fallback: Multiaddr): Multiaddr[] {+ for (const c of candidatesFromRouterInfos(this.mesh.routers, this.mesh.credential.routerAddresses)) {+ if (c.peerId === peerId && c.addresses.length > 0) {+ return c.addresses;+ }+ }+ const listed = this.mesh.credential.routerAddresses+ .map((a) => {+ try {+ return multiaddr(a);+ } catch {+ return undefined;+ }+ })+ .filter((ma): ma is Multiaddr => ma !== undefined && targetPeerOf(ma) === peerId);+ return listed.length > 0 ? listed : [fallback];}/**@@ -299,44 +502,138 @@ export class MeshSession {}/**- * Makes sure this member holds a relay reservation when it asked for one- * at join: a router that restarted or trimmed the connection dropped it- * and with it the relayed address peers reach this member on. Routers are- * tried in order, each dialed and authenticated again first, since the- * router forgot the admission with the connection. A router rescheduled- * keeps its key and comes back on another address; the list the control- * plane hands out, refreshed by every pull, names the current one, so the- * router is dialed at what that list says and keeps the address the- * connection was made on. Runs on relayCheckIntervalMs; exposed so a- * caller can force it. Concurrent calls share one attempt. Upstream:- * libp2p/js-libp2p#3601.+ * Maintains held routers and relay reservations: when a held router's+ * connection or reservation drops, redials it first (2s, 4s, 8s by default)+ * using its current address from the catalog; if it does not recover or+ * refuses auth, shuns it and tops up from the catalog. Runs on+ * relayCheckIntervalMs and immediately after a /mesh/goaway/1.0.0 frame.*/keepRelay(): Promise<void> {- this.#keepingRelay ??= this.#keepRelayOnce().finally(() => {+ if (this.#keepingRelay !== undefined) {+ this.#keepRelayPending = true;+ return this.#keepingRelay;+ }+ const run = async (): Promise<void> => {+ do {+ this.#keepRelayPending = false;+ await this.#keepRelayOnce();+ } while (this.#keepRelayPending && !this.#closed);+ };+ this.#keepingRelay = run().finally(() => {this.#keepingRelay = undefined;});return this.#keepingRelay;}async #keepRelayOnce(): Promise<void> {- if (this.#relayListener === undefined || this.#closed || this.relayAddresses.length > 0) {+ if (this.#closed) {return;}- const failures: string[] = [];- for (const [i, r] of this.routers.entries()) {- const listed = this.mesh.credential.routerAddresses.map((a) => multiaddr(a)).filter((ma) => targetPeerOf(ma) === r.peerId);- try {- const conn = await this.node.dial(listed.length > 0 ? listed : r.addr);- await authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys);- const addr = connectedAddress(conn, r.peerId);- this.routers[i] = { ...r, addr };- await this.#relayListener.listen(addr.encapsulate("/p2p-circuit"));+ const held = this.routers.filter((r) => this.#heldRouterIds.has(r.peerId));+ for (const r of held) {+ if (this.#closed) {return;- } catch (err) {- failures.push(`${r.peerId}: ${err instanceof Error ? err.message : String(err)}`);+ }+ if (this.#isRouterShunned(r.peerId)) {+ await this.#detachRouter(r.peerId);+ continue;+ }+ const isConnected = this.node+ .getConnections(peerIdFromString(r.peerId))+ .some((c) => c.status === "open" && !c.remoteAddr.toString().includes("/p2p-circuit"));+ const hasRelay = !this.#reserveRelay || this.relayAddresses.some((ma) => ma.toString().includes(`/p2p/${r.peerId}/p2p-circuit`));+ if (isConnected && hasRelay) {+ continue;+ }+ let reconnected = false;+ for (const backoffMs of [0, ...this.#redialBackoffsMs]) {+ if (this.#closed || this.#isRouterShunned(r.peerId)) {+ break;+ }+ if (backoffMs > 0) {+ await new Promise((resolve) => setTimeout(resolve, backoffMs));+ }+ if (this.#closed || this.#isRouterShunned(r.peerId)) {+ break;+ }+ const addrs = this.#candidateAddressesFor(r.peerId, r.addr);+ let conn: Connection;+ try {+ conn = await this.node.dial(addrs);+ } catch {+ continue;+ }+ try {+ const credential = await authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys);+ requireRole(credential, ROLE_ROUTER);+ const addr = connectedAddress(conn, r.peerId);+ if (this.#reserveRelay) {+ await this.#reserveOnRouter(r.peerId, addr);+ }+ this.#upsertHeldRouter({ peerId: r.peerId, addr, credential });+ reconnected = true;+ break;+ } catch {+ // Router refused auth or reservation after connecting; fail over immediately.+ break;+ }+ }+ if (!reconnected && !this.#closed) {+ this.#shunRouter(r.peerId, ROUTER_SHUN_DURATION_MS);+ await this.#detachRouter(r.peerId);}}- throw new Error(`no router granted a relay reservation:\n ${failures.join("\n ")}`);++ if (!this.#closed && this.#heldRouterIds.size < this.#wantRouters()) {+ await this.topUpRouters();+ }+ }++ /**+ * Attaches and reserves on additional routers from the catalog until this+ * session holds wantRouters() routers or no more eligible candidates remain.+ */+ async topUpRouters(signal?: AbortSignal): Promise<string[]> {+ const failures: string[] = [];+ const want = this.#wantRouters();+ const candidates = this.#candidatesForHolding();+ const tried = new Set<string>();+ while (!this.#closed && this.#heldRouterIds.size < want) {+ const need = want - this.#heldRouterIds.size;+ const exclude = new Set<string>([...this.#heldRouterIds, ...tried]);+ const picks = selectRouters(candidates, need, {+ ...(this.#routerSelector !== undefined ? { selector: this.#routerSelector } : {}),+ ...(this.#routerPrefer !== undefined ? { prefer: this.#routerPrefer } : {}),+ attached: exclude,+ shunned: this.shunnedRouters,+ });+ if (picks.length === 0) {+ break;+ }+ let progress = false;+ for (const cand of picks) {+ tried.add(cand.peerId);+ try {+ const conn = await this.node.dial(cand.addresses, signal !== undefined ? { signal } : {});+ const credential = await authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys);+ requireRole(credential, ROLE_ROUTER);+ const addr = connectedAddress(conn, cand.peerId);+ if (this.#reserveRelay) {+ await this.#reserveOnRouter(cand.peerId, addr);+ }+ this.#upsertHeldRouter({ peerId: cand.peerId, addr, credential });+ progress = true;+ } catch (err) {+ this.#shunRouter(cand.peerId, ROUTER_SHUN_DURATION_MS);+ await this.node.hangUp(peerIdFromString(cand.peerId)).catch(() => {});+ failures.push(`${cand.peerId}: ${err instanceof Error ? err.message : String(err)}`);+ }+ }+ if (!progress && picks.length < need) {+ break;+ }+ }+ return failures;}/**@@ -633,6 +930,12 @@ export class MeshSession {const { banned } = this.banned.reconcile(canonicalPeerIds(result.bannedPeerIds), result.fetchedAt);await Promise.all(banned.map((peerId) => this.#evict(peerId)));}+ if (!this.#closed && this.#heldRouterIds.size < this.#wantRouters()) {+ await this.topUpRouters().catch(() => {});+ }+ if (!this.#closed) {+ void this.keepRelay().catch(() => {});+ }if (this.endpoint !== undefined) {try {await this.syncPolicy();@@ -846,6 +1149,184 @@ export class MeshSession {}}+export interface SelectRoutersOptions {+ selector?: Record<string, string>;+ prefer?: Record<string, string>;+ attached?: ReadonlySet<string>;+ shunned?: ReadonlyMap<string, number>;+ nowMs?: number;+ random?: () => number;+}++/**+ * Builds router candidates from ControlPlaneInfoResponse.routers, falling back+ * to router_addresses when routers is empty (an older control plane). When+ * routerMetadata is provided alongside explicit fallbackAddresses, labels and+ * load from routerMetadata are attached by peerId.+ */+export function candidatesFromRouterInfos(+ routers: readonly RouterInfo[],+ fallbackAddresses: readonly string[],+ routerMetadata: readonly RouterInfo[] = [],+): RouterCandidate[] {+ if (routers.length > 0) {+ const out: RouterCandidate[] = [];+ for (const r of routers) {+ let peerId: string | undefined;+ if (r.peerId !== "") {+ try {+ peerId = canonicalPeerId(r.peerId);+ } catch {+ peerId = undefined;+ }+ }+ const addrs: Multiaddr[] = [];+ for (const raw of r.addresses) {+ let ma: Multiaddr;+ try {+ ma = multiaddr(raw);+ } catch {+ continue;+ }+ const target = targetPeerOf(ma);+ if (peerId === undefined && target !== undefined) {+ peerId = target;+ }+ if (peerId !== undefined && (target === undefined || target === peerId)) {+ addrs.push(target === undefined ? ma.encapsulate(`/p2p/${peerId}`) : ma);+ }+ }+ if (peerId === undefined || addrs.length === 0) {+ continue;+ }+ out.push({+ peerId,+ addresses: addrs,+ labels: { ...r.labels },+ connections: r.connections,+ connectionLimit: r.connectionLimit,+ });+ }+ return out;+ }++ const metaByPeer = new Map<string, RouterInfo>();+ for (const r of routerMetadata) {+ if (r.peerId !== "") {+ try {+ metaByPeer.set(canonicalPeerId(r.peerId), r);+ } catch {+ // Ignore malformed peer IDs.+ }+ }+ }++ const byId = new Map<string, RouterCandidate>();+ for (const raw of fallbackAddresses) {+ let ma: Multiaddr;+ try {+ ma = multiaddr(raw);+ } catch {+ continue;+ }+ const peerId = targetPeerOf(ma);+ if (peerId === undefined) {+ continue;+ }+ const existing = byId.get(peerId);+ if (existing !== undefined) {+ existing.addresses.push(ma);+ } else {+ const meta = metaByPeer.get(peerId);+ byId.set(peerId, {+ peerId,+ addresses: [ma],+ labels: meta !== undefined ? { ...meta.labels } : {},+ connections: meta?.connections ?? 0,+ connectionLimit: meta?.connectionLimit ?? 0,+ });+ }+ }+ return [...byId.values()];+}++function matchesLabels(routerLabels: Record<string, string>, selector: Record<string, string> | undefined): boolean {+ if (selector === undefined) {+ return true;+ }+ for (const [k, v] of Object.entries(selector)) {+ if (routerLabels[k] !== v) {+ return false;+ }+ }+ return true;+}++function countMatchingLabels(routerLabels: Record<string, string>, prefer: Record<string, string> | undefined): number {+ if (prefer === undefined) {+ return 0;+ }+ let n = 0;+ for (const [k, v] of Object.entries(prefer)) {+ if (routerLabels[k] === v) {+ n++;+ }+ }+ return n;+}++function routerLoad(c: RouterCandidate): number {+ if (c.connectionLimit <= 0) {+ return 0.5;+ }+ const load = c.connections / c.connectionLimit;+ if (load < 0) {+ return 0;+ }+ if (load > 1) {+ return 1;+ }+ return load;+}++/**+ * Picks up to k routers from candidates, mirroring agentmesh-node's selectRouters:+ * filters by selector, excludes already-attached and currently-shunned routers,+ * and orders by matching prefer labels (descending) then load + jitter (ascending).+ */+export function selectRouters(candidates: readonly RouterCandidate[], k: number, options: SelectRoutersOptions = {}): RouterCandidate[] {+ if (k <= 0) {+ return [];+ }+ const nowMs = options.nowMs ?? Date.now();+ const rand = options.random ?? Math.random;+ const scored: Array<{ candidate: RouterCandidate; preferScore: number; load: number }> = [];+ for (const c of candidates) {+ if (options.attached?.has(c.peerId) === true) {+ continue;+ }+ const shunExpiry = options.shunned?.get(c.peerId);+ if (shunExpiry !== undefined && shunExpiry > nowMs) {+ continue;+ }+ if (!matchesLabels(c.labels, options.selector)) {+ continue;+ }+ scored.push({+ candidate: c,+ preferScore: countMatchingLabels(c.labels, options.prefer),+ load: routerLoad(c) + rand() * 0.05,+ });+ }+ scored.sort((a, b) => {+ if (a.preferScore !== b.preferScore) {+ return b.preferScore - a.preferScore;+ }+ return a.load - b.load;+ });+ return scored.slice(0, k).map((s) => s.candidate);+}+/** Implements AgentMesh.join(); lives here to keep mesh.ts free of libp2p. */export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Promise<MeshSession> {// The pull agentmesh-node makes before it starts: a member resuming from its@@ -859,15 +1340,19 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom} catch {// Joining goes on with what the credential holds.}- const routerAddrs = (options.routerAddresses ?? mesh.credential.routerAddresses).map((a) => multiaddr(a));- if (routerAddrs.length === 0) {+ const rawAddrs = options.routerAddresses ?? mesh.credential.routerAddresses;+ if (rawAddrs.length === 0 && mesh.routers.length === 0) {throw new Error(options.routerAddresses === undefined ? "credential lists no router addresses; the control plane had no active router at enrollment" : "routerAddresses names no router");}+ // Validate explicit routerAddresses up front so malformed multiaddrs fail fast.+ for (const a of rawAddrs) {+ multiaddr(a);+ }const banned = new BanSet();const node = await createMeshHost(mesh.identity, { ...options, banned });- const admitted: AdmittedRouter[] = [];const authenticatedPeers = new Map<string, Date>();+ let session: MeshSession | undefined;try {await node.handle(AUTH_PROTOCOL,@@ -879,36 +1364,28 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom}),AUTH_HANDLER_OPTIONS,);+ await node.handle(+ GOAWAY_PROTOCOL,+ goAwayStreamHandler({+ isHeldRouter: (peerId) => session?.isHeldRouter(peerId) === true,+ onGoAway: (peerId, msg, retryAfterMs) => session?.handleGoAway(peerId, msg, retryAfterMs),+ }),+ AUTH_HANDLER_OPTIONS,+ );- const failures: string[] = [];- for (const addr of routerAddrs) {- const routerPeer = targetPeerOf(addr);- if (routerPeer === undefined) {- failures.push(`${addr.toString()}: no /p2p/<peer id> component`);- continue;- }- try {- const conn = await node.dial(addr, options.signal !== undefined ? { signal: options.signal } : {});- const credential = await authenticateWithPeer(conn, mesh.authFrame(), mesh.credential.controlPlaneKeys);- // Enforced under the key that verified the token; a relay that is- // not a router must not become our way onto the mesh.- requireRole(credential, ROLE_ROUTER);- admitted.push({ peerId: routerPeer, addr: connectedAddress(conn, routerPeer), credential });- } catch (err) {- failures.push(`${addr.toString()}: ${err instanceof Error ? err.message : String(err)}`);- }- }- if (admitted.length === 0) {- throw new Error(`no router admitted this member:\n ${failures.join("\n ")}`);- }-- let relayListener: RelayListener | undefined;- if (options.reserveRelay ?? true) {- relayListener = await listenThroughRelay(node, (admitted[0] as AdmittedRouter).addr);+ session = new MeshSession(mesh, node, [], authenticatedPeers, banned, options);+ const failures = await session.topUpRouters(options.signal);+ if (session.routers.length === 0) {+ const detail = failures.length > 0 ? `:\n ${failures.join("\n ")}` : "";+ throw new Error(`no router admitted this member${detail}`);}- return new MeshSession(mesh, node, admitted, authenticatedPeers, banned, options, relayListener);+ return session;} catch (err) {- await Promise.resolve(node.stop()).catch(() => {});+ if (session !== undefined) {+ await session.close().catch(() => {});+ } else {+ await Promise.resolve(node.stop()).catch(() => {});+ }throw err;}}diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.pyindex 4a2fb2f2..51d71125 100644--- a/sdk/python/src/agent_mesh/__init__.py+++ b/sdk/python/src/agent_mesh/__init__.py@@ -14,7 +14,21 @@"""Native SDK for joining an Agent Mesh from inside a Python process."""-from .auth import AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, auth_stream_handler, authenticate_with_peer+from .auth import (+ AUTH_PROTOCOL,+ GOAWAY_MAX_RETRY_AFTER,+ GOAWAY_PROTOCOL,+ GOAWAY_STREAM_TIMEOUT,+ MAX_GOAWAY_MESSAGE_BYTES,+ MCP_PROTOCOL,+ ROUTER_SHUN_DURATION,+ AuthRejectedError,+ auth_stream_handler,+ authenticate_with_peer,+ clamp_go_away_retry_after,+ go_away_reason_name,+ go_away_stream_handler,+)from .authorizer import BASELINE_DATALOG, AuthorizationError, AuthorizeRequest, ProviderAuthorizerOptions, authorize_callerfrom .biscuit import ROLE_ROUTER, BiscuitVerificationError, VerifiedBiscuit, attenuate_biscuit, require_role, seal_biscuit, verify_peer_biscuitfrom .challenges import (@@ -63,7 +77,16 @@ from .libp2p_http import (from .mcp_client import LabelsNotSatisfiedError, ToolCallResult, ToolInfo, open_mcp_session, require_egress_labels, require_labelsfrom .mesh import AgentMesh, ControlPlaneSync, CredentialRetiredError, JwtSourcefrom .relay import dial_through_relay, reserve_relay-from .session import AdmittedRouter, MeshSession, Peer+from .session import (+ DEFAULT_ROUTERS,+ ROUTER_REDIAL_BACKOFFS,+ AdmittedRouter,+ MeshSession,+ Peer,+ RouterCandidate,+ candidates_from_router_infos,+ select_routers,+)from .sync import GOSSIP_EVENTS_TOPIC, BanSet, verify_mesh_eventfrom .tar import (TaskRequestContext,@@ -101,10 +124,14 @@ __all__ = ["ControlPlaneSync","CredentialRetiredError","DEFAULT_A2A_NAME",+ "DEFAULT_ROUTERS","DHT_PROTOCOL","DiscoveredProvider","Enrollment","EnrollmentRejectedError",+ "GOAWAY_MAX_RETRY_AFTER",+ "GOAWAY_PROTOCOL",+ "GOAWAY_STREAM_TIMEOUT","GOSSIP_EVENTS_TOPIC","HTTP_PROTOCOL","HTTPHandler",@@ -115,6 +142,7 @@ __all__ = ["JwtSource","KeysNotTrustedError","LabelsNotSatisfiedError",+ "MAX_GOAWAY_MESSAGE_BYTES","MCP_PROTOCOL","MESH_PATH_PREFIX","MeshCredential",@@ -125,7 +153,10 @@ __all__ = ["ProviderOptions","ROLE_NODE","ROLE_ROUTER",+ "ROUTER_REDIAL_BACKOFFS",+ "ROUTER_SHUN_DURATION","RefreshResult",+ "RouterCandidate","StreamedResponse","TaskRequestContext","ToolCallResult",@@ -135,7 +166,9 @@ __all__ = ["auth_stream_handler","authenticate_with_peer","authorize_caller",+ "candidates_from_router_infos","canonical_peer_id",+ "clamp_go_away_retry_after","decode_auth_response","decode_tar_block_payload","dial_through_relay",@@ -148,6 +181,8 @@ __all__ = ["enroll_status_challenge","evaluate_task_rules","find_providers",+ "go_away_reason_name",+ "go_away_stream_handler","http_ingress_handler","http_request_over_stream","libp2p_public_key",@@ -171,6 +206,7 @@ __all__ = ["reserve_relay","revocations_challenge","seal_biscuit",+ "select_routers","service_key","rewrite_agent_card","split_mesh_url",diff --git a/sdk/python/src/agent_mesh/auth.py b/sdk/python/src/agent_mesh/auth.pyindex 4a182f67..9c86ffed 100644--- a/sdk/python/src/agent_mesh/auth.py+++ b/sdk/python/src/agent_mesh/auth.py@@ -18,7 +18,7 @@ protobufs, go-msgio style."""from __future__ import annotationsimport logging-from typing import Callable, Optional, Sequence+from typing import Awaitable, Callable, Optional, Sequenceimport triofrom libp2p.abc import IHost, INetStream@@ -39,12 +39,19 @@ logger = logging.getLogger("agent_mesh")AUTH_PROTOCOL = TProtocol("/mesh/auth/1.0.0")MCP_PROTOCOL = TProtocol("/mesh/mcp/1.0.0")+GOAWAY_PROTOCOL = TProtocol("/mesh/goaway/1.0.0")# The first frame on a stream is capped, as msgio.NewVarintReaderSize(s, 64 KiB).MAX_AUTH_FRAME_BYTES = 64 * 1024# How long either side waits for the other's frame.AUTH_HANDSHAKE_TIMEOUT = 10.0+# Bounds on an inbound /mesh/goaway/1.0.0 stream, matching agentmesh-node's HandleGoAway.+MAX_GOAWAY_MESSAGE_BYTES = 1024+GOAWAY_STREAM_TIMEOUT = 5.0+ROUTER_SHUN_DURATION = 5 * 60.0+GOAWAY_MAX_RETRY_AFTER = 60 * 60.0+class AuthRejectedError(Exception):def __init__(self, peer_id: str, reason: str):@@ -121,3 +128,59 @@ def auth_stream_handler(await stream.close()return handle+++def go_away_reason_name(reason: int) -> str:+ """Returns the canonical proto enum name for a RouterGoAway.Reason value."""+ if reason == pb.RouterGoAway.DRAINING:+ return "DRAINING"+ if reason == pb.RouterGoAway.OVERLOADED:+ return "OVERLOADED"+ return "REASON_UNSPECIFIED"+++def clamp_go_away_retry_after(msg: pb.RouterGoAway) -> float:+ """Computes the shun duration in seconds from a RouterGoAway message:+ defaults to ROUTER_SHUN_DURATION (5m) when retry_after <= 0, capped at+ GOAWAY_MAX_RETRY_AFTER (1h)."""+ seconds = 0.0+ if msg.HasField("retry_after"):+ seconds = msg.retry_after.seconds + msg.retry_after.nanos / 1_000_000_000.0+ if seconds <= 0:+ return ROUTER_SHUN_DURATION+ if seconds > GOAWAY_MAX_RETRY_AFTER:+ return GOAWAY_MAX_RETRY_AFTER+ return seconds+++def go_away_stream_handler(+ is_held_router: Callable[[str], bool],+ on_go_away: Callable[[str, pb.RouterGoAway, float], Optional[Awaitable[None]]],+) -> Callable[[INetStream], "trio.lowlevel.Awaitable[None]"]:+ """Server side of /mesh/goaway/1.0.0, mirroring agentmesh-node's HandleGoAway:+ reads one varint-prefixed RouterGoAway message (1024 B cap, 5s timeout) only+ from a router the member currently holds, closes the stream, and notifies+ the session to shun the router and top up from the catalog."""++ async def handle(stream: INetStream) -> None:+ peer_id = str(stream.muxed_conn.peer_id)+ if not is_held_router(peer_id):+ logger.debug("ignoring go-away from unattached peer %s", peer_id)+ await stream.close()+ return+ try:+ with trio.fail_after(GOAWAY_STREAM_TIMEOUT):+ raw = await read_bounded_varint_prefixed_bytes(stream, MAX_GOAWAY_MESSAGE_BYTES)+ msg = pb.RouterGoAway.FromString(raw)+ except Exception as err: # noqa: BLE001+ logger.warning("go-away read from %s failed: %s", peer_id, err)+ await stream.close()+ return+ await stream.close()+ retry_after = clamp_go_away_retry_after(msg)+ res = on_go_away(peer_id, msg, retry_after)+ if res is not None:+ await res++ return handle+diff --git a/sdk/python/src/agent_mesh/conformance_join.py b/sdk/python/src/agent_mesh/conformance_join.pyindex 1c39f7b9..3dcf768b 100644--- a/sdk/python/src/agent_mesh/conformance_join.py+++ b/sdk/python/src/agent_mesh/conformance_join.py@@ -121,7 +121,13 @@ async def _handle(session: MeshSession, command: dict) -> dict:if cmd == "peers":return {"cmd": cmd, "authenticated_peers": sorted(session.authenticated_peers)}if cmd == "routers":- return {"cmd": cmd, "ok": True, "routers": [r.peer_id for r in session.routers], "relay_addresses": session.relay_addresses}+ return {+ "cmd": cmd,+ "ok": True,+ "routers": [r.peer_id for r in session.routers],+ "relay_addresses": session.relay_addresses,+ "go_away_received": dict(session.go_away_received),+ }if cmd == "sync":result = await session.sync()return {@@ -186,11 +192,21 @@ async def main() -> None:# is the floor every provider this member calls must attest.labels = _labels_from_env("AGENTMESH_SDK_LABELS")egress_require_labels = _labels_from_env("AGENTMESH_SDK_EGRESS_REQUIRE_LABELS")+ router_selector = _labels_from_env("AGENTMESH_SDK_ROUTER_SELECTOR")+ router_prefer = _labels_from_env("AGENTMESH_SDK_ROUTER_PREFER")+ router_count_raw = os.environ.get("AGENTMESH_SDK_ROUTER_COUNT")+ redial_backoff_raw = os.environ.get("AGENTMESH_SDK_REDIAL_BACKOFF_SECONDS")# AGENTMESH_SDK_RELAY_CHECK_SECONDS shortens how often the relay reservation is# checked and how soon a failed renewal is retried, so a test that moves# a router sees the member follow it within its budget.relay_check = os.environ.get("AGENTMESH_SDK_RELAY_CHECK_SECONDS")- relay_options = {"reservation_check_interval": float(relay_check), "refresh_retry": float(relay_check)} if relay_check else {}+ relay_options: dict[str, object] = (+ {"reservation_check_interval": float(relay_check), "refresh_retry": float(relay_check)} if relay_check else {}+ )+ if router_count_raw:+ relay_options["routers"] = int(router_count_raw)+ if redial_backoff_raw:+ relay_options["router_redial_backoffs"] = [float(s.strip()) for s in redial_backoff_raw.split(",") if s.strip()]mesh = AgentMesh.enroll(control_plane_url,@@ -209,6 +225,8 @@ async def main() -> None:async with mesh.join(listen_addrs=listen,router_addresses=router_addresses,+ router_selector=router_selector or None,+ router_prefer=router_prefer or None,control_plane_sync_interval=0,control_plane_sync_jitter=0,egress_require_labels=egress_require_labels or None,diff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.pyindex 6e7d864d..dc6c2ba1 100644--- a/sdk/python/src/agent_mesh/mesh.py+++ b/sdk/python/src/agent_mesh/mesh.py@@ -77,6 +77,8 @@ class ControlPlaneSync:fetched_at: float# One entry per part that failed; empty when everything landed.errors: list[str] = field(default_factory=list)+ # The control plane's router catalog (RouterInfo entries), when /info answered.+ routers: Optional[list[pb.RouterInfo]] = Noneclass AgentMesh:@@ -95,6 +97,7 @@ class AgentMesh:self.identity = identityself.control_plane = control_planeself._credential = credential+ self._routers: list[pb.RouterInfo] = []self._state_dir = state_dirself._jwt_source = jwt_source# refresh() and sync_control_plane() run in worker threads of the@@ -110,6 +113,11 @@ class AgentMesh:def credential(self) -> MeshCredential:return self._credential+ @property+ def routers(self) -> list[pb.RouterInfo]:+ """The router catalog (ControlPlaneInfoResponse.routers) from the most recent /info pull."""+ return list(self._routers)+def attenuate(self, rule: pb.TaskAuthorizationRule) -> MeshCredential:"""Returns a new MeshCredential with a tar_block appended offline in memory."""return self._credential.attenuate(rule)@@ -300,19 +308,33 @@ class AgentMesh:errors.append(f"keys: {err}")banned_peer_ids: Optional[list[str]] = None+ routers: Optional[list[pb.RouterInfo]] = None# Taken before the request: a ban recorded after this instant cannot be# in the answer, so its absence must not be read as an unban.fetched_at = time.time()try:info = self.control_plane.info()+ routers = list(info.routers)+ self._routers = routersif info.router_addresses:self._credential = replace(self._credential, router_addresses=list(info.router_addresses))+ elif routers:+ flattened = [addr for r in routers for addr in r.addresses]+ if flattened:+ self._credential = replace(self._credential, router_addresses=flattened)banned_peer_ids = list(info.banned_peer_ids)except Exception as err: # noqa: BLE001errors.append(f"info: {err}")if keys_changed or banned_peer_ids is not None:self.save()- return ControlPlaneSync(keys_changed=keys_changed, refreshed=refreshed, banned_peer_ids=banned_peer_ids, fetched_at=fetched_at, errors=errors)+ return ControlPlaneSync(+ keys_changed=keys_changed,+ refreshed=refreshed,+ banned_peer_ids=banned_peer_ids,+ fetched_at=fetched_at,+ errors=errors,+ routers=routers,+ )def auth_frame(self, target_service: str = "") -> bytes:"""The frame that opens every stream to a peer: this member's biscuit plusdiff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.pyindex c4b4e940..cf715693 100644--- a/sdk/python/src/agent_mesh/session.py+++ b/sdk/python/src/agent_mesh/session.py@@ -20,7 +20,7 @@ import timefrom contextlib import asynccontextmanagerfrom dataclasses import dataclass, field, replacefrom datetime import datetime-from typing import TYPE_CHECKING, Any, AsyncIterator, Awaitable, Callable, Mapping, Optional, Sequence, Union+from typing import TYPE_CHECKING, AbstractSet, Any, AsyncIterator, Awaitable, Callable, Mapping, Optional, Sequence, Unionimport multiaddrimport trio@@ -37,7 +37,15 @@ from mcp import ClientSessionfrom ._proto import circuit_pb2 as circuitfrom ._proto import agentmesh_pb2 as pb-from .auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peer+from .auth import (+ AUTH_PROTOCOL,+ GOAWAY_PROTOCOL,+ ROUTER_SHUN_DURATION,+ auth_stream_handler,+ authenticate_with_peer,+ go_away_reason_name,+ go_away_stream_handler,+)from .authorizer import ProviderAuthorizerOptionsfrom .biscuit import ROLE_ROUTER, VerifiedBiscuit, attenuate_biscuit, require_role, seal_biscuitfrom .controlplane import ROLE_NODE@@ -66,6 +74,11 @@ if TYPE_CHECKING:logger = logging.getLogger("agent_mesh")+# Number of routers a member attaches to and reserves on by default, matching agentmesh-node's defaultRouters.+DEFAULT_ROUTERS = 2+# Backoff delays (seconds) when redialing a held router whose connection dropped before failing over.+ROUTER_REDIAL_BACKOFFS: tuple[float, ...] = (2.0, 4.0, 8.0)+DEFAULT_REFRESH_LEAD = 60 * 60.0DEFAULT_REFRESH_RETRY = 30.0MIN_REFRESH_DELAY = 2.0@@ -132,6 +145,146 @@ class AdmittedRouter:reservation: circuit.Reservation | None = None+@dataclass(frozen=True)+class RouterCandidate:+ """One router candidate from the control plane's /info catalog."""++ peer_id: str+ addresses: list[multiaddr.Multiaddr]+ labels: dict[str, str] = field(default_factory=dict)+ connections: int = 0+ connection_limit: int = 0+++def candidates_from_router_infos(+ routers: Sequence[pb.RouterInfo],+ fallback_addresses: Sequence[str],+ router_metadata: Sequence[pb.RouterInfo] = (),+) -> list[RouterCandidate]:+ """Builds router candidates from ControlPlaneInfoResponse.routers, falling+ back to router_addresses when routers is empty (an older control plane).+ When router_metadata is provided alongside explicit fallback_addresses,+ labels and load from router_metadata are attached by peer_id."""+ if routers:+ out: list[RouterCandidate] = []+ for r in routers:+ peer_id: Optional[str] = None+ if r.peer_id:+ try:+ peer_id = canonical_peer_id(r.peer_id)+ except ValueError:+ peer_id = None+ addrs: list[multiaddr.Multiaddr] = []+ for raw in r.addresses:+ try:+ ma = multiaddr.Multiaddr(raw)+ except Exception: # noqa: BLE001+ continue+ target: Optional[str] = None+ try:+ target = str(info_from_p2p_addr(ma).peer_id)+ except Exception: # noqa: BLE001+ target = None+ if peer_id is None and target is not None:+ peer_id = target+ if peer_id is not None and (target is None or target == peer_id):+ if target is None:+ ma = multiaddr.Multiaddr(f"{ma}/p2p/{peer_id}")+ addrs.append(ma)+ if peer_id is None or not addrs:+ continue+ out.append(+ RouterCandidate(+ peer_id=peer_id,+ addresses=addrs,+ labels=dict(r.labels),+ connections=r.connections,+ connection_limit=r.connection_limit,+ )+ )+ return out++ meta_by_peer: dict[str, pb.RouterInfo] = {}+ for r in router_metadata:+ if r.peer_id:+ try:+ meta_by_peer[canonical_peer_id(r.peer_id)] = r+ except ValueError:+ continue++ by_id: dict[str, RouterCandidate] = {}+ for raw in fallback_addresses:+ try:+ ma = multiaddr.Multiaddr(raw)+ peer_id = str(info_from_p2p_addr(ma).peer_id)+ except Exception: # noqa: BLE001+ continue+ existing = by_id.get(peer_id)+ if existing is not None:+ existing.addresses.append(ma)+ else:+ meta = meta_by_peer.get(peer_id)+ by_id[peer_id] = RouterCandidate(+ peer_id=peer_id,+ addresses=[ma],+ labels=dict(meta.labels) if meta is not None else {},+ connections=meta.connections if meta is not None else 0,+ connection_limit=meta.connection_limit if meta is not None else 0,+ )+ return list(by_id.values())+++def _matches_labels(router_labels: Mapping[str, str], selector: Optional[Mapping[str, str]]) -> bool:+ if not selector:+ return True+ return all(router_labels.get(k) == v for k, v in selector.items())+++def _count_matching_labels(router_labels: Mapping[str, str], prefer: Optional[Mapping[str, str]]) -> int:+ if not prefer:+ return 0+ return sum(1 for k, v in prefer.items() if router_labels.get(k) == v)+++def _router_load(candidate: RouterCandidate) -> float:+ if candidate.connection_limit <= 0:+ return 0.5+ load = candidate.connections / candidate.connection_limit+ return min(max(load, 0.0), 1.0)+++def select_routers(+ candidates: Sequence[RouterCandidate],+ k: int,+ *,+ selector: Optional[Mapping[str, str]] = None,+ prefer: Optional[Mapping[str, str]] = None,+ attached: Optional[AbstractSet[str]] = None,+ shunned: Optional[Mapping[str, float]] = None,+ now: Optional[float] = None,+ rand: Callable[[], float] = random.random,+) -> list[RouterCandidate]:+ """Picks up to k routers from candidates, mirroring agentmesh-node's selectRouters:+ filters by selector, excludes already-attached and currently-shunned routers,+ and orders by matching prefer labels (descending) then load + jitter (ascending)."""+ if k <= 0:+ return []+ now_ts = time.time() if now is None else now+ scored: list[tuple[int, float, int, RouterCandidate]] = []+ for idx, c in enumerate(candidates):+ if attached is not None and c.peer_id in attached:+ continue+ if shunned is not None and shunned.get(c.peer_id, 0.0) > now_ts:+ continue+ if not _matches_labels(c.labels, selector):+ continue+ prefer_score = _count_matching_labels(c.labels, prefer)+ load = _router_load(c) + rand() * 0.05+ scored.append((-prefer_score, load, idx, c))+ scored.sort(key=lambda item: (item[0], item[1], item[2]))+ return [item[3] for item in scored[:k]]++@dataclassclass MeshSession:"""A member that is on the mesh: a libp2p host authenticated with at least@@ -145,18 +298,31 @@ class MeshSession:authenticated_peers: dict[str, datetime] = field(default_factory=dict)# Peers the control plane has banned; connections to and from them are refused.banned: BanSet = field(default_factory=BanSet)+ # Count of /mesh/goaway/1.0.0 frames received from held routers, keyed by reason name (DRAINING, OVERLOADED, REASON_UNSPECIFIED).+ go_away_received: dict[str, int] = field(default_factory=dict)+ # Routers currently shunned (after a go-away or failed redial), mapped to the unix seconds when the shun expires.+ shunned_routers: dict[str, float] = field(default_factory=dict)# This member's agent, once accept_a2a was called.endpoint: Optional[A2AEndpoint] = None# agentmesh-node's egress.require_labels for an SDK member: every provider this# session calls must attest all of these pairs, on top of a call's# required_labels. Held on every call, MCP and HTTP alike; no call waives it.egress_require_labels: Optional[Mapping[str, str]] = None+ reserve: bool = True+ target_routers: int = DEFAULT_ROUTERS+ router_selector: Optional[Mapping[str, str]] = None+ router_prefer: Optional[Mapping[str, str]] = None+ pinned_router_addresses: Optional[list[str]] = None+ router_redial_backoffs: Sequence[float] = ROUTER_REDIAL_BACKOFFSpolicy_sync_interval: float = DEFAULT_POLICY_SYNCcontrol_plane_sync_interval: float = DEFAULT_CONTROL_PLANE_SYNCcontrol_plane_sync_jitter: float = DEFAULT_CONTROL_PLANE_SYNC_JITTERreservation_lead: float = RESERVATION_RENEW_LEADreservation_retry: float = DEFAULT_REFRESH_RETRYreservation_check_interval: float = RESERVATION_CHECK_INTERVAL+ _held_router_ids: set[str] = field(default_factory=set, repr=False)+ _relay_lock: trio.Lock = field(default_factory=trio.Lock, repr=False)+ _relay_trigger: trio.Event = field(default_factory=trio.Event, repr=False)_nursery: Optional[trio.Nursery] = field(default=None, repr=False)_policy_rules: Optional[list[str]] = field(default=None, repr=False)_sync_lock: trio.Lock = field(default_factory=trio.Lock, repr=False)@@ -165,6 +331,11 @@ class MeshSession:_egress_verdicts: dict[str, float] = field(default_factory=dict, repr=False)_task_biscuit: Optional[bytes] = field(default=None, repr=False)+ def __post_init__(self) -> None:+ if not self._held_router_ids and self.routers:+ for r in self.routers:+ self._held_router_ids.add(r.peer_id)+@propertydef peer_id(self) -> str:return str(self.host.get_id())@@ -174,6 +345,92 @@ class MeshSession:"""The Biscuit presented on outbound service calls (task-attenuated when derived via attenuate())."""return self._task_biscuit if self._task_biscuit is not None else self.mesh.credential.biscuit+ def is_held_router(self, peer_id: str) -> bool:+ """Whether peer_id is currently in this member's held router set."""+ return peer_id in self._held_router_ids++ def _want_routers(self) -> int:+ if self.pinned_router_addresses is not None:+ candidates = candidates_from_router_infos([], self.pinned_router_addresses, getattr(self.mesh, "routers", ()))+ return min(self.target_routers, max(1, len(candidates)))+ return self.target_routers++ def _candidates_for_holding(self) -> list[RouterCandidate]:+ if self.pinned_router_addresses is not None:+ return candidates_from_router_infos([], self.pinned_router_addresses, getattr(self.mesh, "routers", ()))+ return candidates_from_router_infos(getattr(self.mesh, "routers", ()), self.mesh.credential.router_addresses)++ def _shun_router(self, peer_id: str, duration: float = ROUTER_SHUN_DURATION) -> None:+ now = time.time()+ for k, exp in list(self.shunned_routers.items()):+ if exp <= now:+ self.shunned_routers.pop(k, None)+ until = now + (duration if duration > 0 else ROUTER_SHUN_DURATION)+ existing = self.shunned_routers.get(peer_id, 0.0)+ if until > existing:+ self.shunned_routers[peer_id] = until++ async def _detach_router(self, peer_id: str) -> None:+ self._held_router_ids.discard(peer_id)+ self.routers[:] = [r for r in self.routers if r.peer_id != peer_id]+ try:+ await self.host.disconnect(ID.from_base58(peer_id))+ except Exception: # noqa: BLE001 - not connected, or already gone+ pass++ async def handle_go_away(self, peer_id: str, msg: pb.RouterGoAway, retry_after: float) -> bool:+ """Handles a RouterGoAway message from a router: ignores it if peer_id is+ not in the held set; otherwise records the reason, shuns the router for+ retry_after seconds, drops it from the held set, and tops up from the+ catalog immediately."""+ if peer_id not in self._held_router_ids:+ return False+ reason = go_away_reason_name(msg.reason)+ self.go_away_received[reason] = self.go_away_received.get(reason, 0) + 1+ self._shun_router(peer_id, retry_after)+ await self._detach_router(peer_id)+ await self.top_up_routers()+ self._relay_trigger.set()+ return True++ async def top_up_routers(self) -> list[str]:+ """Attaches and reserves on additional routers from the catalog until this+ session holds _want_routers() routers or no more eligible candidates remain."""+ failures: list[str] = []+ want = self._want_routers()+ if len(self._held_router_ids) >= want:+ return failures+ candidates = self._candidates_for_holding()+ tried: set[str] = set()+ while len(self._held_router_ids) < want:+ need = want - len(self._held_router_ids)+ exclude = self._held_router_ids | tried | set(self.banned.peers())+ picks = select_routers(+ candidates,+ need,+ selector=self.router_selector,+ prefer=self.router_prefer,+ attached=exclude,+ shunned=self.shunned_routers,+ )+ if not picks:+ break+ tried.update(c.peer_id for c in picks)+ admitted = await _admit_candidates(self.host, self.mesh, picks, self.reserve, failures)+ for router in admitted:+ self._held_router_ids.add(router.peer_id)+ idx = next((i for i, r in enumerate(self.routers) if r.peer_id == router.peer_id), None)+ if idx is not None:+ self.routers[idx] = router+ else:+ self.routers.append(router)+ for c in picks:+ if not any(r.peer_id == c.peer_id for r in admitted):+ self._shun_router(c.peer_id, ROUTER_SHUN_DURATION)+ if not admitted and len(picks) < need:+ break+ return failures+def attenuate(self, rule: pb.TaskAuthorizationRule) -> "MeshSession":"""Returns a task-scoped MeshSession view sharing the underlying libp2p hostwhose outbound MCP and HTTP service calls carry a Biscuit attenuated offline@@ -450,6 +707,9 @@ class MeshSession:newly_banned, _ = self.banned.reconcile(canonical_peer_ids(result.banned_peer_ids), result.fetched_at)for peer in newly_banned:await self._evict(peer)+ if len(self._held_router_ids) < self._want_routers():+ await self.top_up_routers()+ self._relay_trigger.set()if self.endpoint is not None:try:await self.sync_policy()@@ -501,6 +761,10 @@ class MeshSession:async def _evict(self, banned_peer: str) -> None:"""Drops a banned peer: its admission and its connections."""self.authenticated_peers.pop(banned_peer, None)+ if banned_peer in self._held_router_ids:+ self._held_router_ids.discard(banned_peer)+ self.routers[:] = [r for r in self.routers if r.peer_id != banned_peer]+ self._relay_trigger.set()try:await self.host.disconnect(ID.from_base58(banned_peer))except Exception: # noqa: BLE001 - not connected, or already gone@@ -529,31 +793,96 @@ class MeshSession:delay = self.control_plane_sync_interval * random.uniform(1.0, 1.1) # noqa: S311async def _reservation_loop(self) -> None:- """Renews the relay reservation on each admitted router before the- relay lets it expire, and again as soon as the connection to that- router is found gone: the relay drops the reservation with the- connection, and a member that kept advertising the relayed address- would have every dial to it fail with NO_RESERVATION. A router that- dropped the connection forgets the admission with it, so that one is- dialed and authenticated again before the reservation is asked for."""+ """Renews the relay reservation on each held router before the relay+ lets it expire, and again as soon as the connection to that router is+ found gone: the relay drops the reservation with the connection, and a+ member that kept advertising the relayed address would have every dial+ to it fail with NO_RESERVATION. When a held router's connection drops,+ it is redialed across router_redial_backoffs first; if it does not come+ back or refuses auth, it is shunned and replaced from the catalog."""+ if not self.reserve and not self._held_router_ids:+ returnwhile True:- reserved = [r for r in self.routers if r.reservation is not None]- if not reserved:+ reserved = [r for r in self.routers if r.peer_id in self._held_router_ids and r.reservation is not None]+ if not self.reserve and not self._held_router_ids:return- due = min(r.reservation.expire for r in reserved) - self.reservation_lead - time.time() # type: ignore[union-attr]- await trio.sleep(min(max(MIN_REFRESH_DELAY, due), self.reservation_check_interval))+ if reserved:+ due = min(r.reservation.expire for r in reserved) - self.reservation_lead - time.time() # type: ignore[union-attr]+ wait_time = min(max(MIN_REFRESH_DELAY, due), self.reservation_check_interval)+ else:+ wait_time = self.reservation_check_interval+ with trio.move_on_after(wait_time):+ await self._relay_trigger.wait()+ self._relay_trigger = trio.Event()+failed = False- for i, r in enumerate(self.routers):- if r.reservation is None:+ held_snapshot = [r for r in self.routers if r.peer_id in self._held_router_ids]+ for r in held_snapshot:+ if r.peer_id not in self._held_router_ids:+ continue+ connected = ID.from_base58(r.peer_id) in self.host.get_connected_peers()+ expiring = (+ r.reservation is not None+ and r.reservation.expire - time.time() <= self.reservation_lead + MIN_REFRESH_DELAY+ )+ missing_res = self.reserve and r.reservation is None+ if connected and not expiring and not missing_res:continue- expiring = r.reservation.expire - time.time() <= self.reservation_lead + MIN_REFRESH_DELAY- if not expiring and ID.from_base58(r.peer_id) in self.host.get_connected_peers():++ if connected:+ # Renewing an expiring reservation on an still-open connection.+ try:+ updated = await _reserve_again(self.host, self.mesh, r, reserve=self.reserve)+ idx = next((i for i, cur in enumerate(self.routers) if cur.peer_id == r.peer_id), None)+ if idx is not None:+ self.routers[idx] = updated+ except Exception as err: # noqa: BLE001 - retried; _reserve_again disconnected so next pass redials+ failed = True+ logger.warning(+ "relay reservation on router %s not renewed, retrying in %.0fs: %s",+ r.peer_id,+ self.reservation_retry,+ err,+ )continue++ # Connection dropped: try immediate reconnect first (covers a router+ # that already restarted or moved to a new address), then redial with+ # router_redial_backoffs before shunning and failing over.+ reconnected = False+ last_err: Optional[Exception] = Nonetry:- self.routers[i] = await _reserve_again(self.host, self.mesh, r)- except Exception as err: # noqa: BLE001 - retried; the relay keeps the old reservation until it expires- failed = True- logger.warning("relay reservation on router %s not renewed, retrying in %.0fs: %s", r.peer_id, self.reservation_retry, err)+ updated = await _reserve_again(self.host, self.mesh, r, reserve=self.reserve)+ idx = next((i for i, cur in enumerate(self.routers) if cur.peer_id == r.peer_id), None)+ if idx is not None:+ self.routers[idx] = updated+ reconnected = True+ except Exception as err: # noqa: BLE001+ last_err = err++ if not reconnected:+ for backoff in self.router_redial_backoffs:+ await trio.sleep(backoff)+ if r.peer_id not in self._held_router_ids:+ reconnected = True+ break+ try:+ updated = await _reserve_again(self.host, self.mesh, r, reserve=self.reserve)+ idx = next((i for i, cur in enumerate(self.routers) if cur.peer_id == r.peer_id), None)+ if idx is not None:+ self.routers[idx] = updated+ reconnected = True+ break+ except Exception as err: # noqa: BLE001+ last_err = err++ if not reconnected and r.peer_id in self._held_router_ids:+ logger.warning("router %s unreachable after redial, shunning and failing over: %s", r.peer_id, last_err)+ self._shun_router(r.peer_id, ROUTER_SHUN_DURATION)+ await self._detach_router(r.peer_id)++ if len(self._held_router_ids) < self._want_routers():+ await self.top_up_routers()if failed:await trio.sleep(self.reservation_retry)@@ -668,6 +997,10 @@ async def join_mesh(*,listen_addrs: Sequence[str] = (),router_addresses: Optional[Sequence[str]] = None,+ routers: int = DEFAULT_ROUTERS,+ router_selector: Optional[Mapping[str, str]] = None,+ router_prefer: Optional[Mapping[str, str]] = None,+ router_redial_backoffs: Sequence[float] = ROUTER_REDIAL_BACKOFFS,reserve: bool = True,refresh_lead: float = DEFAULT_REFRESH_LEAD,refresh_retry: float = DEFAULT_REFRESH_RETRY,@@ -695,13 +1028,30 @@ async def join_mesh(logger.warning("control plane sync before join: %s", "; ".join(result.errors))except Exception as err: # noqa: BLE001 - joining goes on with what the credential holdslogger.warning("control plane sync before join failed: %s", err)- router_addrs = [multiaddr.Multiaddr(a) for a in (mesh.credential.router_addresses if router_addresses is None else router_addresses)]- if not router_addrs:- raise RuntimeError("credential lists no router addresses; the control plane had no active router at enrollment" if router_addresses is None else "router_addresses names no router")++ pinned_addrs = list(router_addresses) if router_addresses is not None else None+ raw_addrs = pinned_addrs if pinned_addrs is not None else list(mesh.credential.router_addresses)+ for a in raw_addrs:+ multiaddr.Multiaddr(a)+ if pinned_addrs is not None:+ catalog = candidates_from_router_infos([], pinned_addrs, getattr(mesh, "routers", ()))+ else:+ catalog = candidates_from_router_infos(getattr(mesh, "routers", ()), raw_addrs)+ if not catalog:+ raise RuntimeError(+ "credential lists no router addresses; the control plane had no active router at enrollment"+ if router_addresses is None+ else "router_addresses names no router"+ )+ target_count = max(1, routers)+ ordered = select_routers(catalog, len(catalog), selector=router_selector, prefer=router_prefer)+ if not ordered:+ raise RuntimeError("no router admitted this member: no router in catalog matched router_selector")host, listen = create_mesh_host(mesh.identity, listen_addrs)authenticated: dict[str, datetime] = {}banned = BanSet()+ session_ref: list[MeshSession] = []host.set_stream_handler(AUTH_PROTOCOL,auth_stream_handler(@@ -711,6 +1061,15 @@ async def join_mesh(is_banned=lambda peer: peer in banned,),)+ host.set_stream_handler(+ GOAWAY_PROTOCOL,+ go_away_stream_handler(+ is_held_router=lambda peer_id: bool(session_ref and session_ref[0].is_held_router(peer_id)),+ on_go_away=lambda peer_id, msg, retry_after: (+ session_ref[0].handle_go_away(peer_id, msg, retry_after) if session_ref else None+ ),+ ),+ )host.set_stream_handler(STOP_PROTOCOL, stop_stream_handler(host))# Built before any connection: Pubsub learns of peers through a notifee it# registers here. StrictSign, as every Go component pins it.@@ -721,7 +1080,7 @@ async def join_mesh(try:async with host.run(listen_addrs=listen), background_trio_service(pubsub), background_trio_service(gossipsub):await pubsub.wait_until_ready()- admitted = await _admit(host, mesh, router_addrs, reserve)+ admitted = await _admit(host, mesh, ordered, reserve, target_count=target_count)async with trio.open_nursery() as nursery:session = MeshSession(mesh=mesh,@@ -730,6 +1089,12 @@ async def join_mesh(authenticated_peers=authenticated,banned=banned,egress_require_labels=egress_require_labels,+ reserve=reserve,+ target_routers=target_count,+ router_selector=router_selector,+ router_prefer=router_prefer,+ pinned_router_addresses=pinned_addrs,+ router_redial_backoffs=tuple(router_redial_backoffs),policy_sync_interval=policy_sync_interval,control_plane_sync_interval=control_plane_sync_interval,control_plane_sync_jitter=control_plane_sync_jitter,@@ -738,6 +1103,7 @@ async def join_mesh(reservation_check_interval=reservation_check_interval,_nursery=nursery,)+ session_ref.append(session)nursery.start_soon(session._refresh_loop, refresh_lead, refresh_retry) # noqa: SLF001nursery.start_soon(session._events_loop, pubsub) # noqa: SLF001nursery.start_soon(session._sync_loop) # noqa: SLF001@@ -753,41 +1119,93 @@ async def join_mesh(raise cause from None-async def _admit(host: IHost, mesh: "AgentMesh", router_addrs: list[multiaddr.Multiaddr], reserve: bool) -> list[AdmittedRouter]:- """Authenticates with every router the control plane named, as the JS SDK- and agentmesh-node do, and reserves a relay slot on the first that admits us.- A peer reserves on the first router of its own list, so a caller that- only knew one router could not reach a peer whose list started- elsewhere; `connect` tries the relayed path through each of these. The- routers are dialed at once: one the control plane lists but this member- cannot reach costs a dial timeout, not one per router behind it."""+async def _admit_candidates(+ host: IHost,+ mesh: "AgentMesh",+ candidates: Sequence[RouterCandidate],+ reserve: bool,+ failures: list[str],+ admitted_any_out: Optional[list[bool]] = None,+) -> list[AdmittedRouter]:+ """Dials and authenticates a batch of router candidates concurrently, and+ reserves a relay slot on each admitted router when reserve is True."""admitted: dict[int, AdmittedRouter] = {}- failures: list[str] = []- async def admit(index: int, addr: multiaddr.Multiaddr) -> None:- try:- info = await peer_info(addr)- await dial(host, info)- credential = await _authenticate_router(host, mesh, info.peer_id)- admitted[index] = AdmittedRouter(peer_id=str(info.peer_id), addr=addr, credential=credential)- except Exception as err: # noqa: BLE001 - every router is tried, the summary names each failure- failures.append(f"{addr}: {err}")+ async def admit_one(index: int, candidate: RouterCandidate) -> None:+ last_err: Optional[Exception] = None+ for addr in candidate.addresses:+ try:+ info = await peer_info(addr)+ await dial(host, info)+ credential = await _authenticate_router(host, mesh, info.peer_id)+ admitted[index] = AdmittedRouter(peer_id=str(info.peer_id), addr=addr, credential=credential)+ return+ except Exception as err: # noqa: BLE001+ last_err = err+ if last_err is not None:+ failures.append(f"{candidate.addresses[0] if candidate.addresses else candidate.peer_id}: {last_err}")async with trio.open_nursery() as nursery:- for index, addr in enumerate(router_addrs):- nursery.start_soon(admit, index, addr)- routers = [admitted[i] for i in sorted(admitted)]- if not routers:- raise RuntimeError("no router admitted this member:\n " + "\n ".join(failures))- if reserve:- for index, router in enumerate(routers):+ for index, candidate in enumerate(candidates):+ nursery.start_soon(admit_one, index, candidate)++ ordered = [admitted[i] for i in sorted(admitted)]+ if ordered and admitted_any_out is not None:+ admitted_any_out.append(True)+ if not reserve:+ return ordered++ reserved: list[AdmittedRouter] = []+ for router in ordered:+ try:+ res = await reserve_relay(host, ID.from_base58(router.peer_id))+ reserved.append(replace(router, reservation=res))+ except Exception as err: # noqa: BLE001+ failures.append(f"{router.addr}: {err}")try:- routers[index] = replace(router, reservation=await reserve_relay(host, ID.from_base58(router.peer_id)))- break- except Exception as err: # noqa: BLE001 - the next admitted router is asked- failures.append(f"{router.addr}: {err}")+ await host.disconnect(ID.from_base58(router.peer_id))+ except Exception: # noqa: BLE001+ pass+ return reserved+++async def _admit(+ host: IHost,+ mesh: "AgentMesh",+ candidates_or_addrs: Sequence[Union[multiaddr.Multiaddr, RouterCandidate]],+ reserve: bool,+ target_count: int = DEFAULT_ROUTERS,+) -> list[AdmittedRouter]:+ """Authenticates with up to target_count chosen routers, dialing each batch+ at once so an unreachable router costs one dial timeout rather than one per+ router behind it, and reserves a relay slot on each chosen router."""+ candidates: list[RouterCandidate] = []+ for item in candidates_or_addrs:+ if isinstance(item, RouterCandidate):+ candidates.append(item)else:+ try:+ pid = str(info_from_p2p_addr(item).peer_id)+ except Exception: # noqa: BLE001+ pid = ""+ candidates.append(RouterCandidate(peer_id=pid, addresses=[item]))++ want = max(1, target_count)+ routers: list[AdmittedRouter] = []+ failures: list[str] = []+ admitted_any: list[bool] = []+ cursor = 0+ while len(routers) < want and cursor < len(candidates):+ need = want - len(routers)+ batch = candidates[cursor : cursor + need]+ cursor += len(batch)+ admitted_batch = await _admit_candidates(host, mesh, batch, reserve, failures, admitted_any)+ routers.extend(admitted_batch)++ if not routers:+ if reserve and admitted_any:raise RuntimeError("no router reserved a relay slot for this member:\n " + "\n ".join(failures))+ raise RuntimeError("no router admitted this member:\n " + "\n ".join(failures))return routers@@ -799,7 +1217,7 @@ async def _authenticate_router(host: IHost, mesh: "AgentMesh", peer_id: ID) -> Vreturn credential-async def _reserve_again(host: IHost, mesh: "AgentMesh", router: AdmittedRouter) -> AdmittedRouter:+async def _reserve_again(host: IHost, mesh: "AgentMesh", router: AdmittedRouter, *, reserve: bool = True) -> AdmittedRouter:"""Reserves on a router again, dialed and authenticated first when itsconnection is gone. A router rescheduled keeps its key and comes back onanother address; the list the control plane hands out, refreshed by@@ -814,7 +1232,7 @@ async def _reserve_again(host: IHost, mesh: "AgentMesh", router: AdmittedRouter)addr, info = await _current_router_info(mesh, router)await dial(host, info)credential = await _authenticate_router(host, mesh, peer_id)- reservation = await reserve_relay(host, peer_id)+ reservation = await reserve_relay(host, peer_id) if reserve else Noneexcept Exception:# A connection that failed us is not kept: it may be half-open, or up# but unauthenticated. The retry then dials and authenticates again.@@ -832,13 +1250,24 @@ async def _current_router_info(mesh: "AgentMesh", router: AdmittedRouter) -> tupaddress to keep; the admitted address when the list has none for therouter."""listed: list[multiaddr.Multiaddr] = []- for text in mesh.credential.router_addresses:- try:- ma = multiaddr.Multiaddr(text)- if str(info_from_p2p_addr(ma).peer_id) == router.peer_id:- listed.append(ma)- except Exception: # noqa: BLE001 - not a router address- continue+ for r in getattr(mesh, "routers", ()):+ if r.peer_id == router.peer_id:+ for raw in r.addresses:+ try:+ ma = multiaddr.Multiaddr(raw)+ if f"/p2p/{router.peer_id}" not in str(ma):+ ma = multiaddr.Multiaddr(f"{ma}/p2p/{router.peer_id}")+ listed.append(ma)+ except Exception: # noqa: BLE001+ continue+ if not listed:+ for text in mesh.credential.router_addresses:+ try:+ ma = multiaddr.Multiaddr(text)+ if str(info_from_p2p_addr(ma).peer_id) == router.peer_id:+ listed.append(ma)+ except Exception: # noqa: BLE001 - not a router address+ continuekept: Optional[multiaddr.Multiaddr] = Nonedialable: list[multiaddr.Multiaddr] = []failures: list[str] = []@@ -852,3 +1281,4 @@ async def _current_router_info(mesh: "AgentMesh", router: AdmittedRouter) -> tupif kept is None:raise RuntimeError("no address to dial router at:\n " + "\n ".join(failures))return kept, PeerInfo(ID.from_base58(router.peer_id), dialable)+diff --git a/sdk/python/tests/test_session.py b/sdk/python/tests/test_session.pyindex 12c55c2b..d8d214ea 100644--- a/sdk/python/tests/test_session.py+++ b/sdk/python/tests/test_session.py@@ -40,7 +40,15 @@ from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytfrom agent_mesh._proto import circuit_pb2 as circuitfrom agent_mesh._proto import agentmesh_pb2 as pb-from agent_mesh.auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peer+from agent_mesh.auth import (+ AUTH_PROTOCOL,+ GOAWAY_MAX_RETRY_AFTER,+ GOAWAY_PROTOCOL,+ ROUTER_SHUN_DURATION,+ auth_stream_handler,+ authenticate_with_peer,+ clamp_go_away_retry_after,+)from agent_mesh.authorizer import ProviderAuthorizerOptionsfrom agent_mesh.biscuit import ROLE_ROUTER, BiscuitVerificationErrorfrom agent_mesh.controlplane import ROLE_NODE@@ -51,7 +59,8 @@ from agent_mesh.libp2p_http import HTTP_PROTOCOL, A2AEndpoint, HTTPResponse, Profrom agent_mesh.mcp_client import LabelsNotSatisfiedErrorfrom agent_mesh.mesh import AgentMeshfrom agent_mesh.relay import HOP_PROTOCOL as RELAY_HOP_PROTOCOL-from agent_mesh.session import AdmittedRouter, MeshSession+from agent_mesh.session import AdmittedRouter, MeshSession, candidates_from_router_infos, select_routers+from google.protobuf.duration_pb2 import Durationfrom google.protobuf.timestamp_pb2 import Timestamp@@ -92,10 +101,10 @@ POLICY_RULES = []-def fake_control_plane(router_addresses):+def fake_control_plane(router_addresses, routers=None):"""Approves every enrollment with a biscuit bound to the requesting peer.- /info lists router_addresses as they are at the time of the request, so- a test that changes the list has the member pull the change."""+ /info lists router_addresses and routers as they are at the time of the+ request, so a test that changes the list has the member pull the change."""def transport(method, url, headers, body):path = urllib.parse.urlsplit(url).path@@ -112,7 +121,10 @@ def fake_control_plane(router_addresses):# Unsigned: the client keeps the enrollment key when /keys cannot be verified.return 200, pb.KeysResponse(public_keys=[CP_KEY], sign_time=_ts_ms(int(time.time() * 1000))).SerializeToString()if (method, path) == ("GET", "/info"):- return 200, pb.ControlPlaneInfoResponse(router_addresses=list(router_addresses)).SerializeToString()+ return 200, pb.ControlPlaneInfoResponse(+ router_addresses=list(router_addresses),+ routers=list(routers) if routers is not None else [],+ ).SerializeToString()return 404, f"no route for {method} {path}".encode()return transport@@ -342,10 +354,8 @@ def test_join_fails_when_the_relay_refuses_the_reservation():def test_join_admits_every_router_and_reserves_on_the_first():- """A peer reserves its relay slot on the first router of its list; a- caller reaches it only through that router. So the member authenticates- with every router the control plane named and connect() can try each,- while one reservation is enough to be reachable."""+ """A member attaches to and reserves a relay slot on up to `routers`+ (default 2) chosen routers."""async def main():async with trio.open_nursery() as nursery:@@ -354,11 +364,14 @@ def test_join_admits_every_router_and_reserves_on_the_first():router_b, addr_b = await start_router(nursery, events=events)mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([addr_a, addr_b]))async with mesh.join(refresh_lead=0) as session:- assert [r.peer_id for r in session.routers] == [str(router_a.get_id()), str(router_b.get_id())]- assert [r.reservation is not None for r in session.routers] == [True, False]- assert session.relay_addresses == [f"{addr_a}/p2p-circuit/p2p/{mesh.peer_id}"]+ assert sorted(r.peer_id for r in session.routers) == sorted([str(router_a.get_id()), str(router_b.get_id())])+ assert [r.reservation is not None for r in session.routers] == [True, True]+ assert sorted(session.relay_addresses) == sorted([+ f"{addr_a}/p2p-circuit/p2p/{mesh.peer_id}",+ f"{addr_b}/p2p-circuit/p2p/{mesh.peer_id}",+ ])assert events.count(("auth", mesh.peer_id)) == 2- assert events.count(("reserve", mesh.peer_id)) == 1+ assert events.count(("reserve", mesh.peer_id)) == 2nursery.cancel_scope.cancel()trio.run(with_timeout, 30, main)@@ -366,9 +379,9 @@ def test_join_admits_every_router_and_reserves_on_the_first():def test_a_router_nobody_answers_costs_join_one_dial_timeout(monkeypatch):"""The control plane may list a router this member cannot reach (a- public address a network policy drops). Every router is dialed at once,- so join ends at DIAL_TIMEOUT whatever the dark one's position, and the- reservation still goes to the first *admitted* router of the list."""+ public address a network policy drops). Routers in the batch are dialed at+ once, so join ends at DIAL_TIMEOUT whatever the dark one's position, and+ reservations go to the admitted routers."""from agent_mesh import session as session_modulefrom agent_mesh.host import DIAL_TIMEOUT@@ -403,8 +416,8 @@ def test_a_router_nobody_answers_costs_join_one_dial_timeout(monkeypatch):routers = await session_module._admit(Host(), None, [multiaddr.Multiaddr(a) for a in (dark, router_a, router_b)], reserve=True)assert trio.current_time() - started == pytest.approx(DIAL_TIMEOUT)assert [r.peer_id[-6:] for r in routers] == ["UNCk88", "AFkdZm"]- assert [r.reservation is not None for r in routers] == [True, False]- assert [p[-6:] for p in reserved] == ["UNCk88"]+ assert [r.reservation is not None for r in routers] == [True, True]+ assert [p[-6:] for p in reserved] == ["UNCk88", "AFkdZm"]trio.run(main, clock=trio.testing.MockClock(autojump_threshold=0))@@ -871,3 +884,147 @@ def test_session_attenuate_and_seal_narrows_outbound_requests():nursery.cancel_scope.cancel()trio.run(with_timeout, 60, main)+++def test_select_routers_filters_orders_and_clamps_retry_after():+ infos = [+ pb.RouterInfo(+ peer_id="12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",+ addresses=["/ip4/127.0.0.1/tcp/5001/p2p/12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"],+ labels={"region": "us-west", "zone": "b"},+ connections=80,+ connection_limit=100,+ ),+ pb.RouterInfo(+ peer_id="12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC",+ addresses=["/ip4/127.0.0.1/tcp/5002/p2p/12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC"],+ labels={"region": "us-west", "zone": "a"},+ connections=90,+ connection_limit=100,+ ),+ pb.RouterInfo(+ peer_id="12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD",+ addresses=["/ip4/127.0.0.1/tcp/5003/p2p/12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD"],+ labels={"region": "us-west", "zone": "b"},+ connections=10,+ connection_limit=100,+ ),+ pb.RouterInfo(+ peer_id="12D3KooWD4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSE",+ addresses=["/ip4/127.0.0.1/tcp/5004/p2p/12D3KooWD4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSE"],+ labels={"region": "eu-west", "zone": "a"},+ connections=1,+ connection_limit=100,+ ),+ ]+ catalog = candidates_from_router_infos(infos, [])+ assert len(catalog) == 4++ picked = select_routers(+ catalog,+ 10,+ selector={"region": "us-west"},+ prefer={"zone": "a"},+ rand=lambda: 0.0,+ )+ assert [c.peer_id for c in picked] == [+ "12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC",+ "12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD",+ "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",+ ]++ without_preferred = select_routers(+ catalog,+ 10,+ selector={"region": "us-west"},+ prefer={"zone": "a"},+ shunned={"12D3KooWB4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSC": time.time() + 60},+ rand=lambda: 0.0,+ )+ assert [c.peer_id for c in without_preferred] == [+ "12D3KooWC4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSD",+ "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",+ ]++ fallback = candidates_from_router_infos([], ["/ip4/127.0.0.1/tcp/5001/p2p/12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"])+ assert len(fallback) == 1+ assert fallback[0].peer_id == "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"++ assert clamp_go_away_retry_after(pb.RouterGoAway()) == ROUTER_SHUN_DURATION+ assert clamp_go_away_retry_after(pb.RouterGoAway(retry_after=Duration(seconds=0))) == ROUTER_SHUN_DURATION+ assert clamp_go_away_retry_after(pb.RouterGoAway(retry_after=Duration(seconds=-5))) == ROUTER_SHUN_DURATION+ assert clamp_go_away_retry_after(pb.RouterGoAway(retry_after=Duration(seconds=600))) == 600.0+ assert clamp_go_away_retry_after(pb.RouterGoAway(retry_after=Duration(seconds=7200))) == GOAWAY_MAX_RETRY_AFTER+++def test_join_holds_two_routers_handles_go_away_and_redials_before_failover():+ async def wait_for(predicate):+ while not predicate():+ await trio.sleep(0.05)++ async def main():+ async with trio.open_nursery() as nursery:+ events1, events2, events3 = [], [], []+ r1, addr1 = await start_router(nursery, events=events1)+ r2, addr2 = await start_router(nursery, events=events2)+ r3, addr3 = await start_router(nursery, events=events3)+ pid1, pid2, pid3 = str(r1.get_id()), str(r2.get_id()), str(r3.get_id())++ router_infos = [+ pb.RouterInfo(peer_id=pid3, addresses=[addr3], labels={"region": "us", "tier": "backup"}, connections=90, connection_limit=100),+ pb.RouterInfo(peer_id=pid1, addresses=[addr1], labels={"region": "us", "tier": "primary"}, connections=50, connection_limit=100),+ pb.RouterInfo(peer_id=pid2, addresses=[addr2], labels={"region": "us", "tier": "backup"}, connections=10, connection_limit=100),+ ]+ all_addrs = [addr3, addr1, addr2]+ mesh = AgentMesh.enroll(+ "http://127.0.0.1:1",+ bootstrap_token="sbt",+ transport=fake_control_plane(all_addrs, routers=router_infos),+ )+ async with mesh.join(+ refresh_lead=0,+ routers=2,+ router_selector={"region": "us"},+ router_prefer={"tier": "primary"},+ reservation_check_interval=0.2,+ router_redial_backoffs=(0.05, 0.1),+ ) as session:+ # Only r1 and r2 were authenticated and reserved on at join; r3 is untouched in the catalog.+ assert sorted(r.peer_id for r in session.routers) == sorted([pid1, pid2])+ assert events3 == []+ assert len(session.relay_addresses) == 2+ assert any(a.startswith(addr1) for a in session.relay_addresses)+ assert any(a.startswith(addr2) for a in session.relay_addresses)++ # A go-away from a peer we do not hold (r3) is ignored.+ assert await session.handle_go_away(pid3, pb.RouterGoAway(reason=pb.RouterGoAway.DRAINING), 600.0) is False+ assert session.go_away_received == {}++ # r1 opens a /mesh/goaway/1.0.0 stream over its existing connection to the member.+ stream = await r1.new_stream(session.host.get_id(), [GOAWAY_PROTOCOL])+ msg = pb.RouterGoAway(reason=pb.RouterGoAway.DRAINING, retry_after=Duration(seconds=600))+ await stream.write(encode_varint_prefixed(msg.SerializeToString()))+ await stream.close()++ await wait_for(+ lambda: sorted(r.peer_id for r in session.routers) == sorted([pid2, pid3])+ and any(a.startswith(addr3) for a in session.relay_addresses)+ )+ assert session.go_away_received == {"DRAINING": 1}+ assert pid1 in session.shunned_routers+ assert any(a.startswith(addr2) for a in session.relay_addresses)+ assert any(a.startswith(addr3) for a in session.relay_addresses)+ assert not any(a.startswith(addr1) for a in session.relay_addresses)++ # Now make r3 refuse future auth handshakes and drop the connection so redial fails and shuns r3.+ r3.set_stream_handler(+ AUTH_PROTOCOL,+ auth_stream_handler(lambda: b"", lambda: [ba.KeyPair().public_key.to_bytes()]),+ )+ await r3.disconnect(session.host.get_id())+ await wait_for(lambda: pid3 in session.shunned_routers)+ assert [r.peer_id for r in session.routers] == [pid2]+ nursery.cancel_scope.cancel()++ trio.run(with_timeout, 60, main)+diff --git a/tests/integration/sdk_mesh_test.go b/tests/integration/sdk_mesh_test.goindex 5c8c28fe..76e789f1 100644--- a/tests/integration/sdk_mesh_test.go+++ b/tests/integration/sdk_mesh_test.go@@ -31,11 +31,13 @@ import ("os/exec""path/filepath""reflect"+ "slices""sort""strconv""strings""sync""sync/atomic"+ "syscall""testing""time"@@ -175,6 +177,7 @@ func startSDKMesh(t *testing.T) *sdkMesh {- name: %sallowed_services: []allowed_targets: ["*"]+ allowed_labels: ["zone=*"]- name: %sallowed_services: ["*"]allowed_targets: ["*"]@@ -1052,6 +1055,79 @@ func TestNativeSDKsFollowAMovedRouter(t *testing.T) {}}+// TestNativeSDKsHoldTwoRoutersAndHandleGoAway verifies that when the control+// plane lists three routers in /info, each SDK member picks two by preference+// and load, authenticates and reserves a relay slot on those two only, and+// when one held router stops and sends a /mesh/goaway/1.0.0 DRAINING frame,+// the member records the go-away reason, drops the draining router, and+// attaches to the remaining router from the catalog.+func TestNativeSDKsHoldTwoRoutersAndHandleGoAway(t *testing.T) {+ mesh := startSDKMesh(t)+ routerJWT := mesh.mintToken(map[string]interface{}{+ "sub": "router-c",+ "groups": []string{"routers"},+ "roles": []string{api.RoleRouter},+ })+ routerC := startLabelledRouter(t, buildBinary(t, "./cmd/agentmesh-router"), t.TempDir(), "router-c", mesh.cpPort, routerJWT, "zone=preferred")+ waitForActiveRouters(t, mesh.cpPort, 3, 10*time.Second)++ var members []*sdkMember+ for _, launcher := range sdkMemberLaunchers {+ cmd, skip := launcher.cmd(mesh.root)+ if skip != "" {+ t.Logf("%s SDK skipped: %s", launcher.name, skip)+ continue+ }+ m := launchSDKMember(t, launcher.name, cmd, mesh.root, mesh.baseURL, mesh.adminToken,+ "AGENTMESH_SDK_ROUTER_PREFER=zone=preferred",+ )+ if len(m.report.Routers) != 2 {+ t.Fatalf("%s joined through %d routers (%v), want 2 of the 3 routers", m.name, len(m.report.Routers), routerIDs(m.report))+ }+ if m.report.Routers[0].PeerID != routerC.peerID.String() {+ t.Fatalf("%s picked %v, want preferred router %s first", m.name, routerIDs(m.report), routerC.peerID)+ }+ if len(m.report.RelayAddresses) != 2 {+ t.Fatalf("%s reserved %d relay addresses (%v), want 2", m.name, len(m.report.RelayAddresses), m.report.RelayAddresses)+ }+ m.accept(t, "agent")+ members = append(members, m)+ }+ if len(members) == 0 {+ t.Skip("no SDK toolchain available; see sdk/README.md")+ }++ // Send SIGTERM to router-c: it drains its members over /mesh/goaway/1.0.0+ // with RouterGoAway_DRAINING before closing.+ if err := routerC.cmd.Process.Signal(syscall.SIGTERM); err != nil {+ t.Fatal(err)+ }++ wantRemaining := []string{extractPeerID(mesh.routerAddrs[0]), extractPeerID(mesh.routerAddrs[1])}+ slices.Sort(wantRemaining)++ for _, m := range members {+ deadline := time.Now().Add(15 * time.Second)+ for {+ ans := m.routersAnswer(t)+ got := slices.Clone(ans.Routers)+ slices.Sort(got)+ if ans.GoAwayReceived["DRAINING"] == 1 && slices.Equal(got, wantRemaining) && len(ans.RelayAddresses) == 2 {+ break+ }+ if time.Now().After(deadline) {+ t.Fatalf("%s after router-c drained: routers=%v relay_addresses=%v go_away_received=%v, want routers=%v and DRAINING=1",+ m.name, ans.Routers, ans.RelayAddresses, ans.GoAwayReceived, wantRemaining)+ }+ time.Sleep(150 * time.Millisecond)+ }+ }++ for _, m := range members {+ m.quit(t)+ }+}+// routerIDs lists the routers a join report says admitted the member.func routerIDs(report sdkJoinReport) []string {var ids []string@@ -1064,8 +1140,7 @@ func routerIDs(report sdkJoinReport) []string {func startSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, adminToken string, routerAddrs []string) *sdkMember {t.Helper()m := launchSDKMember(t, name, cmd, root, baseURL, adminToken, "AGENTMESH_SDK_LISTEN_ADDRS=/ip4/127.0.0.1/tcp/0")- // Every router the control plane named admitted the member, in whatever- // order it was handed them; it reserved on the first of its own list.+ // Both routers in the fixture admit the member and grant it a relay reservation.var admitted []stringfor _, r := range m.report.Routers {admitted = append(admitted, r.PeerID)@@ -1082,13 +1157,13 @@ func startSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, admif !reflect.DeepEqual(admitted, want) {t.Fatalf("%s report routers %v, want every router the control plane listed %v", name, admitted, want)}- if len(m.report.RelayAddresses) == 0 {- t.Fatalf("%s: no relay address, the router did not grant a reservation", name)+ if len(m.report.RelayAddresses) != len(m.report.Routers) {+ t.Fatalf("%s: got %d relay addresses (%v), want one for each of %d routers", name, len(m.report.RelayAddresses), m.report.RelayAddresses, len(m.report.Routers))}- first := m.report.Routers[0]- for _, a := range m.report.RelayAddresses {- if !strings.HasPrefix(a, first.Addr) || !strings.HasSuffix(a, "/p2p-circuit/p2p/"+m.report.PeerID) {- t.Fatalf("%s relay address %s is not <router>/p2p-circuit/p2p/<self> for its first router %s (%s)", name, a, first.PeerID, first.Addr)+ for _, r := range m.report.Routers {+ wantRelay := r.Addr + "/p2p-circuit/p2p/" + m.report.PeerID+ if !contains(m.report.RelayAddresses, wantRelay) {+ t.Fatalf("%s relay addresses %v lack %s for router %s", name, m.report.RelayAddresses, wantRelay, r.PeerID)}}return m@@ -1115,6 +1190,7 @@ func launchSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, adfunc launchSDKRunner(t *testing.T, name string, cmd *exec.Cmd, root, baseURL string, env ...string) *sdkMember {t.Helper()cmd.Env = append(append(os.Environ(),+ "PYTHONPATH="+filepath.Join(root, "sdk", "python", "src"),"AGENTMESH_CONTROL_PLANE_URL="+baseURL,"AGENTMESH_SDK_STATE_DIR="+filepath.Join(t.TempDir(), "state"),), env...)@@ -1442,10 +1518,11 @@ func (m *sdkMember) relayAddresses(t *testing.T) []string {}func (m *sdkMember) routersAnswer(t *testing.T) (res struct {- OK bool `json:"ok"`- Error string `json:"error"`- Routers []string `json:"routers"`- RelayAddresses []string `json:"relay_addresses"`+ OK bool `json:"ok"`+ Error string `json:"error"`+ Routers []string `json:"routers"`+ RelayAddresses []string `json:"relay_addresses"`+ GoAwayReceived map[string]int `json:"go_away_received"`}) {t.Helper()if line := m.send(t, map[string]string{"cmd": "routers"}); json.Unmarshal(line, &res) != nil {