ceulen 0.8.0 → 0.10.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 (122) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/extensions/lib/registry.ts +16 -3
  3. package/extensions/modules/a2a/configPanel.ts +435 -0
  4. package/extensions/modules/a2a/index.ts +1117 -0
  5. package/extensions/modules/a2a/lib/activity.ts +173 -0
  6. package/extensions/modules/a2a/lib/client.ts +1061 -0
  7. package/extensions/modules/a2a/lib/config.ts +920 -0
  8. package/extensions/modules/a2a/lib/discovery.ts +158 -0
  9. package/extensions/modules/a2a/lib/gateway.ts +889 -0
  10. package/extensions/modules/a2a/lib/mdns.ts +233 -0
  11. package/extensions/modules/a2a/lib/outcome.ts +48 -0
  12. package/extensions/modules/a2a/lib/persistence.ts +123 -0
  13. package/extensions/modules/a2a/lib/protocol.ts +506 -0
  14. package/extensions/modules/a2a/lib/registry.ts +146 -0
  15. package/extensions/modules/a2a/lib/retry.ts +86 -0
  16. package/extensions/modules/a2a/lib/security.ts +394 -0
  17. package/extensions/modules/a2a/lib/server.ts +1436 -0
  18. package/extensions/modules/a2a/test/activity.test.ts +138 -0
  19. package/extensions/modules/a2a/test/bridge.test.ts +101 -0
  20. package/extensions/modules/a2a/test/broadcast-parse.test.ts +31 -0
  21. package/extensions/modules/a2a/test/chai.ts +101 -0
  22. package/extensions/modules/a2a/test/client.test.ts +856 -0
  23. package/extensions/modules/a2a/test/completion-guard.test.ts +73 -0
  24. package/extensions/modules/a2a/test/config.test.ts +1396 -0
  25. package/extensions/modules/a2a/test/configPanel.test.ts +393 -0
  26. package/extensions/modules/a2a/test/discovery.test.ts +144 -0
  27. package/extensions/modules/a2a/test/extension.test.ts +135 -0
  28. package/extensions/modules/a2a/test/gateway.test.ts +1449 -0
  29. package/extensions/modules/a2a/test/helpers.ts +39 -0
  30. package/extensions/modules/a2a/test/mdns.test.ts +131 -0
  31. package/extensions/modules/a2a/test/outcome.test.ts +61 -0
  32. package/extensions/modules/a2a/test/persistence.test.ts +92 -0
  33. package/extensions/modules/a2a/test/protocol.test.ts +217 -0
  34. package/extensions/modules/a2a/test/registry.test.ts +114 -0
  35. package/extensions/modules/a2a/test/retry.test.ts +136 -0
  36. package/extensions/modules/a2a/test/security.test.ts +281 -0
  37. package/extensions/modules/a2a/test/server.test.ts +1966 -0
  38. package/extensions/modules/a2a/test/tmp.ts +59 -0
  39. package/extensions/modules/a2a/test/vendor.test.ts +57 -0
  40. package/extensions/modules/a2a/types/bonjour-service.d.ts +22 -0
  41. package/extensions/modules/a2a/vendor/VENDORED.md +18 -0
  42. package/extensions/modules/a2a/vendor/package.json +1 -0
  43. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/LICENSE +23 -0
  44. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.d.ts +14 -0
  45. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.js +57 -0
  46. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.d.ts +4 -0
  47. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.js +3 -0
  48. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.d.ts +13 -0
  49. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.js +50 -0
  50. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.d.ts +41 -0
  51. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.js +209 -0
  52. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.d.ts +9 -0
  53. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.js +42 -0
  54. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.d.ts +14 -0
  55. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.js +119 -0
  56. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.d.ts +14 -0
  57. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.js +142 -0
  58. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.d.ts +7 -0
  59. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.js +53 -0
  60. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.d.ts +58 -0
  61. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.js +130 -0
  62. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.d.ts +1 -0
  63. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.js +13 -0
  64. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.d.ts +1 -0
  65. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.js +17 -0
  66. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.d.ts +4 -0
  67. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.js +22 -0
  68. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.d.ts +3 -0
  69. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.js +6 -0
  70. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/LICENSE +21 -0
  71. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/classes.js +23 -0
  72. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/index.js +1761 -0
  73. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/opcodes.js +50 -0
  74. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/optioncodes.js +59 -0
  75. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/rcodes.js +50 -0
  76. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/types.js +103 -0
  77. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/LICENSE +21 -0
  78. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/es6.js +73 -0
  79. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/index.js +46 -0
  80. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/LICENSE +21 -0
  81. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/index.cjs +250 -0
  82. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/LICENSE +21 -0
  83. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/index.js +205 -0
  84. package/extensions/modules/a2a/vendor/vendored_deps/thunky/LICENSE +21 -0
  85. package/extensions/modules/a2a/vendor/vendored_deps/thunky/index.js +55 -0
  86. package/extensions/modules/composer/test/module.test.ts +2 -2
  87. package/extensions/modules/config/index.ts +3 -0
  88. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  89. package/extensions/modules/gh/configPanel.ts +82 -0
  90. package/extensions/modules/gh/index.ts +86 -0
  91. package/extensions/modules/gh/lib/gh-cli.ts +337 -0
  92. package/extensions/modules/gh/lib/ops.ts +771 -0
  93. package/extensions/modules/gh/test/gh.test.ts +280 -0
  94. package/extensions/modules/plan/lib/plan-tools.ts +8 -0
  95. package/extensions/modules/repair/index.ts +138 -0
  96. package/extensions/modules/repair/lib/guards.ts +1 -1
  97. package/extensions/modules/repair/lib/read-selector.ts +242 -0
  98. package/extensions/modules/repair/test/read-selector.test.ts +198 -0
  99. package/extensions/modules/steering/configPanel.ts +8 -0
  100. package/extensions/modules/steering/index.ts +6 -0
  101. package/extensions/modules/steering/lib/settings.ts +6 -2
  102. package/extensions/modules/steering/lib/think.ts +66 -0
  103. package/extensions/modules/steering/test/harness.ts +5 -0
  104. package/extensions/modules/steering/test/settings.test.ts +2 -0
  105. package/extensions/modules/steering/test/think.test.ts +77 -0
  106. package/extensions/modules/todo/configPanel.ts +55 -0
  107. package/extensions/modules/todo/index.ts +46 -13
  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 +276 -0
  111. package/extensions/modules/web/index.ts +37 -1
  112. package/extensions/modules/web/lib/a11y.ts +252 -0
  113. package/extensions/modules/web/test/a11y.test.ts +218 -0
  114. package/extensions/modules/web/test/extension.test.ts +2 -2
  115. package/extensions/modules/web/test/hook.test.ts +2 -2
  116. package/extensions/modules/web/vendor/axe/LICENSE +362 -0
  117. package/extensions/modules/web/vendor/axe/LICENSE-3RD-PARTY.txt +66 -0
  118. package/extensions/modules/web/vendor/axe/README.md +19 -0
  119. package/extensions/modules/web/vendor/axe/axe.min.js +12 -0
  120. package/package.json +2 -2
  121. package/skills/a2a/SKILL.md +63 -0
  122. package/skills/web/SKILL.md +1 -0
@@ -0,0 +1,1117 @@
1
+ /**
2
+ * pi-a2a — A2A Protocol v1.0 bidirectional extension for the Pi coding agent.
3
+ *
4
+ * OUTBOUND (always available): Pi discovers and delegates tasks to remote
5
+ * A2A agents (Hermes, Google ADK, LangChain, CrewAI, any A2A peer).
6
+ * INBOUND (opt-in via a2a.server.enabled): Pi exposes itself as an
7
+ * A2A-discoverable agent other agents can call.
8
+ *
9
+ * Zero runtime deps — pure stdlib + global fetch. Follows the A2A v1.0 wire
10
+ * format (JSON-RPC 2.0 over HTTP), tolerant of v0.3 peers. Security model
11
+ * ported from Hermes: localhost-default bind, token-gated remote, outbound
12
+ * redaction, inbound injection filtering, audit log, anti-loop.
13
+ */
14
+
15
+ import { homedir } from "node:os";
16
+ import { chmodSync, realpathSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { Type } from "typebox";
20
+
21
+ import { stripInputRequired, terminalOutcomeError } from "./lib/outcome.js";
22
+ import { childRetrySettings, isTransientChannelError } from "./lib/retry.js";
23
+ import { getGatewayPeers, loadConfig, setConfigOverrides, type A2AConfig } from "./lib/config";
24
+ import {
25
+ a2aCall,
26
+ a2aDiscover,
27
+ a2aHistory,
28
+ a2aList,
29
+ a2aOrchestrate,
30
+ a2aStatus,
31
+ metrics,
32
+ } from "./lib/client";
33
+ import { A2AServer, type SessionRunner } from "./lib/server";
34
+ import { formatPeers, listPeers } from "./lib/discovery";
35
+ import { childTranscriptDir } from "./lib/persistence";
36
+ import { activityLine, activityStatusLine, activityToText, classifyLine, dispatchLabel, preview, type InboundActivity } from "./lib/activity";
37
+
38
+ import { Container, Text } from "@earendil-works/pi-tui";
39
+ // ponytail: vendored from @bacnh85/pi-a2a 0.7.13 — ported into ceulen.
40
+ // /a2a-config DROPPED: the central /config panel owns A2A settings
41
+ // (configPanel.ts). ceulen deltas: ceulen-a2a-inbound customType/status key,
42
+ // per-tool kill-switch wrap, resources_discover skill, restart bridge export.
43
+ import { readDisabledTools } from "../../lib/tools.js";
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Module state
47
+ // ---------------------------------------------------------------------------
48
+
49
+ let server: A2AServer | null = null;
50
+
51
+ function piDir(): string {
52
+ return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
53
+ }
54
+
55
+ function cfgFor(ctx: ExtensionContext): A2AConfig {
56
+ return loadConfig({ ctx, cwd: ctx.cwd ?? process.cwd() });
57
+ }
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Session runner — spawn an isolated Pi agent session per inbound task.
61
+ // (Same proven path pi-subagent uses; lazy import to avoid load cost.)
62
+ // ---------------------------------------------------------------------------
63
+
64
+ function makeSessionRunner(ctx: ExtensionContext, cfg?: A2AConfig): SessionRunner {
65
+ return async ({ message, taskId, signal, onProgress }) => {
66
+ const sdk = await import("@earendil-works/pi-coding-agent");
67
+ const { createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader } = sdk;
68
+ const modelRegistry = ctx.modelRegistry as any;
69
+ const model = ctx.model;
70
+ if (!model) throw new Error("no active model on the host session");
71
+ const cwd = ctx.cwd || process.cwd();
72
+ // Auto-compaction is the only recovery path a long dispatch has near
73
+ // the context window: pi clamps max_tokens to the remaining budget
74
+ // (down to 1 at the extreme), so without compact-and-retry the final
75
+ // turn is cut and the task dies with a truncated or empty reply. The
76
+ // keep window is scaled to the model's context window (stock: flat
77
+ // 20k) because pi's cut-point walk never cuts at tool results — a
78
+ // single tool-result batch bigger than the keep budget strands the
79
+ // walk and auto-compaction silently no-ops exactly when it is most
80
+ // needed. Dispatched coding tasks routinely produce such batches (one
81
+ // large read or command dump), so the keep budget needs headroom
82
+ // proportional to the window.
83
+ const keepRecentTokens = Math.max(
84
+ 20_000,
85
+ Math.floor((model.contextWindow ?? 128_000) / 5),
86
+ );
87
+ // retry: the SDK agent loop retries a failed model turn IN PLACE (removes
88
+ // the errored assistant message, re-runs the same turn with backoff) and
89
+ // already narrows to the transient class (503/429/5xx/network, never
90
+ // quota/billing/4xx). The stock child budget was maxRetries:1 — a single
91
+ // 2s retry — so a transient distributor 503 ("no available channel") on
92
+ // the FINAL turn killed the run and left the dispatched task silently open
93
+ // (task #470, incident f4b6578c). childRetrySettings() lifts it to a
94
+ // bounded 3 retries / short backoff (~7s of coverage), converting the
95
+ // channel blip into a blip. See lib/retry.ts.
96
+ const settingsManager = SettingsManager.inMemory({
97
+ compaction: { enabled: true, keepRecentTokens },
98
+ retry: childRetrySettings(),
99
+ });
100
+ // The loader must NOT receive the inMemory settingsManager: it would then
101
+ // resolve zero extension packages and the child session would run without
102
+ // any host extensions (pi-model-tools' ds-anchor bootstrap included).
103
+ // Letting DefaultResourceLoader fall back to SettingsManager.create(cwd,
104
+ // agentDir) loads the real on-disk settings/packages — the same path
105
+ // pi-subagent's runner uses.
106
+ const resourceLoader = new DefaultResourceLoader({
107
+ cwd,
108
+ agentDir: sdk.getAgentDir(),
109
+ });
110
+ await resourceLoader.reload({
111
+ // Forward the host's trust decision so project-local (.pi/) extensions
112
+ // load in child sessions when the user already trusted the project —
113
+ // same behavior as pi-subagent's runner; never prompt (no UI).
114
+ resolveProjectTrust: async () => (ctx as any).isProjectTrusted?.() ?? false,
115
+ });
116
+ // Persist the child's transcript (fleet task #252). Stock pi-a2a ran
117
+ // children on SessionManager.inMemory, so a dispatched worker that
118
+ // stalled or was killed mid-run left NO step history — the only evidence
119
+ // was its final A2A reply (196d39be: a worker stopped mid-sentence at
120
+ // 989s and the cause could not be determined). AgentSession appends every
121
+ // entry (user message, assistant turns, tool calls and results) to its
122
+ // SessionManager synchronously as it runs, so a REAL SessionManager
123
+ // gives each dispatch a full pi session file at
124
+ // <agentDir>/a2a_sessions/<timestamp>_<taskId>.jsonl — openable with pi's
125
+ // own session tooling and complete up to the moment of death even on a
126
+ // window kill (the file materializes on the child's first assistant
127
+ // output; a child that dies before ANY model output leaves no transcript,
128
+ // covered instead by the FAILED task + audit line). Keyed by the A2A
129
+ // taskId so ledger rows, the audit log, and the transcript all join on
130
+ // one key; the host session lineage is preserved via parentSession.
131
+ // Privacy: the transcript carries everything the worker read — the file
132
+ // is chmod 600 at turn end, and server.childTranscriptRetentionDays
133
+ // bounds its lifetime (swept on server start); set
134
+ // a2a.server.childTranscripts=false for stock in-memory behavior.
135
+ // Best-effort by design: any persistence failure falls back to the
136
+ // in-memory manager — forensics must never break the dispatch itself.
137
+ let transcriptPath: string | undefined;
138
+ let sessionManager: any;
139
+ if (taskId && cfg?.server.childTranscripts !== false) {
140
+ try {
141
+ const hostSession = (ctx as any).sessionManager;
142
+ const hostSessionFile = hostSession?.getSessionFile?.();
143
+ sessionManager = SessionManager.create(cwd, childTranscriptDir(piDir()), {
144
+ id: taskId,
145
+ ...(hostSessionFile ? { parentSession: hostSessionFile } : {}),
146
+ });
147
+ // Attribution entry: plain custom entries persist in the session
148
+ // file but never enter the child's LLM context. Ties the transcript
149
+ // to the dispatch and the host session lineage.
150
+ sessionManager.appendCustomEntry("a2a/dispatch", {
151
+ taskId,
152
+ hostSessionId: hostSession?.getSessionId?.(),
153
+ hostSessionFile,
154
+ });
155
+ transcriptPath = sessionManager.getSessionFile();
156
+ } catch {
157
+ sessionManager = undefined; // fall back to stock in-memory
158
+ }
159
+ }
160
+ // Fallback (transcripts off or persistence failed): the in-memory child
161
+ // inherits the HOST session's id (fleet task #238) so its MCP calls
162
+ // (pi-mcp-extension stamps getSessionId() as pi/session) and outbound A2A
163
+ // attribute to the host conversation instead of an ephemeral id nobody
164
+ // can map back. The persisted path above keys the child on the taskId
165
+ // and records hostSessionId in its a2a/dispatch entry instead.
166
+ if (!sessionManager) {
167
+ const hostSessionId = (ctx as any).sessionManager?.getSessionId?.();
168
+ sessionManager = SessionManager.inMemory(cwd, hostSessionId ? { id: hostSessionId } : undefined);
169
+ }
170
+ const created = await createAgentSession({
171
+ cwd,
172
+ model,
173
+ thinkingLevel: ctx.thinkingLevel ?? "medium",
174
+ resourceLoader,
175
+ sessionManager,
176
+ settingsManager,
177
+ ...(modelRegistry?.runtime ? { modelRuntime: modelRegistry.runtime } : {}),
178
+ ...(modelRegistry?.authStorage
179
+ ? { authStorage: modelRegistry.authStorage, modelRegistry }
180
+ : {}),
181
+ } as any);
182
+ const session = created.session;
183
+ // Fire the extension session lifecycle for the child. createAgentSession
184
+ // loads extension packages but never emits session_start — the SDK's own
185
+ // print/rpc modes emit it via bindExtensions() right after creation — so
186
+ // without this the child runs every extension's factory but none of their
187
+ // session_start handlers: extensions that register tools there (e.g.
188
+ // pi-mcp-extension, which wires ALL of its MCP servers/tools on
189
+ // session_start) are silently missing from dispatched sessions. mode
190
+ // "print" with no uiContext keeps ctx.hasUI === false, matching how the
191
+ // host-only session_start guard below classifies child sessions.
192
+ try {
193
+ await session.bindExtensions({ mode: "print" });
194
+ } catch {
195
+ // Best-effort: a child that fails to bind still runs base tools.
196
+ }
197
+ let reply = "";
198
+ let inputRequired = false;
199
+ // Stop reason of the LAST assistant message and whether it carried any
200
+ // text — consumed by the stunted-reply check after the run completes.
201
+ let terminalStopReason: string | undefined;
202
+ let terminalHadText = false;
203
+ let terminalErrorMessage: string | undefined;
204
+ let sawAssistant = false;
205
+ // Cheap progress marker for post-mortems (#256): assistant turns + tool
206
+ // executions observed before the run ended.
207
+ let stepCount = 0;
208
+ let resolveDone!: () => void;
209
+ const done = new Promise<void>((r) => (resolveDone = r));
210
+ const unsub = session.subscribe((event: any) => {
211
+ // Forward meaningful activity to the host TUI (0.3.0): tool calls and
212
+ // assistant text deltas become one-line progress entries.
213
+ const line = activityLine(event);
214
+ if (line && onProgress) onProgress(line);
215
+ if (event.type === "tool_execution_start") {
216
+ stepCount += 1;
217
+ }
218
+ if (event.type === "message_end" && event.message?.role === "assistant") {
219
+ stepCount += 1;
220
+ // Agent-session events carry the OpenAI-style message shape: the text
221
+ // parts live under `content` (e.g. [{type:"text",text:"..."}]), not
222
+ // `parts` — reading `parts` yields nothing and the reply comes back
223
+ // "(no reply)" even though the model answered correctly.
224
+ const content = event.message?.content ?? event.message?.parts ?? [];
225
+ const text = content
226
+ .map((p: any) => (typeof p?.text === "string" ? p.text : ""))
227
+ .join("");
228
+ if (text) reply = text;
229
+ terminalStopReason = event.message?.stopReason;
230
+ terminalHadText = Boolean(text);
231
+ terminalErrorMessage = event.message?.errorMessage;
232
+ sawAssistant = true;
233
+ // Tail-anchored: only a marker ENDING this (final) assistant message
234
+ // flips the state — see stripInputRequired.
235
+ if (text) {
236
+ const stripped = stripInputRequired(text);
237
+ reply = stripped.text;
238
+ inputRequired = stripped.inputRequired;
239
+ }
240
+ }
241
+ });
242
+ const onAbort = () => {
243
+ // Settle the race (see the prompt race below) so a prompt() that
244
+ // outlives session.abort() cannot hang the runner past the server's
245
+ // reply window.
246
+ resolveDone();
247
+ try {
248
+ session.abort();
249
+ } catch {
250
+ /* ignore */
251
+ }
252
+ };
253
+ signal.addEventListener("abort", onAbort, { once: true });
254
+ // Whether the turn finished on its own before any abort fired, captured
255
+ // the instant the race settles: an abort landing during the cleanup below
256
+ // (the server clears its reply-window timer only after this runner
257
+ // returns) must not retroactively fail a turn that already completed.
258
+ let completedCleanly = false;
259
+ try {
260
+ // Settle the race on prompt() completion, not on agent_end: agent_end
261
+ // fires when the model turn ends — BEFORE the post-run overflow
262
+ // recovery that prompt() awaits (agent-session's _handlePostAgentRun
263
+ // → compact-and-retry). Settling at agent_end let the cleanup below
264
+ // dispose() the session while that recovery compaction was still in
265
+ // flight (dispose → abortCompaction), so a context-clamped turn could
266
+ // never recover even though pi's compact-and-retry would have saved
267
+ // it. prompt() resolves only after recovery and any continuation
268
+ // turns finish; aborts still settle the race immediately via onAbort
269
+ // above.
270
+ await Promise.race([session.prompt(message), done]);
271
+ completedCleanly = !signal.aborted;
272
+ } finally {
273
+ signal.removeEventListener("abort", onAbort);
274
+ unsub();
275
+ // dispose() does NOT emit session_shutdown (it only invalidates the
276
+ // extension runner), so emit it explicitly first: extensions that
277
+ // started processes on session_start (pi-mcp-extension's stdio MCP
278
+ // servers) stop them on session_shutdown and would otherwise leak one
279
+ // process per inbound task.
280
+ try {
281
+ await session.extensionRunner?.emit({ type: "session_shutdown", reason: "quit" });
282
+ } catch {
283
+ /* best-effort */
284
+ }
285
+ try {
286
+ session.dispose();
287
+ } catch {
288
+ /* ignore */
289
+ }
290
+ // The session file materializes lazily (SessionManager buffers
291
+ // entries until the first assistant message), so tighten permissions
292
+ // here — best-effort 0600 for a file that carries everything the
293
+ // worker read.
294
+ if (transcriptPath) {
295
+ try {
296
+ chmodSync(transcriptPath, 0o600);
297
+ } catch {
298
+ /* file never materialized (no model output) — nothing to chmod */
299
+ }
300
+ }
301
+ }
302
+ if (!completedCleanly) {
303
+ // The reply window expired (or the caller canceled) mid-run: the race
304
+ // ended because of the abort, not because the turn finished, so `reply`
305
+ // holds at most a truncated partial answer. Throw so messageSend maps
306
+ // the task to FAILED/CANCELED — returning normally takes the success
307
+ // path and hands the dispatcher a truncated reply labelled COMPLETED,
308
+ // indistinguishable from a finished worker (#247). Carry the transcript
309
+ // forensics on the error so the failure audit line points at the step
310
+ // history (#252).
311
+ const err =
312
+ signal.reason instanceof Error
313
+ ? signal.reason
314
+ : new Error("inbound session aborted before completing");
315
+ try {
316
+ if (transcriptPath) (err as any).transcriptPath = transcriptPath;
317
+ (err as any).stepCount = stepCount;
318
+ } catch {
319
+ /* best-effort */
320
+ }
321
+ throw err;
322
+ }
323
+
324
+ // Endings with no usable answer map to FAILED, never COMPLETED with a
325
+ // stale/empty reply: a length stop with no text (#314), a final turn the
326
+ // provider failed (#425 — e.g. HTTP 503 "no available channel", which
327
+ // previously came back COMPLETED "(no reply)"), and a run that produced
328
+ // no assistant output at all. See lib/outcome.ts.
329
+ let outcomeError = terminalOutcomeError({
330
+ stopReason: terminalStopReason,
331
+ hadText: terminalHadText,
332
+ sawAssistant,
333
+ errorMessage: terminalErrorMessage,
334
+ });
335
+ if (outcomeError) {
336
+ // If the final turn died on a transient provider/channel error, the SDK
337
+ // already retried it within the bounded budget above and still failed —
338
+ // say so, so a post-mortem does not chase a phantom permanent fault
339
+ // (task #470).
340
+ if (terminalStopReason === "error" && isTransientChannelError(terminalErrorMessage)) {
341
+ outcomeError += " (transient provider/channel error — bounded retries exhausted)";
342
+ }
343
+ const err = new Error(outcomeError);
344
+ try {
345
+ if (transcriptPath) (err as any).transcriptPath = transcriptPath;
346
+ (err as any).stepCount = stepCount;
347
+ } catch {
348
+ /* best-effort */
349
+ }
350
+ throw err;
351
+ }
352
+ return {
353
+ reply: reply || "(no reply)",
354
+ inputRequired,
355
+ ...(transcriptPath ? { transcriptPath } : {}),
356
+ stepCount,
357
+ };
358
+ };
359
+ }
360
+
361
+ // ---------------------------------------------------------------------------
362
+ // Inbound activity → host TUI (0.3.0)
363
+ // ---------------------------------------------------------------------------
364
+
365
+ /** In-flight inbound tasks (identity + taskId), for the footer status line. */
366
+ const activeInboundTasks = new Map<string, { identity: string; last: InboundActivity }>();
367
+
368
+ /**
369
+ * Surface an inbound activity event to the host TUI.
370
+ * - transcript on: sendMessage (custom message, visible in transcript)
371
+ * - always: notify() toast on arrived/completed/failed
372
+ * Caller provides the ctx for ui access (may be undefined in tests).
373
+ */
374
+ function broadcastActivity(
375
+ pi: ExtensionAPI,
376
+ ctx: ExtensionContext | undefined,
377
+ cfg: A2AConfig | undefined,
378
+ a: InboundActivity,
379
+ ): void {
380
+ const transcript = cfg?.ui?.transcript ?? true;
381
+ if (transcript) {
382
+ try {
383
+ pi.sendMessage({
384
+ customType: "ceulen-a2a-inbound", // ponytail: ceulen customType prefix convention
385
+ content: activityToText(a),
386
+ display: true,
387
+ });
388
+ } catch {
389
+ /* session may be mid-replace; ignore */
390
+ }
391
+ }
392
+ if (!ctx) return;
393
+ switch (a.type) {
394
+ case "arrived":
395
+ activeInboundTasks.set(a.taskId, { identity: a.identity, last: a });
396
+ // Toast stays short (it would flood the TUI); the transcript carries full text.
397
+ ctx.ui.notify(`A2A dispatch from ${a.identity}: ${preview(a.text, 160)}`, "info");
398
+ break;
399
+ case "progress":
400
+ activeInboundTasks.set(a.taskId, { identity: activeInboundTasks.get(a.taskId)?.identity ?? "peer", last: a });
401
+ break;
402
+ case "completed":
403
+ case "failed":
404
+ activeInboundTasks.delete(a.taskId);
405
+ ctx.ui.notify(
406
+ a.type === "completed"
407
+ ? `A2A dispatch ${dispatchLabel(a.taskId)} completed (${(a.elapsedMs / 1000).toFixed(1)}s)`
408
+ : `A2A dispatch ${dispatchLabel(a.taskId)} failed: ${a.error}`,
409
+ a.type === "completed" ? "info" : "error",
410
+ );
411
+ break;
412
+ }
413
+ // Footer status while tasks are active.
414
+ const active = [...activeInboundTasks.values()].map((t) => ({ taskId: t.last.taskId, identity: t.identity }));
415
+ const status = activityStatusLine(active);
416
+ try {
417
+ ctx.ui.setStatus("ceulen-a2a-inbound", status);
418
+ } catch {
419
+ /* best-effort */
420
+ }
421
+ }
422
+
423
+ /** Status lines (gateway registration, channel open, …) → transcript + toast,
424
+ * rendered like the [A2A inbound] activity lines instead of vanishing in the
425
+ * console. */
426
+ function statusSink(pi: ExtensionAPI, ctx: ExtensionContext | undefined): (m: string) => void {
427
+ return (m) => {
428
+ // DELIBERATELY not pi.sendMessage: custom messages are converted to USER
429
+ // MESSAGES in the LLM context (buildSessionContext), so routing lifecycle
430
+ // lines through it polluted every model request with "[a2a] registered…"
431
+ // / "gateway channel open…" noise — enough to derail DeepSeek v4 Pro's
432
+ // minimal-mode bootstrap (request #1 must be a clean user message).
433
+ // TUI notification only: visible to the human, invisible to the model.
434
+ // Headless modes (json/print, hasUI=false) fall back to stderr so the
435
+ // lifecycle remains observable — same pattern as errorSink.
436
+ const ui = ctx && ctx.hasUI ? ctx.ui : undefined;
437
+ if (ui) {
438
+ try {
439
+ ui.notify(m, "info");
440
+ } catch {
441
+ /* best-effort */
442
+ }
443
+ } else {
444
+ try {
445
+ console.error(m);
446
+ } catch {
447
+ /* best-effort */
448
+ }
449
+ }
450
+ };
451
+ }
452
+
453
+ /** Gateway diagnostic/error lines → error toast only — a SEPARATE surface
454
+ * from the [a2a] status lines above, so failures don't render interleaved
455
+ * with lifecycle output in the transcript. Headless falls back to stderr. */
456
+ function errorSink(ctx: ExtensionContext | undefined): (m: string) => void {
457
+ return (m) => {
458
+ const ui = ctx && ctx.hasUI ? ctx.ui : undefined;
459
+ if (ui) {
460
+ try {
461
+ ui.notify(m, "error");
462
+ return;
463
+ } catch {
464
+ /* fall through */
465
+ }
466
+ }
467
+ console.error(m);
468
+ };
469
+ }
470
+
471
+ // ---------------------------------------------------------------------------
472
+ // Tool parameter schemas
473
+ // ---------------------------------------------------------------------------
474
+
475
+ const agentParam = Type.String({
476
+ description:
477
+ "Configured peer name (from a2a.peers in settings.json) OR a full http(s):// URL of an A2A agent.",
478
+ });
479
+ const messageParam = Type.String({ description: "Task message to send to the agent." });
480
+ const contextIdParam = Type.Optional(
481
+ Type.String({
482
+ description:
483
+ "Context id from a prior call — reuse for multi-turn conversations. Omit for a new conversation.",
484
+ }),
485
+ );
486
+
487
+ /** Parse `/a2a-broadcast` args. The --agents flag is only recognized LEADING
488
+ * or TRAILING — an occurrence inside the message body is content, not a flag. */
489
+ export function parseBroadcastArgs(raw: string): { message: string; agents: string[] } {
490
+ const s = raw.trim();
491
+ const lead = /^--agents\s+(\S+)\s*/.exec(s);
492
+ const trail = lead ? null : /\s+--agents\s+(\S+)$/.exec(s);
493
+ if (lead) return { message: s.slice(lead[0].length).trim(), agents: lead[1].split(",") };
494
+ if (trail) return { message: s.slice(0, trail.index).trim(), agents: trail[1].split(",") };
495
+ return { message: s, agents: [] };
496
+ }
497
+
498
+ // ---------------------------------------------------------------------------
499
+ // Extension entrypoint
500
+ // ---------------------------------------------------------------------------
501
+
502
+ export default function a2aExtension(pi: ExtensionAPI): void {
503
+ // Compact transcript renderer for inbound activity messages (0.3.0 → 0.6.2 UX).
504
+ // Class-colored so the three phases of an A2A exchange read at a glance:
505
+ // ⚑ warning — received from a peer (like a user turn, different color)
506
+ // ⚙ dim — isolated session executing tools to answer
507
+ // ✎ success — reply being sent back
508
+ // ✓ success / ✗ error — completion markers
509
+ pi.registerMessageRenderer?.("ceulen-a2a-inbound", (message, _opts, theme) => {
510
+ try {
511
+ const fg = theme.fg.bind(theme);
512
+ const raw = message.content;
513
+ const content = typeof raw === "string"
514
+ ? raw
515
+ : (Array.isArray(raw) ? raw.map((p: any) => (typeof p?.text === "string" ? p.text : "")).join("") : "");
516
+ const kind = classifyLine(content);
517
+ const icon =
518
+ kind === "received" ? "⚑" :
519
+ kind === "failed" ? "✗" :
520
+ kind === "replying" || kind === "completed" ? "✓" : "⇄";
521
+ const color =
522
+ kind === "received" ? "warning" :
523
+ kind === "failed" ? "error" :
524
+ kind === "executing" ? "dim" : "success";
525
+ const c = new Container();
526
+ c.addChild(new Text(fg(color, `${icon} ${content}`), 0, 0));
527
+ return c;
528
+ } catch {
529
+ return undefined; // pi-tui unavailable → fall back to default rendering
530
+ }
531
+ });
532
+
533
+ // -------------------------------------------------------------------------
534
+ // Tools (outbound client) — always registered
535
+ // -------------------------------------------------------------------------
536
+
537
+ // Per-tool kill-switch (ceulen.disabledTools): listed tools register
538
+ // inactive; /config's tool rows re-activate live via setActiveTools
539
+ // (web module pattern).
540
+ const disabledTools = readDisabledTools();
541
+ const registerTool = pi.registerTool.bind(pi);
542
+ pi.registerTool = ((tool: Parameters<typeof pi.registerTool>[0]) =>
543
+ registerTool({ ...tool, defaultActive: !disabledTools.has((tool as { name: string }).name) })) as typeof pi.registerTool;
544
+
545
+ // Skill ships in-package (../../../skills/a2a) and is contributed through
546
+ // resources_discover — NOT via the package.json pi.skills manifest — so the
547
+ // kill-switch gates it too (web module pattern).
548
+ pi.on("resources_discover", () => {
549
+ const skillsRoot = new URL("../../../skills/", import.meta.url).pathname;
550
+ return { skillPaths: [join(realpathSync(skillsRoot), "a2a")] };
551
+ });
552
+
553
+ pi.registerTool({
554
+ name: "a2a_call",
555
+ label: "A2A Call",
556
+ description:
557
+ "Call a remote A2A (Agent2Agent) agent with a task message and return its reply. " +
558
+ "Use to delegate work to other agents (Hermes, ADK, LangChain, CrewAI, any A2A peer). " +
559
+ "Pass context_id to continue a multi-turn conversation. Set async_dispatch true for " +
560
+ "long-running work: the call returns an ack with a task id immediately and the peer " +
561
+ "keeps working — poll it with a2a_status.",
562
+ promptSnippet: "delegate a task to a remote A2A agent and get its reply",
563
+ promptGuidelines: [
564
+ "Use for cross-agent task distribution and specialist delegation.",
565
+ "The agent param is a configured peer name OR a full URL.",
566
+ "For jobs that may run long, set async_dispatch true — you get a task id back " +
567
+ "immediately instead of holding the call open; check a2a_status for the result.",
568
+ ],
569
+ parameters: Type.Object({
570
+ agent: agentParam,
571
+ message: messageParam,
572
+ context_id: contextIdParam,
573
+ async_dispatch: Type.Optional(
574
+ Type.Boolean({
575
+ description:
576
+ "Non-blocking dispatch (A2A v1.0 returnImmediately): return an ack with the task id " +
577
+ "as soon as the peer accepts, instead of waiting for the work to finish. " +
578
+ "The peer runs the task detached — poll a2a_status for the result.",
579
+ default: false,
580
+ }),
581
+ ),
582
+ }),
583
+ execute: async (_id, args, _signal, _onUpdate, ctx) => {
584
+ const cfg = cfgFor(ctx);
585
+ return {
586
+ content: [
587
+ {
588
+ type: "text" as const,
589
+ text: await a2aCall({
590
+ cfg,
591
+ piDir: piDir(),
592
+ agent: String(args.agent ?? ""),
593
+ message: String(args.message ?? ""),
594
+ contextId: args.context_id ? String(args.context_id) : undefined,
595
+ asyncDispatch: args.async_dispatch === true,
596
+ sessionId: (ctx as any).sessionManager?.getSessionId?.(),
597
+ discoveredPeers: listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() }),
598
+ }),
599
+ },
600
+ ],
601
+ details: {},
602
+ };
603
+ },
604
+ });
605
+
606
+ pi.registerTool({
607
+ name: "a2a_status",
608
+ label: "A2A Status",
609
+ description:
610
+ "Check the status of a task previously dispatched to a remote A2A agent (by task id — " +
611
+ "see the ack from an async_dispatch a2a_call). Returns the task state, and the reply " +
612
+ "text once the task is completed/failed. Optionally wait (wait_seconds) and poll until " +
613
+ "the task reaches a terminal state.",
614
+ promptSnippet: "poll the status of a task dispatched to a remote A2A agent",
615
+ promptGuidelines: [
616
+ "Use after an async_dispatch a2a_call to fetch the result of a long-running task.",
617
+ "Without wait_seconds it fetches once; with it, the tool polls until the task is " +
618
+ "terminal or the deadline passes (the task keeps running on the peer either way).",
619
+ ],
620
+ parameters: Type.Object({
621
+ agent: agentParam,
622
+ task_id: Type.String({
623
+ description: "Task id from the dispatch ack (e.g. task-1b4f8d1c30d54819).",
624
+ }),
625
+ wait_seconds: Type.Optional(
626
+ Type.Number({
627
+ description: "If positive, poll until the task is terminal or this many seconds pass. " +
628
+ "Omit (or 0/negative) for a single status fetch.",
629
+ }),
630
+ ),
631
+ }),
632
+ execute: async (_id, args, signal, _onUpdate, ctx) => {
633
+ const cfg = cfgFor(ctx);
634
+ return {
635
+ content: [
636
+ {
637
+ type: "text" as const,
638
+ text: await a2aStatus({
639
+ cfg,
640
+ piDir: piDir(),
641
+ agent: String(args.agent ?? ""),
642
+ taskId: String(args.task_id ?? ""),
643
+ waitSeconds: typeof args.wait_seconds === "number" ? args.wait_seconds : undefined,
644
+ discoveredPeers: listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() }),
645
+ signal: signal ?? undefined,
646
+ }),
647
+ },
648
+ ],
649
+ details: {},
650
+ };
651
+ },
652
+ });
653
+
654
+ pi.registerTool({
655
+ name: "a2a_discover",
656
+ label: "A2A Discover",
657
+ description:
658
+ "Discover an A2A agent at a URL — fetches and summarizes its Agent Card (name, skills, capabilities, auth).",
659
+ promptSnippet: "fetch a remote agent's Agent Card to learn its capabilities",
660
+ parameters: Type.Object({
661
+ url: Type.String({ description: "Base URL of the A2A agent (e.g. http://localhost:9900)." }),
662
+ }),
663
+ execute: async (_id, args, _signal, _onUpdate, ctx) => {
664
+ const cfg = cfgFor(ctx);
665
+ return {
666
+ content: [
667
+ { type: "text" as const, text: await a2aDiscover({ cfg, url: String(args.url ?? "") }) },
668
+ ],
669
+ details: {},
670
+ };
671
+ },
672
+ });
673
+
674
+ pi.registerTool({
675
+ name: "a2a_list",
676
+ label: "A2A List",
677
+ description: "List configured A2A peers, persisted conversations, and call metrics.",
678
+ promptSnippet: "show configured A2A peers and recent conversations",
679
+ parameters: Type.Object({}),
680
+ execute: async (_id, _args, _signal, _onUpdate, ctx) => {
681
+ const cfg = cfgFor(ctx);
682
+ return {
683
+ content: [
684
+ {
685
+ type: "text" as const,
686
+ text: a2aList({
687
+ cfg,
688
+ piDir: piDir(),
689
+ discoveredPeers: listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "" }),
690
+ }),
691
+ },
692
+ ],
693
+ details: {},
694
+ };
695
+ },
696
+ });
697
+
698
+ pi.registerTool({
699
+ name: "a2a_history",
700
+ label: "A2A History",
701
+ description: "Recall a persisted A2A conversation by context_id (survives compaction/restart).",
702
+ promptSnippet: "reload a prior A2A conversation by context_id",
703
+ parameters: Type.Object({
704
+ context_id: Type.String({ description: "Context id of the conversation to recall." }),
705
+ limit: Type.Optional(Type.Number({ description: "Max messages (default 50).", default: 50 })),
706
+ }),
707
+ execute: async (_id, args, _signal, _onUpdate, _ctx) => {
708
+ return {
709
+ content: [
710
+ {
711
+ type: "text" as const,
712
+ text: a2aHistory({
713
+ piDir: piDir(),
714
+ contextId: String(args.context_id ?? ""),
715
+ limit: typeof args.limit === "number" ? args.limit : undefined,
716
+ }),
717
+ },
718
+ ],
719
+ details: {},
720
+ };
721
+ },
722
+ });
723
+
724
+ pi.registerTool({
725
+ name: "a2a_orchestrate",
726
+ label: "A2A Orchestrate",
727
+ description:
728
+ "Fan a task out to every configured A2A peer advertising a capability, in parallel. " +
729
+ "Modes: 'all' (default, every reply), 'first' (first success), 'best' (longest success).",
730
+ promptSnippet: "delegate one task to multiple capable A2A peers in parallel",
731
+ promptGuidelines: [
732
+ "Peers advertise capabilities in a2a.peers.<name>.capabilities.",
733
+ "All matching peers are contacted and awaited either way; 'first' returns the first-listed successful reply, 'best' the longest. Narrow `capabilities` to limit the fan-out.",
734
+ ],
735
+ parameters: Type.Object({
736
+ capability: Type.String({
737
+ description: "Capability tag to match against peer capabilities (e.g. 'web_search', 'coding').",
738
+ }),
739
+ message: messageParam,
740
+ mode: Type.Optional(
741
+ Type.String({
742
+ description:
743
+ "Fan-out mode: 'all' (default, every reply), 'first' (first success), 'best' (longest success).",
744
+ default: "all",
745
+ }),
746
+ ),
747
+ }),
748
+ execute: async (_id, args, _signal, _onUpdate, ctx) => {
749
+ const cfg = cfgFor(ctx);
750
+ return {
751
+ content: [
752
+ {
753
+ type: "text" as const,
754
+ text: await a2aOrchestrate({
755
+ cfg,
756
+ piDir: piDir(),
757
+ capability: String(args.capability ?? ""),
758
+ message: String(args.message ?? ""),
759
+ mode: args.mode === "first" || args.mode === "best" ? args.mode : "all",
760
+ sessionId: (ctx as any).sessionManager?.getSessionId?.(),
761
+ }),
762
+ },
763
+ ],
764
+ details: {},
765
+ };
766
+ },
767
+ });
768
+
769
+ pi.registerTool({
770
+ name: "a2a_peers",
771
+ label: "A2A Peers",
772
+ description:
773
+ "List discoverable A2A peers (local file registry, mDNS, and configured) with their " +
774
+ "working folder, model, and tools. Use before a2a_call to pick the right peer for a task.",
775
+ promptSnippet: "list discoverable A2A peers with their cwd/model/tools",
776
+ promptGuidelines: [
777
+ "Returns peers from three sources: local registry (same machine), mDNS (network), and configured (settings.json).",
778
+ "Use it to choose which peer to delegate to based on working folder, model, or abilities.",
779
+ ],
780
+ parameters: Type.Object({}),
781
+ execute: async (_id, _args, _signal, _onUpdate, ctx) => {
782
+ const cfg = cfgFor(ctx);
783
+ const peers = listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() });
784
+ return { content: [{ type: "text" as const, text: formatPeers(peers) }], details: {} };
785
+ },
786
+ });
787
+
788
+ // -------------------------------------------------------------------------
789
+ // Commands
790
+ // -------------------------------------------------------------------------
791
+
792
+ pi.registerCommand("a2a-discover", {
793
+ description: "Discover an A2A agent at a URL: /a2a-discover <url>",
794
+ handler: async (args, ctx) => {
795
+ const url = String(args ?? "").trim();
796
+ if (!url) {
797
+ ctx.ui.notify("Usage: /a2a-discover <url>", "error");
798
+ return;
799
+ }
800
+ const cfg = cfgFor(ctx as unknown as ExtensionContext);
801
+ ctx.ui.notify(await a2aDiscover({ cfg, url }), "info");
802
+ },
803
+ });
804
+
805
+ pi.registerCommand("a2a-agents", {
806
+ description: "List configured A2A peers",
807
+ handler: async (_args, ctx) => {
808
+ const cfg = cfgFor(ctx as unknown as ExtensionContext);
809
+ ctx.ui.notify(
810
+ a2aList({
811
+ cfg,
812
+ piDir: piDir(),
813
+ discoveredPeers: listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() }),
814
+ }),
815
+ "info",
816
+ );
817
+ },
818
+ });
819
+
820
+ pi.registerCommand("a2a-send", {
821
+ description: "Send a task to an A2A agent: /a2a-send <agent> <message>",
822
+ getArgumentCompletions: (prefix) => {
823
+ // Only the first token (peer name) is completable; the rest is free text.
824
+ if (/\s/.test(prefix)) return null;
825
+ // lastA2aCtx is undefined until the first session_start (e.g. hot-reload);
826
+ // cfgFor(undefined) would throw.
827
+ if (!lastA2aCtx) return null;
828
+ const cfg = cfgFor(lastA2aCtx as unknown as ExtensionContext);
829
+ const peers = listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() });
830
+ const q = prefix.trim().toLowerCase();
831
+ const items = peers
832
+ .filter((p) => p.name.toLowerCase().startsWith(q))
833
+ .map((p) => ({ value: p.name, label: p.name, description: p.url }));
834
+ return items.length > 0 ? items : null;
835
+ },
836
+ handler: async (args, ctx) => {
837
+ const parts = String(args ?? "").trim().split(/\s+/);
838
+ const agent = parts[0] ?? "";
839
+ const message = parts.slice(1).join(" ");
840
+ if (!agent || !message) {
841
+ ctx.ui.notify("Usage: /a2a-send <agent> <message>", "error");
842
+ return;
843
+ }
844
+ const cfg = cfgFor(ctx as unknown as ExtensionContext);
845
+ const discoveredPeers = listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() });
846
+ ctx.ui.notify(await a2aCall({ cfg, piDir: piDir(), agent, message, discoveredPeers }), "info");
847
+ },
848
+ });
849
+
850
+ pi.registerCommand("a2a-broadcast", {
851
+ description: "Broadcast a task to multiple agents: /a2a-broadcast <msg> --agents a,b,c",
852
+ getArgumentCompletions: (prefix) => {
853
+ // Offer the --agents flag while it isn't present yet.
854
+ if (/--agents\b/.test(prefix)) return null;
855
+ return [{ value: "--agents", label: "--agents", description: "comma-separated peer list" }];
856
+ },
857
+ handler: async (args, ctx) => {
858
+ const { message, agents } = parseBroadcastArgs(String(args ?? ""));
859
+ if (!message || agents.length === 0) {
860
+ ctx.ui.notify("Usage: /a2a-broadcast <msg> --agents a,b,c", "error");
861
+ return;
862
+ }
863
+ const cfg = cfgFor(ctx as unknown as ExtensionContext);
864
+ const discoveredPeers = listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() });
865
+ const results = await Promise.all(
866
+ agents.map((a) => a2aCall({ cfg, piDir: piDir(), agent: a, message, discoveredPeers })),
867
+ );
868
+ ctx.ui.notify(results.join("\n\n---\n\n"), "info");
869
+ },
870
+ });
871
+
872
+ pi.registerCommand("a2a-status", {
873
+ description: "Show A2A metrics, server status, and config summary (/config → Tasks → A2A is the editor)",
874
+ handler: async (_args, ctx) => {
875
+ const cfg = cfgFor(ctx as unknown as ExtensionContext);
876
+ const m = metrics.snapshot();
877
+ const lines = [
878
+ `Name: ${server?.name ?? (cfg.server.agentName || "(default: <hostname>-<port> once started)")}`,
879
+ `Server: ${server ? "running at " + server.url : cfg.server.enabled ? "enabled (not started)" : "disabled"}`,
880
+ `Outbound: ${m.outbound_total} sent / ${m.inbound_total} replies`,
881
+ `Dispatches: ${m.tasks_completed} completed, ${m.tasks_failed} failed`,
882
+ `Avg latency: ${m.avg_latency_ms}ms`,
883
+ // Old /a2a-config show summary — the interactive editor moved to the
884
+ // central /config panel (Tasks tab, A2A sections); keep the headless
885
+ // config disclosure here (munin /munin-status precedent).
886
+ "",
887
+ "Config:",
888
+ ` server.enabled: ${cfg.server.enabled}`,
889
+ ` server.port: ${cfg.server.port}`,
890
+ ` server.host: ${cfg.server.host}`,
891
+ ` discovery: local=${cfg.discovery.local.enabled} mdns=${cfg.discovery.mdns.enabled} enrichCard=${cfg.discovery.enrichCard}`,
892
+ ` gateway: ${cfg.discovery.gateway ? `${cfg.discovery.gateway.enabled ? "enabled" : "disabled"} ${cfg.discovery.gateway.url || "(no url)"}${cfg.discovery.gateway.token ? " · token (set)" : ""}` : "not configured"}`,
893
+ ` gateways: ${Object.keys(cfg.discovery.gateways ?? {}).join(", ") || "(none)"}`,
894
+ ` ui.transcript: ${cfg.ui.transcript}`,
895
+ ` peers: ${Object.keys(cfg.peers).join(", ") || "(none)"}`,
896
+ " Edit via /config → Tasks → A2A (or ~/.pi/agent/settings.json 'a2a' key).",
897
+ ];
898
+ ctx.ui.notify(lines.join("\n"), "info");
899
+ },
900
+ });
901
+
902
+
903
+ pi.registerCommand("a2a-server", {
904
+ description: "Manage the inbound A2A server: /a2a-server start|stop|status",
905
+ getArgumentCompletions: (prefix) => {
906
+ const items = ["start", "stop", "status"]
907
+ .filter((k) => k.startsWith(prefix.trim().toLowerCase()))
908
+ .map((k) => ({ value: k, label: k }));
909
+ return items.length > 0 ? items : null;
910
+ },
911
+ handler: async (args, ctx) => {
912
+ const sub = String(args ?? "").trim().toLowerCase();
913
+ const ectx = ctx as unknown as ExtensionContext;
914
+ const cfg = cfgFor(ectx);
915
+ if (sub === "start") {
916
+ if (server) {
917
+ ctx.ui.notify(`A2A server already running at ${server.url}`, "info");
918
+ return;
919
+ }
920
+ try {
921
+ server = new A2AServer({
922
+ cfg,
923
+ ctx: ectx,
924
+ cwd: ectx.cwd,
925
+ piDir: piDir(),
926
+ runner: makeSessionRunner(ectx, cfg),
927
+ api: pi,
928
+ onActivity: (a) => broadcastActivity(pi, ectx, cfg, a),
929
+ onStatus: statusSink(pi, ectx),
930
+ onError: errorSink(ectx),
931
+ });
932
+ const info = await server.start();
933
+ const defaultNote =
934
+ cfg.server.port > 0 && info.port !== cfg.server.port
935
+ ? ` (configured port ${cfg.server.port} was busy)`
936
+ : "";
937
+ ctx.ui.notify(
938
+ `A2A server listening on ${info.host}:${info.port}${defaultNote} (Agent Card at ${info.url}.well-known/agent-card.json)`,
939
+ "info",
940
+ );
941
+ } catch (e: any) {
942
+ server = null;
943
+ ctx.ui.notify(`Failed to start A2A server: ${e?.message || e}`, "error");
944
+ }
945
+ return;
946
+ }
947
+ if (sub === "stop") {
948
+ if (!server) {
949
+ ctx.ui.notify("A2A server is not running.", "info");
950
+ return;
951
+ }
952
+ await server.stop();
953
+ server = null;
954
+ ctx.ui.notify("A2A server stopped.", "info");
955
+ return;
956
+ }
957
+ ctx.ui.notify(
958
+ server ? `A2A server running at ${server.url} (port ${server.port})` : "A2A server not running.",
959
+ "info",
960
+ );
961
+ },
962
+ });
963
+
964
+ pi.registerCommand("a2a-peers", {
965
+ description: "List discoverable A2A peers (local registry + mDNS + configured + gateway)",
966
+ handler: async (_args, ctx) => {
967
+ const cfg = cfgFor(ctx as unknown as ExtensionContext);
968
+ const peers = listPeers({ cfg, piDir: piDir(), mdnsPeers: server?.discoveredMdnsPeers ?? [], selfUrl: server?.url ?? "", gatewayPeers: getGatewayPeers() });
969
+ ctx.ui.notify(formatPeers(peers), "info");
970
+ },
971
+ });
972
+
973
+ pi.registerCommand("a2a-help", {
974
+ description: "Show A2A help",
975
+ handler: async (_args, ctx) => {
976
+ ctx.ui.notify(
977
+ [
978
+ "A2A (Agent2Agent) Protocol v1.0 — commands:",
979
+ " /a2a-discover <url> Fetch an agent's Agent Card",
980
+ " /a2a-agents List configured peers",
981
+ " /a2a-send <agent> <msg> Send a task to a peer",
982
+ " /a2a-broadcast <msg> --agents a,b,c Parallel fan-out",
983
+ " /a2a-status Metrics + server status",
984
+ " /a2a-status (also prints the config summary)",
985
+ " /a2a-server start|stop|status Manage inbound server",
986
+ "",
987
+ "Settings: /config → Tasks → A2A (or ~/.pi/agent/settings.json 'a2a' key).",
988
+ "Tools: a2a_call, a2a_status, a2a_discover, a2a_peers, a2a_list, a2a_history, a2a_orchestrate",
989
+ ].join("\n"),
990
+ "info",
991
+ );
992
+ },
993
+ });
994
+
995
+ // -------------------------------------------------------------------------
996
+ // Server lifecycle hooks (auto-start only when a2a.server.enabled)
997
+ // -------------------------------------------------------------------------
998
+
999
+ // Live model changes → refresh the session descriptor (registry file + card).
1000
+ pi.on("model_select", async () => {
1001
+ if (server) server.refreshDescriptor();
1002
+ });
1003
+
1004
+ let lastA2aCtx: ExtensionContext | undefined;
1005
+ pi.on("session_start", async (_event, ctx) => {
1006
+ // Only HOST sessions serve inbound A2A. SDK-created child sessions (a2a
1007
+ // inbound tasks via makeSessionRunner, pi-subagent children) have
1008
+ // hasUI=false AND mode='print' — without this guard every child would
1009
+ // auto-start its own A2AServer: same-pid registry overwrite, port climbing
1010
+ // per task, and duplicate gateway registration. The host session is the
1011
+ // single inbound server; children only run the task. json-mode hosts are
1012
+ // long-lived headless HOSTS (mode='json'), not children — they keep the
1013
+ // auto-start. lastA2aCtx (completions/cfgFor context) is captured BELOW
1014
+ // the guard so a child session can't overwrite the host's ctx.
1015
+ if (!ctx.hasUI && ctx.mode !== "json") return;
1016
+ lastA2aCtx = ctx;
1017
+ const cfg = cfgFor(ctx);
1018
+ if (!cfg.server.enabled) return;
1019
+ try {
1020
+ server = new A2AServer({
1021
+ cfg,
1022
+ ctx,
1023
+ cwd: ctx.cwd,
1024
+ piDir: piDir(),
1025
+ runner: makeSessionRunner(ctx, cfg),
1026
+ api: pi,
1027
+ onActivity: (a) => broadcastActivity(pi, ctx, cfg, a),
1028
+ onStatus: statusSink(pi, ctx),
1029
+ onError: errorSink(ctx),
1030
+ });
1031
+ const info = await server.start();
1032
+ const defaultNote =
1033
+ cfg.server.port > 0 && info.port !== cfg.server.port
1034
+ ? ` (configured port ${cfg.server.port} was busy)`
1035
+ : "";
1036
+ ctx.ui.notify(
1037
+ `A2A server listening on ${info.host}:${info.port}${defaultNote}. Agent Card: ${info.url}.well-known/agent-card.json`,
1038
+ "info",
1039
+ );
1040
+ } catch (e: any) {
1041
+ // Non-fatal: port fallback already handled EADDRINUSE; this only fires on
1042
+ // a genuine bind failure (permissions, invalid host, …). Outbound tools
1043
+ // keep working; only inbound serving is unavailable for this session.
1044
+ server = null;
1045
+ ctx.ui.notify(
1046
+ `A2A inbound server unavailable (${e?.message || e}). Outbound a2a_* tools still work.`,
1047
+ "warning",
1048
+ );
1049
+ }
1050
+ });
1051
+
1052
+ pi.on("session_shutdown", async (_event, ctx) => {
1053
+ // Only the HOST session owns the inbound server. Child sessions share
1054
+ // this cached extension factory (the loader caches it per process), so
1055
+ // the session_shutdown makeSessionRunner now emits for each child would
1056
+ // otherwise stop the host's shared `server` mid-dispatch. Same host-only
1057
+ // classification as session_start above: children have hasUI=false and
1058
+ // mode "print"; json-mode hosts are long-lived HOSTS, not children —
1059
+ // they keep the shutdown.
1060
+ if (!ctx.hasUI && ctx.mode !== "json") return;
1061
+ if (server) {
1062
+ try {
1063
+ await server.stop();
1064
+ } catch {
1065
+ /* best-effort */
1066
+ }
1067
+ server = null;
1068
+ }
1069
+ });
1070
+ }
1071
+
1072
+ // ---------------------------------------------------------------------------
1073
+ // Restart bridge — the /config contribution (configPanel.ts) calls these to
1074
+ // apply a saved config to a RUNNING inbound server without /reload. Lifted
1075
+ // from the dropped /a2a-config save path.
1076
+ // ---------------------------------------------------------------------------
1077
+
1078
+ /** True when this session's inbound server is running. */
1079
+ export function a2aServerRunning(): boolean {
1080
+ return server !== null;
1081
+ }
1082
+
1083
+ /** Restart the inbound server with fresh config (stop → cfgFor → start).
1084
+ * No-op notification path when nothing is running; the caller gates on
1085
+ * a2aServerRunning() first. Errors surface as a toast and clear the
1086
+ * server handle (upstream /a2a-config restart semantics, verbatim). */
1087
+ export async function restartA2AServer(
1088
+ piApi: ExtensionAPI,
1089
+ ctx: ExtensionContext,
1090
+ ): Promise<void> {
1091
+ if (!server) return;
1092
+ ctx.ui.notify("A2A config changed — restarting inbound server…", "info");
1093
+ try {
1094
+ await server.stop();
1095
+ } catch {
1096
+ /* best-effort */
1097
+ }
1098
+ const fresh = cfgFor(ctx);
1099
+ server = new A2AServer({
1100
+ cfg: fresh,
1101
+ ctx,
1102
+ cwd: ctx.cwd,
1103
+ piDir: piDir(),
1104
+ runner: makeSessionRunner(ctx, fresh),
1105
+ api: piApi,
1106
+ onActivity: (a) => broadcastActivity(piApi, ctx, fresh, a),
1107
+ onStatus: statusSink(piApi, ctx),
1108
+ onError: errorSink(ctx),
1109
+ });
1110
+ try {
1111
+ const info = await server.start();
1112
+ ctx.ui.notify(`A2A server restarted on ${info.host}:${info.port}`, "info");
1113
+ } catch (e: any) {
1114
+ server = null;
1115
+ ctx.ui.notify(`A2A server restart failed: ${e?.message || e}`, "error");
1116
+ }
1117
+ }