ceulen 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/extensions/lib/registry.test.ts +67 -0
  3. package/extensions/lib/registry.ts +24 -7
  4. package/extensions/modules/a2a/configPanel.ts +435 -0
  5. package/extensions/modules/a2a/index.ts +1117 -0
  6. package/extensions/modules/a2a/lib/activity.ts +173 -0
  7. package/extensions/modules/a2a/lib/client.ts +1061 -0
  8. package/extensions/modules/a2a/lib/config.ts +920 -0
  9. package/extensions/modules/a2a/lib/discovery.ts +158 -0
  10. package/extensions/modules/a2a/lib/gateway.ts +889 -0
  11. package/extensions/modules/a2a/lib/mdns.ts +233 -0
  12. package/extensions/modules/a2a/lib/outcome.ts +48 -0
  13. package/extensions/modules/a2a/lib/persistence.ts +123 -0
  14. package/extensions/modules/a2a/lib/protocol.ts +506 -0
  15. package/extensions/modules/a2a/lib/registry.ts +146 -0
  16. package/extensions/modules/a2a/lib/retry.ts +86 -0
  17. package/extensions/modules/a2a/lib/security.ts +394 -0
  18. package/extensions/modules/a2a/lib/server.ts +1436 -0
  19. package/extensions/modules/a2a/test/activity.test.ts +138 -0
  20. package/extensions/modules/a2a/test/bridge.test.ts +101 -0
  21. package/extensions/modules/a2a/test/broadcast-parse.test.ts +31 -0
  22. package/extensions/modules/a2a/test/chai.ts +101 -0
  23. package/extensions/modules/a2a/test/client.test.ts +856 -0
  24. package/extensions/modules/a2a/test/completion-guard.test.ts +73 -0
  25. package/extensions/modules/a2a/test/config.test.ts +1396 -0
  26. package/extensions/modules/a2a/test/configPanel.test.ts +393 -0
  27. package/extensions/modules/a2a/test/discovery.test.ts +144 -0
  28. package/extensions/modules/a2a/test/extension.test.ts +135 -0
  29. package/extensions/modules/a2a/test/gateway.test.ts +1449 -0
  30. package/extensions/modules/a2a/test/helpers.ts +39 -0
  31. package/extensions/modules/a2a/test/mdns.test.ts +131 -0
  32. package/extensions/modules/a2a/test/outcome.test.ts +61 -0
  33. package/extensions/modules/a2a/test/persistence.test.ts +92 -0
  34. package/extensions/modules/a2a/test/protocol.test.ts +217 -0
  35. package/extensions/modules/a2a/test/registry.test.ts +114 -0
  36. package/extensions/modules/a2a/test/retry.test.ts +136 -0
  37. package/extensions/modules/a2a/test/security.test.ts +281 -0
  38. package/extensions/modules/a2a/test/server.test.ts +1966 -0
  39. package/extensions/modules/a2a/test/tmp.ts +59 -0
  40. package/extensions/modules/a2a/test/vendor.test.ts +57 -0
  41. package/extensions/modules/a2a/types/bonjour-service.d.ts +22 -0
  42. package/extensions/modules/a2a/vendor/VENDORED.md +18 -0
  43. package/extensions/modules/a2a/vendor/package.json +1 -0
  44. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/LICENSE +23 -0
  45. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.d.ts +14 -0
  46. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.js +57 -0
  47. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.d.ts +4 -0
  48. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.js +3 -0
  49. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.d.ts +13 -0
  50. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.js +50 -0
  51. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.d.ts +41 -0
  52. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.js +209 -0
  53. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.d.ts +9 -0
  54. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.js +42 -0
  55. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.d.ts +14 -0
  56. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.js +119 -0
  57. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.d.ts +14 -0
  58. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.js +142 -0
  59. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.d.ts +7 -0
  60. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.js +53 -0
  61. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.d.ts +58 -0
  62. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.js +130 -0
  63. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.d.ts +1 -0
  64. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.js +13 -0
  65. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.d.ts +1 -0
  66. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.js +17 -0
  67. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.d.ts +4 -0
  68. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.js +22 -0
  69. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.d.ts +3 -0
  70. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.js +6 -0
  71. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/LICENSE +21 -0
  72. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/classes.js +23 -0
  73. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/index.js +1761 -0
  74. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/opcodes.js +50 -0
  75. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/optioncodes.js +59 -0
  76. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/rcodes.js +50 -0
  77. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/types.js +103 -0
  78. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/LICENSE +21 -0
  79. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/es6.js +73 -0
  80. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/index.js +46 -0
  81. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/LICENSE +21 -0
  82. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/index.cjs +250 -0
  83. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/LICENSE +21 -0
  84. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/index.js +205 -0
  85. package/extensions/modules/a2a/vendor/vendored_deps/thunky/LICENSE +21 -0
  86. package/extensions/modules/a2a/vendor/vendored_deps/thunky/index.js +55 -0
  87. package/extensions/modules/advisor/index.ts +20 -2
  88. package/extensions/modules/advisor/lib/watcher.ts +3 -1
  89. package/extensions/modules/advisor/test/module.test.ts +64 -1
  90. package/extensions/modules/composer/test/module.test.ts +2 -2
  91. package/extensions/modules/config/index.ts +2 -0
  92. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  93. package/extensions/modules/munin/configPanel.ts +5 -2
  94. package/extensions/modules/munin/test/configPanel.test.ts +27 -2
  95. package/extensions/modules/router/configPanel.ts +24 -10
  96. package/extensions/modules/router/lib/client.ts +6 -4
  97. package/extensions/modules/router/test/unit.test.ts +83 -2
  98. package/extensions/modules/rules/index.ts +120 -0
  99. package/extensions/modules/rules/lib/rules.ts +348 -0
  100. package/extensions/modules/rules/test/lib.test.ts +263 -0
  101. package/extensions/modules/rules/test/module.test.ts +222 -0
  102. package/extensions/modules/subagent/index.ts +19 -6
  103. package/extensions/modules/subagent/lib/routing.ts +11 -6
  104. package/extensions/modules/subagent/lib/security.ts +12 -1
  105. package/extensions/modules/subagent/test/routing.test.ts +174 -0
  106. package/extensions/modules/todo/configPanel.ts +55 -0
  107. package/extensions/modules/todo/index.ts +511 -0
  108. package/extensions/modules/todo/lib/render.ts +271 -0
  109. package/extensions/modules/todo/lib/settings.ts +73 -0
  110. package/extensions/modules/todo/test/todo.test.ts +528 -0
  111. package/extensions/modules/usage/index.ts +11 -0
  112. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  113. package/extensions/modules/web/configPanel.ts +38 -13
  114. package/extensions/modules/web/lib/settings.ts +11 -2
  115. package/extensions/modules/web/test/configPanel.test.ts +67 -1
  116. package/extensions/modules/zai/configPanel.ts +5 -2
  117. package/extensions/modules/zai/lib/signing.ts +4 -1
  118. package/extensions/modules/zai/test/configPanel.test.ts +23 -0
  119. package/extensions/modules/zai/test/signing.test.ts +19 -0
  120. package/package.json +2 -2
  121. package/skills/a2a/SKILL.md +63 -0
@@ -0,0 +1,1061 @@
1
+ /**
2
+ * A2A outbound client — Pi as an A2A Client calling remote agents.
3
+ *
4
+ * Ported from Hermes tools.py. Uses global `fetch` (Node 18+); no deps.
5
+ * Wire format: A2A v1.0 JSON-RPC `SendMessage`; v0.3 peers tolerated.
6
+ *
7
+ * Every call: redact → audit → persist → POST → unwrap → reply text.
8
+ */
9
+
10
+ import {
11
+ PROTOCOL_VERSION,
12
+ STATE_INPUT_REQUIRED,
13
+ TERMINAL_STATES,
14
+ extractText,
15
+ newContextId,
16
+ newTaskId,
17
+ normalizeState,
18
+ ROLE_USER,
19
+ textMessage,
20
+ unwrapSendMessageResponse,
21
+ type AgentCard,
22
+ type JsonRpcRequest,
23
+ type Task,
24
+ } from "./protocol";
25
+ import {
26
+ authHeaders,
27
+ gatewayEntries,
28
+ getGatewayCallerName,
29
+ getGatewayPeers,
30
+ getGatewayRegistrationName,
31
+ normUrl,
32
+ type A2AConfig,
33
+ type Peer,
34
+ resolvePeer,
35
+ } from "./config";
36
+ import {
37
+ audit,
38
+ redactOutbound,
39
+ } from "./security";
40
+ import {
41
+ listConversations,
42
+ loadConversation,
43
+ persistMessage,
44
+ } from "./persistence";
45
+ import { clean, type DiscoveredPeer } from "./discovery";
46
+ import { list as listRegistry } from "./registry";
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Card discovery
50
+ // ---------------------------------------------------------------------------
51
+
52
+ function cardUrl(base: string): string {
53
+ return base.replace(/\/+$/, "") + "/.well-known/agent-card.json";
54
+ }
55
+ function legacyCardUrl(base: string): string {
56
+ return base.replace(/\/+$/, "") + "/.well-known/agent.json";
57
+ }
58
+
59
+ /**
60
+ * SSRF guard — block outbound requests to private/internal IP ranges unless
61
+ * explicitly allowed. Prevents the model (or a prompt-injected instruction)
62
+ * from exfiltrating data via cloud metadata endpoints (169.254.169.254) or
63
+ * probing internal services. Loopback is allowed by default (local A2A peers
64
+ * like Hermes on the same host are common).
65
+ */
66
+ export function isPrivateHost(hostname: string): boolean {
67
+ const raw = hostname.toLowerCase().replace(/^\[|\]$/g, "");
68
+ const h = raw;
69
+ // IPv4 literals: private ranges (RFC 1918), link-local (169.254), CGNAT
70
+ // (100.64/10), and "this-network" (0/8). Loopback (127) is allowed for local peers.
71
+ if (
72
+ /^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.|169\.254\.|0\.|100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.)/.test(
73
+ h,
74
+ )
75
+ ) {
76
+ return true;
77
+ }
78
+ // IPv4-mapped IPv6 — Node canonicalizes to HEX form (::ffff:a9fe:a9fe),
79
+ // but peers may also send dotted-decimal (::ffff:169.254.169.254).
80
+ // Handle both by extracting the v4 octets and re-testing.
81
+ const v4mappedDotted = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(h);
82
+ if (v4mappedDotted) return isPrivateHost(v4mappedDotted[1]!);
83
+ const v4mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(h);
84
+ if (v4mappedHex) {
85
+ const a = parseInt(v4mappedHex[1]!, 16);
86
+ const b = parseInt(v4mappedHex[2]!, 16);
87
+ // Reconstruct dotted-decimal: a = octet1.octet2, b = octet3.octet4
88
+ const dotted = `${(a >> 8) & 0xff}.${a & 0xff}.${(b >> 8) & 0xff}.${b & 0xff}`;
89
+ return isPrivateHost(dotted);
90
+ }
91
+ // IPv6 link-local (fe80::/10), ULA (fc00::/7), unspecified (::), loopback
92
+ // beyond ::1, multicast (ff00::/8).
93
+ if (/^fe[89ab][0-9a-f]:/.test(h)) return true; // link-local
94
+ if (/^f[cd][0-9a-f]{2}:/.test(h)) return true; // ULA fc00::/7
95
+ if (/^::1?$/.test(h)) return false; // ::1 loopback allowed
96
+ if (h === "::") return true; // unspecified
97
+ if (/^ff[0-9a-f]{2}:/.test(h)) return true; // multicast
98
+ return false;
99
+ }
100
+
101
+ function assertSafeUrl(rawUrl: string): void {
102
+ let u: URL;
103
+ try {
104
+ u = new URL(rawUrl);
105
+ } catch {
106
+ throw new Error(`invalid URL: ${rawUrl}`);
107
+ }
108
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
109
+ throw new Error(`unsupported protocol: ${u.protocol} (only http/https)`);
110
+ }
111
+ // Block cloud-metadata and other private ranges (loopback excepted).
112
+ if (isPrivateHost(u.hostname)) {
113
+ throw new Error(`refused SSRF: ${u.hostname} is a private/internal host`);
114
+ }
115
+ }
116
+
117
+ /** Operator-configured gateway origins (all entries) — used to pin
118
+ * gateway-proxy peer URLs to a known gateway. */
119
+ function gatewayOrigins(cfg: A2AConfig): Set<string> {
120
+ const out = new Set<string>();
121
+ for (const { entry } of gatewayEntries(cfg)) {
122
+ try {
123
+ out.add(new URL(entry.url).origin);
124
+ } catch {
125
+ /* skip malformed */
126
+ }
127
+ }
128
+ return out;
129
+ }
130
+
131
+ /** Gateway key from a `gw/<key>/<name>` peer label, or null. */
132
+ function gatewayKeyOfPeer(agentLabel: string): string | null {
133
+ const m = /^gw\/([A-Za-z0-9._-]{1,64})\//.exec(agentLabel);
134
+ return m ? m[1]! : null;
135
+ }
136
+
137
+ /** assertSafeUrl for gateway-proxy peers: the private-range block would reject
138
+ * LAN-hosted a2a-switchboard gateways (the primary self-hosted topology). Overlay URLs
139
+ * are same-origin-pinned to an operator-configured gateway URL by
140
+ * mergeGatewayPeers, so only those origins are permitted — never anything
141
+ * else. */
142
+ function assertGatewayUrl(rawUrl: string, origins: Set<string>): void {
143
+ let u: URL;
144
+ try {
145
+ u = new URL(rawUrl);
146
+ } catch {
147
+ throw new Error(`invalid URL: ${rawUrl}`);
148
+ }
149
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
150
+ throw new Error(`unsupported protocol: ${u.protocol} (only http/https)`);
151
+ }
152
+ if (!origins.has(u.origin)) {
153
+ throw new Error(`refused SSRF: ${rawUrl} is outside the configured gateway origins`);
154
+ }
155
+ }
156
+
157
+ export async function fetchCard(
158
+ baseUrl: string,
159
+ headers: Record<string, string>,
160
+ timeoutMs: number,
161
+ /** Gateway-origin allowlist (postJsonRpc parity): when set, baseUrl must be
162
+ * one of those origins instead of passing the private-range SSRF guard —
163
+ * a LAN-hosted switchboard's /peer/<name>/ proxy URLs are private-range
164
+ * by design but operator-vouched. */
165
+ gatewayOrigins?: Set<string>,
166
+ ): Promise<AgentCard | null> {
167
+ if (gatewayOrigins) assertGatewayUrl(baseUrl, gatewayOrigins);
168
+ else assertSafeUrl(baseUrl);
169
+ const ctrl = new AbortController();
170
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
171
+ try {
172
+ let resp = await fetch(cardUrl(baseUrl), { headers, signal: ctrl.signal });
173
+ if (resp.status === 404) {
174
+ resp = await fetch(legacyCardUrl(baseUrl), { headers, signal: ctrl.signal });
175
+ }
176
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
177
+ return (await resp.json()) as AgentCard;
178
+ } finally {
179
+ clearTimeout(timer);
180
+ }
181
+ }
182
+
183
+ /** Pick the JSON-RPC dispatch URL: prefer the card's JSONRPC interface (v1.0
184
+ * supportedInterfaces), then the card's top-level url, then the base. */
185
+ export function rpcUrl(baseUrl: string, card: AgentCard | null): string {
186
+ if (card) {
187
+ const iface = (card.supportedInterfaces ?? []).find(
188
+ (i: any) => i?.protocolBinding === "JSONRPC" && i?.url,
189
+ );
190
+ if (iface?.url) return String(iface.url);
191
+ if (typeof card.url === "string" && card.url) return card.url;
192
+ }
193
+ return baseUrl.replace(/\/+$/, "");
194
+ }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // HTTP POST (JSON-RPC)
198
+ // ---------------------------------------------------------------------------
199
+
200
+ async function postJsonRpc(
201
+ url: string,
202
+ body: JsonRpcRequest,
203
+ headers: Record<string, string>,
204
+ timeoutMs: number,
205
+ gatewayOrigins?: Set<string>,
206
+ ): Promise<any> {
207
+ if (gatewayOrigins) assertGatewayUrl(url, gatewayOrigins);
208
+ else assertSafeUrl(url);
209
+ const ctrl = new AbortController();
210
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
211
+ try {
212
+ let resp: Response;
213
+ try {
214
+ resp = await fetch(url, {
215
+ method: "POST",
216
+ headers: {
217
+ "Content-Type": "application/json",
218
+ "A2A-Version": PROTOCOL_VERSION,
219
+ ...headers,
220
+ },
221
+ body: JSON.stringify(body),
222
+ signal: ctrl.signal,
223
+ });
224
+ } catch (e: any) {
225
+ if (ctrl.signal.aborted) {
226
+ throw new Error(
227
+ `reply timed out after ${timeoutMs}ms; delivery status unknown (requestId=${String(body.id)})`,
228
+ );
229
+ }
230
+ throw new Error(`connection failed — ${e?.message || String(e)}`);
231
+ }
232
+ const text = await resp.text();
233
+ let json: any;
234
+ try {
235
+ json = JSON.parse(text);
236
+ } catch {
237
+ // Don't leak internal service response bodies into model-facing errors.
238
+ throw new Error(`peer returned non-JSON (HTTP ${resp.status})`);
239
+ }
240
+ if (!resp.ok && !json.error) {
241
+ throw new Error(`HTTP ${resp.status}`);
242
+ }
243
+ return json;
244
+ } finally {
245
+ clearTimeout(timer);
246
+ }
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Reply extraction
251
+ // ---------------------------------------------------------------------------
252
+
253
+ function replyTextFromResult(result: any): string {
254
+ const payload = unwrapSendMessageResponse(result);
255
+ if (!payload || typeof payload !== "object") return String(payload ?? "");
256
+ // Artifacts first (final output), then status message, then bare message.
257
+ const artifacts = payload.artifacts;
258
+ if (Array.isArray(artifacts)) {
259
+ for (const a of artifacts) {
260
+ const t = extractText(a);
261
+ if (t) return t;
262
+ }
263
+ }
264
+ const status = payload.status ?? {};
265
+ if (status.message) {
266
+ return extractText(status.message);
267
+ }
268
+ return extractText(payload);
269
+ }
270
+
271
+ function stateFromResult(result: any): string {
272
+ const payload = unwrapSendMessageResponse(result);
273
+ if (payload && typeof payload === "object") {
274
+ return normalizeState(payload.status?.state);
275
+ }
276
+ return "";
277
+ }
278
+
279
+ function contextFromResult(result: any, fallback: string): string {
280
+ const payload = unwrapSendMessageResponse(result);
281
+ if (payload && typeof payload === "object" && payload.contextId) {
282
+ return String(payload.contextId);
283
+ }
284
+ return fallback;
285
+ }
286
+
287
+ // ---------------------------------------------------------------------------
288
+ // Metrics (module singleton — shared across calls in a session)
289
+ // ---------------------------------------------------------------------------
290
+
291
+ export class Metrics {
292
+ outboundTotal = 0;
293
+ inboundTotal = 0;
294
+ tasksCompleted = 0;
295
+ tasksFailed = 0;
296
+ streamsStarted = 0;
297
+ antiLoopTriggers = 0;
298
+ rateLimited = 0;
299
+ pushSent = 0;
300
+ private latencies: number[] = [];
301
+
302
+ recordLatency(ms: number): void {
303
+ this.latencies.push(ms);
304
+ if (this.latencies.length > 200) this.latencies.shift();
305
+ }
306
+
307
+ snapshot(): Record<string, number | string> {
308
+ const avg =
309
+ this.latencies.length > 0
310
+ ? Math.round(this.latencies.reduce((a, b) => a + b, 0) / this.latencies.length)
311
+ : 0;
312
+ return {
313
+ outbound_total: this.outboundTotal,
314
+ inbound_total: this.inboundTotal,
315
+ tasks_completed: this.tasksCompleted,
316
+ tasks_failed: this.tasksFailed,
317
+ streams_started: this.streamsStarted,
318
+ push_sent: this.pushSent,
319
+ anti_loop_triggers: this.antiLoopTriggers,
320
+ rate_limited: this.rateLimited,
321
+ avg_latency_ms: avg,
322
+ };
323
+ }
324
+
325
+ reset(): void {
326
+ this.outboundTotal = 0;
327
+ this.inboundTotal = 0;
328
+ this.tasksCompleted = 0;
329
+ this.tasksFailed = 0;
330
+ this.streamsStarted = 0;
331
+ this.antiLoopTriggers = 0;
332
+ this.rateLimited = 0;
333
+ this.pushSent = 0;
334
+ this.latencies = [];
335
+ }
336
+ }
337
+
338
+ export const metrics = new Metrics();
339
+
340
+ // ---------------------------------------------------------------------------
341
+ // Core send path
342
+ // ---------------------------------------------------------------------------
343
+
344
+ export interface SendResult {
345
+ reply: string;
346
+ contextId: string;
347
+ state: string;
348
+ /** Set when the peer returned a Task (v1.0 wire) — the caller can poll it
349
+ * with GetTask (a2a_status). Always present for non-blocking dispatches. */
350
+ taskId?: string;
351
+ }
352
+
353
+ /** Auth + asserted-identity headers for an outbound request to a peer.
354
+ * X-A2A-Identity (selfIdentity, falling back to server.agentName) names the
355
+ * caller for the RECEIVING side's audit log / attribution — behind a reverse
356
+ * proxy every caller arrives from the proxy's address, so address-based
357
+ * attribution cannot tell agents apart. Advisory display provenance only,
358
+ * never authentication: any client can assert any name, so a receiver must
359
+ * only use it to refine the display of a caller it has ALREADY admitted.
360
+ * Omitted when no identity is configured. Shared by EVERY outbound request
361
+ * (SendMessage dispatches AND the GetTask polls of a2a_status) so the
362
+ * receiver sees the same caller on dispatch and on every later poll. */
363
+ function peerRequestHeaders(cfg: A2AConfig, peer: Peer): Record<string, string> {
364
+ const headers = authHeaders(peer);
365
+ const self = cfg.selfIdentity || cfg.server.agentName;
366
+ if (self) headers["X-A2A-Identity"] = self;
367
+ return headers;
368
+ }
369
+
370
+ async function sendTask(opts: {
371
+ cfg: A2AConfig;
372
+ piDir: string;
373
+ peer: Peer;
374
+ agentLabel: string;
375
+ message: string;
376
+ contextId?: string;
377
+ /** Non-blocking dispatch (A2A v1.0 §3.2.2 returnImmediately): the peer
378
+ * acks with an in-progress Task and runs the work detached from this
379
+ * call — the reply arrives later via GetTask (a2a_status). */
380
+ asyncDispatch?: boolean;
381
+ /** Sender's pi session id — stamped on the outbound message metadata
382
+ * ("pi/session") so the receiving peer can join this dispatch to its own
383
+ * ledger rows and records (fleet task #238). */
384
+ sessionId?: string;
385
+ }): Promise<SendResult> {
386
+ const { cfg, piDir, peer, agentLabel, message } = opts;
387
+ const headers = peerRequestHeaders(cfg, peer);
388
+ // Advisory caller attribution for the gateway's routing log/dashboard.
389
+ // Self-declared display name — stripped by the gateway before forwarding.
390
+ if (peer.viaGateway) {
391
+ // Prefer the operator-pinned identity; fall back to the runtime-resolved
392
+ // registration name of the gateway this peer came from (set by the
393
+ // server's upstream at start) or the base agent name so the dashboard
394
+ // shows a real caller name, not a fingerprint. The registration name is
395
+ // session-scoped and never persisted.
396
+ const key = gatewayKeyOfPeer(agentLabel);
397
+ // Manually-configured gateway peers (viaGateway without a `gw/<key>/`
398
+ // label) fall back to the SINGLE configured gateway's registration name
399
+ // (when exactly one gateway is configured) — otherwise there's no
400
+ // unambiguous gateway to attribute to.
401
+ let gwName: string | null = null;
402
+ if (key) {
403
+ gwName = getGatewayCallerName(key);
404
+ } else {
405
+ const entries = gatewayEntries(cfg);
406
+ if (entries.length === 1) gwName = getGatewayCallerName(entries[0]!.key);
407
+ else gwName = getGatewayRegistrationName();
408
+ }
409
+ const caller =
410
+ cfg.selfIdentity || gwName || cfg.server.agentName || "";
411
+ if (caller) headers["X-Gateway-Caller"] = caller;
412
+ }
413
+ const timeout = peer.timeout || cfg.timeouts.send;
414
+
415
+ // Best-effort card fetch (to learn the rpc URL); non-fatal on failure.
416
+ // Gateway peers are exempt: a proxied card advertises the peer's DIRECT
417
+ // url, which would bypass the gateway — pin the RPC to the proxy URL.
418
+ let card: AgentCard | null = null;
419
+ if (!peer.viaGateway) {
420
+ try {
421
+ card = await fetchCard(peer.url, headers, Math.min(timeout, 30000));
422
+ } catch {
423
+ /* tolerate */
424
+ }
425
+ }
426
+
427
+ const ctx = opts.contextId || newContextId();
428
+ const safe = redactOutbound(message);
429
+ const outbound = textMessage(ROLE_USER, safe, ctx);
430
+ // Sender attribution (A2A v1.0 permits metadata on Message). "pi/session"
431
+ // is the pi session id; "pi/self" the configured identity. Both are
432
+ // advisory display/join data — receiving peers must not authenticate on
433
+ // them.
434
+ const senderMeta: Record<string, unknown> = {};
435
+ if (opts.sessionId) senderMeta["pi/session"] = opts.sessionId;
436
+ if (cfg.selfIdentity) senderMeta["pi/self"] = cfg.selfIdentity;
437
+ if (Object.keys(senderMeta).length > 0) outbound.metadata = senderMeta;
438
+ const rpcBody: JsonRpcRequest = {
439
+ jsonrpc: "2.0",
440
+ id: newTaskId(),
441
+ method: "SendMessage",
442
+ params: {
443
+ message: outbound,
444
+ ...(opts.asyncDispatch ? { configuration: { returnImmediately: true } } : {}),
445
+ },
446
+ };
447
+
448
+ audit({ piDir, direction: "outbound", identity: agentLabel, taskId: String(rpcBody.id), text: safe });
449
+ metrics.outboundTotal += 1;
450
+
451
+ const started = Date.now();
452
+ // SSRF pin: prefer the peer's own publishing gateway origin (overlay-first
453
+ // routing works even when the live config has no gateway block); fall back
454
+ // to the configured gateway origins; an empty set means the peer is not
455
+ // gateway-pinned → normal assertSafeUrl applies.
456
+ let gwOrigins: Set<string> | undefined;
457
+ if (peer.viaGateway) {
458
+ if (peer.gatewayUrl) {
459
+ try {
460
+ gwOrigins = new Set([new URL(peer.gatewayUrl).origin]);
461
+ } catch {
462
+ gwOrigins = undefined;
463
+ }
464
+ } else {
465
+ const origins = gatewayOrigins(cfg);
466
+ // Empty set = no gateway configured → normal assertSafeUrl applies.
467
+ gwOrigins = origins.size > 0 ? origins : undefined;
468
+ }
469
+ }
470
+ // RPC target: gateway peers ALWAYS post to their proxy URL — a proxied card
471
+ // advertises the peer's DIRECT url, which would bypass the gateway (and is
472
+ // private-range, so the SSRF pin refuses it). Only non-gateway peers use the
473
+ // card-derived rpcUrl.
474
+ const rpcTarget = peer.viaGateway ? peer.url.replace(/\/+$/, "") : rpcUrl(peer.url, card);
475
+ const resp = await postJsonRpc(rpcTarget, rpcBody, headers, timeout, gwOrigins);
476
+ metrics.recordLatency(Date.now() - started);
477
+ if (resp.error) {
478
+ const msg = resp.error.message || JSON.stringify(resp.error);
479
+ throw new Error(`peer '${agentLabel}' returned an error: ${msg}`);
480
+ }
481
+ const result = resp.result ?? {};
482
+ const payload = unwrapSendMessageResponse(result);
483
+ const taskId = payload && typeof payload === "object" && payload.id ? String(payload.id) : undefined;
484
+ const reply = replyTextFromResult(result);
485
+ const replyCtx = contextFromResult(result, ctx);
486
+ const state = stateFromResult(result);
487
+ // Persist BOTH the user message and the agent reply under the SAME contextId
488
+ // (replyCtx) so a2a_history returns the complete conversation, not half.
489
+ // For a non-blocking dispatch the "reply" side is an ack marker — the real
490
+ // reply arrives later via GetTask (a2a_status).
491
+ const agentText =
492
+ opts.asyncDispatch && taskId && !reply
493
+ ? `(dispatched non-blocking — task ${taskId} is running on the peer; poll with a2a_status)`
494
+ : reply;
495
+ persistMessage({ piDir, contextId: replyCtx, role: "user", text: safe, taskId: String(rpcBody.id), peer: agentLabel });
496
+ persistMessage({ piDir, contextId: replyCtx, role: "agent", text: agentText, taskId: String(rpcBody.id), peer: agentLabel });
497
+ metrics.inboundTotal += 1;
498
+ if (state === "TASK_STATE_COMPLETED") metrics.tasksCompleted += 1;
499
+ if (state === "TASK_STATE_FAILED") metrics.tasksFailed += 1;
500
+ return { reply, contextId: replyCtx, state, taskId };
501
+ }
502
+
503
+ // ---------------------------------------------------------------------------
504
+ // Tool handlers (return formatted text for the model)
505
+ // ---------------------------------------------------------------------------
506
+
507
+ function shortState(state: string): string {
508
+ return state ? state.replace("TASK_STATE_", "").replace(/_/g, "-").toLowerCase() : "";
509
+ }
510
+
511
+ export async function a2aDiscover(opts: {
512
+ cfg: A2AConfig;
513
+ url: string;
514
+ }): Promise<string> {
515
+ const url = (opts.url || "").trim();
516
+ if (!url) return "Error: 'url' is required (e.g. http://localhost:9900).";
517
+ // A URL on a configured gateway's origin (its /peer/<name>/ proxy form) is
518
+ // operator-vouched: allowlist it past the private-range guard, and present
519
+ // that gateway's token — the proxy rejects an anonymous card fetch with 401.
520
+ let gwAllow: Set<string> | undefined;
521
+ let gwHeaders: Record<string, string> = {};
522
+ try {
523
+ const origin = new URL(url).origin;
524
+ const entry = gatewayEntries(opts.cfg).find((e) => {
525
+ try {
526
+ return new URL(e.entry.url).origin === origin;
527
+ } catch {
528
+ return false;
529
+ }
530
+ });
531
+ if (entry) {
532
+ gwAllow = new Set([origin]);
533
+ if (entry.entry.token) gwHeaders = { authorization: `Bearer ${entry.entry.token}` };
534
+ }
535
+ } catch {
536
+ /* invalid URL — fetchCard reports it */
537
+ }
538
+ let card: AgentCard | null;
539
+ try {
540
+ card = await fetchCard(url, gwHeaders, opts.cfg.timeouts.send, gwAllow);
541
+ } catch (e: any) {
542
+ const msg = e?.message || String(e);
543
+ if (/HTTP 404/.test(msg)) return `Error: discovery failed — no Agent Card at ${url}.`;
544
+ if (/HTTP 401|HTTP 403/.test(msg))
545
+ return `Error: ${url} rejected auth (${msg}) — a gateway proxy URL needs the gateway token set in a2a.discovery.gateways.`;
546
+ return `Error: could not reach ${url} — ${msg}`;
547
+ }
548
+ if (!card) return `Error: discovery failed — no Agent Card at ${url}.`;
549
+ const caps = (card as any).capabilities || {};
550
+ const skills = card.skills || [];
551
+ const auth = (card as any).security ? "yes" : "no";
552
+ const ifaces = (card.supportedInterfaces ?? []) as any[];
553
+ const proto =
554
+ ifaces
555
+ .filter((i) => i && typeof i === "object")
556
+ .map((i) => `${i.protocolBinding ?? "?"} v${i.protocolVersion ?? "?"}`)
557
+ .join(", ") || `v${(card as any).protocolVersion ?? "?"} (pre-1.0 card)`;
558
+ const lines = [
559
+ `Agent: ${card.name || "?"}`,
560
+ `Description: ${(card as any).description ?? ""}`,
561
+ `URL: ${rpcUrl(url, card)}`,
562
+ `Protocol: ${proto}`,
563
+ `Streaming: ${!!caps.streaming} Push: ${!!caps.pushNotifications} Auth required: ${auth}`,
564
+ `Skills (${skills.length}):`,
565
+ ];
566
+ for (const s of skills.slice(0, 20)) {
567
+ lines.push(` - ${s.name || s.id}: ${s.description ?? ""}`);
568
+ }
569
+ // Full session-metadata tool list from the pi-session extension (matches
570
+ // the card's metadata.tools — never truncated).
571
+ const meta = (card as any).metadata ?? {};
572
+ const tools = Array.isArray(meta.tools) ? meta.tools.map(String) : [];
573
+ if (tools.length) {
574
+ lines.push(`Tools (${tools.length}):`);
575
+ for (let i = 0; i < tools.length; i += 10) {
576
+ lines.push(` ${tools.slice(i, i + 10).join(", ")}`);
577
+ }
578
+ }
579
+ return lines.join("\n");
580
+ }
581
+
582
+ /** Resolve an agent label (configured name, URL, or discovered name) to a
583
+ * peer for an outbound call. Returns an error string instead of a peer when
584
+ * the label cannot be resolved. Shared by a2a_call and a2a_status. */
585
+ function resolveCallPeer(opts: {
586
+ cfg: A2AConfig;
587
+ piDir: string;
588
+ agent: string;
589
+ /** Live discovered peers (listPeers output) — lets local/mDNS peers be called by name. */
590
+ discoveredPeers?: DiscoveredPeer[];
591
+ }): { peer: Peer } | { error: string } {
592
+ const agent = opts.agent;
593
+ const known = knownLoopbackUrls(opts.cfg, opts.piDir);
594
+ let peer = resolvePeer(opts.cfg, agent, { knownLoopbackUrls: known });
595
+ if (!peer || !peer.url) {
596
+ // Discovered-peer name lookup (local registry / mDNS). Ambiguous names
597
+ // error with the candidate URLs instead of guessing a target.
598
+ const matches = (opts.discoveredPeers ?? []).filter((d) => d.name === agent && d.url);
599
+ if (matches.length > 1) {
600
+ return {
601
+ error:
602
+ `Error: ${matches.length} discovered peers share the name '${agent}' — ` +
603
+ `call by URL: ${matches.map((m) => m.url).join(", ")}`,
604
+ };
605
+ }
606
+ if (matches.length === 1) {
607
+ // ponytail: re-resolve via the URL branch so loopback-token/SSRF policy is inherited verbatim
608
+ peer = resolvePeer(opts.cfg, matches[0]!.url, { knownLoopbackUrls: known });
609
+ }
610
+ }
611
+ if (!peer || !peer.url) {
612
+ return {
613
+ error:
614
+ `Error: unknown agent '${agent}'. Configure it under 'a2a.peers' in ` +
615
+ `settings.json, pass a full http(s):// URL, or use a name from a2a_peers.`,
616
+ };
617
+ }
618
+ return { peer };
619
+ }
620
+
621
+ export async function a2aCall(opts: {
622
+ cfg: A2AConfig;
623
+ piDir: string;
624
+ agent: string;
625
+ message: string;
626
+ contextId?: string;
627
+ sessionId?: string;
628
+ /** Live discovered peers (listPeers output) — lets local/mDNS peers be called by name. */
629
+ discoveredPeers?: DiscoveredPeer[];
630
+ /** Non-blocking dispatch (A2A v1.0 §3.2.2 returnImmediately): return an
631
+ * ack with the task id as soon as the peer accepts the task, instead of
632
+ * holding this call open until the work finishes. Long jobs keep running
633
+ * on the peer no matter how long the caller waits — poll a2a_status. */
634
+ asyncDispatch?: boolean;
635
+ }): Promise<string> {
636
+ const agent = (opts.agent || "").trim();
637
+ const message = (opts.message || "").trim();
638
+ if (!agent || !message) return "Error: both 'agent' and 'message' are required.";
639
+ const resolved = resolveCallPeer({
640
+ cfg: opts.cfg,
641
+ piDir: opts.piDir,
642
+ agent,
643
+ discoveredPeers: opts.discoveredPeers,
644
+ });
645
+ if ("error" in resolved) return resolved.error;
646
+ const peer = resolved.peer;
647
+ let result: SendResult;
648
+ try {
649
+ result = await sendTask({
650
+ cfg: opts.cfg,
651
+ piDir: opts.piDir,
652
+ peer,
653
+ agentLabel: agent,
654
+ message,
655
+ contextId: opts.contextId,
656
+ asyncDispatch: opts.asyncDispatch,
657
+ sessionId: opts.sessionId,
658
+ });
659
+ } catch (e: any) {
660
+ const msg = e?.message || String(e);
661
+ if (/HTTP 401|HTTP 403/.test(msg)) return `Error: peer '${agent}' rejected auth. Check the configured token.`;
662
+ if (/HTTP 429/.test(msg)) return `Error: peer '${agent}' rate limited us (HTTP 429). Retry later.`;
663
+ return `Error: call to '${agent}' failed — ${msg}`;
664
+ }
665
+ // Non-blocking ack: the peer accepted the task and is running it detached
666
+ // from this call. (A peer that does not support returnImmediately simply
667
+ // blocks and returns a terminal task — fall through to normal formatting.)
668
+ if (opts.asyncDispatch && result.taskId && !TERMINAL_STATES.has(result.state)) {
669
+ return (
670
+ `[A2A → ${agent} · context ${result.contextId} · ${shortState(result.state)} · detached]\n` +
671
+ `Dispatch accepted — task ${result.taskId} is running on the peer (non-blocking). ` +
672
+ `This call has already returned; the peer keeps working regardless of how long it takes. ` +
673
+ `Poll the result with a2a_status(agent: "${agent}", task_id: "${result.taskId}").`
674
+ );
675
+ }
676
+ let header = `[A2A → ${agent} · context ${result.contextId}`;
677
+ if (result.state) header += ` · ${shortState(result.state)}`;
678
+ header += "]";
679
+ let body = result.reply || "(no text reply)";
680
+ if (result.state === STATE_INPUT_REQUIRED) {
681
+ body +=
682
+ `\n\n(The peer needs more input — answer by calling a2a_call again ` +
683
+ `with context_id '${result.contextId}'.)`;
684
+ }
685
+ return `${header}\n${body}`;
686
+ }
687
+
688
+ // ---------------------------------------------------------------------------
689
+ // Task status / polling (GetTask)
690
+ // ---------------------------------------------------------------------------
691
+
692
+ /** sleep that also resolves when `signal` aborts, so poll waits do not hold
693
+ * a canceled tool call open — a2a_status with wait_seconds=300 must stay
694
+ * interruptible. */
695
+ function sleepAbortable(ms: number, signal?: AbortSignal): Promise<void> {
696
+ return new Promise((resolve) => {
697
+ const t = setTimeout(done, ms);
698
+ function done(): void {
699
+ clearTimeout(t);
700
+ signal?.removeEventListener("abort", done);
701
+ resolve();
702
+ }
703
+ if (signal) {
704
+ if (signal.aborted) return done();
705
+ signal.addEventListener("abort", done, { once: true });
706
+ }
707
+ });
708
+ }
709
+
710
+ /** Fetch one task's current state from a peer via GetTask (A2A v1.0). The
711
+ * peer's per-identity task ownership applies: only the caller that created
712
+ * the task can read it. */
713
+ export async function getTask(opts: {
714
+ cfg: A2AConfig;
715
+ peer: Peer;
716
+ taskId: string;
717
+ }): Promise<Task> {
718
+ const headers = peerRequestHeaders(opts.cfg, opts.peer);
719
+ const timeout = opts.peer.timeout || opts.cfg.timeouts.send;
720
+ const gwOrigins = opts.peer.viaGateway
721
+ ? (opts.peer.gatewayUrl
722
+ ? new Set([new URL(opts.peer.gatewayUrl).origin])
723
+ : (() => { const o = gatewayOrigins(opts.cfg); return o.size > 0 ? o : undefined; })())
724
+ : undefined;
725
+ // Best-effort card fetch (to learn the rpc URL); non-fatal on failure.
726
+ // Gateway peers are exempt (proxied card advertises the peer's DIRECT url)
727
+ // and pinned to peer.url below — the same rule sendTask applies.
728
+ let card: AgentCard | null = null;
729
+ if (!opts.peer.viaGateway) {
730
+ try {
731
+ card = await fetchCard(opts.peer.url, headers, Math.min(timeout, 30000));
732
+ } catch {
733
+ /* tolerate */
734
+ }
735
+ }
736
+ const rpcBody: JsonRpcRequest = {
737
+ jsonrpc: "2.0",
738
+ id: newTaskId(),
739
+ method: "GetTask",
740
+ params: { id: opts.taskId },
741
+ };
742
+ const rpcTarget = opts.peer.viaGateway ? opts.peer.url.replace(/\/+$/, "") : rpcUrl(opts.peer.url, card);
743
+ const resp = await postJsonRpc(rpcTarget, rpcBody, headers, timeout, gwOrigins);
744
+ if (resp.error) {
745
+ const err = new Error(`peer returned an error: ${resp.error.message || JSON.stringify(resp.error)}`);
746
+ (err as any).code = resp.error.code;
747
+ throw err;
748
+ }
749
+ return unwrapSendMessageResponse(resp.result ?? {}) as Task;
750
+ }
751
+
752
+ function formatTask(task: Task): string {
753
+ const header = `[task ${task.id} · context ${task.contextId} · ${shortState(task.status?.state ?? "")}` +
754
+ (task.status?.timestamp ? ` · ${task.status.timestamp}` : "") + "]";
755
+ // Artifacts first (final output), then status message — same precedence as
756
+ // replyTextFromResult.
757
+ let body = "";
758
+ if (Array.isArray(task.artifacts)) {
759
+ for (const a of task.artifacts) {
760
+ const t = extractText(a);
761
+ if (t) { body = t; break; }
762
+ }
763
+ }
764
+ if (!body && task.status?.message) body = extractText(task.status.message);
765
+ if (!body) body = "(no text yet — task is in progress)";
766
+ return `${header}\n${body}`;
767
+ }
768
+
769
+ export async function a2aStatus(opts: {
770
+ cfg: A2AConfig;
771
+ piDir: string;
772
+ agent: string;
773
+ taskId: string;
774
+ /** When POSITIVE (seconds), poll until the task reaches a terminal state
775
+ * or the deadline — polls at cfg.timeouts.async intervals (the documented
776
+ * "async task poll interval"). 0, negative, or undefined = a single
777
+ * fetch. */
778
+ waitSeconds?: number;
779
+ discoveredPeers?: DiscoveredPeer[];
780
+ /** Aborts the polling loop promptly (tool cancel): checked before each
781
+ * fetch, raced into the poll sleep, and re-checked after it — a canceled
782
+ * a2a_status with wait_seconds=300 must not hold the tool call open.
783
+ * Aborting does NOT affect the task on the peer; it keeps running. */
784
+ signal?: AbortSignal;
785
+ }): Promise<string> {
786
+ const agent = (opts.agent || "").trim();
787
+ const taskId = (opts.taskId || "").trim();
788
+ if (!agent || !taskId) return "Error: both 'agent' and 'task_id' are required.";
789
+ const resolved = resolveCallPeer({
790
+ cfg: opts.cfg,
791
+ piDir: opts.piDir,
792
+ agent,
793
+ discoveredPeers: opts.discoveredPeers,
794
+ });
795
+ if ("error" in resolved) return resolved.error;
796
+ const peer = resolved.peer;
797
+ // Non-positive wait_seconds is treated as "unset" — a single fetch. A
798
+ // negative value would otherwise poll once, immediately expire, and print
799
+ // nonsense like "after -5s of polling".
800
+ const waitSeconds = typeof opts.waitSeconds === "number" && opts.waitSeconds > 0 ? opts.waitSeconds : undefined;
801
+ const deadline = waitSeconds !== undefined ? Date.now() + waitSeconds * 1000 : 0;
802
+ const interval = Math.max(250, opts.cfg.timeouts.async);
803
+ let lastTask: Task | null = null;
804
+ for (;;) {
805
+ if (opts.signal?.aborted) return statusCanceled(agent, taskId, lastTask);
806
+ let task: Task;
807
+ try {
808
+ task = await getTask({ cfg: opts.cfg, peer, taskId });
809
+ } catch (e: any) {
810
+ if ((e as any).code === -32001) {
811
+ return `Error: peer '${agent}' does not know task '${taskId}' (unknown id, already evicted, or created by a different caller — tasks are visible only to the identity that sent them).`;
812
+ }
813
+ const msg = e?.message || String(e);
814
+ if (/HTTP 401|HTTP 403/.test(msg)) return `Error: peer '${agent}' rejected auth. Check the configured token.`;
815
+ return `Error: status check for '${agent}' task '${taskId}' failed — ${msg}`;
816
+ }
817
+ lastTask = task;
818
+ const state = normalizeState(task.status?.state);
819
+ if (TERMINAL_STATES.has(state) || waitSeconds === undefined) {
820
+ return formatTask(task);
821
+ }
822
+ if (Date.now() >= deadline) {
823
+ return (
824
+ formatTask(task) +
825
+ `\n\n(Still non-terminal after ${waitSeconds}s of polling — the task keeps running on the peer; call a2a_status again later.)`
826
+ );
827
+ }
828
+ await sleepAbortable(Math.min(interval, Math.max(0, deadline - Date.now())), opts.signal);
829
+ }
830
+ }
831
+
832
+ /** a2a_status's abort message: report the last-known state (the task itself
833
+ * is untouched — aborting a poll never touches the peer's run) and how to
834
+ * pick the poll back up. */
835
+ function statusCanceled(agent: string, taskId: string, lastTask: Task | null): string {
836
+ const body = lastTask ? formatTask(lastTask) : `task ${taskId}: status not yet fetched.`;
837
+ return (
838
+ body +
839
+ `\n\n(Status polling canceled — the task keeps running on the peer regardless; call a2a_status(agent: "${agent}", task_id: "${taskId}") again later.)`
840
+ );
841
+ }
842
+
843
+ /** Build the set of loopback URLs that are KNOWN peers (same-machine, same-user):
844
+ * configured peers + live local-registry entries. mDNS peers are excluded —
845
+ * their URLs come from the network and must not receive the shared token. */
846
+ function knownLoopbackUrls(cfg: A2AConfig, piDir: string): Set<string> {
847
+ const known = new Set<string>();
848
+ for (const p of Object.values(cfg.peers)) {
849
+ if (p.url) known.add(normUrl(p.url));
850
+ }
851
+ try {
852
+ for (const d of listRegistry({ piDir, ttlSec: cfg.discovery.local.ttlSec })) {
853
+ if (d.url) known.add(normUrl(d.url));
854
+ }
855
+ } catch {
856
+ /* registry read is best-effort */
857
+ }
858
+ return known;
859
+ }
860
+
861
+ export function a2aList(opts: {
862
+ cfg: A2AConfig;
863
+ piDir: string;
864
+ /** Pre-merged discovered peers (local registry + mDNS). When provided, an
865
+ * extra "Discovered peers" section is appended. */
866
+ discoveredPeers?: Array<{
867
+ name: string;
868
+ url: string;
869
+ source: string;
870
+ cwd?: string;
871
+ model?: { provider: string; id: string; name?: string } | null;
872
+ tools?: string[];
873
+ }>;
874
+ }): string {
875
+ const { cfg, piDir } = opts;
876
+ const peers = cfg.peers;
877
+ const lines: string[] = [];
878
+ const names = Object.keys(peers);
879
+ if (names.length > 0) {
880
+ lines.push(`Configured peers (${names.length}):`);
881
+ for (const name of names) {
882
+ const p = peers[name]!;
883
+ const capStr = p.capabilities.length ? ` caps: ${p.capabilities.join(", ")}` : "";
884
+ lines.push(` - ${name}: ${p.url} (auth: ${p.auth.type})${capStr}`);
885
+ }
886
+ } else {
887
+ lines.push("No peers configured. Add them under 'a2a.peers' in settings.json.");
888
+ }
889
+
890
+ // Gateway overlay (read-only, in-memory — refreshed after each gateway
891
+ // heartbeat; never written to settings.json).
892
+ const gateway = Object.entries(getGatewayPeers());
893
+ if (gateway.length > 0) {
894
+ lines.push("");
895
+ lines.push(`Gateway peers (${gateway.length}) — call by name, routed via the a2a-switchboard proxy:`);
896
+ for (const [name, p] of gateway) {
897
+ const capStr = p.capabilities.length ? ` caps: ${p.capabilities.join(", ")}` : "";
898
+ lines.push(` - ${name}: ${p.url} (auth: ${p.auth.type})${capStr}`);
899
+ }
900
+ }
901
+
902
+ // Discovered peers (0.2.0) — exclude any already listed above (by URL):
903
+ // configured peers AND gateway proxy entries (same underlying agent would
904
+ // otherwise appear twice — once as gw/remote/x, once as a local discovery).
905
+
906
+ const listedUrls = new Set([
907
+ ...names.map((n) => peers[n]!.url.replace(/\/+$/, "").toLowerCase()),
908
+ ...gateway.map(([, p]) => p.url.replace(/\/+$/, "").toLowerCase()),
909
+ ]);
910
+ const discovered = (opts.discoveredPeers ?? []).filter(
911
+ (p) => !listedUrls.has(p.url.replace(/\/+$/, "").toLowerCase()),
912
+ );
913
+ if (discovered.length > 0) {
914
+ lines.push("");
915
+ lines.push(`Discovered peers (${discovered.length}):`);
916
+ for (const p of discovered) {
917
+ const parts = [` - ${clean(p.name)}`, clean(p.url), `[${p.source}]`];
918
+ if (p.cwd) parts.push(`cwd=${clean(p.cwd)}`);
919
+ if (p.model) parts.push(`model=${clean(p.model.provider)}/${clean(p.model.id)}`);
920
+ if (p.tools && p.tools.length) {
921
+ const shown = p.tools.slice(0, 20).map(clean).join(",");
922
+ parts.push(`tools=${shown}${p.tools.length > 20 ? ` (+${p.tools.length - 20} more)` : ""}`);
923
+ }
924
+ lines.push(parts.join(" "));
925
+ }
926
+ }
927
+
928
+ const convos = listConversations(piDir);
929
+ if (convos.length > 0) {
930
+ lines.push("");
931
+ lines.push(`Persisted conversations (${convos.length}) — recall with a2a_history:`);
932
+ for (const c of convos.slice(0, 25)) lines.push(` - ${c}`);
933
+ }
934
+ const m = metrics.snapshot();
935
+ lines.push("");
936
+ lines.push(
937
+ `Metrics: ${m.outbound_total} out / ${m.inbound_total} in, ` +
938
+ `${m.tasks_completed} completed, ${m.tasks_failed} failed, ` +
939
+ `avg ${m.avg_latency_ms}ms`,
940
+ );
941
+ return lines.join("\n");
942
+ }
943
+
944
+ export function a2aHistory(opts: { piDir: string; contextId: string; limit?: number }): string {
945
+ const ctx = (opts.contextId || "").trim();
946
+ if (!ctx) return "Error: 'context_id' is required (see a2a_list for known conversations).";
947
+ const limit = Math.max(1, Math.min(opts.limit ?? 50, 200));
948
+ const msgs = loadConversation(opts.piDir, ctx, limit);
949
+ if (msgs.length === 0) return `No persisted conversation for context '${ctx}'.`;
950
+ const lines = [`Conversation ${ctx} (last ${msgs.length} messages):`];
951
+ for (const m of msgs) {
952
+ const role = m.role === "agent" ? "AGENT" : "USER";
953
+ const t = (m.text || "").trim().slice(0, 1000);
954
+ lines.push(`[${role}] ${t}`);
955
+ }
956
+ return lines.join("\n");
957
+ }
958
+
959
+ // ---------------------------------------------------------------------------
960
+ // Orchestration: fan-out one task to every peer advertising a capability
961
+ // ---------------------------------------------------------------------------
962
+
963
+ function peerHasCapability(peer: Peer, capability: string): boolean {
964
+ if (!peer.capabilities || peer.capabilities.length === 0) return false;
965
+ const lc = capability.toLowerCase();
966
+ return peer.capabilities.some((c) => c.toLowerCase() === lc);
967
+ }
968
+
969
+ const ORCHESTRATE_CONCURRENCY = 6;
970
+
971
+ async function mapWithConcurrency<T, R>(
972
+ items: T[],
973
+ limit: number,
974
+ fn: (item: T, index: number) => Promise<R>,
975
+ ): Promise<R[]> {
976
+ const results: R[] = new Array(items.length);
977
+ let cursor = 0;
978
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
979
+ while (true) {
980
+ const i = cursor++;
981
+ if (i >= items.length) break;
982
+ results[i] = await fn(items[i]!, i);
983
+ }
984
+ });
985
+ await Promise.all(workers);
986
+ return results;
987
+ }
988
+
989
+ export async function a2aOrchestrate(opts: {
990
+ cfg: A2AConfig;
991
+ piDir: string;
992
+ capability: string;
993
+ message: string;
994
+ mode?: "all" | "first" | "best";
995
+ sessionId?: string;
996
+ }): Promise<string> {
997
+ const mode = opts.mode || "all";
998
+ // Configured peers + gateway overlay (read-only). Dedupe: a configured peer
999
+ // wins over its gateway alias — by URL or by the gateway key's underlying
1000
+ // name (`gw/<key>/<name>` → `<name>`) — same precedence as resolvePeer.
1001
+ const configuredUrls = new Set(Object.values(opts.cfg.peers).map((p) => normUrl(p!.url)));
1002
+ const configuredNames = new Set(Object.keys(opts.cfg.peers));
1003
+ const gwUnderlying = (k: string) => k.split("/").pop() ?? k;
1004
+ const pool: Array<[string, Peer]> = [
1005
+ ...Object.entries(getGatewayPeers()).filter(
1006
+ ([k, p]) => !configuredUrls.has(normUrl(p.url)) && !configuredNames.has(gwUnderlying(k)),
1007
+ ),
1008
+ ...Object.entries(opts.cfg.peers),
1009
+ ];
1010
+ const matching = pool.filter(([, p]) => peerHasCapability(p, opts.capability));
1011
+ if (matching.length === 0) {
1012
+ return `No peers advertise capability '${opts.capability}'.`;
1013
+ }
1014
+ const entries = matching.map(([name, peer]) => ({ name, peer }));
1015
+
1016
+ const outcomes = await mapWithConcurrency(entries, ORCHESTRATE_CONCURRENCY, async ({ name, peer }) => {
1017
+ try {
1018
+ const r = await sendTask({
1019
+ cfg: opts.cfg,
1020
+ piDir: opts.piDir,
1021
+ peer,
1022
+ agentLabel: name,
1023
+ message: opts.message,
1024
+ sessionId: opts.sessionId,
1025
+ });
1026
+ return { name, ok: true as const, reply: r.reply, ctx: r.contextId, state: r.state };
1027
+ } catch (e: any) {
1028
+ return { name, ok: false as const, error: e?.message || String(e) };
1029
+ }
1030
+ });
1031
+
1032
+ const ok = outcomes.filter((o) => o.ok);
1033
+ const bad = outcomes.filter((o) => !o.ok);
1034
+
1035
+ if (mode === "first") {
1036
+ const f = ok[0];
1037
+ if (f) return `[${f.name} · context ${f.ctx}]\n${f.reply || "(no reply)"}`;
1038
+ }
1039
+ if (mode === "best") {
1040
+ // Longest successful reply; errors never win. All-error → report failures.
1041
+ if (ok.length > 0) {
1042
+ const best = ok.slice().sort((a, b) => (b.reply?.length ?? 0) - (a.reply?.length ?? 0))[0]!;
1043
+ return `[${best.name} · context ${best.ctx}]\n${best.reply || "(no reply)"}`;
1044
+ }
1045
+ }
1046
+ // mode === "all" (or best with no successes)
1047
+ const lines: string[] = [];
1048
+ if (ok.length > 0) {
1049
+ lines.push(`Replies from ${ok.length}/${outcomes.length} peer(s) for '${opts.capability}':`);
1050
+ for (const o of ok) {
1051
+ lines.push(`\n── ${o.name} (context ${o.ctx}${o.state ? ` · ${shortState(o.state)}` : ""}) ──`);
1052
+ lines.push(o.reply || "(no reply)");
1053
+ }
1054
+ }
1055
+ if (bad.length > 0) {
1056
+ if (lines.length === 0) lines.push(`All ${bad.length} peer(s) failed for '${opts.capability}':`);
1057
+ else lines.push(`\nFailures (${bad.length}):`);
1058
+ for (const o of bad) lines.push(` - ${o.name}: ${o.error}`);
1059
+ }
1060
+ return lines.join("\n");
1061
+ }