Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk/js: a join that hangs says where; the probe's programs print each stage
Sauravbd19159dd9f1
diff --git a/sdk/js/README.md b/sdk/js/README.mdindex 1e067d4f..db2bc683 100644--- a/sdk/js/README.md+++ b/sdk/js/README.md@@ -61,15 +61,21 @@ if (argv[0] !== undefined && !argv[0].includes("://")) {}const [service = peerId !== undefined ? "a2a://agent" : "mcp://everything", toolOrPath = peerId !== undefined ? "/card" : "echo", args = '{"message": "hi"}'] = argv;+// Each stage goes to stderr as it is reached, so a run that hangs shows the+// last one it got to; stdout carries only what callers parse.+const controlPlaneUrl = process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com";+console.error(`enrolling with ${controlPlaneUrl}`);const mesh = await AgentMesh.enroll({- controlPlaneUrl: process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com",+ controlPlaneUrl,bootstrapTokenPath: process.env.AGENTMESH_BOOTSTRAP_TOKEN_PATH,jwtPath: process.env.AGENTMESH_JWT_PATH,stateDir: process.env.AGENTMESH_STATE_DIR ?? `${homedir()}/.config/agentmesh/caller`,// A plaintext http:// control plane is otherwise accepted only on loopback.allowInsecure: process.env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",});+console.error(`enrolled ${mesh.peerId}`);const session = await mesh.join();+console.error(`joined via ${session.routers.map((r) => r.peerId).join(", ")}`);console.log(`on the mesh as ${session.peerId}`);// The peer to call: an agent named by ID, or a provider of a published service.@@ -77,9 +83,13 @@ let provider: DiscoveredProvider = { peerId: peerId ?? "", addrs: [] };if (peerId !== undefined) {// An agent is not in the discovery table; the SDK finds the path to its// peer ID through the routers.+ console.error(`dialing ${peerId}`);await session.connect(peerId);} else {const providers = await session.discover(service);+ for (const p of providers) {+ console.error(`provider ${p.peerId}`);+ }if (providers.length === 0) {throw new Error(`no member of the mesh serves ${service}`);}@@ -87,6 +97,7 @@ if (peerId !== undefined) {let reached = false;for (const candidate of providers) {try {+ console.error(`dialing ${candidate.peerId}`);await session.connect(candidate);provider = candidate;reached = true;diff --git a/sdk/js/examples/a2a-agent.ts b/sdk/js/examples/a2a-agent.tsindex 3d2f17f1..c3c87280 100644--- a/sdk/js/examples/a2a-agent.ts+++ b/sdk/js/examples/a2a-agent.ts@@ -20,15 +20,21 @@ import { AgentEvent, DefaultRequestHandler, InMemoryTaskStore, type AgentExecutoimport { UserBuilder, agentCardHandler, jsonRpcHandler } from "@a2a-js/sdk/server/express";import { AgentMesh, MeshSession } from "@agentmesh-p2p/sdk";+// Each stage goes to stderr as it is reached, so a run that hangs shows the+// last one it got to; stdout carries only what callers parse.+const controlPlaneUrl = process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com";+console.error(`enrolling with ${controlPlaneUrl}`);const mesh = await AgentMesh.enroll({- controlPlaneUrl: process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com",+ controlPlaneUrl,bootstrapTokenPath: process.env.AGENTMESH_BOOTSTRAP_TOKEN_PATH,jwtPath: process.env.AGENTMESH_JWT_PATH,stateDir: process.env.AGENTMESH_STATE_DIR ?? `${homedir()}/.config/agentmesh/a2a-agent`,// A plaintext http:// control plane is otherwise accepted only on loopback.allowInsecure: process.env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",});+console.error(`enrolled ${mesh.peerId}`);const session = await mesh.join();+console.error(`joined via ${session.routers.map((r) => r.peerId).join(", ")}`);// The card names the agent as the mesh reaches it: the URL an A2A client on// the mesh gives its fetch, http://mesh/mesh/<peer-id>/a2a/agent.diff --git a/sdk/js/examples/a2a-call.ts b/sdk/js/examples/a2a-call.tsindex 8890f6f1..f66eeb88 100644--- a/sdk/js/examples/a2a-call.ts+++ b/sdk/js/examples/a2a-call.ts@@ -21,15 +21,21 @@ if (peerId === undefined) {throw new Error("usage: a2a-call.js <peer-id> [text]");}+// Each stage goes to stderr as it is reached, so a run that hangs shows the+// last one it got to; stdout carries only what callers parse.+const controlPlaneUrl = process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com";+console.error(`enrolling with ${controlPlaneUrl}`);const mesh = await AgentMesh.enroll({- controlPlaneUrl: process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com",+ controlPlaneUrl,bootstrapTokenPath: process.env.AGENTMESH_BOOTSTRAP_TOKEN_PATH,jwtPath: process.env.AGENTMESH_JWT_PATH,stateDir: process.env.AGENTMESH_STATE_DIR ?? `${homedir()}/.config/agentmesh/a2a-caller`,// A plaintext http:// control plane is otherwise accepted only on loopback.allowInsecure: process.env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",});+console.error(`enrolled ${mesh.peerId}`);const session = await mesh.join();+console.error(`joined via ${session.routers.map((r) => r.peerId).join(", ")}`);console.log(`on the mesh as ${session.peerId}`);// The agent's URL on the mesh, and a fetch that carries requests to it.@@ -40,6 +46,7 @@ const factory = new ClientFactory({cardResolver: new DefaultAgentCardResolver({ fetchImpl }),});// The card lives under the agent's URL; the trailing slash keeps the last segment when the resolver appends the well-known path.+console.error(`dialing ${peerId}`);const client = await factory.createFromUrl(agentURL + "/");const card = await client.getAgentCard();console.log(`agent: ${card.name}, ${card.description}`);diff --git a/sdk/js/examples/call.ts b/sdk/js/examples/call.tsindex 324667cd..6a88ce77 100644--- a/sdk/js/examples/call.ts+++ b/sdk/js/examples/call.ts@@ -22,15 +22,21 @@ if (argv[0] !== undefined && !argv[0].includes("://")) {}const [service = peerId !== undefined ? "a2a://agent" : "mcp://everything", toolOrPath = peerId !== undefined ? "/card" : "echo", args = '{"message": "hi"}'] = argv;+// Each stage goes to stderr as it is reached, so a run that hangs shows the+// last one it got to; stdout carries only what callers parse.+const controlPlaneUrl = process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com";+console.error(`enrolling with ${controlPlaneUrl}`);const mesh = await AgentMesh.enroll({- controlPlaneUrl: process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com",+ controlPlaneUrl,bootstrapTokenPath: process.env.AGENTMESH_BOOTSTRAP_TOKEN_PATH,jwtPath: process.env.AGENTMESH_JWT_PATH,stateDir: process.env.AGENTMESH_STATE_DIR ?? `${homedir()}/.config/agentmesh/caller`,// A plaintext http:// control plane is otherwise accepted only on loopback.allowInsecure: process.env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",});+console.error(`enrolled ${mesh.peerId}`);const session = await mesh.join();+console.error(`joined via ${session.routers.map((r) => r.peerId).join(", ")}`);console.log(`on the mesh as ${session.peerId}`);// The peer to call: an agent named by ID, or a provider of a published service.@@ -38,9 +44,13 @@ let provider: DiscoveredProvider = { peerId: peerId ?? "", addrs: [] };if (peerId !== undefined) {// An agent is not in the discovery table; the SDK finds the path to its// peer ID through the routers.+ console.error(`dialing ${peerId}`);await session.connect(peerId);} else {const providers = await session.discover(service);+ for (const p of providers) {+ console.error(`provider ${p.peerId}`);+ }if (providers.length === 0) {throw new Error(`no member of the mesh serves ${service}`);}@@ -48,6 +58,7 @@ if (peerId !== undefined) {let reached = false;for (const candidate of providers) {try {+ console.error(`dialing ${candidate.peerId}`);await session.connect(candidate);provider = candidate;reached = true;diff --git a/sdk/js/src/discovery.test.ts b/sdk/js/src/discovery.test.tsindex 1f2d4826..10bd289d 100644--- a/sdk/js/src/discovery.test.ts+++ b/sdk/js/src/discovery.test.ts@@ -99,3 +99,25 @@ test("a lookup one router answers with nothing is put to the next; an announcemeawait assert.rejects(request([{ peerId: "nobody", connection: () => undefined }], find), DirectoryError);});++test("a request no router answered names every router and what each said", async () => {+ const key = await serviceKey("mcp", "calculator");+ const find = create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit: 20 } } });+ answers.set("a", () => create(DirectoryResponseSchema, { error: "routing table empty" }));+ answers.set("b", () => create(DirectoryResponseSchema, { error: "rate limited" }));+ try {+ await assert.rejects(request([held(routerA), held(routerB)], find), (err: Error) => {+ assert.ok(err instanceof DirectoryError, `got ${err.name}, want DirectoryError`);+ for (const [router, said] of [+ [routerA, "routing table empty"],+ [routerB, "rate limited"],+ ] as const) {+ assert.ok(err.message.includes(`${router.peerId.toString()}: ${said}`), `got ${JSON.stringify(err.message)}, want ${router.peerId.toString()} and what it said`);+ }+ return true;+ });+ } finally {+ answers.delete("a");+ answers.delete("b");+ }+});diff --git a/sdk/js/src/discovery.ts b/sdk/js/src/discovery.tsindex 711a7784..37dbf94a 100644--- a/sdk/js/src/discovery.ts+++ b/sdk/js/src/discovery.ts@@ -110,7 +110,7 @@ async function ask(conn: Connection, req: DirectoryRequest, signal: AbortSignal)*/export async function request(routers: DirectoryRouter[], req: DirectoryRequest, signal?: AbortSignal): Promise<DirectoryResponse> {const lookup = req.request.case === "findProviders" || req.request.case === "findPeer";- let last: unknown;+ const failures: string[] = [];let asked = 0;let empty: DirectoryResponse | undefined;for (const router of routers) {@@ -128,7 +128,7 @@ export async function request(routers: DirectoryRouter[], req: DirectoryRequest,}return resp;} catch (err) {- last = err;+ failures.push(`${router.peerId}: ${err instanceof Error ? err.message : String(err)}`);if (signal?.aborted === true) {break;}@@ -140,7 +140,7 @@ export async function request(routers: DirectoryRouter[], req: DirectoryRequest,if (asked === 0) {throw new DirectoryError("no held router to ask");}- throw new DirectoryError(`no held router answered: ${last instanceof Error ? last.message : String(last)}`);+ throw new DirectoryError(`no held router answered: ${failures.join("; ")}`);}/**diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.tsindex 947fd3ba..3d32b898 100644--- a/sdk/js/src/index.ts+++ b/sdk/js/src/index.ts@@ -54,6 +54,7 @@ export {} from "./challenges.ts";export {DEFAULT_ROUTERS,+ JOIN_TIMEOUT_MS,MeshSession,ROUTER_REDIAL_BACKOFFS_MS,candidatesFromRouterInfos,diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.tsindex db5442ed..fb6204b9 100644--- a/sdk/js/src/session.test.ts+++ b/sdk/js/src/session.test.ts@@ -36,7 +36,7 @@ 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, GOAWAY_MAX_RETRY_AFTER_MS, GOAWAY_PROTOCOL, ROUTER_SHUN_DURATION_MS, authenticateWithPeer, authStreamHandler, clampGoAwayRetryAfterMs } from "./auth.ts";+import { AUTH_HANDLER_OPTIONS, AUTH_HANDSHAKE_TIMEOUT_MS, 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, DirectoryRequestSchema, DirectoryResponseSchema, PeerRecordSchema, RouterGoAwaySchema, RouterGoAway_Reason, RouterInfoSchema, TokenRefreshRequestSchema, TokenRefreshResponseSchema, type RouterInfo } from "./gen/agentmesh_pb.ts";@@ -44,7 +44,7 @@ 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, candidatesFromRouterInfos, selectRouters, type JoinOptions } from "./session.ts";+import { MeshSession, candidatesFromRouterInfos, joinDeadline, selectRouters, type JoinOptions } from "./session.ts";type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;type KeyPair = InstanceType<Wasm["KeyPair"]>;@@ -605,6 +605,82 @@ test("join reports a router that refuses the handshake", async () => {}});+test("a join bounded by its signal names the router whose handshake never answered", async () => {+ const silent = await createLibp2p({+ addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },+ transports: [tcp()],+ connectionEncrypters: [tls()],+ streamMuxers: [yamux()],+ services: { identify: identify() },+ });+ try {+ // Takes the auth stream and never writes back, as a router whose+ // handshake neither completes nor fails.+ await silent.handle(AUTH_PROTOCOL, () => {});+ const addr = (silent.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString();+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: fakeControlPlane([addr]) });+ const started = Date.now();+ await assert.rejects(mesh.join({ signal: AbortSignal.timeout(500) }), (err: Error) => {+ assert.match(err.message, new RegExp(`${silent.peerId.toString()}: auth handshake: `), `got ${JSON.stringify(err.message)}, want the router and the step it hung in`);+ return true;+ });+ const took = Date.now() - started;+ assert.ok(took < AUTH_HANDSHAKE_TIMEOUT_MS, `join took ${took}ms, want the join's signal to end it before the ${AUTH_HANDSHAKE_TIMEOUT_MS}ms handshake timeout`);+ } finally {+ await silent.stop();+ }+});++test("a join bounded by its signal says when the control plane never answered", async () => {+ const pending: Array<() => void> = [];+ let hang = false;+ const routes = fakeControlPlane([routerAddr]);+ // Once enrolled, /keys and /info take the request and never answer, until+ // the request is aborted or the test ends.+ const stalling = (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ const path = new URL(new Request(input, init).url).pathname;+ if (!hang || (path !== "/keys" && path !== "/info")) {+ return routes(input, init);+ }+ return new Promise<Response>((_, reject) => {+ const stop = () => reject(init?.signal?.reason ?? new Error("test over"));+ pending.push(stop);+ init?.signal?.addEventListener("abort", stop, { once: true });+ });+ }) as typeof fetch;+ try {+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: stalling });+ hang = true;+ const started = Date.now();+ await assert.rejects(mesh.join({ signal: AbortSignal.timeout(500) }), (err: Error) => {+ assert.match(err.message, /syncing with the control plane at http:\/\/127\.0\.0\.1:1/, `got ${JSON.stringify(err.message)}, want the control plane named`);+ return true;+ });+ const took = Date.now() - started;+ assert.ok(took < 10_000, `join took ${took}ms, want the join's signal to end it, not the control plane client's 30s request timeout`);+ } finally {+ // The sync the join gave up on goes on to its next request; let it+ // through so no request is left holding the client's 30s timer.+ hang = false;+ for (const stop of pending) {+ stop();+ }+ }+});++test("a join without a signal of its own still has a deadline", async () => {+ const given = AbortSignal.timeout(60_000);+ const own = joinDeadline(given, 20);+ assert.equal(own.signal, given, "a caller's signal bounds the join as given");+ own.clear();++ const deadline = joinDeadline(undefined, 20);+ await new Promise((resolve) => deadline.signal.addEventListener("abort", resolve, { once: true }));+ const reason = deadline.signal.reason as Error;+ assert.match(reason.message, /^join timed out after 20ms$/, `abort reason ${JSON.stringify(reason.message)}`);+ deadline.clear();+});+test("an explicit rejection is reported with its reason", async () => {const reason = new AuthRejectedError("12D3KooWtest", "peer is revoked");assert.match(reason.message, /12D3KooWtest.*peer is revoked/);diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.tsindex 3e3fe5d1..d7476c03 100644--- a/sdk/js/src/session.ts+++ b/sdk/js/src/session.ts@@ -125,7 +125,12 @@ export interface JoinOptions extends MeshHostOptions {* requiredLabels. Held on every call, MCP and HTTP alike; no call waives it.*/egressRequireLabels?: Record<string, string>;- /** Bounds the whole join. */+ /**+ * Bounds the whole join: the control plane sync, and the dial, auth+ * handshake and relay reservation with every router tried. Without one the+ * join is bounded by JOIN_TIMEOUT_MS (60s). An aborted join throws an error+ * naming each router tried and the step it was in.+ */signal?: AbortSignal;}@@ -198,6 +203,11 @@ const DEFAULT_RELAY_CHECK_MS = 30 * 1000;const DEFAULT_ANNOUNCE_MS = 5 * 60 * 1000;/** What close() waits for the member's record to be withdrawn. */const WITHDRAW_TIMEOUT_MS = 2 * 1000;+/**+ * Bounds a join whose caller passed no signal: each step has a timeout of+ * its own, but a join tries them in turn over every router it is offered.+ */+export const JOIN_TIMEOUT_MS = 60_000;/** How long a provider's positive egress verdict is kept; agentmesh-node's labelGateTTL. */const EGRESS_VERDICT_TTL_MS = 5 * 60 * 1000;@@ -394,7 +404,7 @@ export class MeshSession {* the mesh's record TTL. A member with no relayed address announces* nothing: there is nothing to reach it at.*/- async announce(): Promise<void> {+ async announce(signal?: AbortSignal): Promise<void> {if (this.#closed || this.#isTaskView) {return;}@@ -402,7 +412,7 @@ export class MeshSession {if (addrs.length === 0) {return;}- await provide(this.#directoryRouters(), await peerKey(this.peerId), addrs);+ await provide(this.#directoryRouters(), await peerKey(this.peerId), addrs, signal);this.#announced = addrs;}@@ -699,20 +709,28 @@ export class MeshSession {let progress = false;for (const cand of picks) {tried.add(cand.peerId);+ // Each step has a timeout of its own; the failure names the one the+ // router was in, so a join that hangs says where.+ let step = `dial ${cand.addresses.map(String).join(", ")}`;try {const conn = await this.node.dial(cand.addresses, signal !== undefined ? { signal } : {});- const credential = await this.#authenticateRouter(conn);+ step = "auth handshake";+ const credential = await untilAborted(this.#authenticateRouter(conn), signal);requireRole(credential, ROLE_ROUTER);const addr = connectedAddress(conn, cand.peerId);if (this.#reserveRelay) {- await this.#reserveOnRouter(cand.peerId, addr);+ step = "relay reservation";+ await untilAborted(this.#reserveOnRouter(cand.peerId, addr), signal);}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)}`);+ failures.push(`${cand.peerId}: ${step}: ${errorText(err)}`);+ if (signal?.aborted === true) {+ return failures;+ }}}if (!progress && picks.length < need) {@@ -1408,8 +1426,31 @@ export function selectRouters(candidates: readonly RouterCandidate[], k: number,return scored.slice(0, k).map((s) => s.candidate);}+/**+ * The signal a join runs under: the caller's, or one that aborts after ms+ * with an error saying the join timed out. clear() stops the timer once the+ * join is over.+ */+export function joinDeadline(signal: AbortSignal | undefined, ms = JOIN_TIMEOUT_MS): { signal: AbortSignal; clear(): void } {+ if (signal !== undefined) {+ return { signal, clear: () => {} };+ }+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(new Error(`join timed out after ${ms}ms`)), ms);+ return { signal: controller.signal, clear: () => clearTimeout(timer) };+}+/** Implements AgentMesh.join(); lives here to keep mesh.ts free of libp2p. */export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Promise<MeshSession> {+ const deadline = joinDeadline(options.signal);+ try {+ return await joinUnder(mesh, options, deadline.signal);+ } finally {+ deadline.clear();+ }+}++async function joinUnder(mesh: AgentMesh, options: JoinOptions, signal: AbortSignal): Promise<MeshSession> {// The pull agentmesh-node makes before it starts: a member resuming from its// state directory after a key rotation would otherwise verify the routers,// which already hold credentials under the new key, against the keys it@@ -1417,9 +1458,13 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom// once joined. Best effort; the stored credential serves when the control// plane cannot be reached.try {- await mesh.syncControlPlane();+ await untilAborted(mesh.syncControlPlane(), signal);} catch {- // Joining goes on with what the credential holds.+ // Joining goes on with what the credential holds, unless the join itself+ // ran out while the control plane kept it waiting.+ if (signal.aborted) {+ throw new Error(`join stopped while syncing with the control plane at ${mesh.controlPlane.url}: ${errorText(signal.reason)}`);+ }}const rawAddrs = options.routerAddresses ?? mesh.credential.routerAddresses;if (rawAddrs.length === 0 && mesh.routers.length === 0) {@@ -1455,14 +1500,14 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom);session = new MeshSession(mesh, node, [], authenticatedPeers, banned, options);- const failures = await session.topUpRouters(options.signal);- if (session.routers.length === 0) {+ const failures = await session.topUpRouters(signal);+ if (signal.aborted || session.routers.length === 0) {const detail = failures.length > 0 ? `:\n ${failures.join("\n ")}` : "";- throw new Error(`no router admitted this member${detail}`);+ throw new Error(signal.aborted ? `join stopped: ${errorText(signal.reason)}${detail}` : `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(() => {});+ await session.announce(signal).catch(() => {});return session;} catch (err) {if (session !== undefined) {@@ -1474,6 +1519,30 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom}}+/**+ * Settles as p does, or rejects with the signal's reason as soon as it+ * aborts. p is not cancelled: it ends on its own timeout, and the caller+ * tears down what it was using.+ */+function untilAborted<T>(p: Promise<T>, signal: AbortSignal | undefined): Promise<T> {+ if (signal === undefined) {+ return p;+ }+ if (signal.aborted) {+ p.catch(() => {});+ return Promise.reject(signal.reason);+ }+ return new Promise<T>((resolve, reject) => {+ const onAbort = () => reject(signal.reason);+ signal.addEventListener("abort", onAbort, { once: true });+ void p.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));+ });+}++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}+/** The peer a multiaddr ends at, in canonical form: its trailing `/p2p/<id>`, or undefined for a relay address with no target yet. */function targetPeerOf(ma: Multiaddr): string | undefined {const last = ma.getComponents().at(-1);diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.mdindex 6035e758..85743f36 100644--- a/site/content/docs/guides/native-sdks.md+++ b/site/content/docs/guides/native-sdks.md@@ -286,15 +286,21 @@ if (argv[0] !== undefined && !argv[0].includes("://")) {}const [service = peerId !== undefined ? "a2a://agent" : "mcp://everything", toolOrPath = peerId !== undefined ? "/card" : "echo", args = '{"message": "hi"}'] = argv;+// Each stage goes to stderr as it is reached, so a run that hangs shows the+// last one it got to; stdout carries only what callers parse.+const controlPlaneUrl = process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com";+console.error(`enrolling with ${controlPlaneUrl}`);const mesh = await AgentMesh.enroll({- controlPlaneUrl: process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com",+ controlPlaneUrl,bootstrapTokenPath: process.env.AGENTMESH_BOOTSTRAP_TOKEN_PATH,jwtPath: process.env.AGENTMESH_JWT_PATH,stateDir: process.env.AGENTMESH_STATE_DIR ?? `${homedir()}/.config/agentmesh/caller`,// A plaintext http:// control plane is otherwise accepted only on loopback.allowInsecure: process.env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",});+console.error(`enrolled ${mesh.peerId}`);const session = await mesh.join();+console.error(`joined via ${session.routers.map((r) => r.peerId).join(", ")}`);console.log(`on the mesh as ${session.peerId}`);// The peer to call: an agent named by ID, or a provider of a published service.@@ -302,9 +308,13 @@ let provider: DiscoveredProvider = { peerId: peerId ?? "", addrs: [] };if (peerId !== undefined) {// An agent is not in the discovery table; the SDK finds the path to its// peer ID through the routers.+ console.error(`dialing ${peerId}`);await session.connect(peerId);} else {const providers = await session.discover(service);+ for (const p of providers) {+ console.error(`provider ${p.peerId}`);+ }if (providers.length === 0) {throw new Error(`no member of the mesh serves ${service}`);}@@ -312,6 +322,7 @@ if (peerId !== undefined) {let reached = false;for (const candidate of providers) {try {+ console.error(`dialing ${candidate.peerId}`);await session.connect(candidate);provider = candidate;reached = true;@@ -525,15 +536,21 @@ import { AgentEvent, DefaultRequestHandler, InMemoryTaskStore, type AgentExecutoimport { UserBuilder, agentCardHandler, jsonRpcHandler } from "@a2a-js/sdk/server/express";import { AgentMesh, MeshSession } from "@agentmesh-p2p/sdk";+// Each stage goes to stderr as it is reached, so a run that hangs shows the+// last one it got to; stdout carries only what callers parse.+const controlPlaneUrl = process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com";+console.error(`enrolling with ${controlPlaneUrl}`);const mesh = await AgentMesh.enroll({- controlPlaneUrl: process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com",+ controlPlaneUrl,bootstrapTokenPath: process.env.AGENTMESH_BOOTSTRAP_TOKEN_PATH,jwtPath: process.env.AGENTMESH_JWT_PATH,stateDir: process.env.AGENTMESH_STATE_DIR ?? `${homedir()}/.config/agentmesh/a2a-agent`,// A plaintext http:// control plane is otherwise accepted only on loopback.allowInsecure: process.env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",});+console.error(`enrolled ${mesh.peerId}`);const session = await mesh.join();+console.error(`joined via ${session.routers.map((r) => r.peerId).join(", ")}`);// The card names the agent as the mesh reaches it: the URL an A2A client on// the mesh gives its fetch, http://mesh/mesh/<peer-id>/a2a/agent.@@ -736,15 +753,21 @@ if (peerId === undefined) {throw new Error("usage: a2a-call.js <peer-id> [text]");}+// Each stage goes to stderr as it is reached, so a run that hangs shows the+// last one it got to; stdout carries only what callers parse.+const controlPlaneUrl = process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com";+console.error(`enrolling with ${controlPlaneUrl}`);const mesh = await AgentMesh.enroll({- controlPlaneUrl: process.env.AGENTMESH_CONTROL_PLANE_URL ?? "https://mesh.example.com",+ controlPlaneUrl,bootstrapTokenPath: process.env.AGENTMESH_BOOTSTRAP_TOKEN_PATH,jwtPath: process.env.AGENTMESH_JWT_PATH,stateDir: process.env.AGENTMESH_STATE_DIR ?? `${homedir()}/.config/agentmesh/a2a-caller`,// A plaintext http:// control plane is otherwise accepted only on loopback.allowInsecure: process.env.AGENTMESH_INSECURE_CONTROL_PLANE === "true",});+console.error(`enrolled ${mesh.peerId}`);const session = await mesh.join();+console.error(`joined via ${session.routers.map((r) => r.peerId).join(", ")}`);console.log(`on the mesh as ${session.peerId}`);// The agent's URL on the mesh, and a fetch that carries requests to it.@@ -755,6 +778,7 @@ const factory = new ClientFactory({cardResolver: new DefaultAgentCardResolver({ fetchImpl }),});// The card lives under the agent's URL; the trailing slash keeps the last segment when the resolver appends the well-known path.+console.error(`dialing ${peerId}`);const client = await factory.createFromUrl(agentURL + "/");const card = await client.getAgentCard();console.log(`agent: ${card.name}, ${card.description}`);