Skip to content

Agent Mesh

sdk: a member announces where it is reached under its peer key

Antonio Ojea0b09ba4b3f86
diff --git a/sdk/js/src/discovery.ts b/sdk/js/src/discovery.ts
index 909db12b..711a7784 100644
--- a/sdk/js/src/discovery.ts
+++ b/sdk/js/src/discovery.ts
@@ -152,6 +152,14 @@ export async function provide(routers: DirectoryRouter[], key: Uint8Array, addrs
await request(routers, create(DirectoryRequestSchema, { request: { case: "provide", value: { key, addrs } } }), signal);
}
+/**
+ * Removes this member's record under key from the held router and from the
+ * routers it was placed on.
+ */
+export async function withdraw(routers: DirectoryRouter[], key: Uint8Array, signal?: AbortSignal): Promise<void> {
+ await request(routers, create(DirectoryRequestSchema, { request: { case: "withdraw", value: { key } } }), signal);
+}
+
/** Who provides key, up to limit, with their addresses; empty when nobody does. */
export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise<PeerRecord[]> {
const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit: Math.max(limit, 1) } } }), signal);
diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.ts
index 54344127..9bea398d 100644
--- a/sdk/js/src/session.test.ts
+++ b/sdk/js/src/session.test.ts
@@ -28,7 +28,7 @@ import type { Libp2p } from "@libp2p/interface";
import { tcp } from "@libp2p/tcp";
import { tls } from "@libp2p/tls";
import { lpStream } from "@libp2p/utils";
-import { DIRECTORY_PROTOCOL } from "./discovery.ts";
+import { DIRECTORY_PROTOCOL, peerKey } from "./discovery.ts";
import { multiaddr } from "@multiformats/multiaddr";
import { createLibp2p } from "libp2p";
import assert from "node:assert/strict";
@@ -454,6 +454,49 @@ test("discovery asks a held router over the directory protocol and connects to n
}
});
+test("a member announces where it is reached under its peer key and withdraws it on close", async () => {
+ // A member with a relay reservation announces its relayed addresses so
+ // that a peer on other routers finds it by ID; a member that reserves
+ // nothing has nothing to announce.
+ const requests: Array<{ op: string; key: Uint8Array; addrs: string[] }> = [];
+ await router.handle(DIRECTORY_PROTOCOL, (stream) => {
+ void (async () => {
+ const lp = lpStream(stream, { maxDataLength: 64 * 1024 });
+ const req = fromBinary(DirectoryRequestSchema, (await lp.read()).subarray());
+ const value = req.request.value as { key?: Uint8Array; addrs?: string[] } | undefined;
+ requests.push({ op: req.request.case ?? "", key: value?.key ?? new Uint8Array(), addrs: value?.addrs ?? [] });
+ await lp.write(toBinary(DirectoryResponseSchema, create(DirectoryResponseSchema, {})));
+ await stream.close();
+ })();
+ });
+ try {
+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: fakeControlPlane([routerAddr]) });
+ const session = await mesh.join({ refreshLeadMs: 0 });
+ const relayed = session.relayAddresses.map(String).sort();
+ assert.ok(relayed.length > 0, "no relayed address after the reservation");
+ const key = await peerKey(session.peerId);
+ assert.deepEqual(
+ requests.map((r) => r.op),
+ ["provide"],
+ );
+ assert.equal(Buffer.from(requests[0]?.key ?? []).toString("hex"), Buffer.from(key).toString("hex"));
+ assert.deepEqual(requests[0]?.addrs, relayed);
+ await session.close();
+ assert.deepEqual(
+ requests.map((r) => r.op),
+ ["provide", "withdraw"],
+ );
+ assert.equal(Buffer.from(requests[1]?.key ?? []).toString("hex"), Buffer.from(key).toString("hex"));
+
+ requests.length = 0;
+ const silent = await mesh.join({ refreshLeadMs: 0, reserveRelay: false });
+ await silent.close();
+ assert.deepEqual(requests, [], "a member with no relayed address announces nothing");
+ } finally {
+ await router.unhandle(DIRECTORY_PROTOCOL);
+ }
+});
+
test("a resumed member adopts a rotated key before admitting routers", async () => {
// The control plane rotated its signing key while this member was not
// running: the routers already hold credentials under the new key, and
diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts
index 3d426f63..598efbef 100644
--- a/sdk/js/src/session.ts
+++ b/sdk/js/src/session.ts
@@ -32,7 +32,7 @@ import { ROLE_ROUTER, attenuateBiscuit, requireRole, sealBiscuit, type VerifiedB
import { ROLE_NODE } from "./controlplane.ts";
import { encodeAuthFrame } from "./credential.ts";
import { canonicalPeerId } from "./identity.ts";
-import { findPeer, findProviders, isServiceType, parseServiceTarget, serviceKey, type DirectoryRouter } from "./discovery.ts";
+import { findPeer, findProviders, isServiceType, parseServiceTarget, peerKey, provide, serviceKey, withdraw, type DirectoryRouter } from "./discovery.ts";
import type { PeerRecord, 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";
@@ -114,6 +114,11 @@ export interface JoinOptions extends MeshHostOptions {
* how long the member is unreachable at most before it reserves again.
*/
relayCheckIntervalMs?: number;
+ /**
+ * How often this member announces where it is reached under its peer
+ * key (default 5 minutes, agentmesh-node's reprovide interval).
+ */
+ announceIntervalMs?: number;
/**
* 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
@@ -186,6 +191,13 @@ const DEFAULT_CONTROL_PLANE_SYNC_MS = 15 * 60 * 1000;
const FIRST_CONTROL_PLANE_SYNC_MS = 2_000;
const DEFAULT_CONTROL_PLANE_SYNC_JITTER_MS = 2_000;
const DEFAULT_RELAY_CHECK_MS = 30 * 1000;
+/**
+ * How often a member announces where it is reached: agentmesh-node's default
+ * reprovide interval, a third of the mesh's default record TTL.
+ */
+const DEFAULT_ANNOUNCE_MS = 5 * 60 * 1000;
+/** What close() waits for the member's record to be withdrawn. */
+const WITHDRAW_TIMEOUT_MS = 2 * 1000;
/** How long a provider's positive egress verdict is kept; agentmesh-node's labelGateTTL. */
const EGRESS_VERDICT_TTL_MS = 5 * 60 * 1000;
@@ -212,6 +224,9 @@ export class MeshSession {
#policyTimer: ReturnType<typeof setInterval> | undefined;
#syncTimer: ReturnType<typeof setTimeout> | undefined;
#relayTimer: ReturnType<typeof setInterval> | undefined;
+ #announceTimer: ReturnType<typeof setInterval> | undefined;
+ /** The addresses of the record last announced under this member's peer key. */
+ #announced: string[] = [];
#syncing: Promise<ControlPlaneSync> | undefined;
#keepingRelay: Promise<void> | undefined;
#keepRelayPending = false;
@@ -286,6 +301,8 @@ export class MeshSession {
}
this.#relayTimer = setInterval(() => void this.keepRelay().catch(() => {}), options.relayCheckIntervalMs ?? DEFAULT_RELAY_CHECK_MS);
this.#relayTimer.unref?.();
+ this.#announceTimer = setInterval(() => void this.announce().catch(() => {}), options.announceIntervalMs ?? DEFAULT_ANNOUNCE_MS);
+ this.#announceTimer.unref?.();
}
}
@@ -369,6 +386,26 @@ export class MeshSession {
});
}
+ /**
+ * Announces where this member is reached, its relayed addresses on the
+ * routers it holds, under its peer key, so that a peer attached to other
+ * routers finds it by ID. Runs after join, when the addresses change and
+ * every announceIntervalMs; the record outlives its last announcement by
+ * the mesh's record TTL. A member with no relayed address announces
+ * nothing: there is nothing to reach it at.
+ */
+ async announce(): Promise<void> {
+ if (this.#closed || this.#isTaskView) {
+ return;
+ }
+ const addrs = this.relayAddresses.map(String).sort();
+ if (addrs.length === 0) {
+ return;
+ }
+ await provide(this.#directoryRouters(), await peerKey(this.peerId), addrs);
+ this.#announced = addrs;
+ }
+
/** Whether peerId is currently one of the routers this member holds. */
isHeldRouter(peerId: string): boolean {
try {
@@ -567,6 +604,17 @@ export class MeshSession {
if (this.#closed) {
return;
}
+ try {
+ await this.#maintainRouters();
+ } finally {
+ const addrs = this.relayAddresses.map(String).sort();
+ if (!this.#closed && addrs.length > 0 && addrs.join(" ") !== this.#announced.join(" ")) {
+ await this.announce().catch(() => {});
+ }
+ }
+ }
+
+ async #maintainRouters(): Promise<void> {
const held = this.routers.filter((r) => this.#heldRouterIds.has(r.peerId));
for (const r of held) {
if (this.#closed) {
@@ -1160,11 +1208,18 @@ export class MeshSession {
}
async close(): Promise<void> {
+ const announced = this.#announced.length > 0 && !this.#closed && !this.#isTaskView;
this.#closed = true;
clearTimeout(this.#refreshTimer);
clearTimeout(this.#syncTimer);
clearInterval(this.#policyTimer);
clearInterval(this.#relayTimer);
+ clearInterval(this.#announceTimer);
+ if (announced) {
+ // Best effort: the record expires on its own within the record TTL.
+ await withdraw(this.#directoryRouters(), await peerKey(this.peerId), AbortSignal.timeout(WITHDRAW_TIMEOUT_MS)).catch(() => {});
+ this.#announced = [];
+ }
if (!this.#isTaskView) {
await this.node.stop();
}
@@ -1401,6 +1456,9 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom
const detail = failures.length > 0 ? `:\n ${failures.join("\n ")}` : "";
throw new Error(`no router admitted this member${detail}`);
}
+ // Best effort: a router that does not take the record is a warning the
+ // next announcement retries; the member is on the mesh regardless.
+ await session.announce().catch(() => {});
return session;
} catch (err) {
if (session !== undefined) {
diff --git a/sdk/python/src/agent_mesh/discovery.py b/sdk/python/src/agent_mesh/discovery.py
index ce901bf2..bad98c31 100644
--- a/sdk/python/src/agent_mesh/discovery.py
+++ b/sdk/python/src/agent_mesh/discovery.py
@@ -141,6 +141,12 @@ async def provide(host: IHost, routers: Iterable[ID], key: bytes, addrs: Iterabl
await request(host, routers, req)
+async def withdraw(host: IHost, routers: Iterable[ID], key: bytes) -> None:
+ """Removes this member's record under key from the held router and from
+ the routers it was placed on."""
+ await request(host, routers, pb.DirectoryRequest(withdraw=pb.DirectoryWithdraw(key=key)))
+
+
async def find_providers(host: IHost, routers: Iterable[ID], key: bytes, limit: int = DEFAULT_LIMIT) -> list[DiscoveredProvider]:
"""Who provides key, up to limit, with their addresses; empty when nobody does."""
req = pb.DirectoryRequest(find_providers=pb.DirectoryFindProviders(key=key, limit=max(limit, 1)))
diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.py
index 73fda5a6..2959d0aa 100644
--- a/sdk/python/src/agent_mesh/session.py
+++ b/sdk/python/src/agent_mesh/session.py
@@ -48,7 +48,7 @@ from .authorizer import ProviderAuthorizerOptions
from .biscuit import ROLE_ROUTER, VerifiedBiscuit, attenuate_biscuit, require_role, seal_biscuit
from .controlplane import ROLE_NODE
from .credential import encode_auth_frame
-from .discovery import DiscoveredProvider, find_peer, find_providers, parse_service_target, service_key
+from .discovery import DiscoveredProvider, find_peer, find_providers, parse_service_target, peer_key, provide, service_key, withdraw
from .host import create_mesh_host, dial, dial_addrs, peer_info
from .identity import canonical_peer_id
from .libp2p_http import (
@@ -94,6 +94,11 @@ DEFAULT_POLICY_SYNC = 15 * 60.0
DEFAULT_CONTROL_PLANE_SYNC = 15 * 60.0
FIRST_CONTROL_PLANE_SYNC = 2.0
DEFAULT_CONTROL_PLANE_SYNC_JITTER = 2.0
+# How often a member announces where it is reached: agentmesh-node's default
+# reprovide interval, a third of the mesh's default record TTL.
+DEFAULT_ANNOUNCE_INTERVAL = 5 * 60.0
+# What leaving the mesh waits for the member's record to be withdrawn.
+WITHDRAW_TIMEOUT = 2.0
# How long a provider's positive egress verdict is kept; agentmesh-node's labelGateTTL.
EGRESS_VERDICT_TTL = 5 * 60.0
@@ -318,7 +323,10 @@ class MeshSession:
reservation_lead: float = RESERVATION_RENEW_LEAD
reservation_retry: float = DEFAULT_REFRESH_RETRY
reservation_check_interval: float = RESERVATION_CHECK_INTERVAL
+ announce_interval: float = DEFAULT_ANNOUNCE_INTERVAL
_held_router_ids: set[str] = field(default_factory=set, repr=False)
+ # The addresses of the record last announced under this member's peer key.
+ _announced: list[str] = field(default_factory=list, 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)
@@ -401,7 +409,14 @@ class MeshSession:
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."""
+ session holds _want_routers() routers or no more eligible candidates remain.
+ One top-up at a time: the reservation loop and a go-away both call it,
+ and two picking the same router at once would hold it twice, or shun
+ it while holding it."""
+ async with self._relay_lock:
+ return await self._top_up_routers()
+
+ async def _top_up_routers(self) -> list[str]:
failures: list[str] = []
want = self._want_routers()
if len(self._held_router_ids) >= want:
@@ -462,6 +477,50 @@ class MeshSession:
"""The mesh URL of this member's own agent, once accept_a2a was called."""
return self.mesh_url(self.peer_id, self.endpoint.service) if self.endpoint is not None else None
+ async def announce(self) -> None:
+ """Announces where this member is reached, its relayed addresses on the
+ routers it holds, under its peer key, so that a peer attached to other
+ routers finds it by ID. Runs after join, when the addresses change and
+ every announce_interval; the record outlives its last announcement by
+ the mesh's record TTL. A member with no relayed address announces
+ nothing: there is nothing to reach it at."""
+ if self._task_biscuit is not None:
+ return
+ addrs = sorted(self.relay_addresses)
+ if not addrs:
+ return
+ await provide(self.host, self._directory_routers(), peer_key(self.host.get_id()), [multiaddr.Multiaddr(a) for a in addrs])
+ self._announced = addrs
+
+ async def _announce_loop(self) -> None:
+ while True:
+ await trio.sleep(self.announce_interval)
+ try:
+ await self.announce()
+ except Exception as err: # noqa: BLE001 - the next announcement retries
+ logger.warning("announcing where this member is reached: %s", err)
+
+ async def _announce_if_moved(self) -> None:
+ """Announces again when the relayed addresses changed since the last
+ announcement, as after a router was replaced."""
+ if self.relay_addresses and sorted(self.relay_addresses) != self._announced:
+ try:
+ await self.announce()
+ except Exception as err: # noqa: BLE001
+ logger.warning("announcing where this member is reached: %s", err)
+
+ async def _withdraw_self(self) -> None:
+ """Withdraws this member's record as it leaves; best effort, the record
+ expires on its own within the record TTL."""
+ if not self._announced or self._task_biscuit is not None:
+ return
+ with trio.move_on_after(WITHDRAW_TIMEOUT):
+ try:
+ await withdraw(self.host, self._directory_routers(), peer_key(self.host.get_id()))
+ except Exception as err: # noqa: BLE001
+ logger.debug("withdrawing this member's record: %s", err)
+ self._announced = []
+
@property
def relay_addresses(self) -> list[str]:
"""The `.../p2p-circuit/p2p/<self>` addresses reserved on routers."""
@@ -601,8 +660,12 @@ class MeshSession:
return direct, relays
def _directory_routers(self) -> list[ID]:
- """The routers this member holds, which answer its directory requests."""
- return [ID.from_base58(r.peer_id) for r in self.routers]
+ """The routers this member holds and is connected to, which answer its
+ directory requests. A request goes over the session the handshake
+ opened, never over a dial of its own: a router admits a connection it
+ has verified, and the reservation loop is what reconnects."""
+ connected = set(self.host.get_connected_peers())
+ return [ID.from_base58(r.peer_id) for r in self.routers if ID.from_base58(r.peer_id) in connected]
async def _admit_router(self, addr: multiaddr.Multiaddr) -> AdmittedRouter:
"""Dials a router, runs the handshake and, its role verified, adds it
@@ -891,6 +954,7 @@ class MeshSession:
if len(self._held_router_ids) < self._want_routers():
await self.top_up_routers()
+ await self._announce_if_moved()
if failed:
await trio.sleep(self.reservation_retry)
@@ -1014,6 +1078,7 @@ async def join_mesh(
refresh_retry: float = DEFAULT_REFRESH_RETRY,
reservation_lead: float = RESERVATION_RENEW_LEAD,
reservation_check_interval: float = RESERVATION_CHECK_INTERVAL,
+ announce_interval: float = DEFAULT_ANNOUNCE_INTERVAL,
policy_sync_interval: float = DEFAULT_POLICY_SYNC,
control_plane_sync_interval: float = DEFAULT_CONTROL_PLANE_SYNC,
control_plane_sync_jitter: float = DEFAULT_CONTROL_PLANE_SYNC_JITTER,
@@ -1111,6 +1176,7 @@ async def join_mesh(
reservation_lead=reservation_lead,
reservation_retry=refresh_retry,
reservation_check_interval=reservation_check_interval,
+ announce_interval=announce_interval,
_nursery=nursery,
)
session_ref.append(session)
@@ -1118,9 +1184,15 @@ async def join_mesh(
nursery.start_soon(session._events_loop, pubsub) # noqa: SLF001
nursery.start_soon(session._sync_loop) # noqa: SLF001
nursery.start_soon(session._reservation_loop) # noqa: SLF001
+ nursery.start_soon(session._announce_loop) # noqa: SLF001
+ # Best effort: a router that does not take the record is a
+ # warning the next announcement retries.
+ await session._announce_if_moved() # noqa: SLF001
try:
yield session
finally:
+ with trio.CancelScope(shield=True):
+ await session._withdraw_self() # noqa: SLF001
nursery.cancel_scope.cancel()
except BaseExceptionGroup as group:
cause = _single_cause(group)
diff --git a/sdk/python/tests/test_session.py b/sdk/python/tests/test_session.py
index c762e642..e767d5ca 100644
--- a/sdk/python/tests/test_session.py
+++ b/sdk/python/tests/test_session.py
@@ -52,7 +52,7 @@ from agent_mesh.auth import (
from agent_mesh.authorizer import ProviderAuthorizerOptions
from agent_mesh.biscuit import ROLE_ROUTER, BiscuitVerificationError
from agent_mesh.controlplane import ROLE_NODE
-from agent_mesh.discovery import DiscoveredProvider
+from agent_mesh.discovery import DIRECTORY_PROTOCOL, DiscoveredProvider, peer_key
from agent_mesh.httpx_transport import MeshTransport
from agent_mesh.identity import Identity
from agent_mesh.libp2p_http import HTTP_PROTOCOL, A2AEndpoint, HTTPResponse, ProviderOptions, http_ingress_handler
@@ -1037,3 +1037,42 @@ def test_join_holds_two_routers_handles_go_away_and_redials_before_failover():
trio.run(with_timeout, 60, main)
+
+
+def test_a_member_announces_where_it_is_reached_and_withdraws_it_on_leaving():
+ """A member with a relay reservation announces its relayed addresses under
+ its peer key to a router it holds, so that a peer on other routers finds
+ it by ID; it withdraws the record as it leaves."""
+ requests = []
+
+ def directory_handler(stream):
+ async def run():
+ req = pb.DirectoryRequest.FromString(await read_varint_prefixed_bytes(stream))
+ requests.append((req.WhichOneof("request"), req))
+ await stream.write(encode_varint_prefixed(pb.DirectoryResponse().SerializeToString()))
+ await stream.close()
+
+ return run()
+
+ async def main():
+ async with trio.open_nursery() as nursery:
+ router, router_addr = await start_router(nursery)
+ router.set_stream_handler(DIRECTORY_PROTOCOL, directory_handler)
+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([router_addr]))
+ async with mesh.join(listen_addrs=["/ip4/127.0.0.1/tcp/0"], refresh_lead=0) as session:
+ relayed = f"{router_addr}/p2p-circuit/p2p/{mesh.peer_id}"
+ assert session.relay_addresses == [relayed]
+ assert [op for op, _ in requests] == ["provide"]
+ assert requests[0][1].provide.key == peer_key(session.host.get_id())
+ assert list(requests[0][1].provide.addrs) == [relayed]
+ assert [op for op, _ in requests] == ["provide", "withdraw"]
+ assert requests[1][1].withdraw.key == peer_key(session.host.get_id())
+
+ # A member that reserves no relay has no address to announce.
+ del requests[:]
+ async with mesh.join(reserve=False) as session:
+ assert session.relay_addresses == []
+ assert requests == []
+ nursery.cancel_scope.cancel()
+
+ trio.run(with_timeout, 30, main)