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.
- package/CHANGELOG.md +83 -0
- package/extensions/lib/registry.test.ts +67 -0
- package/extensions/lib/registry.ts +24 -7
- package/extensions/modules/a2a/configPanel.ts +435 -0
- package/extensions/modules/a2a/index.ts +1117 -0
- package/extensions/modules/a2a/lib/activity.ts +173 -0
- package/extensions/modules/a2a/lib/client.ts +1061 -0
- package/extensions/modules/a2a/lib/config.ts +920 -0
- package/extensions/modules/a2a/lib/discovery.ts +158 -0
- package/extensions/modules/a2a/lib/gateway.ts +889 -0
- package/extensions/modules/a2a/lib/mdns.ts +233 -0
- package/extensions/modules/a2a/lib/outcome.ts +48 -0
- package/extensions/modules/a2a/lib/persistence.ts +123 -0
- package/extensions/modules/a2a/lib/protocol.ts +506 -0
- package/extensions/modules/a2a/lib/registry.ts +146 -0
- package/extensions/modules/a2a/lib/retry.ts +86 -0
- package/extensions/modules/a2a/lib/security.ts +394 -0
- package/extensions/modules/a2a/lib/server.ts +1436 -0
- package/extensions/modules/a2a/test/activity.test.ts +138 -0
- package/extensions/modules/a2a/test/bridge.test.ts +101 -0
- package/extensions/modules/a2a/test/broadcast-parse.test.ts +31 -0
- package/extensions/modules/a2a/test/chai.ts +101 -0
- package/extensions/modules/a2a/test/client.test.ts +856 -0
- package/extensions/modules/a2a/test/completion-guard.test.ts +73 -0
- package/extensions/modules/a2a/test/config.test.ts +1396 -0
- package/extensions/modules/a2a/test/configPanel.test.ts +393 -0
- package/extensions/modules/a2a/test/discovery.test.ts +144 -0
- package/extensions/modules/a2a/test/extension.test.ts +135 -0
- package/extensions/modules/a2a/test/gateway.test.ts +1449 -0
- package/extensions/modules/a2a/test/helpers.ts +39 -0
- package/extensions/modules/a2a/test/mdns.test.ts +131 -0
- package/extensions/modules/a2a/test/outcome.test.ts +61 -0
- package/extensions/modules/a2a/test/persistence.test.ts +92 -0
- package/extensions/modules/a2a/test/protocol.test.ts +217 -0
- package/extensions/modules/a2a/test/registry.test.ts +114 -0
- package/extensions/modules/a2a/test/retry.test.ts +136 -0
- package/extensions/modules/a2a/test/security.test.ts +281 -0
- package/extensions/modules/a2a/test/server.test.ts +1966 -0
- package/extensions/modules/a2a/test/tmp.ts +59 -0
- package/extensions/modules/a2a/test/vendor.test.ts +57 -0
- package/extensions/modules/a2a/types/bonjour-service.d.ts +22 -0
- package/extensions/modules/a2a/vendor/VENDORED.md +18 -0
- package/extensions/modules/a2a/vendor/package.json +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/LICENSE +23 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.js +57 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.d.ts +4 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.js +3 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.d.ts +13 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.d.ts +41 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.js +209 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.d.ts +9 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.js +42 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.js +119 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.js +142 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.d.ts +7 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.js +53 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.d.ts +58 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.js +130 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.d.ts +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.js +13 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.d.ts +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.js +17 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.d.ts +4 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.js +22 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.d.ts +3 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.js +6 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/classes.js +23 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/index.js +1761 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/opcodes.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/optioncodes.js +59 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/rcodes.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/types.js +103 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/es6.js +73 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/index.js +46 -0
- package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/index.cjs +250 -0
- package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/index.js +205 -0
- package/extensions/modules/a2a/vendor/vendored_deps/thunky/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/thunky/index.js +55 -0
- package/extensions/modules/advisor/index.ts +20 -2
- package/extensions/modules/advisor/lib/watcher.ts +3 -1
- package/extensions/modules/advisor/test/module.test.ts +64 -1
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +2 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/munin/configPanel.ts +5 -2
- package/extensions/modules/munin/test/configPanel.test.ts +27 -2
- package/extensions/modules/router/configPanel.ts +24 -10
- package/extensions/modules/router/lib/client.ts +6 -4
- package/extensions/modules/router/test/unit.test.ts +83 -2
- package/extensions/modules/rules/index.ts +120 -0
- package/extensions/modules/rules/lib/rules.ts +348 -0
- package/extensions/modules/rules/test/lib.test.ts +263 -0
- package/extensions/modules/rules/test/module.test.ts +222 -0
- package/extensions/modules/subagent/index.ts +19 -6
- package/extensions/modules/subagent/lib/routing.ts +11 -6
- package/extensions/modules/subagent/lib/security.ts +12 -1
- package/extensions/modules/subagent/test/routing.test.ts +174 -0
- package/extensions/modules/todo/configPanel.ts +55 -0
- package/extensions/modules/todo/index.ts +511 -0
- package/extensions/modules/todo/lib/render.ts +271 -0
- package/extensions/modules/todo/lib/settings.ts +73 -0
- package/extensions/modules/todo/test/todo.test.ts +528 -0
- package/extensions/modules/usage/index.ts +11 -0
- package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
- package/extensions/modules/web/configPanel.ts +38 -13
- package/extensions/modules/web/lib/settings.ts +11 -2
- package/extensions/modules/web/test/configPanel.test.ts +67 -1
- package/extensions/modules/zai/configPanel.ts +5 -2
- package/extensions/modules/zai/lib/signing.ts +4 -1
- package/extensions/modules/zai/test/configPanel.test.ts +23 -0
- package/extensions/modules/zai/test/signing.test.ts +19 -0
- package/package.json +2 -2
- package/skills/a2a/SKILL.md +63 -0
|
@@ -0,0 +1,889 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gateway upstream registration (discovery layer 2): announce this session to
|
|
3
|
+
* a self-hosted a2a-switchboard gateway (https://github.com/bacnh85/a2a-switchboard)
|
|
4
|
+
* so other accepted peers can discover and call it via the gateway's proxy.
|
|
5
|
+
*
|
|
6
|
+
* Lifecycle: register (POST) on server start → PATCH /register heartbeats
|
|
7
|
+
* once the per-peer caller_token is known (POST mints it; the token is
|
|
8
|
+
* persisted per gateway + peer name so restarts skip the mint) → deregister on graceful stop. A crashed
|
|
9
|
+
* session leaves a stale entry; the gateway's health prober marks it
|
|
10
|
+
* unreachable, and the admin can delete it (or the next session with the same
|
|
11
|
+
* name + token takes the entry over via re-registration).
|
|
12
|
+
*
|
|
13
|
+
* After each heartbeat the gateway peer directory (/.well-known/agent.json) is
|
|
14
|
+
* fetched and merged into a read-only `gw/<key>/<name>` → Peer overlay handed to
|
|
15
|
+
* the `onPeers` callback — never written to settings.json.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { Peer } from "./config";
|
|
19
|
+
import * as fs from "node:fs";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
21
|
+
|
|
22
|
+
export interface GatewayConfig {
|
|
23
|
+
/** Gateway base URL, e.g. http://127.0.0.1:9920 */
|
|
24
|
+
url: string;
|
|
25
|
+
/** Gateway API token (pending queue) or bootstrap token (auto-accept). */
|
|
26
|
+
token: string;
|
|
27
|
+
/** Peer name to register as. Default: agentName or "pi". */
|
|
28
|
+
name?: string;
|
|
29
|
+
/** Optional token the gateway should present when proxying TO us. */
|
|
30
|
+
upstreamToken?: string;
|
|
31
|
+
/** Re-registration interval in seconds. Default 60. */
|
|
32
|
+
heartbeatSec?: number;
|
|
33
|
+
/** Outbound call timeout for gw/<name> peers (ms). Default 120000 —
|
|
34
|
+
* decoupled from heartbeatSec: long agent tasks must not be truncated by
|
|
35
|
+
* the directory-refresh cadence. */
|
|
36
|
+
callTimeoutMs?: number;
|
|
37
|
+
/** Open a reverse channel (SSE) so firewalled peers still receive proxied
|
|
38
|
+
* requests — all connections stay peer-initiated. Default true. */
|
|
39
|
+
channel?: boolean;
|
|
40
|
+
/** Local server base URL the channel dispatcher forwards envelopes to.
|
|
41
|
+
* Default: the URL passed to start(). */
|
|
42
|
+
localBase?: string;
|
|
43
|
+
/** Token the LOCAL inbound server accepts (server.sharedToken or the
|
|
44
|
+
* upstreamToken registered with the gateway). Injected on dispatch —
|
|
45
|
+
* the gateway strips caller auth, so the local server needs its own. */
|
|
46
|
+
localToken?: string;
|
|
47
|
+
/** Gateway key (0.6.0) — namespaces the peer overlay as `gw/<key>/<name>`.
|
|
48
|
+
* Default "default". */
|
|
49
|
+
key?: string;
|
|
50
|
+
/** Directory for persisted gateway state (the minted caller_token — the
|
|
51
|
+
* gateway only discloses it at mint, so it must survive restarts).
|
|
52
|
+
* Injected by the server; unset = stateless. */
|
|
53
|
+
piDir?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const DEREG_TIMEOUT_MS = 1500; // best-effort DELETE; stale entries decay via gateway health probing
|
|
57
|
+
|
|
58
|
+
const MAX_BACKOFF_MS = 300_000; // heartbeat backoff cap: a healed gateway is re-registered within ≤5 min
|
|
59
|
+
|
|
60
|
+
/** Numeric `Retry-After` seconds from a response header (null when absent/non-numeric). */
|
|
61
|
+
function retryAfterSeconds(v: string | null): number | null {
|
|
62
|
+
if (!v) return null;
|
|
63
|
+
const n = Number(v);
|
|
64
|
+
return Number.isFinite(n) && n > 0 ? n : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Heartbeat backoff for failed registers: baseMs · 2^(fails−1), capped at
|
|
68
|
+
* 5 min, ±20% jitter; a numeric Retry-After header wins when larger but is
|
|
69
|
+
* capped at MAX_BACKOFF_MS too — a buggy or hostile gateway value must not
|
|
70
|
+
* suppress re-registration indefinitely. The gateway rate-limits /register
|
|
71
|
+
* per client IP with a fixed window that counts rejected requests, so
|
|
72
|
+
* fixed-cadence retries keep that budget saturated (livelock) — backing off
|
|
73
|
+
* lets it drain. Pure; exported for tests. */
|
|
74
|
+
export function backoffDelayMs(
|
|
75
|
+
fails: number,
|
|
76
|
+
baseMs: number,
|
|
77
|
+
retryAfterSec?: number | null,
|
|
78
|
+
): number {
|
|
79
|
+
const exp = Math.max(0, fails - 1);
|
|
80
|
+
let delay = Math.min(MAX_BACKOFF_MS, baseMs * 2 ** exp) * (0.8 + Math.random() * 0.4);
|
|
81
|
+
const retryMs = Math.min(MAX_BACKOFF_MS, (retryAfterSec ?? 0) * 1000);
|
|
82
|
+
if (retryMs > delay) delay = retryMs;
|
|
83
|
+
return Math.round(delay);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
// Peer directory merge (pure — no I/O, no global state)
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
/** One `peers[]` entry of the gateway's /.well-known/agent.json directory. */
|
|
91
|
+
export interface GatewayDirectoryEntry {
|
|
92
|
+
name?: unknown;
|
|
93
|
+
url?: unknown;
|
|
94
|
+
healthy?: unknown;
|
|
95
|
+
capabilities?: unknown;
|
|
96
|
+
skills?: unknown;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Gateway peer names are constrained to [A-Za-z0-9._-] by the gateway's
|
|
100
|
+
* register endpoint; re-check so a hostile/buggy gateway can't smuggle a
|
|
101
|
+
* name that breaks the `gw/<name>` namespace or URL semantics. */
|
|
102
|
+
const GATEWAY_NAME_RE = /^[A-Za-z0-9._-]{1,64}$/;
|
|
103
|
+
|
|
104
|
+
function normUrl(u: string): string {
|
|
105
|
+
return u.trim().replace(/\/+$/, "").toLowerCase();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Port of a URL string, or "" when absent/defaulted. */
|
|
109
|
+
function portOf(rawUrl: string): string {
|
|
110
|
+
try {
|
|
111
|
+
return new URL(rawUrl).port || "";
|
|
112
|
+
} catch {
|
|
113
|
+
return "";
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Single-line, length-capped string from untrusted directory fields. */
|
|
118
|
+
function sanitize(v: unknown): string {
|
|
119
|
+
return String(v ?? "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function sanitizeList(v: unknown): string[] {
|
|
123
|
+
return Array.isArray(v) ? v.map(sanitize).filter(Boolean).slice(0, 50) : [];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** True when a directory entry is THIS session (never call yourself through
|
|
127
|
+
* the proxy): exact registered-name match, `-<port>` suffix match against the
|
|
128
|
+
* port we serve on (the default auto-name is `<base>-<port>`), or absolute-URL
|
|
129
|
+
* match against our publicUrl (defensive — a2a-switchboard only exposes proxy
|
|
130
|
+
* URLs today). */
|
|
131
|
+
export function isSelfEntry(
|
|
132
|
+
entry: { name: string; url: string },
|
|
133
|
+
self: { name: string; url: string; autoName?: string },
|
|
134
|
+
): boolean {
|
|
135
|
+
if (entry.name === self.name) return true;
|
|
136
|
+
// Our own default auto-name (`<base>-<port>`) — NOT any `-<port>` suffix:
|
|
137
|
+
// another machine's peer may coincidentally bind the same port.
|
|
138
|
+
if (self.autoName && entry.name === self.autoName) return true;
|
|
139
|
+
if (
|
|
140
|
+
entry.url &&
|
|
141
|
+
/^https?:\/\//i.test(entry.url) &&
|
|
142
|
+
normUrl(entry.url) === normUrl(self.url)
|
|
143
|
+
) {
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Resolve a gateway-relative peer URL (e.g. /peer/<name>/) against the
|
|
150
|
+
* gateway origin. Only same-origin results pass: the merged peers carry the
|
|
151
|
+
* gateway bearer token, so a crafted absolute URL must never redirect a call
|
|
152
|
+
* to a third-party host. */
|
|
153
|
+
function proxyUrl(gatewayUrl: string, rel: string): string {
|
|
154
|
+
if (!rel.startsWith("/")) return ""; // a2a-switchboard urls are always relative
|
|
155
|
+
try {
|
|
156
|
+
const resolved = new URL(rel, gatewayUrl);
|
|
157
|
+
return resolved.origin === new URL(gatewayUrl).origin ? resolved.toString() : "";
|
|
158
|
+
} catch {
|
|
159
|
+
return "";
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Merge the gateway peer directory into a `gw/<key>/<name>` → Peer overlay.
|
|
164
|
+
* Auth is the gateway bearer token (the proxy swaps in the peer's own
|
|
165
|
+
* upstream token). Unhealthy peers and self are skipped. `key` (0.6.0)
|
|
166
|
+
* namespaces the overlay per gateway — always prefixed, even for a single
|
|
167
|
+
* gateway (uniform naming). */
|
|
168
|
+
export function mergeGatewayPeers(opts: {
|
|
169
|
+
gatewayUrl: string;
|
|
170
|
+
token: string;
|
|
171
|
+
selfName: string;
|
|
172
|
+
selfUrl: string;
|
|
173
|
+
/** Our default auto-name (`<base>-<port>`) for exact-match self-filtering. */
|
|
174
|
+
selfAutoName?: string;
|
|
175
|
+
entries: unknown;
|
|
176
|
+
timeoutMs: number;
|
|
177
|
+
/** Gateway key — emitted as `gw/<key>/<name>`. Default "default". */
|
|
178
|
+
key?: string;
|
|
179
|
+
}): Record<string, Peer> {
|
|
180
|
+
let origin: URL;
|
|
181
|
+
try {
|
|
182
|
+
origin = new URL(opts.gatewayUrl);
|
|
183
|
+
} catch {
|
|
184
|
+
return {}; // malformed gateway url — nothing routable
|
|
185
|
+
}
|
|
186
|
+
const out: Record<string, Peer> = {};
|
|
187
|
+
const key = opts.key || "default";
|
|
188
|
+
if (!Array.isArray(opts.entries)) return out;
|
|
189
|
+
for (const raw of opts.entries) {
|
|
190
|
+
if (!raw || typeof raw !== "object") continue;
|
|
191
|
+
const e = raw as GatewayDirectoryEntry;
|
|
192
|
+
const name = sanitize(e.name);
|
|
193
|
+
if (!GATEWAY_NAME_RE.test(name)) continue;
|
|
194
|
+
if (e.healthy === false) continue; // gateway prober marked it unreachable
|
|
195
|
+
if (
|
|
196
|
+
isSelfEntry(
|
|
197
|
+
{ name, url: String(e.url ?? "") },
|
|
198
|
+
{ name: opts.selfName, url: opts.selfUrl, autoName: opts.selfAutoName },
|
|
199
|
+
)
|
|
200
|
+
) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const url = proxyUrl(origin.toString(), String(e.url ?? ""));
|
|
204
|
+
if (!url) continue;
|
|
205
|
+
// Directory capabilities is either a string array or an A2A card object
|
|
206
|
+
// ({streaming, pushNotifications}); skills carry [{id,name}]. Surface
|
|
207
|
+
// skill names so capability-based peer selection works either way.
|
|
208
|
+
const caps = sanitizeList(e.capabilities).length
|
|
209
|
+
? sanitizeList(e.capabilities)
|
|
210
|
+
: sanitizeList(Array.isArray(e.skills) ? e.skills.map((sk: any) => sk?.name ?? sk?.id) : []);
|
|
211
|
+
out[`gw/${key}/${name}`] = {
|
|
212
|
+
url,
|
|
213
|
+
auth: { type: "bearer", token: opts.token },
|
|
214
|
+
timeout: opts.timeoutMs,
|
|
215
|
+
capabilities: caps,
|
|
216
|
+
description: "via a2a-switchboard",
|
|
217
|
+
viaGateway: true,
|
|
218
|
+
gatewayUrl: opts.gatewayUrl,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
return out;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ---------------------------------------------------------------------------
|
|
225
|
+
// Upstream registration + heartbeat
|
|
226
|
+
// ---------------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
export class GatewayUpstream {
|
|
229
|
+
private timer: NodeJS.Timeout | null = null;
|
|
230
|
+
private stopped = false;
|
|
231
|
+
/** Bumped on stop(): in-flight register() calls check it after each await
|
|
232
|
+
* and bail instead of resurrecting the registration/overlay. */
|
|
233
|
+
private epoch = 0;
|
|
234
|
+
private lastUrl = "";
|
|
235
|
+
/** Shared epoch holder the ChannelClient also watches (stop() kills both). */
|
|
236
|
+
private epochRef = { value: 0 };
|
|
237
|
+
private channel: ChannelClient | null = null;
|
|
238
|
+
|
|
239
|
+
private url(path: string): string {
|
|
240
|
+
return this.cfg.url.replace(/\/+$/, "") + path;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private get name(): string {
|
|
244
|
+
return this.cfg.name || "pi";
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Gateway key (default "default") — prefixes the `gw/<key>/<name>` overlay. */
|
|
248
|
+
private get key(): string {
|
|
249
|
+
return this.cfg.key || "default";
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Human-readable gateway label for messages: `<key>@<host>` (no token, no path). */
|
|
253
|
+
private get label(): string {
|
|
254
|
+
try {
|
|
255
|
+
return `${this.key}@${new URL(this.cfg.url).host}`;
|
|
256
|
+
} catch {
|
|
257
|
+
return this.key;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The server's default per-session auto-name (`<base>-<port>`), only
|
|
262
|
+
* meaningful when the server computed it (passed via cfg.autoName). */
|
|
263
|
+
private get autoName(): string | undefined {
|
|
264
|
+
return (this.cfg as { autoName?: string }).autoName;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Admission state of the last registration ("pending" | "accepted" | …). */
|
|
268
|
+
lastState = "";
|
|
269
|
+
/** True once a register() has succeeded this upstream instance — gates the
|
|
270
|
+
* onRegistered transition callback. */
|
|
271
|
+
private wasRegistered = false;
|
|
272
|
+
|
|
273
|
+
/** Per-peer caller token issued by the gateway at registration. Used as the
|
|
274
|
+
* caller identity for outbound `/peer/*` calls so the gateway's dashboard
|
|
275
|
+
* shows THIS peer's name (not a shared-token fingerprint), and as the
|
|
276
|
+
* auth for PATCH /register heartbeats. Loaded from disk at construction,
|
|
277
|
+
* re-persisted on every mint. */
|
|
278
|
+
private callerToken: string | null;
|
|
279
|
+
/** Sticky false after a 405 (old switchboard without PATCH) — POST-only for
|
|
280
|
+
* the rest of the session to avoid flapping. */
|
|
281
|
+
private patchSupported = true;
|
|
282
|
+
/** Set after we retry an initial 409 with a unique name, so we only retry once. */
|
|
283
|
+
private triedUnique = false;
|
|
284
|
+
/** Last directory-fetch status (0 = none yet). Only a CHANGED failing
|
|
285
|
+
* status is logged — repeated identical failures stay quiet. */
|
|
286
|
+
private lastDirStatus = 0;
|
|
287
|
+
/** Pre-0.6.2 state path, read-only migration fallback. */
|
|
288
|
+
private readonly legacyStateFile: string | null;
|
|
289
|
+
|
|
290
|
+
constructor(
|
|
291
|
+
private readonly cfg: GatewayConfig,
|
|
292
|
+
/** Builds the agent-card JSON body; called on each heartbeat so the card stays fresh. */
|
|
293
|
+
private readonly buildCard: () => Record<string, unknown>,
|
|
294
|
+
private readonly log: (msg: string) => void = console.error,
|
|
295
|
+
/** Receives each refreshed `gw/<name>` → Peer overlay ({} clears it). */
|
|
296
|
+
private readonly onPeers: (peers: Record<string, Peer>) => void = () => {},
|
|
297
|
+
/** Host-TUI status line (transcript) for lifecycle events like the
|
|
298
|
+
* reverse channel opening — surfaced like the registration message. */
|
|
299
|
+
private readonly onStatus: ((msg: string) => void) | undefined = undefined,
|
|
300
|
+
/** Fires on the transition to registered (name + admission state), so
|
|
301
|
+
* the host can publish the gateway-issued identity even when the first
|
|
302
|
+
* register failed at session start and a later beat self-healed. */
|
|
303
|
+
private readonly onRegistered?: (name: string, state: string) => void,
|
|
304
|
+
) {
|
|
305
|
+
this.legacyStateFile = cfg.piDir
|
|
306
|
+
? join(cfg.piDir, "a2a_gateways", `${this.key.replace(/[^A-Za-z0-9._-]/g, "_")}.json`)
|
|
307
|
+
: null;
|
|
308
|
+
this.callerToken = this.loadPersistedToken();
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** State path follows the LIVE peer name: the 409 self-heal renames the
|
|
312
|
+
* peer mid-session, and the persisted file must keep matching the name it
|
|
313
|
+
* was minted for (loadPersistedToken name-matches) — otherwise the token
|
|
314
|
+
* is written under the pre-rename path and never loads again. */
|
|
315
|
+
private get stateFile(): string | null {
|
|
316
|
+
if (!this.cfg.piDir) return null;
|
|
317
|
+
const stateDir = join(this.cfg.piDir, "a2a_gateways");
|
|
318
|
+
const key = this.key.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
319
|
+
const name = this.name.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
320
|
+
return join(stateDir, key, `${name}.json`);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** The name actually registered with the gateway — may differ from the
|
|
324
|
+
* configured name after a 409 self-heal rename. Callers publishing the
|
|
325
|
+
* registration name (X-Gateway-Caller attribution, status lines) must use
|
|
326
|
+
* this, not their own computation. */
|
|
327
|
+
get registeredName(): string {
|
|
328
|
+
return this.name;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Read the named state first; one matching legacy file is migrated on write. */
|
|
332
|
+
private loadPersistedToken(): string | null {
|
|
333
|
+
for (const file of [this.stateFile, this.legacyStateFile]) {
|
|
334
|
+
if (!file) continue;
|
|
335
|
+
try {
|
|
336
|
+
const j = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
337
|
+
if (j?.name === this.name && typeof j.callerToken === "string" && j.callerToken) return j.callerToken;
|
|
338
|
+
} catch {
|
|
339
|
+
/* absent/corrupt state is a first-registration path */
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private persistToken(): void {
|
|
346
|
+
if (!this.stateFile || !this.callerToken) return;
|
|
347
|
+
try {
|
|
348
|
+
fs.mkdirSync(dirname(this.stateFile), { recursive: true, mode: 0o700 });
|
|
349
|
+
fs.writeFileSync(this.stateFile, JSON.stringify({ name: this.name, callerToken: this.callerToken }), { mode: 0o600 });
|
|
350
|
+
} catch {
|
|
351
|
+
/* state file is an optimization — heartbeat still works via fallback */
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
private async send(
|
|
356
|
+
method: "POST" | "PATCH",
|
|
357
|
+
path: string,
|
|
358
|
+
token: string,
|
|
359
|
+
body: unknown,
|
|
360
|
+
): Promise<{ res: Response | null; err: string | null }> {
|
|
361
|
+
try {
|
|
362
|
+
const res = await fetch(this.url(path), {
|
|
363
|
+
method,
|
|
364
|
+
headers: {
|
|
365
|
+
authorization: `Bearer ${token}`,
|
|
366
|
+
"content-type": "application/json",
|
|
367
|
+
},
|
|
368
|
+
body: JSON.stringify(body),
|
|
369
|
+
signal: AbortSignal.timeout(10_000),
|
|
370
|
+
});
|
|
371
|
+
return { res, err: null };
|
|
372
|
+
} catch (e) {
|
|
373
|
+
const cause = (e as { cause?: { code?: string } }).cause;
|
|
374
|
+
// Errno code when present (EHOSTUNREACH, ECONNREFUSED, …), else the
|
|
375
|
+
// cause message ('bad port') or the abort name (TimeoutError).
|
|
376
|
+
const err =
|
|
377
|
+
cause?.code ?? ((cause instanceof Error && cause.message) || (e as Error).name);
|
|
378
|
+
return { res: null, err }; // gateway down / network error — heartbeat will retry
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Register-failure label: HTTP status, or network error with its cause.
|
|
383
|
+
* Per-call (not instance state) so overlapping beats can't mislabel. */
|
|
384
|
+
private failLabel(res: Response | null, err: string | null): string {
|
|
385
|
+
return res ? String(res.status) : `network error${err ? ` (${err})` : ""}`;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Failure-log dedup (mirrors refreshPeers' lastDirStatus): with the
|
|
389
|
+
* heartbeat now armed from start, a permanent failure (revoked token,
|
|
390
|
+
* bad URL) would repeat every beat — log on change only; reset on
|
|
391
|
+
* success so a recovered-then-broken gateway re-logs immediately. */
|
|
392
|
+
private lastFailLabel: string | null = null;
|
|
393
|
+
/** Consecutive failed registers + the wall-clock instant the next beat is
|
|
394
|
+
* allowed at (0 = now). The heartbeat timer skips while backed off. */
|
|
395
|
+
private beatFails = 0;
|
|
396
|
+
private backoffUntil = 0;
|
|
397
|
+
|
|
398
|
+
/** Failure handling shared by every register() exit: schedule exponential
|
|
399
|
+
* backoff for the heartbeat, then log (deduped on the failure label, so
|
|
400
|
+
* the growing delay doesn't defeat the dedup — it's shown on first emit). */
|
|
401
|
+
private noteFailure(label: string, res: Response | null): void {
|
|
402
|
+
const baseMs = Math.max(15, this.cfg.heartbeatSec ?? 60) * 1000;
|
|
403
|
+
const delay = backoffDelayMs(
|
|
404
|
+
this.beatFails + 1,
|
|
405
|
+
baseMs,
|
|
406
|
+
retryAfterSeconds(res?.headers.get("retry-after") ?? null),
|
|
407
|
+
);
|
|
408
|
+
this.beatFails += 1;
|
|
409
|
+
this.backoffUntil = Date.now() + delay;
|
|
410
|
+
this.logFailure(label, ` — backing off ${Math.round(delay / 1000)}s`);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
private logFailure(label: string, suffix = ""): void {
|
|
414
|
+
if (label === this.lastFailLabel) return;
|
|
415
|
+
this.lastFailLabel = label;
|
|
416
|
+
// darwin only: on Linux EHOSTUNREACH is genuine routing, but on macOS it
|
|
417
|
+
// usually means Local Network privacy is blocking this binary (Apple-signed
|
|
418
|
+
// curl works, masking the cause). The dedup above makes the hint appear
|
|
419
|
+
// once per cause-change, not per heartbeat beat.
|
|
420
|
+
const hint =
|
|
421
|
+
process.platform === "darwin" && label.includes("EHOSTUNREACH")
|
|
422
|
+
? " — likely macOS Local Network privacy blocking this binary. Fix: System Settings → Privacy & Security → Local Network → allow the hosting app (Terminal/herdr). Apple-signed curl works, masking the cause"
|
|
423
|
+
: "";
|
|
424
|
+
this.log(`[a2a-gateway:${this.label}] register failed: ${label}${suffix}${hint}`);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** POST /register with our current card. Idempotent: gateway updates in place.
|
|
428
|
+
* After each (re-)registration, refresh the peer-directory overlay. */
|
|
429
|
+
async register(url: string): Promise<boolean> {
|
|
430
|
+
const at = this.epoch;
|
|
431
|
+
// The card must carry the name ACTUALLY registered: after a 409 self-heal
|
|
432
|
+
// rename, this.name differs from the card factory's own sessionName()
|
|
433
|
+
// (which still computes the pre-rename name) — directory entry and card
|
|
434
|
+
// identity would disagree.
|
|
435
|
+
const card = this.buildCard();
|
|
436
|
+
if (card && typeof card === "object") (card as Record<string, unknown>).name = this.name;
|
|
437
|
+
const body: Record<string, unknown> = { name: this.name, url, card };
|
|
438
|
+
if (this.cfg.upstreamToken) body.upstream_token = this.cfg.upstreamToken;
|
|
439
|
+
// Steady-state heartbeats PATCH with the per-peer caller_token (full card
|
|
440
|
+
// refresh; url re-send covers IP changes). POST is the mint path and the
|
|
441
|
+
// fallback when PATCH can't work (405 old gateway, 401 stale token,
|
|
442
|
+
// 404 deleted entry).
|
|
443
|
+
let res: Response | null = null;
|
|
444
|
+
let err: string | null = null;
|
|
445
|
+
if (this.callerToken && this.patchSupported) {
|
|
446
|
+
({ res, err } = await this.send("PATCH", "/register", this.callerToken, body));
|
|
447
|
+
if (at !== this.epoch) return false; // stop() raced us — registration is dead
|
|
448
|
+
if (!res) {
|
|
449
|
+
this.noteFailure(this.failLabel(res, err), res);
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
if (res.status === 405) {
|
|
453
|
+
this.patchSupported = false; // old switchboard — POST-only this session
|
|
454
|
+
res = null; // fall through to POST
|
|
455
|
+
} else if (!res.ok) {
|
|
456
|
+
// 401 (rejected caller_token) / 404 (entry deleted): the token is
|
|
457
|
+
// known-dead — clear it so the overlay falls back to the shared token
|
|
458
|
+
// until a POST re-mints (a POST response carrying no mint leaves it null).
|
|
459
|
+
if (res.status === 401 || res.status === 404) {
|
|
460
|
+
this.callerToken = null;
|
|
461
|
+
res = null; // fall through to POST
|
|
462
|
+
} else {
|
|
463
|
+
// 403 (revoked peer) / 409 etc.: a shared-token POST is not a valid
|
|
464
|
+
// rescue for this admission state — fail the beat.
|
|
465
|
+
this.noteFailure(String(res.status), res);
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
if (!res) ({ res, err } = await this.send("POST", "/register", this.cfg.token, body));
|
|
471
|
+
if (at !== this.epoch) return false; // stop() raced us — registration is dead
|
|
472
|
+
if (!res?.ok) {
|
|
473
|
+
// Initial mint POST hit a 409: the port-derived name is already held by a
|
|
474
|
+
// stale entry from a previous session (the switchboard issues each peer a
|
|
475
|
+
// per-peer caller_token and rejects shared-token re-registration by
|
|
476
|
+
// design, so we can't take it over). Retry ONCE with a unique suffix so
|
|
477
|
+
// registration self-heals without manual switchboard cleanup.
|
|
478
|
+
if (!this.callerToken && !this.triedUnique && res?.status === 409) {
|
|
479
|
+
this.triedUnique = true;
|
|
480
|
+
// Remove the pre-rename state file: it would persist a token the
|
|
481
|
+
// gateway bound to the OLD name, and loadPersistedToken (name-match)
|
|
482
|
+
// would never load it — a dead file.
|
|
483
|
+
const preRename = this.stateFile;
|
|
484
|
+
this.cfg.name = `${this.cfg.name}-${Math.random().toString(36).slice(2, 8)}`;
|
|
485
|
+
try {
|
|
486
|
+
if (preRename) fs.rmSync(preRename, { force: true });
|
|
487
|
+
} catch {
|
|
488
|
+
/* best-effort */
|
|
489
|
+
}
|
|
490
|
+
return this.register(url);
|
|
491
|
+
}
|
|
492
|
+
this.noteFailure(this.failLabel(res, err), res);
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
this.lastFailLabel = null; // recovered — a later failure re-logs immediately
|
|
496
|
+
this.beatFails = 0;
|
|
497
|
+
this.backoffUntil = 0;
|
|
498
|
+
try {
|
|
499
|
+
const j = (await res.clone?.().json?.().catch?.(() => null)) ?? (await res.json().catch(() => null));
|
|
500
|
+
this.lastState = String(j?.state ?? "");
|
|
501
|
+
if (typeof j?.caller_token === "string" && j.caller_token) {
|
|
502
|
+
this.callerToken = j.caller_token;
|
|
503
|
+
this.persistToken();
|
|
504
|
+
}
|
|
505
|
+
} catch {
|
|
506
|
+
this.lastState = "";
|
|
507
|
+
}
|
|
508
|
+
// A stop() may have landed while we awaited the body above. Bail WITHOUT
|
|
509
|
+
// resurrecting state (stop() already cleared the overlay via onPeers({})).
|
|
510
|
+
if (at !== this.epoch || this.stopped) return false;
|
|
511
|
+
this.lastUrl = url;
|
|
512
|
+
this.stopped = false;
|
|
513
|
+
// Transition to registered — fires on the first success, including a
|
|
514
|
+
// late beat after start() returned false (gateway was down at session
|
|
515
|
+
// start). The host uses it to publish the registered name + status.
|
|
516
|
+
if (!this.wasRegistered) {
|
|
517
|
+
this.wasRegistered = true;
|
|
518
|
+
this.onRegistered?.(this.name, this.lastState);
|
|
519
|
+
}
|
|
520
|
+
await this.refreshPeers(at);
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** GET /.well-known/agent.json → merged overlay via onPeers. Failures keep
|
|
525
|
+
* the last known overlay (a blip between heartbeats shouldn't evaporate
|
|
526
|
+
* peers). */
|
|
527
|
+
private async refreshPeers(guardEpoch?: number): Promise<void> {
|
|
528
|
+
const at = guardEpoch ?? this.epoch;
|
|
529
|
+
try {
|
|
530
|
+
const res = await fetch(this.url("/.well-known/agent.json"), {
|
|
531
|
+
headers: { authorization: `Bearer ${this.cfg.token}` },
|
|
532
|
+
signal: AbortSignal.timeout(10_000),
|
|
533
|
+
});
|
|
534
|
+
if (!res?.ok) {
|
|
535
|
+
// Log only when the failing status CHANGES — a directory down for N
|
|
536
|
+
// beats shouldn't emit one log line per heartbeat.
|
|
537
|
+
const status = res?.status ?? 0;
|
|
538
|
+
if (status !== this.lastDirStatus) {
|
|
539
|
+
this.log(`[a2a-gateway:${this.label}] peer directory refresh failed: ${status}`);
|
|
540
|
+
}
|
|
541
|
+
this.lastDirStatus = status;
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
this.lastDirStatus = res.status;
|
|
545
|
+
const json = (await res.json()) as { peers?: unknown };
|
|
546
|
+
if (at !== this.epoch) return; // stop() cleared the overlay — don't refill it
|
|
547
|
+
this.onPeers(
|
|
548
|
+
mergeGatewayPeers({
|
|
549
|
+
gatewayUrl: this.cfg.url,
|
|
550
|
+
token: this.callerToken ?? this.cfg.token,
|
|
551
|
+
selfName: this.name,
|
|
552
|
+
selfUrl: this.lastUrl,
|
|
553
|
+
selfAutoName: this.autoName,
|
|
554
|
+
entries: json?.peers,
|
|
555
|
+
timeoutMs: this.cfg.callTimeoutMs ?? 120_000,
|
|
556
|
+
key: this.key,
|
|
557
|
+
}),
|
|
558
|
+
);
|
|
559
|
+
} catch {
|
|
560
|
+
/* best-effort — next heartbeat retries */
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** Register + start the heartbeat loop. Each beat re-registers and
|
|
565
|
+
* refreshes the peer overlay. A failed fresh start clears any stale
|
|
566
|
+
* overlay from a previous upstream instance — and the heartbeat keeps
|
|
567
|
+
* running, so the gateway self-heals (e.g. the macOS Local Network
|
|
568
|
+
* permission granted mid-session) without a restart. */
|
|
569
|
+
async start(url: string): Promise<boolean> {
|
|
570
|
+
this.onPeers({});
|
|
571
|
+
this.wasRegistered = false;
|
|
572
|
+
this.beatFails = 0;
|
|
573
|
+
this.backoffUntil = 0;
|
|
574
|
+
const ok = await this.register(url);
|
|
575
|
+
if (ok) this.openChannel(url);
|
|
576
|
+
if (!this.timer) {
|
|
577
|
+
const intervalMs = Math.max(15, this.cfg.heartbeatSec ?? 60) * 1000;
|
|
578
|
+
this.timer = setInterval(() => {
|
|
579
|
+
void this.maybeBeat(url);
|
|
580
|
+
}, intervalMs);
|
|
581
|
+
this.timer.unref?.();
|
|
582
|
+
}
|
|
583
|
+
return ok;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** One heartbeat beat — the timer's unit of work. Never throws (a beat
|
|
587
|
+
* error must not surface as an unhandled rejection); opens the reverse
|
|
588
|
+
* channel on the first successful register after a failed start. Skipped
|
|
589
|
+
* entirely while stopped or backed off. */
|
|
590
|
+
private async maybeBeat(url: string): Promise<void> {
|
|
591
|
+
if (this.stopped || Date.now() < this.backoffUntil) return;
|
|
592
|
+
await this.beat(url);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
private async beat(url: string): Promise<void> {
|
|
596
|
+
let ok = false;
|
|
597
|
+
try {
|
|
598
|
+
ok = await this.register(url);
|
|
599
|
+
} catch (e) {
|
|
600
|
+
this.log(`[a2a-gateway:${this.label}] heartbeat error: ${e instanceof Error ? e.message : e}`);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
if (ok) this.openChannel(url);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** Reverse channel (default on): firewalled peers still receive proxied
|
|
607
|
+
* requests — everything rides connections WE initiated. Idempotent —
|
|
608
|
+
* beats re-call it after a failed start. */
|
|
609
|
+
private openChannel(url: string): void {
|
|
610
|
+
if (this.cfg.channel === false || this.channel) return;
|
|
611
|
+
this.channel = new ChannelClient(
|
|
612
|
+
// Channel open is a management action (switchboard issue #3): once a
|
|
613
|
+
// per-peer caller_token exists it is the ONLY accepted credential —
|
|
614
|
+
// the shared token 403s. register() above has already minted/loaded it.
|
|
615
|
+
{ ...this.cfg, token: this.callerToken ?? this.cfg.token, localToken: this.cfg.localToken ?? this.cfg.upstreamToken },
|
|
616
|
+
this.cfg.localBase ?? url,
|
|
617
|
+
this.log,
|
|
618
|
+
this.epochRef,
|
|
619
|
+
this.onStatus,
|
|
620
|
+
);
|
|
621
|
+
void this.channel.start();
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** DELETE /register?name=... Best-effort; no throw. Clears the overlay. */
|
|
625
|
+
async stop(): Promise<void> {
|
|
626
|
+
this.stopped = true;
|
|
627
|
+
this.epoch += 1; // in-flight register()/refreshPeers() must not resurrect us
|
|
628
|
+
this.epochRef.value = this.epoch; // channel reconnect loops die too
|
|
629
|
+
this.channel?.stop();
|
|
630
|
+
this.channel = null;
|
|
631
|
+
if (this.timer) clearInterval(this.timer);
|
|
632
|
+
this.timer = null;
|
|
633
|
+
try {
|
|
634
|
+
await fetch(this.url(`/register?name=${encodeURIComponent(this.name)}`), {
|
|
635
|
+
method: "DELETE",
|
|
636
|
+
headers: { authorization: `Bearer ${this.callerToken ?? this.cfg.token}` },
|
|
637
|
+
signal: AbortSignal.timeout(DEREG_TIMEOUT_MS),
|
|
638
|
+
});
|
|
639
|
+
} catch {
|
|
640
|
+
/* best-effort — stale entry decays via gateway health probing */
|
|
641
|
+
}
|
|
642
|
+
this.onPeers({});
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// ---------------------------------------------------------------------------
|
|
647
|
+
// Reverse channel client — receive proxied requests over our own SSE stream
|
|
648
|
+
// ---------------------------------------------------------------------------
|
|
649
|
+
|
|
650
|
+
/** One request envelope pushed down /channel (mirrors gateway Envelope). */
|
|
651
|
+
interface ChannelEnvelope {
|
|
652
|
+
id: number;
|
|
653
|
+
method: string;
|
|
654
|
+
path: string;
|
|
655
|
+
query?: string | null;
|
|
656
|
+
headers: Record<string, string>;
|
|
657
|
+
body_b64: string;
|
|
658
|
+
/** Per-connection secret from the gateway `hello` event — echoed in the
|
|
659
|
+
* response so a shared-token peer can't answer foreign requests. */
|
|
660
|
+
chan_secret?: string;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
interface ChannelRespEnvelope {
|
|
664
|
+
id: number;
|
|
665
|
+
status: number;
|
|
666
|
+
headers: Record<string, string>;
|
|
667
|
+
body_b64: string;
|
|
668
|
+
chan_secret?: string;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** Max channel body (matches gateway MAX_CHANNEL_BODY — 4 MiB). */
|
|
672
|
+
const MAX_CHANNEL_BODY = 4 * 1024 * 1024;
|
|
673
|
+
const MAX_B64 = Math.floor((MAX_CHANNEL_BODY * 4) / 3) + 4;
|
|
674
|
+
|
|
675
|
+
/** Opens GET /channel and dispatches each `request` event to the local A2A
|
|
676
|
+
* server, posting the answer to /channel/response/{id}. Reconnects with
|
|
677
|
+
* capped backoff; aborts cleanly on stop() (epoch-guarded like register). */
|
|
678
|
+
export class ChannelClient {
|
|
679
|
+
private controller: AbortController | null = null;
|
|
680
|
+
private stopped = false;
|
|
681
|
+
private epoch = 0;
|
|
682
|
+
/** Per-connection secret from the gateway hello event. */
|
|
683
|
+
private chanSecret = "";
|
|
684
|
+
/** In-flight dispatches — stop() waits for them (bounded). */
|
|
685
|
+
private inflight = new Set<Promise<void>>();
|
|
686
|
+
|
|
687
|
+
constructor(
|
|
688
|
+
private readonly cfg: GatewayConfig,
|
|
689
|
+
private readonly localBase: string,
|
|
690
|
+
private readonly log: (msg: string) => void = console.error,
|
|
691
|
+
/** Bumped by GatewayUpstream.stop() to stop reconnect loops. */
|
|
692
|
+
private readonly sharedEpoch: { value: number },
|
|
693
|
+
/** Host-TUI status line (transcript) for lifecycle events — the channel
|
|
694
|
+
* opening is surfaced like the registration message instead of raw
|
|
695
|
+
* console output. Falls back to `log` when absent. */
|
|
696
|
+
private readonly onStatus: ((msg: string) => void) | undefined = undefined,
|
|
697
|
+
) {}
|
|
698
|
+
|
|
699
|
+
/** Human-readable gateway label for messages: `<key>@<host>`. */
|
|
700
|
+
private get label(): string {
|
|
701
|
+
try {
|
|
702
|
+
return `${this.cfg.key || "default"}@${new URL(this.cfg.url).host}`;
|
|
703
|
+
} catch {
|
|
704
|
+
return this.cfg.key || "default";
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** Route a lifecycle line to the transcript (onStatus) when available,
|
|
709
|
+
* else to the diagnostic log. Never throws. */
|
|
710
|
+
private status(msg: string): void {
|
|
711
|
+
if (this.onStatus) {
|
|
712
|
+
try {
|
|
713
|
+
this.onStatus(msg);
|
|
714
|
+
return;
|
|
715
|
+
} catch {
|
|
716
|
+
/* fall back to log */
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
this.log(msg);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
private url(path: string): string {
|
|
723
|
+
return this.cfg.url.replace(/\/+$/, "") + path;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** Open the stream; resolves true once connected (reading continues in
|
|
727
|
+
* the background until stop()). Never throws. */
|
|
728
|
+
async start(): Promise<boolean> {
|
|
729
|
+
this.stopped = false;
|
|
730
|
+
return this.connect(0);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
private connect(attempt: number): Promise<boolean> {
|
|
734
|
+
if (this.stopped || this.sharedEpoch.value !== this.epoch) return Promise.resolve(false);
|
|
735
|
+
const ctrl = new AbortController();
|
|
736
|
+
this.controller = ctrl;
|
|
737
|
+
return fetch(this.url(`/channel?name=${encodeURIComponent(this.cfg.name || "pi")}`), {
|
|
738
|
+
headers: { authorization: `Bearer ${this.cfg.token}` },
|
|
739
|
+
signal: ctrl.signal,
|
|
740
|
+
})
|
|
741
|
+
.then((res) => {
|
|
742
|
+
if (!res.ok || !res.body) throw new Error(`channel open failed: HTTP ${res.status}`);
|
|
743
|
+
if (attempt === 0)
|
|
744
|
+
this.status(
|
|
745
|
+
`[a2a] gateway channel open: ${this.label} as ${this.cfg.name || "pi"} (firewall-safe receive)`,
|
|
746
|
+
);
|
|
747
|
+
const connected = attempt === 0;
|
|
748
|
+
// readStream never resolves while healthy — keep it detached.
|
|
749
|
+
void this.readStream(res.body!)
|
|
750
|
+
.then(() => this.reconnect(attempt))
|
|
751
|
+
.catch((e: unknown) => {
|
|
752
|
+
if (!ctrl.signal.aborted) void this.reconnect(attempt, e);
|
|
753
|
+
});
|
|
754
|
+
return connected;
|
|
755
|
+
})
|
|
756
|
+
.catch((e: unknown) => {
|
|
757
|
+
if (ctrl.signal.aborted) return false; // stop()
|
|
758
|
+
return this.reconnect(attempt, e);
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
private async reconnect(attempt: number, why?: unknown): Promise<boolean> {
|
|
763
|
+
if (this.stopped || this.sharedEpoch.value !== this.epoch) return false;
|
|
764
|
+
const delay = Math.min(30_000, 1000 * 2 ** Math.min(attempt, 5));
|
|
765
|
+
if (attempt === 0 && why) this.log(`[a2a-gateway:${this.label}] channel dropped, reconnecting: ${String(why)}`);
|
|
766
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
767
|
+
return this.connect(attempt + 1);
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** Minimal SSE reader: CRLF/LF-tolerant, ignores comments, captures the
|
|
771
|
+
* `hello` secret, dispatches `request` envelopes with a size guard. */
|
|
772
|
+
private async readStream(body: ReadableStream<Uint8Array>): Promise<void> {
|
|
773
|
+
const reader = body.getReader();
|
|
774
|
+
const dec = new TextDecoder();
|
|
775
|
+
let buf = "";
|
|
776
|
+
for (;;) {
|
|
777
|
+
const { done, value } = await reader.read();
|
|
778
|
+
if (done) return;
|
|
779
|
+
buf += dec.decode(value, { stream: true });
|
|
780
|
+
// Normalize CRLF → LF so \n\n framing works for both line endings.
|
|
781
|
+
buf = buf.replace(/\r\n/g, "\n");
|
|
782
|
+
let idx: number;
|
|
783
|
+
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
784
|
+
const frame = buf.slice(0, idx);
|
|
785
|
+
buf = buf.slice(idx + 2);
|
|
786
|
+
this.handleFrame(frame);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
private handleFrame(frame: string): void {
|
|
792
|
+
let event = "message";
|
|
793
|
+
const dataLines: string[] = [];
|
|
794
|
+
for (const line of frame.split("\n")) {
|
|
795
|
+
const l = line.replace(/\r$/, "");
|
|
796
|
+
if (!l || l.startsWith(":")) continue; // blank + comments
|
|
797
|
+
if (l.startsWith("event:")) event = l.slice(6).trim();
|
|
798
|
+
else if (l.startsWith("data:")) dataLines.push(l.slice(5).trimStart());
|
|
799
|
+
}
|
|
800
|
+
const data = dataLines.join("\n");
|
|
801
|
+
if (event === "hello") {
|
|
802
|
+
this.chanSecret = data.trim();
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
if (event !== "request") return; // ping/lagged ignored
|
|
806
|
+
let env: ChannelEnvelope;
|
|
807
|
+
try {
|
|
808
|
+
env = JSON.parse(data);
|
|
809
|
+
} catch {
|
|
810
|
+
return; // malformed envelope — drop
|
|
811
|
+
}
|
|
812
|
+
// Oversized envelope guard BEFORE decode (OOM protection).
|
|
813
|
+
if (env.body_b64.length > MAX_B64) {
|
|
814
|
+
this.log(`[a2a-gateway:${this.label}] dropped oversized envelope (${env.body_b64.length} b64 chars)`);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
const p = this.dispatch(env);
|
|
818
|
+
this.inflight.add(p);
|
|
819
|
+
void p.finally(() => this.inflight.delete(p));
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/** Forward one envelope to the local server and post the answer back. */
|
|
823
|
+
private async dispatch(env: ChannelEnvelope): Promise<void> {
|
|
824
|
+
// Path must stay inside the local origin — reject traversal outright.
|
|
825
|
+
if (!env.path.startsWith("/") || env.path.includes("..")) {
|
|
826
|
+
this.log(`[a2a-gateway:${this.label}] dropped envelope with unsafe path: ${env.path}`);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
const binary = Uint8Array.from(atob(env.body_b64), (c) => c.charCodeAt(0));
|
|
830
|
+
const qs = env.query ? `?${env.query}` : "";
|
|
831
|
+
const headers: Record<string, string> = { ...env.headers };
|
|
832
|
+
if (this.cfg.localToken) headers.authorization = `Bearer ${this.cfg.localToken}`;
|
|
833
|
+
try {
|
|
834
|
+
const res = await fetch(this.localBase.replace(/\/+$/, "") + env.path + qs, {
|
|
835
|
+
method: env.method,
|
|
836
|
+
headers,
|
|
837
|
+
body: ["GET", "HEAD"].includes(env.method) ? undefined : binary,
|
|
838
|
+
});
|
|
839
|
+
const buf = new Uint8Array(await res.arrayBuffer());
|
|
840
|
+
if (buf.length > MAX_CHANNEL_BODY) {
|
|
841
|
+
this.log(`[a2a-gateway:${this.label}] local reply too large (${buf.length}B) — not posted`);
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
let b64 = "";
|
|
845
|
+
for (let i = 0; i < buf.length; i += 0x8000) {
|
|
846
|
+
b64 += String.fromCharCode(...buf.subarray(i, i + 0x8000));
|
|
847
|
+
}
|
|
848
|
+
const outHeaders: Record<string, string> = {};
|
|
849
|
+
res.headers.forEach((v, k) => {
|
|
850
|
+
if (!["transfer-encoding", "content-length", "connection"].includes(k.toLowerCase())) outHeaders[k] = v;
|
|
851
|
+
});
|
|
852
|
+
await this.postResponse({
|
|
853
|
+
id: env.id,
|
|
854
|
+
status: res.status,
|
|
855
|
+
headers: outHeaders,
|
|
856
|
+
body_b64: btoa(b64),
|
|
857
|
+
chan_secret: this.chanSecret,
|
|
858
|
+
});
|
|
859
|
+
} catch (e) {
|
|
860
|
+
this.log(`[a2a-gateway:${this.label}] channel dispatch failed: ${String(e)}`);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
private async postResponse(resp: ChannelRespEnvelope): Promise<void> {
|
|
865
|
+
try {
|
|
866
|
+
await fetch(this.url(`/channel/response/${resp.id}?name=${encodeURIComponent(this.cfg.name || "pi")}`), {
|
|
867
|
+
method: "POST",
|
|
868
|
+
headers: {
|
|
869
|
+
authorization: `Bearer ${this.cfg.token}`,
|
|
870
|
+
"content-type": "application/json",
|
|
871
|
+
},
|
|
872
|
+
body: JSON.stringify(resp),
|
|
873
|
+
signal: AbortSignal.timeout(15_000),
|
|
874
|
+
});
|
|
875
|
+
} catch {
|
|
876
|
+
/* id may already be expired — nothing to do */
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
stop(): void {
|
|
881
|
+
this.stopped = true;
|
|
882
|
+
this.epoch += 1; // kill in-flight connect/reconnect
|
|
883
|
+
this.controller?.abort();
|
|
884
|
+
this.controller = null;
|
|
885
|
+
// In-flight dispatches are NOT awaited: responses may race shutdown and
|
|
886
|
+
// post after the session ends — the gateway expires pending response ids.
|
|
887
|
+
this.inflight.clear();
|
|
888
|
+
}
|
|
889
|
+
}
|