Prompt-First Example 12 · Durable Habitats · A2A 1.0 · Multi-Agent Mesh
Multi-A2A Mesh:
Pi Driving Remote Agents
Boot two isolated A2A 1.0 DurableHabitat peers on loopback, discover their Agent Cards, drive them from real Pi CLI slash commands, and verify on a clean machine.
01 — The Prompt You Give Pi
“Stand up two isolated A2A 1.0 DurableHabitat peers (researcher and reviewer) on loopback, verify fail-closed 401 auth and Agent Card discovery (/.well-known/agent-card.json), write an isolated agents.json config, drive /a2a list, /a2a send, and /a2a result end-to-end through the real Pi CLI (@leocavalcante/pi-a2a), and pair it with a clean-machine shell verifier.”
Paste directly into
pi or your coding agent with @umwelten/* installed.
5 min walkthrough
02 — The Example That Gets Built
Live workspace source: examples/multi-a2a/e2e.ts
Read directly from disk at site-build time — byte-for-byte identical to the typechecked script in this repo.
TypeScript
examples/multi-a2a/e2e.ts
pnpm run demo:multi-a2a
1#!/usr/bin/env node
2/**
3 * End-to-End Multi-A2A Pi Verification Script.
4 *
5 * Boots two independent A2A 1.0 `DurableHabitat` servers on loopback ports
6 * (with separate bearer tokens), writes an isolated temporary `agents.json`,
7 * verifies endpoint discovery + fail-closed 401 auth, and drives both agents
8 * through the real `pi` CLI using `@leocavalcante/pi-a2a/extension`.
9 *
10 * Run:
11 * pnpm run demo:multi-a2a
12 * pnpm run demo:multi-a2a -- --interactive
13 * pnpm run demo:multi-a2a -- --live --model google:gemini-4-hydrogen
14 */
15
16import assert from "node:assert/strict";
17import { spawn, spawnSync } from "node:child_process";
18import { randomBytes } from "node:crypto";
19import { existsSync } from "node:fs";
20import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
21import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
22import { createRequire } from "node:module";
23import { tmpdir } from "node:os";
24import { dirname, join, resolve } from "node:path";
25import { fileURLToPath } from "node:url";
26import { parseArgs } from "node:util";
27import {
28 createModels,
29 fauxAssistantMessage,
30 fauxProvider,
31 type TranscriptContext,
32} from "@earendil-works/pi-ai";
33import { DurableHabitat } from "@umwelten/habitat";
34import {
35 parseModelSpecString,
36 resolvePiModel,
37 type ResolvedPiInvocationTarget,
38} from "@umwelten/pi";
39import { discoverAgentEndpoint } from "@umwelten/protocols";
40
41interface RunningAgentServer {
42 id: string;
43 url: string;
44 token: string;
45 habitat: DurableHabitat;
46 server: Server;
47 close: () => Promise<void>;
48}
49
50interface PiA2ADetails {
51 ok: boolean;
52 agent?: string;
53 agents?: string[];
54 messageId?: string;
55 taskId?: string;
56 contextId?: string;
57 state?: string;
58 text?: string;
59 error?: { code?: string; message?: string };
60}
61
62interface PiJsonEvent {
63 type?: string;
64 message?: {
65 customType?: string;
66 details?: PiA2ADetails;
67 };
68}
69
70function extractLastUserPrompt(ctx: TranscriptContext): string {
71 for (let i = ctx.messages.length - 1; i >= 0; i--) {
72 const msg = ctx.messages[i];
73 if (msg.role !== "user") continue;
74 if (typeof msg.content === "string") return msg.content;
75 if (Array.isArray(msg.content)) {
76 const texts: string[] = [];
77 for (const block of msg.content) {
78 if (
79 typeof block === "object" &&
80 block !== null &&
81 block.type === "text" &&
82 typeof block.text === "string"
83 ) {
84 texts.push(block.text);
85 }
86 }
87 if (texts.length > 0) return texts.join("\n");
88 }
89 }
90 return "";
91}
92
93function createScriptedTarget(
94 agentLabel: string,
95 roleHint: string,
96): ResolvedPiInvocationTarget {
97 const modelId = `${agentLabel}-v1`;
98 const faux = fauxProvider({ provider: "faux", models: [{ id: modelId }] });
99 const step = (ctx: TranscriptContext) => {
100 faux.appendResponses([step]);
101 const prompt = extractLastUserPrompt(ctx).replace(/\s+/g, " ").trim();
102 const preview = prompt.length > 120 ? `${prompt.slice(0, 117)}...` : prompt;
103 return fauxAssistantMessage(
104 `[${agentLabel}] ${roleHint} — handled request: "${preview}"`,
105 );
106 };
107 faux.setResponses([step]);
108 const models = createModels();
109 models.setProvider(faux.provider);
110 const piModel = models.getModel("faux", modelId);
111 if (!piModel) {
112 throw new Error(`Failed to register scripted faux model ${modelId}`);
113 }
114 return { models, piModel };
115}
116
117async function startA2AAgentServer(opts: {
118 id: string;
119 name: string;
120 description: string;
121 instructions: string;
122 roleHint: string;
123 baseWorkDir: string;
124 token: string;
125 liveTarget?: ResolvedPiInvocationTarget;
126}): Promise<RunningAgentServer> {
127 const target = opts.liveTarget ?? createScriptedTarget(opts.id, opts.roleHint);
128 const workDir = join(opts.baseWorkDir, opts.id);
129 await mkdir(workDir, { recursive: true });
130
131 const habitat = await DurableHabitat.open({
132 id: opts.id,
133 name: opts.name,
134 description: opts.description,
135 instructions: opts.instructions,
136 workDir,
137 models: target.models,
138 model: { provider: target.piModel.provider, modelId: target.piModel.id },
139 });
140
141 let httpHandler:
142 | ((req: IncomingMessage, res: ServerResponse) => Promise<boolean>)
143 | undefined;
144
145 const server = createServer((req, res) => {
146 if (!httpHandler) {
147 res.writeHead(503).end("Initializing");
148 return;
149 }
150 void httpHandler(req, res).then((handled) => {
151 if (!handled && !res.headersSent) {
152 res.writeHead(404).end("Not found");
153 }
154 });
155 });
156
157 await new Promise<void>((resolveListen, rejectListen) => {
158 server.once("error", rejectListen);
159 server.listen(0, "127.0.0.1", () => {
160 server.removeListener("error", rejectListen);
161 resolveListen();
162 });
163 });
164
165 const addr = server.address();
166 const port = typeof addr === "object" && addr ? addr.port : 0;
167 if (!port) {
168 server.close();
169 await habitat.close();
170 throw new Error(`Failed to bind loopback port for ${opts.id}`);
171 }
172
173 const url = `http://127.0.0.1:${port}`;
174 const surface = habitat.createA2ASurface({
175 endpointUrl: `${url}/a2a`,
176 bearerToken: opts.token,
177 });
178 httpHandler = surface.httpHandler;
179
180 return {
181 id: opts.id,
182 url,
183 token: opts.token,
184 habitat,
185 server,
186 async close() {
187 server.closeIdleConnections?.();
188 await new Promise<void>((resolveClose) => {
189 server.close(() => resolveClose());
190 });
191 await habitat.close();
192 },
193 };
194}
195
196function assertPiInstalled(): string {
197 const res = spawnSync("pi", ["--version"], { encoding: "utf8" });
198 if (res.error || res.status !== 0) {
199 throw new Error(
200 `The \`pi\` CLI was not found on PATH.\n` +
201 `Install it on a clean machine with:\n` +
202 ` pnpm add -g @earendil-works/pi-coding-agent\n` +
203 `or run:\n` +
204 ` ./examples/multi-a2a/clean-machine.sh`,
205 );
206 }
207 return res.stdout.trim();
208}
209
210async function spawnProcess(
211 command: string,
212 args: string[],
213 env: NodeJS.ProcessEnv,
214 timeoutMs: number,
215): Promise<{ status: number; stdout: string; stderr: string }> {
216 return new Promise((resolveProc, rejectProc) => {
217 const child = spawn(command, args, {
218 env,
219 stdio: ["ignore", "pipe", "pipe"],
220 });
221 let stdout = "";
222 let stderr = "";
223 let timedOut = false;
224
225 const timer = setTimeout(() => {
226 timedOut = true;
227 child.kill("SIGTERM");
228 }, timeoutMs);
229
230 child.stdout.on("data", (chunk) => {
231 stdout += String(chunk);
232 });
233 child.stderr.on("data", (chunk) => {
234 stderr += String(chunk);
235 });
236 child.once("error", (err) => {
237 clearTimeout(timer);
238 rejectProc(err);
239 });
240 child.once("close", (code) => {
241 clearTimeout(timer);
242 if (timedOut) {
243 rejectProc(
244 new Error(
245 `Process timed out after ${timeoutMs}ms: ${command} ${args.join(" ")}\nstdout:\n${stdout}\nstderr:\n${stderr}`,
246 ),
247 );
248 return;
249 }
250 resolveProc({ status: code ?? 1, stdout, stderr });
251 });
252 });
253}
254
255async function runPiA2aCommand(
256 command: string,
257 env: NodeJS.ProcessEnv,
258 extPath: string,
259): Promise<PiA2ADetails> {
260 const res = await spawnProcess(
261 "pi",
262 [
263 "-p",
264 "--mode",
265 "json",
266 "--no-session",
267 "--no-extensions",
268 "--no-skills",
269 "--no-prompt-templates",
270 "--no-themes",
271 "--no-context-files",
272 "--no-mcp",
273 "--offline",
274 "-e",
275 extPath,
276 command,
277 ],
278 env,
279 60_000,
280 );
281
282 let found: PiA2ADetails | undefined;
283 for (const rawLine of res.stdout.split("\n")) {
284 const line = rawLine.trim();
285 if (!line.startsWith("{")) continue;
286 try {
287 const ev = JSON.parse(line) as PiJsonEvent;
288 if (
289 ev.type === "message_end" &&
290 ev.message?.customType === "pi-a2a" &&
291 ev.message.details
292 ) {
293 found = ev.message.details;
294 }
295 } catch {
296 // Ignore non-JSON lines if any
297 }
298 }
299
300 if (!found || res.status !== 0) {
301 throw new Error(
302 `Pi command failed (${command}) with exit=${res.status}.\nstdout:\n${res.stdout}\nstderr:\n${res.stderr}`,
303 );
304 }
305 return found;
306}
307
308function printUsage(): void {
309 console.log(`Usage: pnpm run demo:multi-a2a [-- [options]]
310
311Starts two isolated A2A 1.0 DurableHabitat servers (researcher + reviewer),
312verifies endpoint discovery + 401 auth fail-closed checks, and drives both
313agents from the Pi CLI using @leocavalcante/pi-a2a.
314
315Options:
316 --interactive Keep both A2A agents running and open an interactive Pi TUI
317 --live Back both agents with a real LLM and run a multi-agent Pi turn
318 --model <spec> Model spec for --live backend agents (default: google:gemini-4-hydrogen)
319 --help, -h Show this help message`);
320}
321
322async function main(): Promise<void> {
323 const { values } = parseArgs({
324 args: process.argv.slice(2).filter((a) => a !== "--"),
325 options: {
326 interactive: { type: "boolean", default: false },
327 live: { type: "boolean", default: false },
328 model: { type: "string", default: "google:gemini-4-hydrogen" },
329 help: { type: "boolean", short: "h", default: false },
330 },
331 allowPositionals: true,
332 });
333
334 if (values.help) {
335 printUsage();
336 return;
337 }
338
339 const here = dirname(fileURLToPath(import.meta.url));
340 const repoRoot = resolve(here, "../..");
341 const req = createRequire(join(repoRoot, "packages", "protocols", "package.json"));
342 const extPath = req.resolve("@leocavalcante/pi-a2a/extension");
343 assert.ok(existsSync(extPath), `Extension entry not found at ${extPath}`);
344
345 const piVersion = assertPiInstalled();
346 const modeLabel = values.live ? `live (${values.model})` : "offline mock (fauxProvider)";
347 console.log(`=== Multi-A2A Pi E2E Verification (${modeLabel}) ===`);
348 console.log(`Pi CLI version: ${piVersion}`);
349 console.log(`A2A Extension: ${extPath}`);
350
351 let liveTarget: ResolvedPiInvocationTarget | undefined;
352 if (values.live) {
353 liveTarget = await resolvePiModel(parseModelSpecString(values.model));
354 }
355
356 const tmpRoot = await mkdtemp(join(tmpdir(), "umwelten-multi-a2a-"));
357 const tokenA = randomBytes(16).toString("hex");
358 const tokenB = randomBytes(16).toString("hex");
359
360 let researcherServer: RunningAgentServer | undefined;
361 let reviewerServer: RunningAgentServer | undefined;
362
363 try {
364 researcherServer = await startA2AAgentServer({
365 id: "researcher",
366 name: "Researcher Agent",
367 description: "Investigates technical tradeoffs and summarizes findings.",
368 instructions:
369 "You are a concise architecture researcher. Answer technical questions in 2-3 tight bullets.",
370 roleHint: "Analyzes architecture tradeoffs and risks",
371 baseWorkDir: tmpRoot,
372 token: tokenA,
373 liveTarget,
374 });
375
376 reviewerServer = await startA2AAgentServer({
377 id: "reviewer",
378 name: "Security Reviewer Agent",
379 description: "Audits proposals for security, auth, and operational risks.",
380 instructions:
381 "You are a concise security reviewer. Flag auth, credential, and blast-radius risks in 2-3 tight bullets.",
382 roleHint: "Audits auth boundaries and failure modes",
383 baseWorkDir: tmpRoot,
384 token: tokenB,
385 liveTarget,
386 });
387
388 console.log(`\n1. Started two isolated A2A 1.0 DurableHabitat servers:`);
389 console.log(` - researcher -> ${researcherServer.url}`);
390 console.log(` - reviewer -> ${reviewerServer.url}`);
391
392 const cardA = await discoverAgentEndpoint(researcherServer.url, {
393 bearerToken: tokenA,
394 });
395 const cardB = await discoverAgentEndpoint(reviewerServer.url, {
396 bearerToken: tokenB,
397 });
398 assert.ok(cardA && cardA.kind === "a2a", "Expected A2A card for researcher");
399 assert.ok(cardB && cardB.kind === "a2a", "Expected A2A card for reviewer");
400 assert.equal(cardA.streaming, true, "researcher should advertise streaming");
401 assert.equal(cardB.streaming, true, "reviewer should advertise streaming");
402 assert.equal(cardA.auth, "bearer", "researcher should advertise bearer auth");
403 assert.equal(cardB.auth, "bearer", "reviewer should advertise bearer auth");
404
405 const unauthRes = await fetch(`${researcherServer.url}/a2a`, {
406 method: "POST",
407 headers: { "content-type": "application/json", "a2a-version": "1.0" },
408 body: JSON.stringify({
409 jsonrpc: "2.0",
410 id: "unauth-1",
411 method: "SendMessage",
412 params: {
413 message: {
414 messageId: "unauth-msg-1",
415 role: "ROLE_USER",
416 parts: [{ text: "Unauthorized ping" }],
417 },
418 },
419 }),
420 });
421 assert.equal(
422 unauthRes.status,
423 401,
424 `Expected 401 fail-closed without bearer token, got ${unauthRes.status}`,
425 );
426 console.log(`2. Verified Agent Card discovery + fail-closed 401 auth.`);
427
428 const configPath = join(tmpRoot, "agents.json");
429 const agentsConfig = {
430 agents: {
431 researcher: {
432 url: researcherServer.url,
433 allowHttpLoopback: true,
434 bearerTokenEnv: "RESEARCHER_A2A_TOKEN",
435 },
436 reviewer: {
437 url: reviewerServer.url,
438 allowHttpLoopback: true,
439 bearerTokenEnv: "REVIEWER_A2A_TOKEN",
440 },
441 },
442 };
443 await writeFile(configPath, `${JSON.stringify(agentsConfig, null, 2)}\n`, "utf8");
444 console.log(`3. Wrote isolated A2A config: ${configPath}`);
445
446 const childEnv: NodeJS.ProcessEnv = {
447 ...process.env,
448 PI_A2A_CONFIG: configPath,
449 RESEARCHER_A2A_TOKEN: tokenA,
450 REVIEWER_A2A_TOKEN: tokenB,
451 };
452
453 if (values.interactive) {
454 console.log("\nLaunching interactive Pi session with both agents connected.");
455 console.log("Try inside Pi:");
456 console.log(" /a2a list");
457 console.log(" /a2a send researcher List two architectural tradeoffs of a shared cache.");
458 console.log(" /a2a send reviewer Audit a shared cache for token leaks.");
459 console.log(' Or prompt the model: "Ask researcher and reviewer to review Redis vs SQLite, then synthesize."');
460 const exitCode = await new Promise<number>((resolveExit, rejectExit) => {
461 const child = spawn("pi", ["--no-session", "--no-extensions", "-e", extPath], {
462 env: childEnv,
463 stdio: "inherit",
464 });
465 child.once("error", rejectExit);
466 child.once("exit", (code) => resolveExit(code ?? 0));
467 });
468 if (exitCode !== 0) {
469 process.exitCode = exitCode;
470 }
471 return;
472 }
473
474 console.log("\n4. Driving both A2A agents via real `pi` CLI:");
475
476 const listReply = await runPiA2aCommand("/a2a list", childEnv, extPath);
477 assert.equal(listReply.ok, true, "Expected /a2a list ok=true");
478 assert.deepEqual(
479 [...(listReply.agents ?? [])].sort(),
480 ["researcher", "reviewer"],
481 "Expected both researcher and reviewer in /a2a list",
482 );
483 console.log(` - PASS /a2a list -> ${JSON.stringify(listReply.agents)}`);
484
485 const sendResearcher = await runPiA2aCommand(
486 "/a2a send researcher List two architectural risks of a shared cache.",
487 childEnv,
488 extPath,
489 );
490 assert.equal(sendResearcher.ok, true, "Expected researcher send ok=true");
491 assert.ok(
492 sendResearcher.state?.includes("COMPLETED"),
493 `Expected COMPLETED state for researcher, got ${sendResearcher.state}`,
494 );
495 assert.ok(sendResearcher.taskId, "Expected researcher taskId");
496 assert.ok(sendResearcher.contextId, "Expected researcher contextId");
497 assert.ok(sendResearcher.text && sendResearcher.text.length > 0, "Expected non-empty researcher response");
498 if (!values.live) {
499 assert.ok(
500 sendResearcher.text.includes("[researcher]"),
501 `Expected scripted [researcher] marker, got: ${sendResearcher.text}`,
502 );
503 }
504 console.log(` - PASS /a2a send researcher -> ${sendResearcher.text}`);
505
506 const sendReviewer = await runPiA2aCommand(
507 "/a2a send reviewer Audit a shared cache for auth and token-leak risks.",
508 childEnv,
509 extPath,
510 );
511 assert.equal(sendReviewer.ok, true, "Expected reviewer send ok=true");
512 assert.ok(
513 sendReviewer.state?.includes("COMPLETED"),
514 `Expected COMPLETED state for reviewer, got ${sendReviewer.state}`,
515 );
516 assert.ok(sendReviewer.taskId, "Expected reviewer taskId");
517 assert.ok(sendReviewer.contextId, "Expected reviewer contextId");
518 assert.ok(sendReviewer.text && sendReviewer.text.length > 0, "Expected non-empty reviewer response");
519 if (!values.live) {
520 assert.ok(
521 sendReviewer.text.includes("[reviewer]"),
522 `Expected scripted [reviewer] marker, got: ${sendReviewer.text}`,
523 );
524 }
525 console.log(` - PASS /a2a send reviewer -> ${sendReviewer.text}`);
526
527 const taskLookup = await runPiA2aCommand(
528 `/a2a result researcher ${sendResearcher.taskId}`,
529 childEnv,
530 extPath,
531 );
532 assert.equal(taskLookup.ok, true, "Expected /a2a result researcher ok=true");
533 assert.equal(taskLookup.taskId, sendResearcher.taskId, "Expected matching taskId");
534 assert.ok(
535 taskLookup.state?.includes("COMPLETED"),
536 `Expected COMPLETED task lookup state, got ${taskLookup.state}`,
537 );
538 console.log(` - PASS /a2a result researcher ${taskLookup.taskId} -> ${taskLookup.state}`);
539
540 if (values.live) {
541 console.log("\n5. Running LLM-orchestrated multi-agent turn via Pi model tools:");
542 const llmRun = await spawnProcess(
543 "pi",
544 [
545 "-p",
546 "--no-session",
547 "--no-extensions",
548 "--no-skills",
549 "--no-prompt-templates",
550 "--no-themes",
551 "--no-context-files",
552 "--no-mcp",
553 "--no-builtin-tools",
554 "-e",
555 extPath,
556 "Use a2a_agents to list configured agents, call a2a_send on both researcher and reviewer, then summarize both responses in 3 bullets.",
557 ],
558 childEnv,
559 120_000,
560 );
561 if (llmRun.status !== 0) {
562 throw new Error(
563 `LLM multi-agent turn failed (exit=${llmRun.status}):\n${llmRun.stdout}\n${llmRun.stderr}`,
564 );
565 }
566 console.log(llmRun.stdout.trim());
567 }
568
569 console.log("\nALL MULTI-A2A PI CHECKS PASSED.");
570 } finally {
571 await Promise.allSettled([
572 researcherServer ? researcherServer.close() : Promise.resolve(),
573 reviewerServer ? reviewerServer.close() : Promise.resolve(),
574 ]);
575 await rm(tmpRoot, { recursive: true, force: true });
576 }
577}
578
579main().catch((err) => {
580 console.error("\nMulti-A2A E2E failed:", err);
581 process.exit(1);
582});
03 — Captured Execution Telemetry
Captured stdout from running pnpm run demo:multi-a2a
Captured Run Output
pnpm run demo:multi-a2a
=== Multi-A2A Pi E2E Verification (offline mock (fauxProvider)) === Pi CLI version: 1.5.2 1. Started two isolated A2A 1.0 DurableHabitat servers: - researcher -> http://127.0.0.1:61477 - reviewer -> http://127.0.0.1:61478 2. Verified Agent Card discovery + fail-closed 401 auth. 3. Wrote isolated A2A config: .../agents.json 4. Driving both A2A agents via real `pi` CLI: - PASS /a2a list -> ["researcher","reviewer"] - PASS /a2a send researcher -> [researcher] Analyzes architecture tradeoffs and risks - PASS /a2a send reviewer -> [reviewer] Audits auth boundaries and failure modes - PASS /a2a result researcher -> TASK_STATE_COMPLETED ALL MULTI-A2A PI CHECKS PASSED.
04 — How & Why This Extends Pi
Architectural notes
Demonstrates Pi acting as a multi-agent coordinator via @leocavalcante/pi-a2a against live DurableHabitat
endpoints, complete with clean-machine.sh so every claim reproduces from scratch.