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,920 @@
1
+ /**
2
+ * A2A config + peer registry.
3
+ *
4
+ * Config precedence (highest first): tool/command params → settings.json
5
+ * `a2a` key (project file ONLY when trusted + security-sanitized — ceulen
6
+ * port) → env (A2A_* via process.env; ceulen's bundle env.ts owns .env file
7
+ * ingestion) → defaults.
8
+ *
9
+ * NOTE: an explicit `discovery.gateway.enabled` in settings.json overrides
10
+ * `A2A_GATEWAY_ENABLED` (the env var only feeds the fallback when the
11
+ * settings field is absent).
12
+ *
13
+ * Multiple gateways (0.6.0): the legacy single `discovery.gateway` block
14
+ * (settings or env) coexists with the new `discovery.gateways` map. The
15
+ * canonical runtime view is `gatewayEntries(cfg)` — legacy yields the
16
+ * derived key `host-port` (fallback `default`), named entries yield their
17
+ * own keys. Every consumer (server lifecycle, overlay, panel, persistence)
18
+ * iterates that list only.
19
+ */
20
+
21
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
22
+ import { homedir } from "node:os";
23
+ import { dirname, join } from "node:path";
24
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
25
+ import { parsePeerTokens } from "./security";
26
+ import { isProjectTrusted } from "../../../lib/registry.js"; // ponytail: ceulen trust gate (project settings read only when trusted)
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Types
30
+ // ---------------------------------------------------------------------------
31
+
32
+ export type PeerTokensMap = Record<string, string>;
33
+
34
+ export interface PeerAuth {
35
+ type: "bearer" | "apiKey" | "none";
36
+ token?: string;
37
+ }
38
+
39
+ export interface Peer {
40
+ url: string;
41
+ auth: PeerAuth;
42
+ timeout: number;
43
+ capabilities: string[];
44
+ description?: string;
45
+ /** True for a2a-switchboard proxy peers (`gw/<key>/<name>`): the card fetch is
46
+ * skipped (a proxied card may advertise the peer's DIRECT url, which would
47
+ * bypass the gateway) and JSON-RPC is pinned to the proxy URL. */
48
+ viaGateway?: boolean;
49
+ /** Gateway origin that published this proxied peer (set by mergeGatewayPeers).
50
+ * Lets the client SSRF-pin the proxy URL to the peer's own gateway even
51
+ * when the live config has no gateway block (overlay-first routing). */
52
+ gatewayUrl?: string;
53
+ }
54
+
55
+ /** One upstream a2a-switchboard registration entry. */
56
+ export interface GatewayEntry {
57
+ /** Explicit on/off. Defaults to true when url+token are both set and no
58
+ * explicit value is given (backward compat); explicit false disables. */
59
+ enabled: boolean;
60
+ url: string;
61
+ token: string;
62
+ name?: string;
63
+ upstreamToken?: string;
64
+ heartbeatSec?: number;
65
+ /** Open a reverse channel so firewalled peers receive traffic (default true). */
66
+ channel?: boolean;
67
+ }
68
+
69
+ /** Gateway map keys must match the peer-name charset — they land in
70
+ * `gw/<key>/<name>` peer keys. */
71
+ export const GATEWAY_KEY_RE = /^[A-Za-z0-9._-]{1,64}$/;
72
+
73
+ /** Derive a stable gateway key from a gateway URL (host:port). */
74
+ export function gatewayKeyFromUrl(url: string): string {
75
+ try {
76
+ const u = new URL(url);
77
+ const host = u.hostname.replace(/[^A-Za-z0-9._-]/g, "-");
78
+ const port = u.port ? `-${u.port}` : "";
79
+ const key = `${host}${port}`;
80
+ return GATEWAY_KEY_RE.test(key) ? key : "default";
81
+ } catch {
82
+ return "default";
83
+ }
84
+ }
85
+
86
+ /** Canonical runtime view: every configured gateway as `{ key, entry }`.
87
+ * Legacy `discovery.gateway` (settings/env) maps to the derived key; the
88
+ * `discovery.gateways` map contributes its own keys (invalid keys skipped).
89
+ * A map entry whose key equals the legacy derived key wins — the legacy
90
+ * block is skipped so each key maps to exactly one upstream. */
91
+ export function gatewayEntries(cfg: A2AConfig): Array<{ key: string; entry: GatewayEntry }> {
92
+ const out: Array<{ key: string; entry: GatewayEntry }> = [];
93
+ const legacyKey = cfg.discovery.gateway ? gatewayKeyFromUrl(cfg.discovery.gateway.url) : null;
94
+ const mapKeys = new Set<string>();
95
+ for (const [key, entry] of Object.entries(cfg.discovery.gateways ?? {})) {
96
+ if (!GATEWAY_KEY_RE.test(key)) continue;
97
+ mapKeys.add(key);
98
+ out.push({ key, entry });
99
+ }
100
+ if (cfg.discovery.gateway && (!legacyKey || !mapKeys.has(legacyKey))) {
101
+ out.unshift({ key: legacyKey!, entry: cfg.discovery.gateway });
102
+ }
103
+ return out;
104
+ }
105
+
106
+ export interface A2AConfig {
107
+ peers: Record<string, Peer>;
108
+ /** Name THIS session presents as the caller identity (outbound). Maps to an
109
+ * entry in `server.peerTokens` — that token is attached to outbound calls so
110
+ * the receiver attributes the call to this session (not the shared token's
111
+ * anonymous `ip:` identity). Empty = use the shared token (anonymous caller). */
112
+ selfIdentity: string;
113
+ server: {
114
+ enabled: boolean;
115
+ port: number;
116
+ /** If the configured port is busy (EADDRINUSE), try up to this many
117
+ * consecutive ports before falling back to OS-assigned (0). 0 = configured
118
+ * port only, straight to OS-assigned on conflict. */
119
+ portFallback: number;
120
+ host: string;
121
+ workspace: string;
122
+ maxConcurrent: number;
123
+ /** Blocking-send supervision window in seconds — the HTTP request stays
124
+ * open at most this long. 0 = no reply-window timer (unbounded): the
125
+ * request stays open until the run settles. Deliberate, rare — same 0
126
+ * semantics as asyncTimeoutSec. */
127
+ replyTimeoutSec: number;
128
+ /** Supervision window for detached (returnImmediately) tasks, in seconds.
129
+ * The caller's HTTP request already returned an ACK, so the reply window
130
+ * does not apply — this bounds a detached run instead. 0 = unbounded
131
+ * (caller-supervised via GetTask / CancelTask). */
132
+ asyncTimeoutSec: number;
133
+ agentName: string;
134
+ publicUrl: string;
135
+ sharedToken: string;
136
+ peerTokens: PeerTokensMap;
137
+ trustedPeers: string[];
138
+ allowAllUsers: boolean;
139
+ maxPingpongTurns: number;
140
+ rateLimitPerMin: number;
141
+ /** Persist each dispatched child session's transcript to
142
+ * <agentDir>/a2a_sessions/<timestamp>_<taskId>.jsonl (fleet task #252).
143
+ * Stock pi-a2a ran children on an in-memory SessionManager, so a worker
144
+ * that stalled or was killed mid-run left no step history at all. On,
145
+ * every entry (user message, assistant turns, tool calls and results)
146
+ * is written synchronously and the file is a real pi session, openable
147
+ * with pi's own session tooling. Off = fully in-memory (stock). */
148
+ childTranscripts: boolean;
149
+ /** Delete child transcripts older than N days when the inbound server
150
+ * starts. 0 = keep forever. Transcripts carry everything the dispatched
151
+ * worker read, so keep the retention window bounded. */
152
+ childTranscriptRetentionDays: number;
153
+ skills: Array<{ id: string; name: string; description: string; tags?: string[] }>;
154
+ };
155
+ timeouts: { send: number; async: number; stream: number };
156
+ retryAttempts: number;
157
+ verifySsl: boolean;
158
+ /** Session self-declaration + local/network discovery (0.2.0). */
159
+ discovery: {
160
+ local: { enabled: boolean; heartbeatSec: number; ttlSec: number };
161
+ mdns: { enabled: boolean; serviceType: string };
162
+ /** Upstream a2a-switchboard registration (annex: gateway layer). */
163
+ gateway?: GatewayEntry;
164
+ /** Multiple upstream a2a-switchboard gateways (0.6.0) — keyed map; keys must match
165
+ * `[A-Za-z0-9._-]{1,64}` (they land in `gw/<key>/<name>` peer keys). */
166
+ gateways?: Record<string, GatewayEntry>;
167
+ enrichCard: boolean;
168
+ };
169
+ /** Host-TUI presentation (0.3.0). */
170
+ ui: {
171
+ /** Show inbound task activity as transcript messages (default true). When
172
+ * false, activity is still surfaced via notify() toasts + footer status. */
173
+ transcript: boolean;
174
+ };
175
+ }
176
+
177
+ const DEFAULTS: A2AConfig = {
178
+ peers: {},
179
+ selfIdentity: "",
180
+ server: {
181
+ enabled: false,
182
+ port: 9910,
183
+ portFallback: 10,
184
+ host: "127.0.0.1",
185
+ workspace: "",
186
+ maxConcurrent: 3,
187
+ replyTimeoutSec: 300,
188
+ asyncTimeoutSec: 86400,
189
+ agentName: "",
190
+ publicUrl: "",
191
+ sharedToken: "",
192
+ peerTokens: {},
193
+ trustedPeers: [],
194
+ allowAllUsers: false,
195
+ maxPingpongTurns: 5,
196
+ rateLimitPerMin: 60,
197
+ childTranscripts: true,
198
+ childTranscriptRetentionDays: 30,
199
+ skills: [],
200
+ },
201
+ timeouts: { send: 360000, async: 30000, stream: 120000 },
202
+ retryAttempts: 2,
203
+ verifySsl: true,
204
+ discovery: {
205
+ local: { enabled: true, heartbeatSec: 15, ttlSec: 60 },
206
+ mdns: { enabled: false, serviceType: "a2a" },
207
+ gateway: undefined,
208
+ enrichCard: true,
209
+ },
210
+ ui: { transcript: true },
211
+ };
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // Env — ceulen port: process.env ONLY. The upstream cwd→root .env.local walk
215
+ // is DELETED: ceulen's bundle env.ts already ingests agent-dir .env files at
216
+ // import + trusted-cwd .env files at session_start into process.env, so the
217
+ // env chain IS process.env. Stronger than upstream for the threat model: an
218
+ // untrusted repo's .env files never load at all (upstream only stripped
219
+ // SECURITY_ENV_KEYS from the walk). SECURITY_ENV_KEYS stays exported for the
220
+ // env/settings parity test.
221
+ // ---------------------------------------------------------------------------
222
+
223
+ /**
224
+ * Security-relevant A2A_* env keys — the surface that must never originate
225
+ * from repo-controlled files. In ceulen the bundle's trust-gated env.ts
226
+ * ingestion subsumes the old walk-strip: untrusted cwd .env files never
227
+ * load into process.env; trusted ones are operator-vouched (same trust
228
+ * level as upstream's global .env.local).
229
+ *
230
+ * Exported for the env/settings parity test: the set must cover the same
231
+ * server abuse-control surface that sanitizeRepoA2ASettings strips from
232
+ * repo-controlled settings.json.
233
+ */
234
+ export const SECURITY_ENV_KEYS: ReadonlySet<string> = new Set([
235
+ "A2A_SERVER_ENABLED",
236
+ "A2A_HOST",
237
+ "A2A_BEARER_TOKEN",
238
+ "A2A_PEER_TOKENS",
239
+ "A2A_TRUSTED_PEERS",
240
+ "A2A_ALLOW_ALL_USERS",
241
+ "A2A_MAX_PINGPONG_TURNS",
242
+ "A2A_RATE_LIMIT",
243
+ "A2A_CHILD_TRANSCRIPTS",
244
+ "A2A_CHILD_TRANSCRIPT_RETENTION_DAYS",
245
+ // Abuse-control parity with sanitizeRepoA2ASettings ("maxConcurrent",
246
+ // "replyTimeoutSec", "asyncTimeoutSec"): a repo must not be able to raise
247
+ // the concurrency ceiling or stretch either supervision window
248
+ // (asyncTimeoutSec 0 = unbounded; a huge window pins maxConcurrent slots
249
+ // for the whole window).
250
+ "A2A_MAX_CONCURRENT",
251
+ "A2A_REPLY_TIMEOUT",
252
+ "A2A_ASYNC_TIMEOUT",
253
+ "A2A_VERIFY_SSL",
254
+ "A2A_DISCOVERY_MDNS",
255
+ "A2A_ENRICH_CARD",
256
+ "A2A_GATEWAY_URL",
257
+ "A2A_GATEWAY_TOKEN",
258
+ "A2A_GATEWAY_ENABLED",
259
+ "A2A_PUBLIC_URL",
260
+ ]);
261
+
262
+ export function loadEnv(_cwd: string): Record<string, string> {
263
+ // ceulen port: process.env is the ONLY env source (env.ts owns file ingestion).
264
+ const env: Record<string, string> = {};
265
+ for (const [k, v] of Object.entries(process.env)) {
266
+ if (typeof v === "string" && k.startsWith("A2A_")) env[k] = v;
267
+ }
268
+ return env;
269
+ }
270
+
271
+ // ---------------------------------------------------------------------------
272
+ // Settings.json `a2a` key reader
273
+ // ---------------------------------------------------------------------------
274
+
275
+ /** Security-relevant a2a settings paths stripped from a REPO-CONTROLLED
276
+ * `.pi/settings.json` (same threat model as SECURITY_ENV_KEYS: a repo the
277
+ * agent opens must not enable the server, widen the bind, install tokens,
278
+ * redirect the gateway, or disable TLS verification). */
279
+ function sanitizeRepoA2ASettings(s: any): any {
280
+ if (!s || typeof s !== "object") return s;
281
+ const c = { ...s };
282
+ if (c.server && typeof c.server === "object") {
283
+ const srv = { ...c.server };
284
+ for (const k of [
285
+ "enabled",
286
+ "host",
287
+ "sharedToken",
288
+ "peerTokens",
289
+ "trustedPeers",
290
+ "allowAllUsers",
291
+ "publicUrl",
292
+ // Abuse-control parity with SECURITY_ENV_KEYS (A2A_RATE_LIMIT,
293
+ // A2A_MAX_PINGPONG_TURNS) — a repo must not be able to neuter rate
294
+ // limiting, the anti-loop cap, or the concurrency ceiling.
295
+ "rateLimitPerMin",
296
+ "maxPingpongTurns",
297
+ "maxConcurrent",
298
+ "replyTimeoutSec",
299
+ // Audit-trail parity with SECURITY_ENV_KEYS (A2A_CHILD_TRANSCRIPTS,
300
+ // A2A_CHILD_TRANSCRIPT_RETENTION_DAYS) — a repo must not be able to
301
+ // opt its dispatched runs out of the #252 transcript audit trail, nor
302
+ // move the retention window (aggressive evidence deletion at 0/1 day,
303
+ // keep-forever disk-fill when raised).
304
+ "childTranscripts",
305
+ "childTranscriptRetentionDays",
306
+ "asyncTimeoutSec",
307
+ ])
308
+ delete srv[k];
309
+ c.server = srv;
310
+ }
311
+ if (c.discovery && typeof c.discovery === "object") {
312
+ const d = { ...c.discovery };
313
+ delete d.gateway; // url + token
314
+ delete d.gateways; // multi-gateway map (tokens)
315
+ // Disclosure-flipping flags: repo files must not be able to force mDNS
316
+ // LAN broadcast (TXT leaks cwd + model) or card enrichment (cwd/pid/
317
+ // model/tools in the public agent card).
318
+ if (d.mdns && typeof d.mdns === "object") delete d.mdns.enabled;
319
+ delete d.enrichCard;
320
+ c.discovery = d;
321
+ }
322
+ delete c.verifySsl;
323
+ return c;
324
+ }
325
+
326
+ function readSettingsA2A(ctx: ExtensionContext | undefined, cwd: string): { s: any; fromRepo: boolean } {
327
+ // Try the SDK settings infra first (object form), then on-disk settings.json.
328
+ // The ctx form is sanitized defensively (and flagged repo-scope): the current
329
+ // SDK's ExtensionContext has no `settings` property (dead code today), but a
330
+ // future layered-settings SDK could merge project scope in — sanitize, and
331
+ // if a key is stripped that only existed there, the operator's own on-disk
332
+ // files below still supply it. (Security review follow-up.)
333
+ const fromCtx = (ctx as any)?.settings?.a2a;
334
+ if (fromCtx && typeof fromCtx === "object" && !Array.isArray(fromCtx))
335
+ return { s: sanitizeRepoA2ASettings(fromCtx), fromRepo: true };
336
+ // ceulen port: the repo-controlled project file is read ONLY when the
337
+ // project is TRUSTED (router/munin/web rule — an untrusted checkout must
338
+ // not redirect anything, peers included). When trusted, the security
339
+ // sanitize still applies verbatim: server-relevant keys remain
340
+ // global-only even from a trusted project (upstream hardening kept).
341
+ const repoSettings = join(cwd, ".pi", "settings.json");
342
+ const projectEligible = isProjectTrusted(cwd);
343
+ // When PI_CODING_AGENT_DIR is set (tests use this for isolation), do NOT fall
344
+ // back to the operator's hardcoded ~/.pi/agent path — only cwd + that dir.
345
+ const explicit = process.env.PI_CODING_AGENT_DIR;
346
+ const candidates = explicit
347
+ ? [projectEligible ? repoSettings : null, join(explicit, "settings.json")].filter((p): p is string => p !== null)
348
+ : [
349
+ ...(projectEligible ? [repoSettings] : []),
350
+ join(homedir(), ".pi", "agent", "settings.json"),
351
+ join(homedir(), ".pi", "agents", "settings.json"),
352
+ ];
353
+ for (const p of candidates) {
354
+ if (!existsSync(p)) continue;
355
+ try {
356
+ const j = JSON.parse(readFileSync(p, "utf-8"));
357
+ if (j?.a2a && typeof j.a2a === "object")
358
+ return { s: p === repoSettings ? sanitizeRepoA2ASettings(j.a2a) : j.a2a, fromRepo: p === repoSettings };
359
+ } catch {
360
+ /* ignore */
361
+ }
362
+ }
363
+ return { s: {}, fromRepo: false };
364
+ }
365
+
366
+ // ---------------------------------------------------------------------------
367
+ // Merge settings + env into config
368
+ // ---------------------------------------------------------------------------
369
+
370
+ function num(v: any, fallback: number): number {
371
+ const n = typeof v === "string" ? parseInt(v, 10) : v;
372
+ return Number.isFinite(n) ? n : fallback;
373
+ }
374
+
375
+ function bool(v: any, fallback: boolean): boolean {
376
+ if (typeof v === "boolean") return v;
377
+ if (typeof v === "string") return /^(1|true|yes|on)$/i.test(v.trim());
378
+ return fallback;
379
+ }
380
+
381
+ export function loadConfig(opts: {
382
+ ctx?: ExtensionContext;
383
+ cwd: string;
384
+ env?: Record<string, string>;
385
+ }): A2AConfig {
386
+ const { ctx, cwd } = opts;
387
+ const env = opts.env ?? loadEnv(cwd);
388
+ const { s, fromRepo: settingsFromRepo } = readSettingsA2A(ctx, cwd);
389
+
390
+ const cfg: A2AConfig = {
391
+ peers: {},
392
+ selfIdentity: "",
393
+ server: { ...DEFAULTS.server },
394
+ timeouts: { ...DEFAULTS.timeouts },
395
+ retryAttempts: DEFAULTS.retryAttempts,
396
+ verifySsl: DEFAULTS.verifySsl,
397
+ discovery: {
398
+ local: { ...DEFAULTS.discovery.local },
399
+ mdns: { ...DEFAULTS.discovery.mdns },
400
+ enrichCard: DEFAULTS.discovery.enrichCard,
401
+ },
402
+ ui: { ...DEFAULTS.ui },
403
+ };
404
+
405
+ // Peers from settings.json `a2a.peers`
406
+ const peers = (s.peers && typeof s.peers === "object" ? s.peers : {}) as Record<string, any>;
407
+ // Reset per load: only peers from a REPO-SCOPE settings file get flagged.
408
+ repoPeerUrls = new Set();
409
+ for (const [name, entry] of Object.entries(peers)) {
410
+ if (!entry || typeof entry !== "object") continue;
411
+ cfg.peers[name] = {
412
+ url: String(entry.url || ""),
413
+ auth: {
414
+ type: (entry.auth?.type as PeerAuth["type"]) || "none",
415
+ token: entry.auth?.token,
416
+ },
417
+ timeout: num(entry.timeout, DEFAULTS.timeouts.send / 1000) * 1000,
418
+ capabilities: Array.isArray(entry.capabilities) ? entry.capabilities.map(String) : [],
419
+ description: entry.description ? String(entry.description) : undefined,
420
+ };
421
+ if (settingsFromRepo && cfg.peers[name]!.url) repoPeerUrls.add(normUrl(cfg.peers[name]!.url));
422
+ }
423
+
424
+ // Server settings
425
+ const srv = (s.server && typeof s.server === "object" ? s.server : {}) as Record<string, any>;
426
+ cfg.server.enabled = bool(srv.enabled ?? env.A2A_SERVER_ENABLED, DEFAULTS.server.enabled);
427
+ cfg.server.port = num(srv.port ?? env.A2A_PORT, DEFAULTS.server.port);
428
+ cfg.server.portFallback = num(srv.portFallback ?? env.A2A_PORT_FALLBACK, DEFAULTS.server.portFallback);
429
+ cfg.server.host = String(srv.host ?? env.A2A_HOST ?? DEFAULTS.server.host);
430
+ cfg.server.workspace = String(srv.workspace ?? "");
431
+ cfg.server.maxConcurrent = num(srv.maxConcurrent, DEFAULTS.server.maxConcurrent);
432
+ cfg.server.replyTimeoutSec = num(srv.replyTimeoutSec ?? env.A2A_REPLY_TIMEOUT, DEFAULTS.server.replyTimeoutSec);
433
+ cfg.server.asyncTimeoutSec = num(srv.asyncTimeoutSec ?? env.A2A_ASYNC_TIMEOUT, DEFAULTS.server.asyncTimeoutSec);
434
+ cfg.server.agentName = String(srv.agentName ?? env.A2A_AGENT_NAME ?? "");
435
+ cfg.server.publicUrl = String(srv.publicUrl ?? env.A2A_PUBLIC_URL ?? "");
436
+ cfg.server.sharedToken = String(srv.sharedToken ?? env.A2A_BEARER_TOKEN ?? "");
437
+ // Object form (README-documented: `"peerTokens": { "alice": "tok-a" }`) —
438
+ // keep only string-valued entries. String + env paths unchanged.
439
+ cfg.server.peerTokens =
440
+ srv.peerTokens && typeof srv.peerTokens === "object"
441
+ ? Object.entries(srv.peerTokens)
442
+ .filter(([, v]) => typeof v === "string" && v)
443
+ .reduce<Record<string, string>>((m, [k, v]) => ((m[k] = v as string), m), {})
444
+ : parsePeerTokens(
445
+ typeof srv.peerTokens === "string"
446
+ ? srv.peerTokens
447
+ : env.A2A_PEER_TOKENS,
448
+ );
449
+ cfg.server.trustedPeers = Array.isArray(srv.trustedPeers)
450
+ ? srv.trustedPeers.map(String)
451
+ : (env.A2A_TRUSTED_PEERS || "").split(",").map((x) => x.trim()).filter(Boolean);
452
+ cfg.server.allowAllUsers = bool(srv.allowAllUsers ?? env.A2A_ALLOW_ALL_USERS, DEFAULTS.server.allowAllUsers);
453
+ cfg.server.maxPingpongTurns = num(srv.maxPingpongTurns ?? env.A2A_MAX_PINGPONG_TURNS, DEFAULTS.server.maxPingpongTurns);
454
+ cfg.server.rateLimitPerMin = num(srv.rateLimitPerMin ?? env.A2A_RATE_LIMIT, DEFAULTS.server.rateLimitPerMin);
455
+ cfg.server.childTranscripts = bool(
456
+ srv.childTranscripts ?? env.A2A_CHILD_TRANSCRIPTS,
457
+ DEFAULTS.server.childTranscripts,
458
+ );
459
+ cfg.server.childTranscriptRetentionDays = num(
460
+ srv.childTranscriptRetentionDays ?? env.A2A_CHILD_TRANSCRIPT_RETENTION_DAYS,
461
+ DEFAULTS.server.childTranscriptRetentionDays,
462
+ );
463
+ cfg.server.skills = Array.isArray(srv.skills) ? srv.skills : [];
464
+
465
+ // Timeouts
466
+ const t = (s.timeouts && typeof s.timeouts === "object" ? s.timeouts : {}) as Record<string, any>;
467
+ cfg.timeouts.send = num(t.send, DEFAULTS.timeouts.send);
468
+ cfg.timeouts.async = num(t.async, DEFAULTS.timeouts.async);
469
+ cfg.timeouts.stream = num(t.stream, DEFAULTS.timeouts.stream);
470
+
471
+ cfg.retryAttempts = num(s.retryAttempts, DEFAULTS.retryAttempts);
472
+ cfg.verifySsl = bool(s.verifySsl ?? env.A2A_VERIFY_SSL, DEFAULTS.verifySsl);
473
+
474
+ // Discovery (0.2.0)
475
+ const d = (s.discovery && typeof s.discovery === "object" ? s.discovery : {}) as Record<string, any>;
476
+ const dl = (d.local && typeof d.local === "object" ? d.local : {}) as Record<string, any>;
477
+ const dm = (d.mdns && typeof d.mdns === "object" ? d.mdns : {}) as Record<string, any>;
478
+ cfg.discovery.local.enabled = bool(dl.enabled ?? env.A2A_DISCOVERY_LOCAL, DEFAULTS.discovery.local.enabled);
479
+ cfg.discovery.local.heartbeatSec = num(dl.heartbeatSec ?? env.A2A_HEARTBEAT_SEC, DEFAULTS.discovery.local.heartbeatSec);
480
+ cfg.discovery.local.ttlSec = num(dl.ttlSec ?? env.A2A_TTL_SEC, DEFAULTS.discovery.local.ttlSec);
481
+ cfg.discovery.mdns.enabled = bool(dm.enabled ?? d.mdnsEnabled ?? env.A2A_DISCOVERY_MDNS, DEFAULTS.discovery.mdns.enabled);
482
+ cfg.discovery.mdns.serviceType = String(dm.serviceType ?? env.A2A_MDNS_TYPE ?? DEFAULTS.discovery.mdns.serviceType);
483
+ cfg.discovery.enrichCard = bool(d.enrichCard ?? env.A2A_ENRICH_CARD, DEFAULTS.discovery.enrichCard);
484
+
485
+ // Upstream a2a-switchboard registration. The block is materialized whenever
486
+ // ANY gateway config exists (settings `dg` has fields, or url/token from
487
+ // env) so the panel can display/edit it — including explicitly-disabled
488
+ // gateways (enabled:false), which must stay visible or unrelated discovery
489
+ // edits would erase them. Registration only happens when enabled AND
490
+ // url+token are set. `enabled` defaults to true when url+token exist and
491
+ // no explicit value (backward compat with the pre-0.5.0 implicit activation).
492
+ const dg = (d.gateway && typeof d.gateway === "object" ? d.gateway : {}) as Record<string, any>;
493
+ const gwUrl = String(dg.url ?? env.A2A_GATEWAY_URL ?? "");
494
+ const gwToken = String(dg.token ?? env.A2A_GATEWAY_TOKEN ?? "");
495
+ const hasSettingsGateway = Object.keys(dg).length > 0;
496
+ const gwEnabled =
497
+ dg.enabled !== undefined
498
+ ? bool(dg.enabled, true)
499
+ : bool(env.A2A_GATEWAY_ENABLED, Boolean(gwUrl && gwToken));
500
+ if (hasSettingsGateway || gwUrl || gwToken) {
501
+ cfg.discovery.gateway = {
502
+ enabled: gwEnabled,
503
+ url: gwUrl,
504
+ token: gwToken,
505
+ name: dg.name ? String(dg.name) : undefined,
506
+ upstreamToken: dg.upstreamToken ? String(dg.upstreamToken) : undefined,
507
+ heartbeatSec: num(dg.heartbeatSec, 60),
508
+ channel: dg.channel === undefined ? undefined : bool(dg.channel, true),
509
+ };
510
+ }
511
+
512
+ // Multiple gateways (0.6.0): the `discovery.gateways` map. Same per-entry
513
+ // materialization as the legacy block; invalid keys are skipped (they would
514
+ // pollute the `gw/<key>/` peer namespace).
515
+ const dgs = (d.gateways && typeof d.gateways === "object" ? d.gateways : {}) as Record<string, any>;
516
+ const gateways: Record<string, GatewayEntry> = {};
517
+ for (const [key, raw] of Object.entries(dgs)) {
518
+ if (!GATEWAY_KEY_RE.test(key)) continue;
519
+ if (!raw || typeof raw !== "object") continue;
520
+ const g = raw as Record<string, any>;
521
+ const u = String(g.url ?? "");
522
+ const t = String(g.token ?? "");
523
+ const enabled = g.enabled !== undefined ? bool(g.enabled, true) : Boolean(u && t);
524
+ gateways[key] = {
525
+ enabled,
526
+ url: u,
527
+ token: t,
528
+ name: g.name ? String(g.name) : undefined,
529
+ upstreamToken: g.upstreamToken ? String(g.upstreamToken) : undefined,
530
+ heartbeatSec: num(g.heartbeatSec, 60),
531
+ channel: g.channel === undefined ? undefined : bool(g.channel, true),
532
+ };
533
+ }
534
+ if (Object.keys(gateways).length > 0) cfg.discovery.gateways = gateways;
535
+
536
+ // Outbound caller identity (0.2.0): the name THIS session presents. Must
537
+ // match an entry in server.peerTokens so the receiver attributes the call
538
+ // here. Empty → fall back to the shared token (anonymous caller).
539
+ cfg.selfIdentity = String(s.selfIdentity ?? env.A2A_SELF_IDENTITY ?? "");
540
+
541
+ // Host-TUI presentation (0.3.0)
542
+ const ui = (s.ui && typeof s.ui === "object" ? s.ui : {}) as Record<string, any>;
543
+ cfg.ui.transcript = bool(ui.transcript ?? env.A2A_UI_TRANSCRIPT, DEFAULTS.ui.transcript);
544
+
545
+ // Live in-memory overrides (set by the /a2a-config panel) — highest
546
+ // precedence, above env + settings.json, so panel edits apply immediately
547
+ // without /reload.
548
+ if (configOverrides) applyOverrides(cfg, configOverrides);
549
+
550
+ return cfg;
551
+ }
552
+
553
+ // ---------------------------------------------------------------------------
554
+ // Live config overrides (0.3.0) — panel edits apply without /reload
555
+ // ---------------------------------------------------------------------------
556
+
557
+ let configOverrides: Partial<A2AConfig> | null = null;
558
+
559
+ /** Replace the live in-memory config overrides (null clears them). */
560
+ export function setConfigOverrides(patch: Partial<A2AConfig> | null): void {
561
+ configOverrides = patch;
562
+ }
563
+
564
+ /** Merge a partial A2AConfig onto a full config (deep for known nested blocks). */
565
+ function applyOverrides(cfg: A2AConfig, patch: Partial<A2AConfig>): void {
566
+ if (patch.peers) cfg.peers = patch.peers;
567
+ if (patch.selfIdentity !== undefined) cfg.selfIdentity = patch.selfIdentity;
568
+ if (patch.server) Object.assign(cfg.server, patch.server);
569
+ if (patch.timeouts) Object.assign(cfg.timeouts, patch.timeouts);
570
+ if (patch.retryAttempts !== undefined) cfg.retryAttempts = patch.retryAttempts;
571
+ if (patch.verifySsl !== undefined) cfg.verifySsl = patch.verifySsl;
572
+ if (patch.discovery) {
573
+ if (patch.discovery.local) Object.assign(cfg.discovery.local, patch.discovery.local);
574
+ if (patch.discovery.mdns) Object.assign(cfg.discovery.mdns, patch.discovery.mdns);
575
+ if (patch.discovery.enrichCard !== undefined) cfg.discovery.enrichCard = patch.discovery.enrichCard;
576
+ // Gateway block(s) — undefined (not set) leaves them alone; set replaces.
577
+ if (patch.discovery.gateway !== undefined) cfg.discovery.gateway = patch.discovery.gateway;
578
+ if (patch.discovery.gateways !== undefined) cfg.discovery.gateways = patch.discovery.gateways;
579
+ }
580
+ if (patch.ui) Object.assign(cfg.ui, patch.ui);
581
+ }
582
+
583
+ // ---------------------------------------------------------------------------
584
+ // Settings.json writer (0.3.0) — the /a2a-config panel persists edits here
585
+ // ---------------------------------------------------------------------------
586
+
587
+ /**
588
+ * Build the settings.json patch for the /a2a-config panel (pure, testable).
589
+ *
590
+ * Rules:
591
+ * - server persisted ONLY when a server field changed (env-sourced secrets
592
+ * like sharedToken/peerTokens must never be copied to disk by a
593
+ * discovery-only edit).
594
+ * - discovery is MERGED over the existing `a2a.discovery` (a gateway block
595
+ * already in settings.json survives unrelated discovery edits
596
+ * byte-for-byte); the gateway sub-block is written only when the user
597
+ * actually edited a gateway field, so env-sourced secrets are not copied.
598
+ * - When the gateway block is written, unedited rows (token / upstreamToken
599
+ * / name) keep the value from the EXISTING settings file (not the
600
+ * env-sourced working value) — a heartbeat-only edit must not copy an env
601
+ * token to disk, and the runtime-resolved registration name must never be
602
+ * pinned. `editedGatewayKeys` carries the row keys the user touched
603
+ * (gateway.token / gateway.upstreamToken / gateway.name).
604
+ * - The same per-entry rules apply to the `discovery.gateways` map (0.6.0):
605
+ * entries keep unedited secret fields from the file; env-sourced entries
606
+ * (not in settings.json) are not written unless their key was edited;
607
+ * row keys are `gw.<key>.token` etc.
608
+ * - peers/selfIdentity/ui persisted only when changed.
609
+ */
610
+ export function buildA2ASettingsPatch(opts: {
611
+ cfg: A2AConfig;
612
+ working: A2AConfig;
613
+ peerChanges: boolean;
614
+ gatewayChanged: boolean;
615
+ /** Row keys the user edited (gateway.* / gw.<key>.*). */
616
+ editedGatewayKeys?: Set<string>;
617
+ }): (a2a: any) => any {
618
+ const { cfg, working, peerChanges, gatewayChanged, editedGatewayKeys } = opts;
619
+ const serverChanged = JSON.stringify(working.server) !== JSON.stringify(cfg.server);
620
+ const discoveryChanged = JSON.stringify(working.discovery) !== JSON.stringify(cfg.discovery);
621
+ const workingDiscovery = { ...working.discovery } as Record<string, unknown>;
622
+ if (!gatewayChanged) delete workingDiscovery.gateway;
623
+ if (!gatewayChanged) delete workingDiscovery.gateways;
624
+ return (a2a: any) => {
625
+ // The server block is persisted wholesale ONLY when a server field
626
+ // changed — but the panel never exposes sharedToken/peerTokens/workspace/
627
+ // publicUrl/skills, so those keep the value from the EXISTING settings
628
+ // file (never copy env-sourced secrets to disk on a port/host edit).
629
+ let serverPatch: Record<string, unknown> | undefined;
630
+ if (serverChanged) {
631
+ serverPatch = { ...working.server } as Record<string, unknown>;
632
+ const ex = (a2a.server ?? {}) as Record<string, unknown>;
633
+ serverPatch.sharedToken = ex.sharedToken ?? "";
634
+ serverPatch.peerTokens = ex.peerTokens ?? {};
635
+ serverPatch.workspace = ex.workspace ?? "";
636
+ serverPatch.publicUrl = ex.publicUrl ?? "";
637
+ serverPatch.skills = ex.skills ?? [];
638
+ }
639
+ // Merge discovery over the existing settings block; the gateway sub-block
640
+ // (when written) keeps unedited secret fields from the file.
641
+ const mergedDiscovery = { ...(a2a.discovery ?? {}) } as Record<string, unknown>;
642
+ // ALWAYS merge the non-gateway working discovery (local/mdns/enrichCard)
643
+ // over the file block — a combined gateway + discovery edit must keep
644
+ // both. Only the gateway sub-blocks get the special unedited-secret
645
+ // handling below.
646
+ const { gateway: _gw, gateways: _gws, ...workingRest } = workingDiscovery;
647
+ Object.assign(mergedDiscovery, workingRest);
648
+ if (gatewayChanged && workingDiscovery.gateway && typeof workingDiscovery.gateway === "object") {
649
+ const g = { ...(workingDiscovery.gateway as Record<string, unknown>) };
650
+ const existing = (mergedDiscovery.gateway ?? {}) as Record<string, unknown>;
651
+ if (!editedGatewayKeys?.has("gateway.token")) g.token = existing.token ?? "";
652
+ if (!editedGatewayKeys?.has("gateway.upstreamToken")) g.upstreamToken = existing.upstreamToken;
653
+ // The registration name is runtime-resolved (server auto-name) unless
654
+ // the user typed it — never persist an ephemeral per-session name.
655
+ if (!editedGatewayKeys?.has("gateway.name")) g.name = existing.name ?? "";
656
+ mergedDiscovery.gateway = g;
657
+ }
658
+ // Same rules for the `gateways` map: merge per-entry over the file's
659
+ // entries, keeping unedited secrets from the file; drop entries the user
660
+ // removed (present in file but not in working).
661
+ if (gatewayChanged && workingDiscovery.gateways && typeof workingDiscovery.gateways === "object") {
662
+ const wg = workingDiscovery.gateways as Record<string, Record<string, unknown>>;
663
+ const existing = (mergedDiscovery.gateways ?? {}) as Record<string, Record<string, unknown>>;
664
+ const out: Record<string, Record<string, unknown>> = {};
665
+ for (const [key, entry] of Object.entries(wg)) {
666
+ const e = { ...entry };
667
+ const ex = existing[key];
668
+ if (ex) {
669
+ // Entry already in settings.json: keep unedited secret fields from
670
+ // the file (a heartbeat-only edit must not copy an env token, and
671
+ // the runtime-resolved registration name must never be pinned).
672
+ if (!editedGatewayKeys?.has(`gw.${key}.token`)) e.token = ex.token ?? "";
673
+ if (!editedGatewayKeys?.has(`gw.${key}.upstreamToken`)) e.upstreamToken = ex.upstreamToken;
674
+ if (!editedGatewayKeys?.has(`gw.${key}.name`)) e.name = ex.name ?? "";
675
+ }
676
+ // Entry absent from the file → NEW (panel-added or override-typed,
677
+ // since discovery.gateways has no env source): persist verbatim so a
678
+ // token typed in the add-flow is not wiped. Fall through.
679
+ out[key] = e;
680
+ }
681
+ mergedDiscovery.gateways = out;
682
+ }
683
+ return {
684
+ ...a2a,
685
+ ...(serverPatch ? { server: serverPatch } : {}),
686
+ // Peers persist in SETTINGS units: timeout in seconds (the loader
687
+ // multiplies by 1000 on read). working.peers holds runtime ms —
688
+ // this is the single writer-side conversion, so panel saves and
689
+ // panel-added peers are idempotent (no 1000× drift per save).
690
+ ...(peerChanges
691
+ ? {
692
+ peers: Object.fromEntries(
693
+ Object.entries(working.peers).map(([name, p]) => [name, { ...p, timeout: Math.round(p.timeout / 1000) }]),
694
+ ),
695
+ }
696
+ : {}),
697
+ ...(discoveryChanged ? { discovery: mergedDiscovery } : {}),
698
+ ...(working.selfIdentity !== cfg.selfIdentity ? { selfIdentity: working.selfIdentity } : {}),
699
+ ...(JSON.stringify(working.ui) !== JSON.stringify(cfg.ui) ? { ui: working.ui } : {}),
700
+ };
701
+ };
702
+ }
703
+
704
+ /**
705
+ * Read-modify-write the `a2a` key in settings.json, preserving all other keys.
706
+ *
707
+ * Target resolution mirrors readSettingsA2A: the first existing file that has
708
+ * an `a2a` key, else the global settings path (PI_CODING_AGENT_DIR, then
709
+ * ~/.pi/agent — the canonical Pi agent dir; never ~/.pi/agents).
710
+ *
711
+ * ponytail: no file lock (SDK uses proper-lockfile internally, but that's a
712
+ * dependency we don't need) — settings edits are rare human actions, and the
713
+ * atomic rename prevents torn writes. Concurrent external edits are out of
714
+ * scope.
715
+ */
716
+ export function writeSettingsA2A(opts: {
717
+ cwd: string;
718
+ patch: (a2a: any) => any;
719
+ }): string {
720
+ const { cwd, patch } = opts;
721
+ const explicit = process.env.PI_CODING_AGENT_DIR;
722
+ const candidates = explicit
723
+ ? [join(cwd, ".pi", "settings.json"), join(explicit, "settings.json")]
724
+ : [
725
+ join(cwd, ".pi", "settings.json"),
726
+ join(homedir(), ".pi", "agent", "settings.json"),
727
+ join(homedir(), ".pi", "agents", "settings.json"),
728
+ ];
729
+
730
+ // Prefer the first file that already has an `a2a` key — but NEVER the
731
+ // repo-controlled cwd file: the operator's tokens (peer tokens, gateway
732
+ // token) saved from the config panel must not land in a file a repo ships
733
+ // or an attacker pre-seeds. (That file is also never re-read unsanitized —
734
+ // readSettingsA2A strips security keys from it.)
735
+ let target: string | undefined;
736
+ const repoSettings = join(cwd, ".pi", "settings.json");
737
+ for (const p of candidates) {
738
+ if (p === repoSettings) continue;
739
+ if (!existsSync(p)) continue;
740
+ try {
741
+ const j = JSON.parse(readFileSync(p, "utf-8"));
742
+ if (j?.a2a && typeof j.a2a === "object") {
743
+ target = p;
744
+ break;
745
+ }
746
+ } catch {
747
+ /* unreadable — try next */
748
+ }
749
+ }
750
+ // Fall back to the canonical global settings file (Pi's getAgentDir()),
751
+ // NOT the last candidate — in the non-explicit branch that is the legacy
752
+ // ~/.pi/agents path, which Pi never reads; a fresh save there would render
753
+ // an orphan a2a block invisible to the real settings.
754
+ target ??= explicit
755
+ ? candidates[candidates.length - 1]!
756
+ : join(homedir(), ".pi", "agent", "settings.json");
757
+
758
+ const dir = dirname(target);
759
+ mkdirSync(dir, { recursive: true });
760
+ let json: any = {};
761
+ try {
762
+ json = existsSync(target) ? JSON.parse(readFileSync(target, "utf-8")) : {};
763
+ } catch {
764
+ json = {}; // corrupt file → start fresh (still preserving nothing, safest)
765
+ }
766
+ if (!json.a2a || typeof json.a2a !== "object" || Array.isArray(json.a2a)) json.a2a = {};
767
+ json.a2a = patch(json.a2a) ?? json.a2a;
768
+
769
+ // Atomic write: temp file + rename.
770
+ const tmp = target + ".tmp";
771
+ writeFileSync(tmp, JSON.stringify(json, null, 2) + "\n", "utf-8");
772
+ renameSync(tmp, target);
773
+ return target;
774
+ }
775
+
776
+ // ---------------------------------------------------------------------------
777
+ // Peer registry
778
+ // ---------------------------------------------------------------------------
779
+
780
+ /** Loopback peer URLs that came from a REPO-CONTROLLED settings file. They
781
+ * may be CALLED (repo's own choice of endpoint) but never auto-attach the
782
+ * operator's shared token — the "known loopback peer" trust assumption
783
+ * (same machine, same user, operator-configured) does not hold for them. */
784
+ let repoPeerUrls = new Set<string>();
785
+
786
+ /** Normalize a URL for dedupe/comparison (lowercase, trailing slashes stripped). */
787
+ export function normUrl(u: string): string {
788
+ return String(u || "").trim().replace(/\/+$/, "").toLowerCase();
789
+ }
790
+
791
+ /** Clean an OS hostname for use as a peer-name base: strip mDNS suffixes
792
+ * (`MBP-Sao.local` → `mbp-sao`) and lowercase. Empty/missing → "pi". */
793
+ export function cleanHostName(host: string | undefined): string {
794
+ const h = String(host || "").replace(/\.(local|lan)\.?$/i, "").trim().toLowerCase();
795
+ return h || "pi";
796
+ }
797
+
798
+ /** Resolve a peer by configured name OR treat as a direct http(s) URL.
799
+ * When the direct URL is loopback AND listed in `knownLoopbackUrls` (known
800
+ * peers: configured peers or local-registry entries — same-machine, same
801
+ * user), a token is auto-attached so discovered local Pi sessions are callable
802
+ * without manual per-peer config. Token preference:
803
+ * 1. THIS session's own peer token (cfg.selfIdentity → cfg.server.peerTokens)
804
+ * so the receiver attributes the call to this named session.
805
+ * 2. else the shared token (anonymous caller).
806
+ * Arbitrary loopback URLs are NOT trusted: a prompt-injected localhost URL
807
+ * must never receive any credential. */
808
+ export function resolvePeer(
809
+ cfg: A2AConfig,
810
+ agent: string,
811
+ opts?: { knownLoopbackUrls?: Set<string> },
812
+ ): Peer | null {
813
+ const a = String(agent || "").trim();
814
+ if (!a) return null;
815
+ if (/^https?:\/\//i.test(a)) {
816
+ const url = a;
817
+ let auth: PeerAuth = { type: "none" };
818
+ if (
819
+ isLoopbackHost(url) &&
820
+ opts?.knownLoopbackUrls?.has(normUrl(url)) &&
821
+ // Repo-sourced peer entries never qualify for auto-attach: the operator
822
+ // never vouched for that endpoint, so it must not receive any credential.
823
+ !repoPeerUrls.has(normUrl(url))
824
+ ) {
825
+ const token = outboundToken(cfg);
826
+ if (token) auth = { type: "bearer", token };
827
+ }
828
+ return { url, auth, timeout: cfg.timeouts.send, capabilities: [] };
829
+ }
830
+ // Gateway overlay sits BEHIND static config: a configured peer with the
831
+ // same name always wins (overlay is read-only, never overrides settings).
832
+ return cfg.peers[a] ?? getGatewayPeers()[a] ?? null;
833
+ }
834
+
835
+ // ---------------------------------------------------------------------------
836
+ // Gateway peer overlay (read-only, in-memory — never persisted to settings.json)
837
+ // ---------------------------------------------------------------------------
838
+
839
+ /** Per-gateway overlay slices, keyed by gateway key. Each GatewayUpstream
840
+ * instance refreshes its own slice; getGatewayPeers() flattens them. */
841
+ const gatewayOverlays: Record<string, Record<string, Peer>> = {};
842
+
843
+ /** Replace ONE gateway's overlay slice (`{}` clears just that gateway — the
844
+ * other gateways' peers stay visible). Keys are the callable names
845
+ * (`gw/<key>/<name>`), values are ready-to-route peers. */
846
+ export function updateGatewayPeers(key: string, peers: Record<string, Peer>): void {
847
+ gatewayOverlays[key] = peers;
848
+ }
849
+
850
+ /** Alias kept for backward compat with existing tests/callers: updates the
851
+ * overlay slice for the legacy `default` gateway. */
852
+ export function setGatewayPeers(peers: Record<string, Peer>): void {
853
+ gatewayOverlays.default = peers;
854
+ }
855
+
856
+ /** Current flattened gateway peer overlay (snapshot for listing/dedup). */
857
+ export function getGatewayPeers(): Record<string, Peer> {
858
+ const out: Record<string, Peer> = {};
859
+ for (const slice of Object.values(gatewayOverlays)) {
860
+ Object.assign(out, slice);
861
+ }
862
+ return out;
863
+ }
864
+
865
+ // ---------------------------------------------------------------------------
866
+ // Gateway registration names (read-only, in-memory — never persisted)
867
+ // ---------------------------------------------------------------------------
868
+
869
+ /** Per-gateway registration names, keyed by gateway key. Set by the server at
870
+ * start; cleared (deleted) when that gateway's upstream stops. */
871
+ const gatewayRegistrationNames: Record<string, string> = {};
872
+
873
+ /** Publish the name this session registered under on ONE upstream gateway
874
+ * (set by the server at start). Session-scoped, in-memory only — NEVER
875
+ * persisted to settings.json. */
876
+ export function setGatewayRegistrationName(name: string | null, key = "default"): void {
877
+ if (name === null) delete gatewayRegistrationNames[key];
878
+ else gatewayRegistrationNames[key] = name;
879
+ }
880
+
881
+ /** The name registered under the given gateway key, or null. */
882
+ export function getGatewayCallerName(key: string): string | null {
883
+ return gatewayRegistrationNames[key] ?? null;
884
+ }
885
+
886
+ /** Legacy single-gateway accessor: the default key's registration name. */
887
+ export function getGatewayRegistrationName(): string | null {
888
+ return gatewayRegistrationNames.default ?? null;
889
+ }
890
+
891
+ /** Pick the token to present outbound: prefer this session's own peer token
892
+ * (so the receiver attributes the call to us), else the shared token. */
893
+ function outboundToken(cfg: A2AConfig): string {
894
+ if (cfg.selfIdentity && cfg.server.peerTokens[cfg.selfIdentity]) {
895
+ return cfg.server.peerTokens[cfg.selfIdentity]!;
896
+ }
897
+ return cfg.server.sharedToken;
898
+ }
899
+
900
+ /** True when the URL's host is localhost / 127.0.0.1 / ::1 (brackets stripped). */
901
+ function isLoopbackHost(rawUrl: string): boolean {
902
+ try {
903
+ const u = new URL(rawUrl);
904
+ const h = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
905
+ return h === "localhost" || h === "127.0.0.1" || h === "::1";
906
+ } catch {
907
+ return false;
908
+ }
909
+ }
910
+
911
+ /** Auth header(s) for an outbound request. */
912
+ export function authHeaders(peer: Peer): Record<string, string> {
913
+ const h: Record<string, string> = {};
914
+ if (peer.auth?.type === "bearer" && peer.auth.token) {
915
+ h.Authorization = `Bearer ${peer.auth.token}`;
916
+ } else if (peer.auth?.type === "apiKey" && peer.auth.token) {
917
+ h.Authorization = `ApiKey ${peer.auth.token}`;
918
+ }
919
+ return h;
920
+ }